commit bf2ffa73154a6b6e3c0677e4d80856d416ca0583 Author: Alan Date: Sun Jun 19 13:45:53 2022 -0500 copying to personal repo diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8c83aa6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +*.pyc +*.npz +*.lock +*.bak +*.dat +cache +i386 +cnmodel/mechanisms/*.c +cnmodel/mechanisms/*.o +cnmodel/an_model/model/*.mexmaci64 +x86_64 +cnmodel/an_model +doc/build +build +dist/ +cnmodel.egg* +.cache* +.pytest* +Figure6* +project/__pycache__ +project/testing.py +how +*.dll +.idea/ +project/run_data/ +*__pycache__/ +.gitattributes + + + + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..dc37192 --- /dev/null +++ b/LICENSE @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2017 Paul B. Manis, Luke Campagnola, University of North Carolina +at Chapel Hill +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..15e08c5 --- /dev/null +++ b/README.rst @@ -0,0 +1,343 @@ +Changes +======= + +This version of cnmodel runs under Python3.6 or later, using Neuron 7.6. New features include a method for changing the data tables on the fly without editing the original tables, and a tool for fitting Exp2Syn "simple" PSCs to the multisite PSC data (or, potentially, to experimental data) to get parameters for the synapse description table. + +About CNModel +============= + +CNModel is a Python-based interface to NEURON models of cochlear nucleus neurons, synapses, network connectivity. To drive the model with sound stimuli, the Zilany et al (2010, 2014) auditory periphery model is used to generate auditory nerve spike trains (either via the "cochlea" Python package or by the original MATLAB model; see below). The overall goal is to provide a platform for modeling networks of cochlear nucleus neurons with different levels of biological realism in the context of an accurate simulation of auditory nerve input. + +At the lowest level are NEURON-based implementations of ion channels and synapses. Ion channel models for potassium channels are derived largely from the measurements and models of Rothman and Manis (2003abc), and Kanold and Manis (1999, 2001); other channels are derived or modified from the literature. Cell models are in turn based on the insertion of ion channels in densities based on measurements in guinea pig and mouse. The "point" somatic cell models, which form the base set of models in CNModel, replicate the data reported in the original papers. + +The postsynaptic receptor/conductance models are based on kinetic models of glutamate (Raman and Trussell, 1992) and glycinergic receptors, as adjusted to match measurements of synaptic conductances from the mouse cochlear nucleus collected in Xie and Manis, 2013. The glutamate receptor models include desensitization and the effects of internal polyamine receptor block, based on the kinetic scheme of Woodhull (1982). + +The presynaptic release model includes a multisite, probabilistic synapse that includes time-dependent changes in release probability based on the Dittman, Kreitzer and Regehr (J Neurosci. 2000 Feb 15;20(4):1374-85) kinetic scheme. Although detailed, this model is computationally expensive and likely not suitable for large scale network simulations. Other simpler models of synapses are also included. + +Network connectivity may be defined programmatically, or based on a table of connectivity patterns. A table with estimates derived from the literature is included in the source. + +Included in this package is a set of test suites for different components. An overriding set of unit tests is available to confirm performance of the base models against a set of reference runs, several of which are in turn directly traceable to the original manuscripts. The test suites are useful in verifying performance of the model after modifications of the code or changes in the installation (upgrades of Python or Matlab, for example). + +A manuscript describing this package has been published: +-------------------------------------------------------- + + Paul B. Manis, Luke Campagnola, + A biophysical modelling platform of the cochlear nucleus and other auditory circuits: + From channels to networks, + Hearing Research, + Volume 360, + 2018, + Pages 76-91, + ISSN 0378-5955, + https://doi.org/10.1016/j.heares.2017.12.017. + Open Access: http://www.sciencedirect.com/science/article/pii/S037859551730360X + +If you use this package, we would appreciate it if you cite our work in any publications or abstracts. + + +Installation requirements +------------------------- +This package depends on the following: + +1. Python 3.6 with numpy (1.14.3), scipy (1.1.0), lmfit (0.9.11), matplotlib (3.0.0), faulthandler, and pyqtgraph (0.11.0). The cochlea module requires pandas as well. + An Anaconda install with the appropriate scientific packages works well:: + + conda install python=3.6 pyqt pyqtgraph matplotlib numpy scipy pandas pytest cython + pip install resampy + pip install lmfit + pip install cochlea + + or: + + conda create --name py3mpl3 python=3.6 pyqt pyqtgraph matplotlib=3 numpy scipy pandas pytest cython + pip install resampy + pip install lmfit + pip install cochlea + + + (Note that under MacOSX, python 3.7 is usable, but the Windows versio of Matlab R2018b is restricted + to python 3.6) + +2. A Python-linked version of NEURON (www.neuron.yale.edu). The code has been tested with NEURON 7.5 and 7.6. +3. A C compiler (gcc). Needed for compilation of mechanisms for NEURON. +4. The Zilany et al (JASA 2014) auditory periphery model. This can be provided one of two ways: + + * The Python-based cochlea model by Rudnicki and Hemmert at https://github.com/mrkrd/cochlea. + This is probably best installed via pip per the instructions on the PyPi site: ``pip install cochlea``. + * The original MATLAB-based Zilany model; requires MATLAB 2011 or later. A C compiler will also + be needed to build this model. The model should be placed in the directory + ``cnmodel/cnmodel/an_model/model``, with the following components: ANmodel.m, complex.c, complex.h, + complex.hpp, ffGn.m, fituaudiogram2.m, mexANmodel.m, model_IHC.c, model_Synapse.c, + and the THRESHOLD_ALL_* files. When cnmodel attempts to access this code the first time, + it will perform the necessary compilation. + +5. neuronvis (optional) available at https://github.com/campagnola/neuronvis or https://github.com/pbmanis/neuronvis). + This provides 3D visualization for morphology. + +After the code is installed, enter the cnmodel directory and compile the NEURON mod files:: + + $ nrnivmodl cnmodel/mechanisms + +This will create a directory ("x86_64" or "special") in the top cnmodel directory with the compiled mechanisms. + +Under Windows 10, use:: + + $ mknrndll cnmodel\mechanisms + +to do the same thing. + + +For more detailed information on setup in a Windows environment, see the file Windows_setup.md. Thanks to Laurel Carney for prompting the generation of this set of instructions, and for identifying issues on Windows. + +Windows caveat: +-------------- +Manually compile the mex files (using Matlab, go to the an_model/models folder, and use mexANmodel.m to compile the files). Then, add the an_model/model folder to the Matlab path, so that it can find the files when needed. + +For more detailed information on setup in a Windows environment, see the file Windows_setup.md. Thanks to Laurel Carney for prompting the generation of this set of instructions, and for identifying issues on Windows. + +Note: *This package is not yet compatible with Python 3.x. Neuron is not yet compatible with Python 3.x* + + +Testing +------- + + +Make sure you are in the cnmodel directory, and that you have selected the right environment in Anaconda (in +my case, this is usually py3mpl3). + +At this point:: + +After the code is installed, enter the cnmodel directory and compile the NEURON mod files:: + + $ nrnivmodl cnmodel/mechanisms + +This will create a directory ("x86_64" or "special") in the top cnmodel directory with the compiled mechanisms. + +Then:: + + $ python examples/toy_model.py + +should generate a plot with several sets of traces showing responses of individual neuron models to depolarizing and hyperpolarizing current steps. + +The test suite should be run as:: + + $ python test.py + +This will test each of the models against reference data, the synapse mechanisms, a number of internal routines, and the auditory nerve model. The tests should pass for each component. Failures may indicate incorrect installation or incorrect function within individual components. These should be corrected before proceeding with simulations. + + +Note +---- +Under Windows, it may be best to use the standard windows command terminal rather than the "bash" terminal provided by NEURON, at least to run the Python scripts. + +Matlab +------ +This version has been tested with the Matlab AN model of Zilany et al., 2014. +Before using, you will need to compile the C code in an_model using Matlab's mex tool. First however, change the following code: +In model_Synapse.c: + +Change (line 63 in the source):: + + $ int nrep, pxbins, lp, outsize[2], totalstim; + +to:: + $ int nrep, pxbins, lp, totalstim; + $ size_t outsize[2]; + +Likewise, in model_IHC.c, change:: + + $ int nrep, pxbins, lp, outsize[2], totalstim, species; + +to:: + + $ int nrep, pxbins, lp, totalstim, species; + $ size_t outsize[2]; + +Then, in Matlab, go to the cnmodel/an_model/model directory, and run:: + + $ mexANmodel + +Then, cd to an_model and run:: + + $ testANmodel + +to confirm that the model is installed and working. +(You may need to add the model directory to the Matlab path.) + + +Figures +------- + +The data for the figures in the manuscript (Manis and Campagnola, Hearing Research 2018) can be generated using the bash script "figures.sh" in the examples subdirectory. +From the main cnmodel directory:: + + $ ./examples figures.sh fignum + +where fignum is one of 2a, 2b, 2c, 3, 4, 5, 6a, 6b, or 7. + +Note that Figure 7 may take several **hours** to generate. + +Example code and tests +---------------------- + +A number of additional tests are included in the examples directory. + + +- `test_an_model.py` verifies that the auditory nerve model can be run. If necessary, it will compile (using MEX) the mechanisms for matlab. +- `test_ccstim.py` tests the generation of different stimulus waveforms by the pulse generator module. +- `test_cells.py` runs different cell models in current or voltage clamp. + Usage:: + + test_cells.py celltype species[-h] [--type TYPE] [--temp TEMP] [-m MORPHOLOGY] + [--nav NAV] [--ttx] [-p PULSETYPE] [--vc | --cc | --rmp] + + For example: ``python test_cells.py bushy mouse --cc --temp 34`` + + +- `test_cells.py` can run protocols on selected cell models. + Usage:: + + test_cells.py [-h] [--type TYPE] [--temp TEMP] [-m MORPHOLOGY] + [--nav NAV] [--ttx] [-p PULSETYPE] [--vc | --cc | --rmp] + celltype species + +- `test_circuit.py` tests the generation of circuits with populations of cells. No simulations are run. +- `test_decorator.py` generates an IV curve for the reconstructed cell LC_bushy.hoc (Figure 5B,C) +- `test_mechanisms.py` runs a voltage clamp I/V protocol on a selected mechanism and displays the result. + Usage:: + + python test_mechanisms.py + + Available channel mechanisms: + + ========== ========= ========== ============= ================== + CaPCalyx KIR bkpkj hcno hcnobo + hh hpkj ihpyr ihsgcApical ihsgcBasalMiddle + ihvcn jsrna k_ion ka kcnq + kdpyr kht kif kis klt + kpkj kpkj2 kpkjslow kpksk leak + lkpkj na naRsg na_ion nacn + nacncoop nap napyr nav11 + ========== ========= ========== ============= ================== + +- `test_mso_inputs.py` runs a circuit that creates a point MSO neuron, innervated by bushy cells from independent "ears". This demonstrates how to construct a binaural circuit using CNModel. +- `test_physiology.py` runs a large VCN circuit that converges onto a single bushy cell. This run can take a long time. The output was used to create Figure 7 of the manuscript. +- `test_populations.py` tests synaptic connections between two cell types. Usage:: + + python test_populations.py + +- `test_sgc_input_phaselocking.py` tests phase locking with SGC inputs to a bushy cell. +- `test_sgc_input_PSTH.py` shows SGC inputs and postsynaptic bushy cell PSTHs. +- `test_sgc_input.py` demonstrates SGC input to a VCN bushy cell. +- `test_simple_synapses.py` tests simple Exp2Syn inputs to different cell types. Usage:: + + python test_synapses.py + + Supported cell types: sgc, bushy, tstellate, dstellate, tuberculoventral, pyramidal +- `test_sound_stim.py` generates spike trains from the selected model (cochlea, matlab) and plots rate-intensity functions for the 3 different SR groups. +- `test_sounds.py` generates waveforms for different kinds of sounds included in the sounds class. +- `test_synapses.py` evokes spikes in a presynaptic cell while recording the postsynaptic potential. Usage:: + + python test_synapses.py + + Supported cell types: sgc, bushy, tstellate, dstellate +- `toy_model.py` generates IV plots for each of the principal point cell types included in CNModel. This is the code that generates Figure 3 of the manuscript. + +Potential Issues and Solutions +------------------------------ + +1. Occasionally one of the AN spike train files, which are stored in the directory `cnmodel/an_model/cache`, become locked. This can occur if the calling routines are aborted (^C, ^Z) in the middle of a transaction accessing the cache file, or perhaps during when parallel processing is enabled and a routine fails or is aborted. In this case, a file with the extension ``".lock"`` exists, which prevents the an_model code from accessing the file. The ``".lock"`` file needs to be deleted from the cache directory. + + * First, print a list of the locked files:: + + $ find /path/to/cache -name '*.lock' + + * Where /path/to/cache may be something like `cnmodel/an_model/cache`. + There is most likely only one such file in the diretory. + + * Next, to delete the files:: + + $ find /path/to/cache -name '*.lock' -delete + + * Under Windows (and other OS's), you should be able do accomplish the same thing + with the File Explorer/Finder, limiting the files by extension. + + +References +---------- + +1. Cao XJ, Oertel D. The magnitudes of hyperpolarization-activated and +low-voltage-activated potassium currents co-vary in neurons of the ventral +cochlear nucleus. J Neurophysiol. 2011 Aug;106(2):630-40. doi: +10.1152/jn.00015.2010. Epub 2011 May 11. PubMed PMID: 21562186; PubMed Central +PMCID: PMC3154804. + +2. Cao XJ, Oertel D. Auditory nerve fibers excite targets through synapses that +vary in convergence, strength, and short-term plasticity. J Neurophysiol. 2010 +Nov;104(5):2308-20. doi: 10.1152/jn.00451.2010. Epub 2010 Aug 25. PubMed PMID: +20739600; PubMed Central PMCID: PMC3350034. + +3. Dittman JS, Kreitzer AC, Regehr WG. Interplay between facilitation, depression, +and residual calcium at three presynaptic terminals. J Neurosci. 2000 +Feb 15;20(4):1374-85. PubMed PMID: 10662828. + +1. Isaacson JS, Walmsley B. Counting quanta: direct measurements of transmitter +release at a central synapse. Neuron. 1995 Oct;15(4):875-84. + +4. Kanold PO, Manis PB. A physiologically based model of discharge pattern +regulation by transient K+ currents in cochlear nucleus pyramidal cells. J +Neurophysiol. 2001 Feb;85(2):523-38. PubMed PMID: 11160490. + +5. Kanold PO, Manis PB. Transient potassium currents regulate the discharge +patterns of dorsal cochlear nucleus pyramidal cells. J Neurosci. 1999 Mar +15;19(6):2195-208. PubMed PMID: 10066273. + +6. Liu Q, Manis PB, Davis RL. Ih and HCN channels in murine spiral ganglion +neurons: tonotopic variation, local heterogeneity, and kinetic model. J Assoc Res +Otolaryngol. 2014 Aug;15(4):585-99. doi: 10.1007/s10162-014-0446-z. Epub 2014 Feb +21. Erratum in: J Assoc Res Otolaryngol. 2014 Aug;15(4):601. PubMed PMID: +24558054; PubMed Central PMCID: PMC4141436. + +7. Raman IM, Trussell LO. The kinetics of the response to glutamate and kainate +in neurons of the avian cochlear nucleus. Neuron. 1992 Jul;9(1):173-86. PubMed +PMID: 1352983. + +8. Rothman JS, Manis PB. The roles potassium currents play in regulating the +electrical activity of ventral cochlear nucleus neurons. J Neurophysiol. 2003 +Jun;89(6):3097-113. PubMed PMID: 12783953. + +9. Rothman JS, Manis PB. Kinetic analyses of three distinct potassium +conductances in ventral cochlear nucleus neurons. J Neurophysiol. 2003 +Jun;89(6):3083-96. PubMed PMID: 12783952. + +10. Rothman JS, Manis PB. Differential expression of three distinct potassium +currents in the ventral cochlear nucleus. J Neurophysiol. 2003 Jun;89(6):3070-82. +PubMed PMID: 12783951. + +11. Rothman JS, Young ED, Manis PB. Convergence of auditory nerve fibers onto +bushy cells in the ventral cochlear nucleus: implications of a computational +model. J Neurophysiol. 1993 Dec;70(6):2562-83. PubMed PMID: 8120599. + +12. Woodhull AM. Ionic blockage of sodium channels in nerve. J Gen Physiol. 1973 +Jun;61(6):687-708. PubMed PMID: 4541078; PubMed Central PMCID: PMC2203489. + +13. Xie R, Manis PB. Target-specific IPSC kinetics promote temporal processing in +auditory parallel pathways. J Neurosci. 2013 Jan 23;33(4):1598-614. doi: +10.1523/JNEUROSCI.2541-12.2013. PubMed PMID: 23345233; PubMed Central PMCID: +PMC3737999. + +14. Zilany MS, Bruce IC, Carney LH. Updated parameters and expanded simulation +options for a model of the auditory periphery. J Acoust Soc Am. 2014 +Jan;135(1):283-6. doi: 10.1121/1.4837815. PubMed PMID: 24437768; PubMed Central +PMCID: PMC3985897. + +15. Zilany MS, Carney LH. Power-law dynamics in an auditory-nerve model can +account for neural adaptation to sound-level statistics. J Neurosci. 2010 Aug +4;30(31):10380-90. doi: 10.1523/JNEUROSCI.0647-10.2010. PubMed PMID: 20685981; +PubMed Central PMCID: PMC2935089. + +16. Zilany MS, Bruce IC, Nelson PC, Carney LH. A phenomenological model of the +synapse between the inner hair cell and auditory nerve: long-term adaptation with +power-law dynamics. J Acoust Soc Am. 2009 Nov;126(5):2390-412. doi: +10.1121/1.3238250. PubMed PMID: 19894822; PubMed Central PMCID: PMC2787068. + diff --git a/Windows_setup.md b/Windows_setup.md new file mode 100644 index 0000000..015d523 --- /dev/null +++ b/Windows_setup.md @@ -0,0 +1,321 @@ +CNMODEL Setup for Windows Systems +================================= + +(as of 2 March 2018, tested on Windows 10) +On a bare system, you will need to install the following packages: + + 1. Anaconda Python 2.7 (this may also include the Microsoft Visual Studio for Python) + 2. git + 3. msvc2.7forpython (required for cochlea) + 4. external python package from PyPi: cochlea + 5. NEURON7.5 (this must be installed last) + 6. cnmodel, cloned from the main repository with git + 7. build the .dll file for the Neuron mechanisms used in cnmodel + +Some installs are accomplished via a graphical interface (anaconda, git, msvc, neuron). +Other parts of the install are done from the terminal (Windows "Command Prompt" - look in the Windows Accessories) + +Follow the instructions below to do this installation. The order only partially matters - msvcforpython must be installed before cochlea can be built; python should be installed before NEURON; and git is required get the cnmodel repository. + +Step 1: Install Anaconda python for Python 2.7 for your system. +Note that NEURON is not yet compatible with Python 3.x + +https://repo.continuum.io/archive/ +The most recent versions of the Anaconda installer (5.x) are OK to use. +Check the box to set DOS path variables so can run from command prompt. +Install only for yourself. + +If you want, create an environment for python 2.7, Using the standard windows terminal ("Command Prompt"), install the additional required packages:: + + conda create --name models python=2.7 pyqt pyqtgraph matplotlib numpy scipy pandas pytest faulthandler + +Note: this may take a while, and will install many other packages that are required dependencies. + +Now, activate the environment:: + + conda activate models + +Or else, just install everything to the root environment: +conda install pyqt pyqtgraph matplotlib numpy scipy pytest faulthandler + +If you are working with a previous Anaconda installation, you might need to do these steps:: + + conda update --all + conda update qt + +The following must be retrieved from the PyPi repository (I had problems with the one in the anaconda repo):: + + pip install lmfit + +Step 2: Install git (a widely used source control module):: + + https://git-scm.com/downloads + +Step 3: Install MS visual studio for python:: + + https://www.visualstudio.com/vs/python/ + +Step 4: Install cochlea (Rudnicki and Hemmert's implementation of several models under python):: + + pip install cochlea + +This should build quickly and have no errors. + +Step 5: Install NEURON7.5 for mswindows from:: + + www.neuron.yale.edu. + +Restart the command window so that the paths to the python installation are updated. +Make sure that python and neuron are installed correctly together by testing the ability to import NEURON:: + + (base) pbmanis: Python $ python + Python 2.7.14 |Anaconda custom (64-bit)| (default, Dec 7 2017, 11:07:58) + [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin + Type "help", "copyright", "credits" or "license" for more information. + >>> from neuron import h + NEURON -- VERSION 7.5 master (6b4c19f) 2017-09-25 + Duke, Yale, and the BlueBrain Project -- Copyright 1984-2016 + See http://neuron.yale.edu/neuron/credits + + >>> + +(^Z to exit) + +Step 6: Go to where you want to put the model code repository, and clone the repo:: + + git clone https://github.com/cnmodel/cnmodel.git + +Jump into the cnmodel directory. + +Step 7: Find the mknrndll gui from where you installed neuron with the Explorer (the program in the nrn folder). Run the program, and select the directory cnmodel\cnmodel\mechanisms, then build. +This will make nrnmech.dll in the mechanisms directory. +Copy the nrnmech.dll into the main cnmodel directory. + +Step 8: Run:: + + python setup.py develop + +in the main cnmodel directory to make a library version in the anaconda site-packages directory. This will make cnmodel accessible as an import into python from any location. However, you will (on Windows) need to copy the nrnmech.dll file to the directory that you are starting in. (If you import cnmodel and there is not a list of mechanisms after the Neuron banner, then nrnmech.dll was not found). + +Running +======= + +The following should be all that is needed once everything is set up. + +Go the the cnmodel main directory. + +if you set up a Python environment, activate it to make sure you have the right dependencies available. + +Now, these scripts should run just fine:: + + python examples/test_mechanisms.py klt + python examples/toy_model.py + python examples/test_synapses.py sgc bushy + python examples/test_phaselocking.py + +You should also be able to run the full battery of tests:: + + python test.py + +All the tests should pass (except perhaps with the exception dstellate->dstellate; this passes under MacOSX so we will need to investigate why it fails under Windows). MacOSX and Windows test results are listed below. + +Notes +===== + +1. You cannot use the "bash" terminal window that comes with neuron - it doesn't set the paths correctly for access to the anaconda python. + +2. Some of the graphical displays are not correctly sized in Windows. You may need to expand the window to see all the plots (specifically, toy_model has this problem). + +3. Report occurrences of failures to "import PyQt4" to: https://github.com/cnmodel/cnmodel/issues. + +4. The test suite (python test.py) may fail on one test: dstellate -> dstellate synapses (as of 23Feb2018), and if you do not have Matlab, the Matlab test will be skipped. + + +Things solved with Windows +========================== + +1. The test suite works and most tests pass (python test.py). +2. Qt5 and current anaconda install are acceptable (we are no longer trying to force Qt4). +3. The prior dependency on pylibrary has been removed. + + +Potential problems +================== + +This software has been tested primarily on Mac OSX and Linux systems. Some tests have been performed on Windows. If issues are found, please report them via github as an issue (as noted above). + +Test results +============ + +Windows 10 (24 Feb 2018; Qt5 Branch) +------------------------------------ + +:: + C:\Users\pbmanis\Desktop\Python\cnmodel>python test.py > testresults.txt + NEURON -- VERSION 7.5 master (6b4c19f) 2017-09-25 + Duke, Yale, and the BlueBrain Project -- Copyright 1984-2016 + See http://neuron.yale.edu/neuron/credits + + loading membrane mechanisms from C:\Users\pbmanis\Desktop\Python\cnmodel\nrnmech.dll + Additional mechanisms from files + CaPCalyx.mod Gly5GC.mod Gly5PL.mod Gly5State.mod Gly6S.mod Iclamp2.mod NMDA.mod NMDA_Kampa.mod + ampa_trussell.mod bkpkj.mod cabpump.mod cadiff.mod cadyn.mod cap.mod capmp.mod capump.mod cleftXmtr.mod + gly.mod gly2.mod hcno.mod hcno_bo.mod iStim.mod ihpkj.mod ihpyr.mod ihsgc_apical.mod ihsgc_ + basalmiddle.mod ihvcn.mod inav11.mod jsrnaf.mod ka.mod kcnq.mod kdpyr.mod kht.mod kif.mod + kir.mod kis.mod klt.mod kpkj.mod kpkj2.mod kpkjslow.mod kpksk.mod leak.mod multisite.mod + na.mod nacn.mod nacncoop.mod nap.mod napyr.mod pkjlk.mod rsg.mod vecevent.mod + + Testing with flags: -v --tb=short cnmodel/ + ============================= test session starts ============================= + platform win32 -- Python 2.7.14, pytest-3.3.2, py-1.5.2, pluggy-0.6.0 -- C:\Users\pbmanis\Anaconda2\python.exe + cachedir: .cache + rootdir: C:\Users\pbmanis\Desktop\Python\cnmodel, inifile: + collecting ... collected 36 items + + cnmodel/an_model/tests/test_cache.py::test_cache PASSED [ 2%] + cnmodel/an_model/tests/test_cache.py::test_parallel PASSED [ 5%] + cnmodel/cells/tests/test_cells.py::test_bushy PASSED [ 8%] + cnmodel/cells/tests/test_cells.py::test_bushy21 PASSED [ 11%] + cnmodel/cells/tests/test_cells.py::test_bushy_mouse PASSED [ 13%] + cnmodel/cells/tests/test_cells.py::test_tstellate PASSED [ 16%] + cnmodel/cells/tests/test_cells.py::test_tstellate_mouse PASSED [ 19%] + cnmodel/cells/tests/test_cells.py::test_tstellatet PASSED [ 22%] + cnmodel/cells/tests/test_cells.py::test_dstellate PASSED [ 25%] + cnmodel/cells/tests/test_cells.py::test_dstellate_mouse PASSED [ 27%] + cnmodel/cells/tests/test_cells.py::test_octopus PASSED [ 30%] + cnmodel/cells/tests/test_cells.py::test_pyramidal PASSED [ 33%] + cnmodel/cells/tests/test_cells.py::test_tuberculoventral PASSED [ 36%] + cnmodel/cells/tests/test_cells.py::test_cartwheel PASSED [ 38%] + cnmodel/cells/tests/test_cells.py::test_sgc_basal_middle PASSED [ 41%] + cnmodel/cells/tests/test_cells.py::test_sgc_apical PASSED [ 44%] + cnmodel/data/tests/test_db.py::test_db PASSED [ 47%] + cnmodel/mechanisms/tests/test_mechanisms.py::test_max_open_probability PASSED [ 50%] + cnmodel/synapses/tests/test_psd.py::test_sgc_bushy_psd PASSED [ 52%] + cnmodel/synapses/tests/test_psd.py::test_sgc_tstellate_psd PASSED [ 55%] + cnmodel/synapses/tests/test_psd.py::test_sgc_dstellate_psd PASSED [ 58%] + cnmodel/synapses/tests/test_psd.py::test_sgc_octopus_psd PASSED [ 61%] + cnmodel/synapses/tests/test_synapses.py::test_sgc_bushy PASSED [ 63%] + cnmodel/synapses/tests/test_synapses.py::test_sgc_tstellate PASSED [ 66%] + cnmodel/synapses/tests/test_synapses.py::test_sgc_tstellate2 PASSED [ 69%] + cnmodel/synapses/tests/test_synapses.py::test_sgc_dstellate PASSED [ 72%] + cnmodel/synapses/tests/test_synapses.py::test_dstellate_bushy PASSED [ 75%] + cnmodel/synapses/tests/test_synapses.py::test_dstellate_tstellate PASSED [ 77%] + cnmodel/synapses/tests/test_synapses.py::test_dstellate_dstellate FAILED [ 80%] + cnmodel/util/tests/test_expfitting.py::test_fit1 PASSED [ 83%] + cnmodel/util/tests/test_expfitting.py::test_fit2 PASSED [ 86%] + cnmodel/util/tests/test_matlab.py::test_matlab SKIPPED [ 88%] + cnmodel/util/tests/test_sound.py::test_conversions PASSED [ 91%] + cnmodel/util/tests/test_sound.py::test_tonepip PASSED [ 94%] + cnmodel/util/tests/test_sound.py::test_noisepip PASSED [ 97%] + cnmodel/util/tests/test_stim.py::test_make_pulse PASSED [100%] + + ================================== FAILURES =================================== + __________________________ test_dstellate_dstellate ___________________________ + cnmodel\synapses\tests\test_synapses.py:40: in test_dstellate_dstellate + SynapseTester('dstellate', 'dstellate') + cnmodel\synapses\tests\test_synapses.py:72: in __init__ + UserTester.__init__(self, "%s_%s" % (pre, post), pre, post) + cnmodel\util\user_tester.py:33: in __init__ + self.assert_test_info(*args, **kwds) + cnmodel\synapses\tests\test_synapses.py:108: in assert_test_info + super(SynapseTester, self).assert_test_info(*args, **kwds) + cnmodel\util\user_tester.py:127: in assert_test_info + self.compare_results(result, expect) + cnmodel\util\user_tester.py:60: in compare_results + self.compare_results(info[k], expect[k]) + cnmodel\util\user_tester.py:63: in compare_results + self.compare_results(info[i], expect[i]) + cnmodel\util\user_tester.py:79: in compare_results + self.compare_results(info[k], expect[k]) + cnmodel\util\user_tester.py:71: in compare_results + assert np.all(inans == enans) + E AssertionError + ---------------------------- Captured stdout call ----------------------------- + << D-stellate: JSR Stellate Type I-II cell model created >> + << D-stellate: JSR Stellate Type I-II cell model created >> + Elapsed time for 1 Repetions: 0.355309 + =============== 1 failed, 34 passed, 1 skipped in 96.33 seconds =============== + + + +Mac OSX (24 Feb 2018; Qt5 Branch) +--------------------- + +:: + (base) pbmanis: cnmodel [qt5+]$ python test.py + NEURON -- VERSION 7.5 master (6b4c19f) 2017-09-25 + Duke, Yale, and the BlueBrain Project -- Copyright 1984-2016 + See http://neuron.yale.edu/neuron/credits + + loading membrane mechanisms from x86_64/.libs/libnrnmech.so + Additional mechanisms from files + cnmodel/mechanisms//CaPCalyx.mod cnmodel/mechanisms//Gly5GC.mod cnmodel/mechanisms//Gly5PL.mod + cnmodel/mechanisms//Gly5State.mod cnmodel/mechanisms//Gly6S.mod cnmodel/mechanisms//Iclamp2.mod + cnmodel/mechanisms//NMDA.mod cnmodel/mechanisms//NMDA_Kampa.mod + cnmodel/mechanisms//ampa_trussell.mod cnmodel/mechanisms//bkpkj.mod + cnmodel/mechanisms//cabpump.mod cnmodel/mechanisms//cadiff.mod cnmodel/mechanisms//cadyn.mod + cnmodel/mechanisms//cap.mod cnmodel/mechanisms//capmp.mod + cnmodel/mechanisms//capump.mod cnmodel/mechanisms//cleftXmtr.mod + cnmodel/mechanisms//gly.mod cnmodel/mechanisms//gly2.mod cnmodel/mechanisms//hcno.mod + cnmodel/mechanisms//hcno_bo.mod cnmodel/mechanisms//iStim.mod cnmodel/mechanisms//ihpkj.mod + cnmodel/mechanisms//ihpyr.mod cnmodel/mechanisms//ihsgc_apical.mod + cnmodel/mechanisms//ihsgc_basalmiddle.mod cnmodel/mechanisms//ihvcn.mod + cnmodel/mechanisms//inav11.mod cnmodel/mechanisms//jsrnaf.mod + cnmodel/mechanisms//ka.mod cnmodel/mechanisms//kcnq.mod cnmodel/mechanisms//kdpyr.mod + cnmodel/mechanisms//kht.mod cnmodel/mechanisms//kif.mod cnmodel/mechanisms//kir.mod + cnmodel/mechanisms//kis.mod cnmodel/mechanisms//klt.mod cnmodel/mechanisms//kpkj.mod + cnmodel/mechanisms//kpkj2.mod cnmodel/mechanisms//kpkjslow.mod cnmodel/mechanisms//kpksk.mod + cnmodel/mechanisms//leak.mod cnmodel/mechanisms//multisite.mod cnmodel/mechanisms//na.mod + cnmodel/mechanisms//nacn.mod cnmodel/mechanisms//nacncoop.mod cnmodel/mechanisms//nap.mod c + nmodel/mechanisms//napyr.mod cnmodel/mechanisms//pkjlk.mod cnmodel/mechanisms//rsg.mod + cnmodel/mechanisms//vecevent.mod + Testing with flags: -v --tb=short cnmodel/ + =============================================== test session starts =============================================== + platform darwin -- Python 2.7.14, pytest-3.0.7, py-1.4.33, pluggy-0.4.0 -- /Users/pbmanis/anaconda/bin/python + cachedir: .cache + rootdir: /Users/pbmanis/Desktop/Python/cnmodel, inifile: + collected 36 items + + cnmodel/an_model/tests/test_cache.py::test_cache PASSED + cnmodel/an_model/tests/test_cache.py::test_parallel PASSED + cnmodel/cells/tests/test_cells.py::test_bushy PASSED + cnmodel/cells/tests/test_cells.py::test_bushy21 PASSED + cnmodel/cells/tests/test_cells.py::test_bushy_mouse PASSED + cnmodel/cells/tests/test_cells.py::test_tstellate PASSED + cnmodel/cells/tests/test_cells.py::test_tstellate_mouse PASSED + cnmodel/cells/tests/test_cells.py::test_tstellatet PASSED + cnmodel/cells/tests/test_cells.py::test_dstellate PASSED + cnmodel/cells/tests/test_cells.py::test_dstellate_mouse PASSED + cnmodel/cells/tests/test_cells.py::test_octopus PASSED + cnmodel/cells/tests/test_cells.py::test_pyramidal PASSED + cnmodel/cells/tests/test_cells.py::test_tuberculoventral PASSED + cnmodel/cells/tests/test_cells.py::test_cartwheel PASSED + cnmodel/cells/tests/test_cells.py::test_sgc_basal_middle PASSED + cnmodel/cells/tests/test_cells.py::test_sgc_apical PASSED + cnmodel/data/tests/test_db.py::test_db PASSED + cnmodel/mechanisms/tests/test_mechanisms.py::test_max_open_probability PASSED + cnmodel/synapses/tests/test_psd.py::test_sgc_bushy_psd PASSED + cnmodel/synapses/tests/test_psd.py::test_sgc_tstellate_psd PASSED + cnmodel/synapses/tests/test_psd.py::test_sgc_dstellate_psd PASSED + cnmodel/synapses/tests/test_psd.py::test_sgc_octopus_psd PASSED + cnmodel/synapses/tests/test_synapses.py::test_sgc_bushy PASSED + cnmodel/synapses/tests/test_synapses.py::test_sgc_tstellate PASSED + cnmodel/synapses/tests/test_synapses.py::test_sgc_tstellate2 PASSED + cnmodel/synapses/tests/test_synapses.py::test_sgc_dstellate PASSED + cnmodel/synapses/tests/test_synapses.py::test_dstellate_bushy PASSED + cnmodel/synapses/tests/test_synapses.py::test_dstellate_tstellate PASSED + cnmodel/synapses/tests/test_synapses.py::test_dstellate_dstellate PASSED + cnmodel/util/tests/test_expfitting.py::test_fit1 PASSED + cnmodel/util/tests/test_expfitting.py::test_fit2 PASSED + cnmodel/util/tests/test_matlab.py::test_matlab PASSED + cnmodel/util/tests/test_sound.py::test_conversions PASSED + cnmodel/util/tests/test_sound.py::test_tonepip PASSED + cnmodel/util/tests/test_sound.py::test_noisepip PASSED + cnmodel/util/tests/test_stim.py::test_make_pulse PASSED + + =========================================== 36 passed in 94.05 seconds ============================================ + (base) pbmanis: cnmodel [qt5+]$ + + + + diff --git a/_config.yml b/_config.yml new file mode 100644 index 0000000..c419263 --- /dev/null +++ b/_config.yml @@ -0,0 +1 @@ +theme: jekyll-theme-cayman \ No newline at end of file diff --git a/cnmodel/__init__.py b/cnmodel/__init__.py new file mode 100755 index 0000000..14906eb --- /dev/null +++ b/cnmodel/__init__.py @@ -0,0 +1,25 @@ +__author__ = "Paul B. Manis and Luke Campagnola" +__version__ = "0.32a" + +try: + import faulthandler + + faulthandler.enable() +except ImportError: + pass + +import logging + +logging.basicConfig(level=logging.INFO, format="[%(process)s] %(message)s") +import os + +dirname = os.path.abspath(os.path.dirname(__file__)) +libpath = os.path.join(dirname, "..") +import neuron + +try: + neuron.h.MultiSiteSynapse +except AttributeError: + neuron.load_mechanisms(libpath) +# flag to allow unit tests to store / overwrite test results +AUDIT_TESTS = False diff --git a/cnmodel/cells/__init__.py b/cnmodel/cells/__init__.py new file mode 100644 index 0000000..b69cd1c --- /dev/null +++ b/cnmodel/cells/__init__.py @@ -0,0 +1,23 @@ +""" +Cell definitions for models. + +This class includes a number of different cell definitions and default +conductances for point models. +""" + +from .bushy import * +from .tstellate import * +from .dstellate import * +from .cartwheel import * +from .pyramidal import * +from .sgc import * +from .octopus import * +from .tuberculoventral import * +from .msoprincipal import * +from .hh import * + +from .cell import Cell + + +def cell_from_section(sec): + return Cell.from_section(sec) diff --git a/cnmodel/cells/bushy.py b/cnmodel/cells/bushy.py new file mode 100644 index 0000000..1661c5f --- /dev/null +++ b/cnmodel/cells/bushy.py @@ -0,0 +1,967 @@ +from __future__ import print_function +from neuron import h +from collections import OrderedDict +from .cell import Cell +from .. import synapses +from ..util import nstomho +from ..util import Params +import numpy as np +from .. import data +import pprint + +pp = pprint.PrettyPrinter(indent=4, width=60) + +__all__ = ["Bushy", "BushyRothman"] + + +class Bushy(Cell): + + type = "bushy" + + @classmethod + def create(cls, model="RM03", **kwds): + if model == "RM03": + return BushyRothman(**kwds) + else: + raise ValueError("Bushy model %s is unknown", model) + + def make_psd(self, terminal, psd_type, **kwds): + """ + Connect a presynaptic terminal to one post section at the specified location, with the fraction + of the "standard" conductance determined by gbar. + The default condition is designed to pass the unit test (loc=0.5) + + Parameters + ---------- + terminal : Presynaptic terminal (NEURON object) + + psd_type : either simple or multisite PSD for bushy cell + + kwds: dictionary of options. + Two are currently handled: + postsite : expect a list consisting of [sectionno, location (float)] + AMPAScale : float to scale the ampa currents + + """ + if ( + "postsite" in kwds + ): # use a defined location instead of the default (soma(0.5) + postsite = kwds["postsite"] + loc = postsite[1] # where on the section? + uname = ( + "sections[%d]" % postsite[0] + ) # make a name to look up the neuron section object + post_sec = self.hr.get_section(uname) # Tell us where to put the synapse. + else: + loc = 0.5 + post_sec = self.soma + + if psd_type == "simple": + if terminal.cell.type in ["sgc", "dstellate", "tuberculoventral"]: + weight = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="weight", + ) + tau1 = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="tau1", + ) + tau2 = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="tau2", + ) + erev = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="erev", + ) + return self.make_exp2_psd( + post_sec, + terminal, + weight=weight, + loc=loc, + tau1=tau1, + tau2=tau2, + erev=erev, + ) + else: + raise TypeError( + "Cannot make simple PSD for %s => %s" + % (terminal.cell.type, self.type) + ) + + elif psd_type == "multisite": + if terminal.cell.type == "sgc": + # Max conductances for the glu mechanisms are calibrated by + # running `synapses/tests/test_psd.py`. The test should fail + # if these values are incorrect + self.AMPAR_gmax = ( + data.get( + "sgc_synapse", + species=self.species, + post_type=self.type, + field="AMPAR_gmax", + ) + * 1e3 + ) + self.NMDAR_gmax = ( + data.get( + "sgc_synapse", + species=self.species, + post_type=self.type, + field="NMDAR_gmax", + ) + * 1e3 + ) + self.Pr = data.get( + "sgc_synapse", species=self.species, post_type=self.type, field="Pr" + ) + self.NMDAR_vshift = data.get( + "sgc_synapse", + species=self.species, + post_type=self.type, + field="NMDAR_vshift", + ) + # adjust gmax to correct for initial Pr + self.AMPAR_gmax = self.AMPAR_gmax / self.Pr + self.NMDAR_gmax = self.NMDAR_gmax / self.Pr + + # original values (now in synapses.py): + # self.AMPA_gmax = 3.314707700918133*1e3 # factor of 1e3 scales to pS (.mod mechanisms) from nS. + # self.NMDA_gmax = 0.4531929783503451*1e3 + if "AMPAScale" in kwds: # normally, this should not be done! + self.AMPAR_gmax = ( + self.AMPAR_gmax * kwds["AMPAScale"] + ) # allow scaling of AMPA conductances + if "NMDAScale" in kwds: + self.NMDAR_gmax = self.NMDAR_gmax * kwds["NMDAScale"] # and NMDA... + return self.make_glu_psd( + post_sec, + terminal, + self.AMPAR_gmax, + self.NMDAR_gmax, + loc=loc, + nmda_vshift=self.NMDAR_vshift, + ) + elif terminal.cell.type == "dstellate": + return self.make_gly_psd(post_sec, terminal, psdtype="glyslow", loc=loc) + elif terminal.cell.type == "tuberculoventral": + return self.make_gly_psd(post_sec, terminal, psdtype="glyslow", loc=loc) + else: + raise TypeError( + "Cannot make PSD for %s => %s" % (terminal.cell.type, self.type) + ) + else: + raise ValueError("Unsupported psd type %s" % psd_type) + + def make_terminal(self, post_cell, term_type, **kwds): + if term_type == "simple": + return synapses.SimpleTerminal(self.soma, post_cell, **kwds) + + elif term_type == "multisite": + if post_cell.type in ["mso"]: + nzones = data.get( + "bushy_synapse", + species=self.species, + post_type=post_cell.type, + field="n_rsites", + ) + delay = data.get( + "bushy_synapse", + species=self.species, + post_type=post_cell.type, + field="delay", + ) + else: + raise NotImplementedError( + "No knowledge as to how to connect Bushy cell to cell type %s" + % type(post_cell) + ) + pre_sec = self.soma + return synapses.StochasticTerminal( + pre_sec, + post_cell, + nzones=nzones, + spike_source=self.spike_source, + delay=delay, + **kwds, + ) + else: + raise ValueError("Unsupported terminal type %s" % term_type) + + +class BushyRothman(Bushy): + """ + VCN bushy cell models. + Rothman and Manis, 2003abc (Type II, Type II-I) + Xie and Manis, 2013 + """ + + def __init__( + self, + morphology=None, + decorator=None, + nach=None, + ttx=False, + species="guineapig", + modelType=None, + modelName=None, + debug=False, + temperature=None, + ): + """ + Create a bushy cell, using the default parameters for guinea pig from + R&M2003, as a type II cell. + Additional modifications to the cell can be made by calling methods below. + + Parameters + ---------- + morphology : string (default: None) + Name of a .hoc file representing the morphology. This file is used to constructe + an electrotonic (cable) model. + If None (default), then a "point" (really, single cylinder) model is made, exactly according to RM03. + + decorator : Python function (default: None) + decorator is a function that "decorates" the morphology with ion channels according + to a set of rules. + If None, a default set of channels is inserted into the first soma section, and the + rest of the structure is "bare". + + nach : string (default: None) + nach selects the type of sodium channel that will be used in the model. A channel mechanism + by that name must exist. The default channel is set to 'nacn' (R&M03) + + temperature : float (default: 22) + temperature to run the cell at. + + ttx : Boolean (default: False) + If ttx is True, then the sodium channel conductance is set to 0 everywhere in the cell. + This flag duplicates the effects of tetrodotoxin in the model. Currently, the flag is not implemented. + + species: string (default 'guineapig') + species defines the pattern of ion channel densities that will be inserted, according to + prior measurements in various species. Note that + if a decorator function is specified, this argument is ignored as the decorator will + specify the channel density. + + modelName: string (default: None) + modelName specifies the source conductance pattern (RM03, XM13, etc). + modelName is passed to the decorator, or to species_scaling to adjust point (single cylinder) models. + + modelType: string (default: None) + modelType specifies the subtype of the cell model that will be used (e.g., "II", "II-I", etc). + modelType is passed to the decorator, or to species_scaling to adjust point (single cylinder) models. + + debug: boolean (default: False) + When True, there will be multiple printouts of progress and parameters. + + Returns + ------- + Nothing + + """ + super(BushyRothman, self).__init__() + self.i_test_range = { + "pulse": (-1, 1, 0.05) + } # note that this might get reset with decorator according to channels + # Changing the default values will cause the unit tests to fail! + if modelType == None: + modelType = "II" + if species == "guineapig": + modelName = "RM03" + temp = 22.0 + if nach == None: + nach = "na" + if species == "mouse": + temp = 34.0 + if modelName is None: + modelName = "XM13" + if nach is None: + nach = "na" + self.debug = debug + self.status = { + "species": species, + "cellClass": self.type, + "modelType": modelType, + "modelName": modelName, + "soma": True, + "axon": False, + "dendrites": False, + "pumps": False, + "hillock": False, + "initialsegment": False, + "myelinatedaxon": False, + "unmyelinatedaxon": False, + "na": nach, + "ttx": ttx, + "name": self.type, + "morphology": morphology, + "decorator": decorator, + "temperature": temperature, + } + + self.spike_threshold = -40 + self.vrange = [-70.0, -55.0] # set a default vrange for searching for rmp + if self.debug: + print( + "model type, model name, species: ", modelType, modelName, species, nach + ) + + self.c_m = 0.9e-6 # default in units of F/cm^2 + + self._valid_temperatures = (temp,) + if self.status["temperature"] == None: + self.status["temperature"] = temp + + if morphology is None: + """ + instantiate a basic soma-only ("point") model + """ + if self.debug: + print("<< Bushy model: Creating point cell >>") + soma = h.Section( + name="Bushy_Soma_%x" % id(self) + ) # one compartment of about 29000 um2 + soma.nseg = 1 + self.add_section(soma, "soma") + else: + """ + instantiate a structured model with the morphology as specified by + the morphology file + """ + if self.debug: + print( + "<< Bushy model: Creating cell with morphology from %s >>" + % morphology + ) + self.set_morphology(morphology_file=morphology) + + # decorate the morphology with ion channels + if decorator is None: # basic model, only on the soma, does not use tables. + self.mechanisms = ["klt", "kht", "ihvcn", "leak", nach] + for mech in self.mechanisms: + self.soma.insert(mech) + self.soma.ena = self.e_na + self.soma.ek = self.e_k + self.soma().ihvcn.eh = self.e_h + self.soma().leak.erev = self.e_leak + self.c_m = 0.9 + self.species_scaling( + silent=True, species=species, modelType=modelType + ) # set the default type II cell parameters + else: # decorate according to a defined set of rules on all cell compartments, with tables. + self.decorate() + self.save_all_mechs() # save all mechanisms inserted, location and gbar values... + self.get_mechs(self.soma) + if debug: + print(" << Created cell >>") + + def get_cellpars(self, dataset, species="guineapig", modelType="II"): + """ + Read data for ion channels and cell parameters from the tables + """ + # cell_type = self.map_celltype(cell_type) + # print('getcellpars: dataset, species, mmodeltype: ', dataset, species, modelType) + # print('model name: ', self.status['modelName']) + cellcap = data.get( + dataset, species=species, model_type=modelType, field="soma_Cap" + ) + chtype = data.get( + dataset, species=species, model_type=modelType, field="na_type" + ) + pars = Params(cap=cellcap, natype=chtype) + # print('pars cell/chtype: ') + if self.debug: + pars.show() + if self.status["modelName"] == "RM03": + for g in [ + "%s_gbar" % pars.natype, + "kht_gbar", + "klt_gbar", + "ih_gbar", + "leak_gbar", + ]: + pars.additem( + g, data.get(dataset, species=species, model_type=modelType, field=g) + ) + if self.status["modelName"] == "XM13": + for g in [ + "%s_gbar" % pars.natype, + "kht_gbar", + "klt_gbar", + "ihvcn_gbar", + "leak_gbar", + ]: + pars.additem( + g, data.get(dataset, species=species, model_type=modelType, field=g) + ) + if self.status["modelName"] == "mGBC": + for g in [ + "%s_gbar" % pars.natype, + "kht_gbar", + "klt_gbar", + "ihvcn_gbar", + "leak_gbar", + ]: + pars.additem( + g, data.get(dataset, species=species, model_type=modelType, field=g) + ) + + return pars + + def species_scaling(self, species="guineapig", modelType="II", silent=True): + """ + This is called for POINT CELLS ONLY + Adjust all of the conductances and the cell size according to the species requested. + This scaling should be used ONLY for point models, as no other compartments + are scaled. + + This scaling routine also sets the temperature for the model to a default value. Some models + can be run at multiple temperatures, and so a default from one of the temperatures is used. + The calling cell.set_temperature(newtemp) will change the conductances and reinitialize + the cell to the new temperature settings. + + Parameters + ---------- + species : string (default: 'guineapig') + name of the species to use for scaling the conductances in the base point model + Must be one of mouse, cat, guineapig + + modelType: string (default: 'II') + definition of model type from RM03 models, type II or type II-I + + silent : boolean (default: True) + run silently (True) or verbosely (False) + + """ + # print '\nSpecies scaling: %s %s' % (species, type) + knownspecies = ["mouse", "guineapig", "cat"] + + soma = self.soma + # cellType = self.map_celltype(modelType) + + if species == "mouse": + # use conductance levels determined from Cao et al., J. Neurophys., 2007. as + # model description in Xie and Manis 2013. Note that + # conductances were not scaled for temperature (rates were) + # so here we reset the default Q10's for conductance (g) to 1.0 + if modelType not in ["II", "II-I"]: + raise ValueError( + "\nModel type %s is not implemented for mouse bushy cells" + % modelType + ) + if self.debug: + print( + " Setting conductances for mouse bushy cell (%s), Xie and Manis, 2013" + % modelType + ) + if modelname == "XM13": + dataset = "XM13_channels" + elif modelname == "XM13nacncoop": + dataset = "XM13_channels_nacncoop" + elif modelname.startswith("mGBC"): + dataset = "mGBC_channels" + else: + raise ValueError( + f"ModelName {modelname:s} not recognized for mouse bushy cells" + ) + self.vrange = [-68.0, -55.0] # set a default vrange for searching for rmp + self.i_test_range = {"pulse": (-1.0, 1.0, 0.05)} + self._valid_temperatures = (34.0,) + if self.status["temperature"] is None: + self.status["temperature"] = 34.0 + + pars = self.get_cellpars(dataset, species=species, modelType=modelType) + self.set_soma_size_from_Cm(pars.cap) + self.status["na"] = pars.natype + self.adjust_na_chans(soma, sf=1.0) + soma().kht.gbar = nstomho(pars.kht_gbar, self.somaarea) + soma().klt.gbar = nstomho(pars.klt_gbar, self.somaarea) + soma().ihvcn.gbar = nstomho(pars.ihvcn_gbar, self.somaarea) + soma().leak.gbar = nstomho(pars.leak_gbar, self.somaarea) + self.axonsf = 0.57 + + elif species == "guineapig": + if self.debug: + print( + " Setting conductances for guinea pig %s bushy cell, Rothman and Manis, 2003" + % modelType + ) + self._valid_temperatures = (22.0, 38.0) + if self.status["temperature"] is None: + self.status["temperature"] = 22.0 + self.i_test_range = {"pulse": (-0.4, 0.4, 0.02)} + sf = 1.0 + if ( + self.status["temperature"] == 38.0 + ): # adjust for 2003 model conductance levels at 38 + sf = 2 # Q10 of 2, 22->38C. (p3106, R&M2003c) + # note that kinetics are scaled in the mod file. + dataset = "RM03_channels" + pars = self.get_cellpars(dataset, species=species, modelType=modelType) + self.set_soma_size_from_Cm(pars.cap) + self.status["na"] = pars.natype + self.adjust_na_chans(soma, sf=sf) + soma().kht.gbar = nstomho(pars.kht_gbar, self.somaarea) + soma().klt.gbar = nstomho(pars.klt_gbar, self.somaarea) + soma().ihvcn.gbar = nstomho(pars.ih_gbar, self.somaarea) + soma().leak.gbar = nstomho(pars.leak_gbar, self.somaarea) + + self.axonsf = 0.57 + + else: + errmsg = ( + 'Species "%s" or model type "%s" is not recognized for Bushy cells.' + % (species, modelType) + ) + errmsg += "\n Valid species are: \n" + for s in knownspecies: + errmsg += " %s\n" % s + errmsg += "-" * 40 + raise ValueError(errmsg) + + self.status["species"] = species + self.status["modelType"] = modelType + self.check_temperature() + # self.cell_initialize(vrange=self.vrange) # no need to do this just yet. + if not silent: + print(" set cell as: ", species) + print(" with Vm rest = %6.3f" % self.vm0) + + # def channel_manager(self, modelType='RM03', cell_type='bushy-II'): + # """ + # This routine defines channel density maps and distance map patterns + # for each type of compartment in the cell. The maps + # are used by the ChannelDecorator class (specifically, its private + # \_biophys function) to decorate the cell membrane. + # These settings are only used if the decorator is called; otherwise + # for point cells, the species_scaling routine defines the channel + # densities. + # + # Parameters + # ---------- + # modelType : string (default: 'RM03') + # A string that defines the type of the model. Currently, 3 types are implemented: + # RM03: Rothman and Manis, 2003 somatic densities for guinea pig + # XM13: Xie and Manis, 2013, somatic densities for mouse + # mGBC: experimental mouse globular bushy cell with dendrites, axon, hillock and initial segment, for + # use with fully reconstructed neurons. + # + # Returns + # ------- + # Nothing + # + # Notes + # ----- + # This routine defines the following variables for the class: + # + # * conductances (gBar) + # * a channelMap (dictonary of channel densities in defined anatomical compartments) + # * a current injection range for IV's (used for testing) + # * a distance map, which defines how each conductance in a selected compartment + # changes with distance from the soma. The current implementation includes both + # linear and exponential gradients, + # the minimum conductance at the end of the gradient, and the space constant or + # slope for the gradient. + # + # """ + # + # + # dataset = '%s_channels' % modelType + # decorationmap = dataset + '_compartments' + # # print('dataset: {0:s} decorationmap: {1:s}'.format(dataset, decorationmap)) + # cellpars = self.get_cellpars(dataset, species=self.status['species'], celltype=cell_type) + # refarea = 1e-3*cellpars.cap / self.c_m + # + # table = data.get_table_info(dataset) + # chscale = data.get_table_info(decorationmap) + # pars = {} + # # retrive the conductances from the data set + # for g in table['field']: + # x = data.get(dataset, species=self.status['species'], cell_type=cell_type, + # field=g) + # if not isinstance(x, float): + # continue + # if '_gbar' in g: + # pars[g] = x/refarea + # else: + # pars[g] = x + # + # self.channelMap = OrderedDict() + # for c in chscale['compartment']: + # self.channelMap[c] = {} + # for g in pars.keys(): + # if g not in chscale['parameter']: + # # print ('Parameter %s not found in chscale parameters!' % g) + # continue + # scale = data.get(decorationmap, species=self.status['species'], cell_type=cell_type, + # compartment=c, parameter=g) + # if '_gbar' in g: + # self.channelMap[c][g] = pars[g]*scale + # else: + # self.channelMap[c][g] = pars[g] + # + # self.irange = np.linspace(-0.6, 1, 9) + + def get_distancemap(self): + return { + "dend": { + "klt": {"gradient": "exp", "gminf": 0.0, "lambda": 50.0}, + "kht": {"gradient": "exp", "gminf": 0.0, "lambda": 50.0}, + "nav11": {"gradient": "exp", "gminf": 0.0, "lambda": 50.0}, + }, # linear with distance, gminf (factor) is multiplied by gbar + "dendrite": { + "klt": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "kht": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "nav11": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + }, # linear with distance, gminf (factor) is multiplied by gbar + "apic": { + "klt": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "kht": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "nav11": {"gradient": "exp", "gminf": 0.0, "lambda": 200.0}, + }, # gradients are: flat, linear, exponential + } + # self.check_temperature() + # return + # + + # + # + # if modelType == 'RM03': + # # + # # Create a model based on the Rothman and Manis 2003 conductance set from guinea pig + # # + # self.c_m = 0.9E-6 # default in units of F/cm^2 + # self._valid_temperatures = (22., 38.) + # sf = 1.0 + # if self.status['temperature'] == None: + # self.status['temperature'] = 22. + # if self.status['temperature'] == 38: + # sf = 3.03 + # dataset = 'RM03_channels' + # pars = self.get_cellpars(dataset, species=self.status['species'], celltype='bushy-II') + # refarea = 1e-3*pars.cap / self.c_m + # self.gBar = Params(nabar=sf*pars.soma_na_gbar/refarea, # 1000.0E-9/refarea, + # khtbar=sf*pars.soma_kht_gbar/refarea, + # kltbar=sf*pars.soma_klt_gbar/refarea, + # ihbar=sf*pars.soma_ih_gbar/refarea, + # leakbar=sf*pars.soma_leak_gbar/refarea, + # ) + # print 'RM03 gbar:\n', self.gBar.show() + # + # self.channelMap = { + # 'axon': {'nacn': self.gBar.nabar, 'klt': self.gBar.kltbar, 'kht': self.gBar.khtbar, 'ihvcn': 0., + # 'leak': self.gBar.leakbar / 2.}, + # 'hillock': {'nacn': self.gBar.nabar, 'klt': self.gBar.kltbar, 'kht': self.gBar.khtbar, 'ihvcn': 0., + # 'leak': self.gBar.leakbar, }, + # 'initseg': {'nacn': self.gBar.nabar, 'klt': self.gBar.kltbar, 'kht': self.gBar.khtbar, + # 'ihvcn': self.gBar.ihbar / 2., 'leak': self.gBar.leakbar, }, + # 'soma': {'nacn': self.gBar.nabar, 'klt': self.gBar.kltbar, 'kht': self.gBar.khtbar, + # 'ihvcn': self.gBar.ihbar, 'leak': self.gBar.leakbar, }, + # 'dend': {'nacn': self.gBar.nabar, 'klt': self.gBar.kltbar * 0.5, 'kht': self.gBar.khtbar * 0.5, + # 'ihvcn': self.gBar.ihbar / 3., 'leak': self.gBar.leakbar * 0.5, }, + # 'apic': {'nacn': self.gBar.nabar, 'klt': self.gBar.kltbar * 0.2, 'kht': self.gBar.khtbar * 0.2, + # 'ihvcn': self.gBar.ihbar / 4., 'leak': self.gBar.leakbar * 0.2, }, + # } + # # self.irange = np.linspace(-1., 1., 21) + # self.distMap = {'dend': {'klt': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # 'kht': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # 'nacn': {'gradient': 'exp', 'gminf': 0., 'lambda': 100.}}, # linear with distance, gminf (factor) is multiplied by gbar + # 'apic': {'klt': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # 'kht': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # 'nacn': {'gradient': 'exp', 'gminf': 0., 'lambda': 100.}}, # gradients are: flat, linear, exponential + # } + # + # elif modelType == 'XM13': + # # + # # Create a model for a mouse bushy cell from Xie and Manis, 2013 + # # based on Cao and Oertel mouse conductance values + # # and Rothman and Manis kinetics. + # self.c_m = 0.9E-6 # default in units of F/cm^2 + # self._valid_temperatures = (34., ) + # if self.status['temperature'] == None: + # self.status['temperature'] = 34. + # dataset = 'XM13_channels' + # pars = self.get_cellpars(dataset, species=self.status['species'], celltype='bushy-II') + # refarea = 1e-3*pars.cap / self.c_m + # # self.gBar = Params(nabar=pars.soma_nav11_gbar/refarea, # 1000.0E-9/refarea, + # # khtbar=pars.soma_kht_gbar/refarea, + # # kltbar=pars.soma_klt_gbar/refarea, + # # ihbar=pars.soma_ihvcn_gbar/refarea, + # # leakbar=pars.soma_leak_gbar/refarea, + # # ) + # # print 'XM13 gbar:\n', self.gBar.show() + # # # create channel map: + # decorationmap = 'XM13_channels_bycompartment' + # + # table = data.get_table_info(dataset) + # pars = {} + # for g in table['field']: + # x = data.get(dataset, species=self.status['species'], cell_type='bushy-II', + # field=g) + # if not isinstance(x, float): + # continue + # pars[g] = (1./refarea)*data.get(dataset, species=self.status['species'], cell_type='bushy-II', + # field=g) + # chscale = data.get_table_info(decorationmap) + # self.channelMap1 = OrderedDict() + # # print chscale['parameter'] + # for c in chscale['compartment']: + # self.channelMap1[c] = {} + # for g in pars.keys(): + # # print g + # if g[5:] not in chscale['parameter']: + # continue + # scale = data.get(decorationmap, species=self.status['species'], cell_type='bushy-II', + # compartment=c, parameter=g[5:]) + # self.channelMap1[c][g] = pars[g]*scale + # + # # + # # self.channelMap = { + # # 'unmyelinatedaxon': {'nav11': self.gBar.nabar*1, 'klt': self.gBar.kltbar * 1.0, 'kht': self.gBar.khtbar, 'ihvcn': 0., + # # 'leak': self.gBar.leakbar * 0.25}, + # # 'hillock': {'nav11': self.gBar.nabar*2, 'klt': self.gBar.kltbar, 'kht': self.gBar.khtbar*2.0, 'ihvcn': 0., + # # 'leak': self.gBar.leakbar, }, + # # 'initialsegment': {'nav11': self.gBar.nabar*3.0, 'klt': self.gBar.kltbar*1, 'kht': self.gBar.khtbar*2, + # # 'ihvcn': self.gBar.ihbar * 0.5, 'leak': self.gBar.leakbar, }, + # # 'soma': {'nav11': self.gBar.nabar*1.0, 'klt': self.gBar.kltbar, 'kht': self.gBar.khtbar, + # # 'ihvcn': self.gBar.ihbar, 'leak': self.gBar.leakbar, }, + # # 'dend': {'nav11': self.gBar.nabar * 0.25, 'klt': self.gBar.kltbar *0.5, 'kht': self.gBar.khtbar *0.5, + # # 'ihvcn': self.gBar.ihbar *0.5, 'leak': self.gBar.leakbar * 0.5, }, + # # 'primarydendrite': {'nav11': self.gBar.nabar * 0.25, 'klt': self.gBar.kltbar *0.5, 'kht': self.gBar.khtbar *0.5, + # # 'ihvcn': self.gBar.ihbar *0.5, 'leak': self.gBar.leakbar * 0.5, }, + # # 'apic': {'nav11': self.gBar.nabar * 0.25, 'klt': self.gBar.kltbar * 0.25, 'kht': self.gBar.khtbar * 0.25, + # # 'ihvcn': self.gBar.ihbar *0.25, 'leak': self.gBar.leakbar * 0.25, }, + # # } + # import pprint + # # print 'original map:\n' + # # for k in self.channelMap.keys(): + # # print('Region: %s' % k) + # # if k in self.channelMap1.keys(): + # # print 'overlapping Region: %s' % k + # # for ch in self.channelMap[k].keys(): + # # # print ch + # # # print self.channelMap1[k].keys() + # # # print self.channelMap[k].keys() + # # if 'soma_' + ch + '_gbar' in self.channelMap1[k].keys(): + # # cx = u'soma_' + ch + u'_gbar' + # # # print ch, cx + # # print( ' {0:>4s} = {1:e} {2:e} {3:<5s}'.format(ch, self.channelMap[k][ch], self.channelMap1[k][cx], + # # str(np.isclose(self.channelMap[k][ch], self.channelMap1[k][cx])))) + # + # # print 'original: ', self.channelMap['soma'] + # self.channelMap = self.channelMap1 # use the data table + # # except need to remove soma_ from keys + # for k in self.channelMap.keys(): + # for n in self.channelMap[k].keys(): + # new_key = n.replace('_gbar', '') + # # new_key = n + # new_key = new_key.replace('soma_', '') + # # strip 'soma_' from key + # #print 'newkey: ', new_key, n + # self.channelMap[k][new_key] = self.channelMap[k].pop(n) + # + # print 'final map: ', self.channelMap['soma'] + # + # self.irange = np.linspace(-0.6, 1, 9) + # self.distMap = {'dend': {'klt': {'gradient': 'exp', 'gminf': 0., 'lambda': 50.}, + # 'kht': {'gradient': 'exp', 'gminf': 0., 'lambda': 50.}, + # 'nav11': {'gradient': 'exp', 'gminf': 0., 'lambda': 50.}}, # linear with distance, gminf (factor) is multiplied by gbar + # 'dendrite': {'klt': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # 'kht': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # 'nav11': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}}, # linear with distance, gminf (factor) is multiplied by gbar + # 'apic': {'klt': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # 'kht': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # 'nav11': {'gradient': 'exp', 'gminf': 0., 'lambda': 200.}}, # gradients are: flat, linear, exponential + # } + # + # elif modelType == 'mGBC': + # # bushy from Xie and Manis, 2013, based on Cao and Oertel mouse conductances, + # # BUT modified ad hoc for SBEM reconstructions. + # dataset = 'mGBC_channels' + # + # self._valid_temperatures = (34.,) + # if self.status['temperature'] == None: + # self.status['temperature'] = 34. + # pars = self.get_cellpars(dataset, species=self.status['species'], celltype='bushy-II') + # refarea = 1e-3*pars.cap / self.c_m + # print (pars.cap, pars.soma_kht_gbar, refarea) # refarea should be about 30e-6 + # + # self.gBar = Params(nabar=pars.soma_na_gbar/refarea, # 1000.0E-9/refarea, + # khtbar=pars.soma_kht_gbar/refarea, + # kltbar=pars.soma_klt_gbar/refarea, + # ihbar=pars.soma_ih_gbar/refarea, + # leakbar=pars.soma_leak_gbar/refarea, + # ) + # print 'mGBC gbar:\n', self.gBar.show() + # sodiumch = 'jsrna' + # self.channelMap = { + # 'axon': {sodiumch: self.gBar.nabar*1., 'klt': self.gBar.kltbar * 1.0, 'kht': self.gBar.khtbar, 'ihvcn': 0., + # 'leak': self.gBar.leakbar * 0.25}, + # 'unmyelinatedaxon': {sodiumch: self.gBar.nabar*3.0, 'klt': self.gBar.kltbar * 2.0, + # 'kht': self.gBar.khtbar*3.0, 'ihvcn': 0., + # 'leak': self.gBar.leakbar * 0.25}, + # 'myelinatedaxon': {sodiumch: self.gBar.nabar*0, 'klt': self.gBar.kltbar * 1e-2, + # 'kht': self.gBar.khtbar*1e-2, 'ihvcn': 0., + # 'leak': self.gBar.leakbar * 0.25*1e-3}, + # 'hillock': {sodiumch: self.gBar.nabar*4.0, 'klt': self.gBar.kltbar*1.0, 'kht': self.gBar.khtbar*3.0, + # 'ihvcn': 0., 'leak': self.gBar.leakbar, }, + # 'initseg': {sodiumch: self.gBar.nabar*3.0, 'klt': self.gBar.kltbar*2, 'kht': self.gBar.khtbar*2, + # 'ihvcn': self.gBar.ihbar * 0.5, 'leak': self.gBar.leakbar, }, + # 'soma': {sodiumch: self.gBar.nabar*0.65, 'klt': self.gBar.kltbar, 'kht': self.gBar.khtbar*1.5, + # 'ihvcn': self.gBar.ihbar, 'leak': self.gBar.leakbar, }, + # 'dend': {sodiumch: self.gBar.nabar * 0.2, 'klt': self.gBar.kltbar *1, 'kht': self.gBar.khtbar *1, + # 'ihvcn': self.gBar.ihbar *0.5, 'leak': self.gBar.leakbar * 0.5, }, + # 'dendrite': {sodiumch: self.gBar.nabar * 0.2, 'klt': self.gBar.kltbar *1, 'kht': self.gBar.khtbar *1, + # 'ihvcn': self.gBar.ihbar *0.5, 'leak': self.gBar.leakbar * 0.5, }, + # 'apic': {sodiumch: self.gBar.nabar * 0.25, 'klt': self.gBar.kltbar * 0.25, 'kht': self.gBar.khtbar * 0.25, + # 'ihvcn': self.gBar.ihbar *0.25, 'leak': self.gBar.leakbar * 0.25, }, + # } + # self.irange = np.arange(-1.5, 2.1, 0.25 ) + # self.distMap = {'dend': {'klt': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # 'kht': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # sodiumch: {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}}, # linear with distance, gminf (factor) is multiplied by gbar + # 'dendrite': {'klt': {'gradient': 'linear', 'gminf': 0., 'lambda': 20.}, + # 'kht': {'gradient': 'linear', 'gminf': 0., 'lambda': 20.}, + # sodiumch: {'gradient': 'linear', 'gminf': 0., 'lambda': 20.}}, # linear with distance, gminf (factor) is multiplied by gbar + # 'apic': {'klt': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # 'kht': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # sodiumch: {'gradient': 'exp', 'gminf': 0., 'lambda': 200.}}, # gradients are: flat, linear, exponential + # } + # else: + # raise ValueError('model type %s is not implemented' % modelType) + # self.check_temperature() + + def adjust_na_chans(self, soma, sf=1.0, gbar=1000.0): + """ + adjust the sodium channel conductance + + Parameters + ---------- + soma : neuron section object + A soma object whose sodium channel complement will have its + conductances adjusted depending on the channel type + + gbar : float (default: 1000.) + The maximal conductance for the sodium channel + + Returns + ------- + Nothing : + + """ + + if self.status["ttx"]: + gnabar = 0.0 + else: + gnabar = nstomho(gbar, self.somaarea) * sf + nach = self.status["na"] + if nach == "jsrna": + soma().jsrna.gbar = gnabar + soma.ena = self.e_na + if self.debug: + print("jsrna gbar: ", soma().jsrna.gbar) + elif nach == "nav11": + soma().nav11.gbar = gnabar + soma.ena = 50 # self.e_na + # print('gnabar: ', soma().nav11.gbar, ' vs: 0.0192307692308') + soma().nav11.vsna = 4.3 + if self.debug: + print("bushy using inva11") + if nach == "nacncoop": + soma().nacncoop.gbar = gnabar + soma().nacncoop.KJ = 2000.0 + soma().nacncoop.p = 0.25 + somae().nacncoop.vsna = 0.0 + soma.ena = self.e_na + if debug: + print("nacncoop gbar: ", soma().nacncoop.gbar) + elif nach in ["na", "nacn"]: + soma().na.gbar = gnabar + soma.ena = self.e_na + # soma().na.vsna = 0. + if self.debug: + print("na gbar: ", soma().na.gbar) + else: + raise ValueError( + "Sodium channel %s is not recognized for Bushy cells", nach + ) + + def add_axon(self): + """ + Add a default axon from the generic cell class to the bushy cell (see cell class). + """ + Cell.add_axon(self, self.c_m, self.R_a, self.axonsf) + + def add_pumps(self): + """ + Insert mechanisms for potassium ion management, sodium ion management, and a + sodium-potassium pump at the soma. + """ + soma = self.soma + soma.insert("k_conc") + + ki0_k_ion = 140 + soma().ki = ki0_k_ion + soma().ki0_k_conc = ki0_k_ion + soma().beta_k_conc = 0.075 + + soma.insert("na_conc") + nai0_na_ion = 5 + soma().nai = nai0_na_ion + soma().nai0_na_conc = nai0_na_ion + soma().beta_na_conc = 0.075 + + soma.insert("nakpump") + soma().nakpump.inakmax = 8 + soma().nao = 145 + soma().ko = 5 + soma().nakpump.Nai_inf = 5 + soma().nakpump.Ki_inf = 140 + soma().nakpump.ATPi = 5 + self.status["pumps"] = True + + def add_dendrites(self): + """ + Add a simple dendrite to the bushy cell. + """ + if self.debug: + print("Adding dendrite to Bushy model") + section = h.Section + primarydendrite = section(cell=self.soma) + primarydendrite.connect(self.soma) + primarydendrite.nseg = 10 + primarydendrite.L = 100.0 + primarydendrite.diam = 2.5 + primarydendrite.insert("klt") + primarydendrite.insert("ihvcn") + primarydendrite().klt.gbar = self.soma().klt.gbar / 2.0 + primarydendrite().ihvcn.gbar = self.soma().ihvcn.gbar / 2.0 + + primarydendrite.cm = self.c_m + primarydendrite.Ra = self.R_a + nsecd = range(0, 5) + secondarydendrite = [] + for ibd in nsecd: + secondarydendrite.append(section(cell=self.soma)) + for ibd in nsecd: + secondarydendrite[ibd].connect(primarydendrite) + secondarydendrite[ibd].diam = 1.0 + secondarydendrite[ibd].L = 15.0 + secondarydendrite[ibd].cm = self.c_m + secondarydendrite[ibd].Ra = self.R_a + self.primarydendrite = primarydendrite + self.secondarydendrite = secondarydendrite + self.status["dendrite"] = True + if self.debug: + print("Bushy: added dendrites") + h.topology() + self.add_section(maindend, "primarydendrite") + self.add_section(secdend, "secondarydendrite") diff --git a/cnmodel/cells/cartwheel.py b/cnmodel/cells/cartwheel.py new file mode 100644 index 0000000..3ad629f --- /dev/null +++ b/cnmodel/cells/cartwheel.py @@ -0,0 +1,447 @@ +from __future__ import print_function + +import numpy as np +from neuron import h + +from .cell import Cell +from .. import data +from .. import synapses +from ..util import Params +from ..util import nstomho + +__all__ = ["Cartwheel", "CartwheelDefault"] + + +class Cartwheel(Cell): + + type = "cartwheel" + + @classmethod + def create(cls, model="CW", **kwds): + if model == "CW": + return CartwheelDefault(**kwds) + else: + raise ValueError("Carthweel model is unknown", model) + + def make_psd(self, terminal, psd_type, **kwds): + """ + Connect a presynaptic terminal to one post section at the specified location, with the fraction + of the "standard" conductance determined by gbar. + The default condition is to try to pass the default unit test (loc=0.5) + + Parameters + ---------- + terminal : Presynaptic terminal (NEURON object) + + psd_type : either simple or multisite PSD for bushy cell + + kwds: dict of options. Two are currently handled: + postsize : expect a list consisting of [sectionno, location (float)] + AMPAScale : float to scale the ampa currents + + """ + self.pre_sec = terminal.section + pre_cell = terminal.cell + post_sec = self.soma + + if psd_type == "simple": + if terminal.cell.type in [ + "sgc", + "dstellate", + "tuberculoventral", + "cartwheel", + ]: + weight = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="weight", + ) + tau1 = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="tau1", + ) + tau2 = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="tau2", + ) + erev = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="erev", + ) + return self.make_exp2_psd( + post_sec, + terminal, + weight=weight, + loc=loc, + tau1=tau1, + tau2=tau2, + erev=erev, + ) + else: + raise TypeError( + "Cannot make simple PSD for %s => %s" + % (terminal.cell.type, self.type) + ) + + else: + raise ValueError( + "Unsupported psd type %s for cartwheel cell (inputs not implemented yet)" + % psd_type + ) + + def make_terminal(self, post_cell, term_type, **kwds): + if term_type == "simple": + return synapses.SimpleTerminal(self.soma, post_cell, **kwds) + elif term_type == "multisite": + if post_cell.type in ["tuberculoventral", "pyramidal"]: + nzones = data.get( + "cartwheel_synapse", + species=self.species, + post_type=post_cell.type, + field="n_rsites", + ) + delay = data.get( + "cartwheel_synapse", + species=self.species, + post_type=post_cell.type, + field="delay", + ) + else: + raise NotImplementedError( + "No knowledge as to how to connect cartwheel cell to cell type %s" + % type(post_cell) + ) + pre_sec = self.soma + return synapses.StochasticTerminal( + pre_sec, + post_cell, + nzones=nzones, + spike_source=self.spike_source, + delay=delay, + **kwds + ) + else: + raise ValueError("Unsupported terminal type %s" % term_type) + + +class CartwheelDefault(Cartwheel, Cell): + """ + DCN cartwheel cell model. + + """ + + def __init__( + self, + morphology=None, + decorator=None, + ttx=False, + nach=None, + species="mouse", + modelType=None, + debug=False, + ): + """ + Create cartwheel cell model, based on a Purkinje cell model from Raman. + There are no variations available for this model. + + Parameters + ---------- + morphology : string (default: None) + Name of a .hoc file representing the morphology. This file is used to constructe + an electrotonic (cable) model. + If None (default), then a "point" (really, single cylinder) model is made, exactly according to RM03. + + decorator : Python function (default: None) + decorator is a function that "decorates" the morphology with ion channels according + to a set of rules. + If None, a default set of channels is inserted into the first soma section, and the + rest of the structure is "bare". + + nach : string (default: None) + nach selects the type of sodium channel that will be used in the model. A channel mechanism + by that name must exist. The default is naRsg, a resurgent sodium channel model. + + ttx : Boolean (default: False) + If ttx is True, then the sodium channel conductance is set to 0 everywhere in the cell. + This flag duplicates the effects of tetrodotoxin in the model. Currently, the flag is not implemented. + + species: string (default 'rat') + species defines the pattern of ion channel densities that will be inserted, according to + prior measurements in various species. Note that + if a decorator function is specified, this argument is ignored as the decorator will + specify the channel density. + + modelType: string (default: None) + modelType specifies the subtype of the cell model that will be used. + modelType is passed to the decorator, or to species_scaling to adjust point (single cylinder) models. + Only type "I" is recognized for the cartwheel cell model. + + debug: boolean (default: False) + When True, there will be multiple printouts of progress and parameters. + + Returns + ------- + Nothing + """ + super(CartwheelDefault, self).__init__() + if modelType == None: + modelType = "I" + if nach == None: + nach = "naRsg" + self.status = { + "soma": True, + "axon": False, + "dendrites": False, + "pumps": False, + "na": nach, + "species": species, + "modelType": modelType, + "ttx": ttx, + "name": "Cartwheel", + "morphology": morphology, + "decorator": decorator, + "temperature": None, + } + + self.i_test_range = {"pulse": (-0.2, 0.2, 0.02)} + # self.spike_threshold = 0 + self.vrange = [-75.0, -52.0] # set a default vrange for searching for rmp + + if morphology is None: + """ + instantiate a basic soma-only ("point") model + """ + soma = h.Section( + name="Cartwheel_Soma_%x" % id(self) + ) # one compartment of about 29000 um2 + # cm = 1 + soma.nseg = 1 + self.add_section(soma, "soma") + else: + """ + instantiate a structured model with the morphology as specified by + the morphology file + """ + self.set_morphology(morphology_file=morphology) + + # decorate the morphology with ion channels + if decorator is None: # basic model, only on the soma + # v_potassium = -80 # potassium reversal potential + # v_sodium = 50 # sodium reversal potential + + self.mechanisms = [ + "naRsg", + "bkpkj", + "hpkj", + "kpkj", + "kpkj2", + "kpkjslow", + "kpksk", + "lkpkj", + "cap", + ] + for mech in self.mechanisms: + self.soma.insert(mech) + self.soma.insert("cadiff") + self.species_scaling( + silent=True, species=species, modelType=modelType + ) # set the default type II cell parameters + else: # decorate according to a defined set of rules on all cell compartments + self.decorate() + self.save_all_mechs() # save all mechanisms inserted, location and gbar values... + self.get_mechs(self.soma) + + if debug: + print( + "<< Cartwheel: Modified version of Raman Purkinje cell model created >>" + ) + + def get_cellpars(self, dataset, species="guineapig", celltype="II"): + somaDia = data.get( + dataset, species=species, cell_type=celltype, field="soma_Dia" + ) + chtype = data.get( + dataset, species=species, cell_type=celltype, field="soma_na_type" + ) + pcabar = data.get( + dataset, species=species, cell_type=celltype, field="soma_pcabar" + ) + pars = Params(soma_Dia=somaDia, soma_natype=chtype, soma_pcabar=pcabar) + for g in [ + "soma_narsg_gbar", + "soma_kpkj_gbar", + "soma_kpkj2_gbar", + "soma_kpkjslow_gbar", + "soma_kpksk_gbar", + "soma_lkpkj_gbar", + "soma_bkpkj_gbar", + "soma_hpkj_gbar", + "soma_hpkj_eh", + "soma_lkpkj_e", + "soma_e_k", + "soma_e_na", + "soma_e_ca", + ]: + pars.additem( + g, data.get(dataset, species=species, cell_type=celltype, field=g) + ) + return pars + + def species_scaling(self, silent=True, species="mouse", modelType="I"): + """ + Adjust all of the conductances and the cell size according to the species requested. + This scaling should be used ONLY for point models, as no other compartments + are scaled. + + Parameters + ---------- + species : string (default: 'rat') + name of the species to use for scaling the conductances in the base point model + Must be one of mouse, cat, guineapig + + modelType: string (default: 'I') + definition of model type from RM03 models, type II or type II-I + + silent : boolean (default: True) + run silently (True) or verbosely (False) + + Note + ---- + For the cartwheel cell model, there is only a single scaling recognized. + """ + if species is not "mouse": + raise ValueError('Cartwheel species: only "mouse" is recognized') + if modelType is not "I": + raise ValueError('Cartwheel modelType: only "I" is recognized') + self._valid_temperatures = (34.0,) + if self.status["temperature"] is None: + self.set_temperature(34.0) + + pars = self.get_cellpars("CW_channels", species=species, celltype="cartwheel") + self.set_soma_size_from_Diam(pars.soma_Dia) + self.soma().bkpkj.gbar = nstomho(pars.soma_bkpkj_gbar, self.somaarea) + self.soma().hpkj.gbar = nstomho(pars.soma_hpkj_gbar, self.somaarea) + self.soma().kpkj.gbar = nstomho(pars.soma_kpkj_gbar, self.somaarea) + self.soma().kpkj2.gbar = nstomho(pars.soma_kpkj2_gbar, self.somaarea) + self.soma().kpkjslow.gbar = nstomho(pars.soma_kpkjslow_gbar, self.somaarea) + self.soma().kpksk.gbar = nstomho(pars.soma_kpksk_gbar, self.somaarea) + self.soma().lkpkj.gbar = nstomho(pars.soma_lkpkj_gbar, self.somaarea) + self.soma().naRsg.gbar = nstomho(pars.soma_narsg_gbar, self.somaarea) + self.soma().cap.pcabar = pars.soma_pcabar + self.soma().ena = pars.soma_e_na # 50 + self.soma().ek = pars.soma_e_k # -80 + self.soma().lkpkj.e = pars.soma_lkpkj_e # -65 + self.soma().hpkj.eh = pars.soma_hpkj_eh # -43 + self.soma().eca = pars.soma_e_ca # 50 + + self.status["na"] = pars.soma_natype + self.status["species"] = species + self.status["modelType"] = modelType + self.check_temperature() + if not silent: + print("set cell as: ", species) + print(" with Vm rest = %f" % self.vm0) + + # print 'set up' + + def i_currents(self, V): + """ + For the steady-state case, return the total current at voltage V + Used to find the zero current point. + Overrides i_currents in cells.py, because this model uses conductances + that are not specified in the default cell mode. + + Parameters + ---------- + V : float, mV (no default) + Voltage at which the current for each conductance is computed. + + Returns + ------- + I : float, nA + The sum of the currents at steady-state for all of the conductances. + """ + for part in self.all_sections.keys(): + for sec in self.all_sections[part]: + sec.v = V + h.celsius = self.status["temperature"] + h.finitialize() + self.ix = {} + + if "naRsg" in self.mechanisms: + self.ix["naRsg"] = self.soma().naRsg.gna * (V - self.soma().ena) + if "cap" in self.mechanisms: + a = self.soma().cap.pcabar * self.soma().cap.minf + self.ix["cap"] = a * self.ghk(V, self.soma().cao, self.soma().cai, 2) + if "kpkj" in self.mechanisms: + self.ix["kpkj"] = self.soma().kpkj.gk * (V - self.soma().ek) + if "kpkj2" in self.mechanisms: + self.ix["kpkj2"] = self.soma().kpkj2.gk * (V - self.soma().ek) + if "kpkjslow" in self.mechanisms: + self.ix["kpkjslow"] = self.soma().kpkjslow.gk * (V - self.soma().ek) + if "kpksk" in self.mechanisms: + self.ix["kpksk"] = self.soma().kpksk.gk * (V - self.soma().ek) + if "bkpkj" in self.mechanisms: + self.ix["bkpkj"] = self.soma().bkpkj.gbkpkj * (V - self.soma().ek) + if "hpkj" in self.mechanisms: + self.ix["hpkj"] = self.soma().hpkj.gh * (V - self.soma().hpkj.eh) + # leak + if "lkpkj" in self.mechanisms: + self.ix["lkpkj"] = self.soma().lkpkj.gbar * (V - self.soma().lkpkj.e) + return np.sum([self.ix[i] for i in self.ix]) + + def ghk(self, v, ci, co, z): + """ + GHK flux equation, used to calculate current density through calcium channels + rather than standard Nernst equation. + + Parameters + ---------- + v : float, mV + voltage for GHK calculation + ci : float, mM + internal ion concentration + co : float, mM + external ion concentraion + z : float, no units + valence + + Returns + ------- + flux : A/m^2 + + """ + F = 9.6485e4 # (coul) + R = 8.3145 # (joule/degC) + T = h.celsius + 273.19 # Kelvin + E = (1e-3) * v # convert mV to V + Ci = ci + (self.soma().cap.monovalPerm) * ( + self.soma().cap.monovalConc + ) # : Monovalent permeability + if ( + np.fabs(1 - np.exp(-z * (F * E) / (R * T))) < 1e-6 + ): # denominator is small -> Taylor series + ghk = ( + (1e-6) + * z + * F + * (Ci - co * np.exp(-z * (F * E) / (R * T))) + * (1 - (z * (F * E) / (R * T))) + ) + else: + ghk = ( + (1e-6) + * z ** 2.0 + * (E * F ** 2.0) + / (R * T) + * (Ci - co * np.exp(-z * (F * E) / (R * T))) + / (1 - np.exp(-z * (F * E) / (R * T))) + ) + return ghk diff --git a/cnmodel/cells/cell.py b/cnmodel/cells/cell.py new file mode 100644 index 0000000..0dcf21c --- /dev/null +++ b/cnmodel/cells/cell.py @@ -0,0 +1,1200 @@ +from __future__ import print_function +import weakref +import numpy as np +import scipy.optimize +from collections import OrderedDict +import neuron +from neuron import h +from ..util import nstomho, mho2ns +from ..util import custom_init +from .. import synapses +from .. import data +from .. import morphology +from .. import decorator + +""" +Term definitions: +cell class is the class of morphological cell: bushy, tstellate, etc. +Each cell class is implmeneted as a separate python class (no pun) +modelName is name of the source model used so it is like the type, but one level up). +ModelNames are RM03, XM13, and for other cell types may refer to the original model, +such as POK (Kanold pyramidal cell), MCG (McGinley octopus), Eager, etc. +These model designations may have only one model type (POK), or may have multiple types (RM03, XM13) +modelType refers to the Rothman and Manis 2003 model classes (I, II, I-c, I-t, II-1, I-II, etc) +These are physiologically based, but in the ion channel tables are mapped to morphological classes sort of, + + +""" + + +class Cell(object): + """ + Base class for all cell types. + + """ + + type = None + + # create a lookup table to map sections to their parent cell + sec_lookup = weakref.WeakValueDictionary() + + @classmethod + def from_section(cls, sec): + return cls.sec_lookup[sec.name()] + + def __init__(self): + # dictionary of all sections associated with this cell + self.hr = None # hoc reader - e.g., we have read a morphology file. + self.all_sections = {} + # the following section types (parts) are known to us: + for k in [ + "soma", + "maindend", + "secdend", + "dend", + "dendrite", + "primarydendrite", + "secondarydendrite", + "internode", + "initialsegment", + "axonnode", + "axon", + "unmyelinatedaxon", + "myelinatedaxon", + "hillock", + ]: + self.all_sections[k] = [] # initialize to an empty list + self.species = "mouse" + self.status = {} # dictionary of parameters used to instantiate the cell. + # Record synaptic inputs and projections + self.inputs = [] # inputs are recorded - synapse object, post_opts and kwds + self.outputs = [] + self.initial_mechanisms = None + # each cell has the following parameters: + self.totcap = None # total membrane capacitance (somatic) + self.somaarea = None # total soma area + self.initsegment = None # hold initial segment sections + self.axnode = None # hold nodes of ranvier sections + self.internode = None # hold internode sections + self.maindend = None # hold main dendrite sections + self.secdend = None # hold secondary dendrite sections + self.dendrite = None + self.axon = None + self.axonsf = None # axon diameter scale factor + # define defaults for these parameters (RM03 model defaults) + self.e_k = -70 # potassium reversal potential, mV + self.e_na = 55 + self.e_h = -43 + self.c_m = 0.9 # specific membrane capacitance, uf/cm^2 + self.R_a = 150 # axial resistivity of cytoplasm/axoplasm, ohm.cm + self.e_leak = -65 + # Recommended current (min, max, step) for testing this cell + self.i_test_range = ( + -0.5, + 0.5, + 0.05, + ) # defines default current steps for IC curve + + # Recommended threshold for detecting spikes from this cell + self.spike_threshold = -40 + + # Resting potential for this cell, determined by calling + # self.find_i0() + self.vm0 = None + + def check_temperature(self): + if self.status["temperature"] not in self._valid_temperatures: + tstring = ", ".join("%3.1f " % t for t in self._valid_temperatures) + raise ValueError( + "Cell %s %s %s temperature %3.1f is invalid; must be in: [%s]" + % ( + self.type, + self.status["species"], + self.status["modelType"], + self.status["temperature"], + tstring, + ) + ) + + def set_temperature(self, temperature): + """ + Set the temperature setting for this cell. + """ + if self.status["decorator"] is None: + if self.status["temperature"] is None: # only if not already set + self.status["temperature"] = temperature + self.species_scaling( + species=self.status["species"], modelType=self.status["modelType"] + ) + else: + self.status["temperature"] = temperature + + # self.decorate() # call the decorator + + def set_morphology(self, morphology_file=None): + """ + Set the cell's morphological structure from a file that defines sections + (for example, a morphology file read by neuronvis), or from a morphology + object that has already been retrieved/created. + + Parameters + ---------- + morphology_file : string or morphology object (default: None) + File name/path for the morphology file (for example, .hoc or .swc file) + Alternatively, this can be a morphology object returned by the morphology class. + + Returns + ------- + nothing + + """ + self.morphology_file = morphology_file # save the source file name + if isinstance(morphology_file, str): + if morphology_file.endswith(".hoc"): + self.morphology = morphology.HocReader(morphology_file) + elif morphology_file.endswith(".swc"): + self.morphology = morphology.SwcReader(morphology_file) + else: + raise ValueError("Unknown morphology file type [must be .hoc or .swc]") + elif isinstance(morphology_file, morphology.Morphology): + self.morphology = morphology_file + else: + print(morphology_file) + raise TypeError("Invalid morphology type: must be filename(str) or ") + self.hr = ( + self.morphology + ) # extensive renaming required in calling classes, temporary fix. + self.morphology.read_section_info() # not sure this is necessary... + # these were not instantiated when the file was read, but when the decorator was run. + for s in self.hr.sec_groups.keys(): + for sec in self.hr.sec_groups[s]: + section = self.hr.get_section(sec) + mechs = self.hr.get_mechanisms(sec) + if s == "myelinatedaxon": + section.cm = 0.002 + self.add_section(section, s) # add the section to the cell. + # print '\nmechanisms for section: %s', section + # self.print_mechs(section) + self.set_soma_size_from_Section( + self.soma + ) # this is used for reporting and setting g values... + if isinstance(self.soma, list): + self.distances(self.soma[1]) + else: + self.distances(self.soma) + self.hr.distanceMap = self.distanceMap + + def add_section(self, sec, sec_type): + """ + Add a section (or list of sections) to this cell. + This adds the section to self.all_sections[sec_type] and also allows + the cell to be accessed from the section using + cells.cell_from_section(). + + Notes: + + *sec_type* must be one of the keys already in self.all_sections. + + This method does not connect sections together; that must be + done manually. + + """ + if not isinstance(sec, list): + sec = [sec] + self.all_sections[sec_type].extend(sec) + for s in sec: + Cell.sec_lookup[s.name()] = self + + def list_sections(self): + # print self.all_sections + print("Known Section names:") + for sec in self.all_sections: + print(" %s" % sec) + s = self.all_sections[sec] + # print 's: ', s + if len(s) > 0: + print(" ------------------------------------------") + print(" Sections present:") + for u in s: + print( + " Type: %s (%s, %s): %s" + % ( + sec, + u.name(), + str(self.hr.get_section(u.name())), + Cell.sec_lookup[u.name()], + ) + ) + print(" ------------------------------------------") + else: + print(" No section of this type in cell") + + def get_section_type(self, sec): + for s in self.all_sections: + if sec in self.all_sections[s]: + return s + return None + + def get_post_sec(self, kwds): + """ + Get the postsynaptic section from the value of postsite + in kwds. This is typically called from the cell-specific make_psd method. + If the key 'postsite' is in the kwds dict, we look it up. + If not, then we use the soma section as a default instead. + + Parameters + ---------- + kwds : dict + dictionary of keywords, may have a key 'postsite' + + Returns: + loc, post_sec + the location (0-1) of the desired point process insertion, and + post_sec, the neuron section where that insertion will take place + """ + if ( + "postsite" in kwds + ): # use a defined location instead of the default (soma(0.5) + postsite = kwds["postsite"] + loc = postsite[1] # where on the section? + uname = ( + "sections[%d]" % postsite[0] + ) # make a name to look up the neuron section object + post_sec = self.hr.get_section(uname) # Tell us where to put the synapse. + else: + loc = 0.5 + post_sec = self.soma + return loc, post_sec + + def set_d_lambda(self, freq=100, d_lambda=0.1): + """ + Sets nseg in each section to an odd value so that its segments are no longer than + d_lambda x the AC length constant at frequency freq in that section. + The defaults are reasonable values for most models + Be sure to specify your own Ra and cm before calling geom_nseg() + + To understand why this works, + and the advantages of using an odd value for nseg, + see Hines, M.L. and Carnevale, N.T. NEURON: a tool for neuroscientists. The Neuroscientist 7:123-135, 2001. + This is a python version of the hoc code. + + Parameters + ---------- + freq : float, default=100. (Hz) + Frequency in Hz to use in computing nseg. + d_lambda : float, default=0.1 + fraction of AC length constant for minimum segment length + + """ + if self.hr is None: # no hoc reader file, so no adjustments + return + for st in self.all_sections.keys(): + for i, section in enumerate(self.all_sections[st]): + nseg = ( + int( + (section.L / (d_lambda * self._lambda_f(freq, section)) + 0.9) + / 2 + ) + * 2 + + 1 + ) + if nseg < 3: + nseg = 3 # ensure at least 3 segments per section... + section.nseg = nseg + + def _lambda_f(self, freq, section): + """ + get lambda_f for the section (internal) + + Parameters + ---------- + freq : float, default=100. (Hz) + Frequency in Hz to use in computing nseg. + section : Neuron section object + + Returns + ------- + section length normalized by the length constant at freq. + """ + self.hr.h("access %s" % section.name()) + if self.hr.h.n3d() < 2: + return 1e-5 * np.sqrt( + section.diam / (4.0 * np.pi * freq * section.Ra * section.cm) + ) + # above was too inaccurate with large variation in 3d diameter + # so now we use all 3-d points to get a better approximate lambda + x1 = self.hr.h.arc3d(0) + d1 = self.hr.h.diam3d(0) + lam = 0.001 + for i in range(int(self.hr.h.n3d()) - 1): + x2 = self.hr.h.arc3d(i) + d2 = self.hr.h.diam3d(i) + lam = lam + ((x2 - x1) / np.sqrt(d1 + d2)) + x1 = x2 + d1 = d2 + + # length of the section in units of lambda + lam = ( + lam + * np.sqrt(2.0) + * 1e-5 + * np.sqrt(4.0 * np.pi * freq * section.Ra * section.cm) + ) + return section.L / lam + + @property + def soma(self): + """ + First (or only) section in the "soma" section group. + """ + if isinstance(self.all_sections["soma"], list): + return self.all_sections["soma"][0] + else: + return self.all_sections["soma"] + + def decorate(self): + """ + decorate the cell with it's own class channel decorator + """ + self.decorated = decorator.Decorator(cell=self) + self.decorated.channelValidate(self, verify=False) + self.mechanisms = ( + self.hr.mechanisms + ) # copy out all of the mechanisms that were inserted + + # def channel_manager(self, modelType='RM03'): + # """ + # Every cell class should have a channel manager if it is set up to handle morphology. + # This function should be overridden in the class with an appropriate routine that + # builds the dictionary needed to decorate the cell. See the bushy cell class for + # an example. + # + # Parameters + # ---------- + # modelType : string (default: 'RM03') + # A string that identifies what type of model the channel manager will implement. + # This may be used to define different kinds of channels, or channel densities + # and compartmental placement for different cells. + # """ + # raise NotImplementedError("No channel manager exists for cells of the class: %s" % + # (self.__class__.__name__)) + + def connect(self, post_cell, pre_opts=None, post_opts=None, **kwds): + """ + Create a new synapse connecting this cell to a postsynaptic cell. + The synapse is automatically created using + pre_cell.make_terminal(post_cell, \**pre_opts) and + post_cell.make_psd(terminal, \**post_opts). + + By default, the cells decide which sections to connect. This can be + overridden by specifying 'section' in pre_opts and/or post_opts. + + Parameters + ---------- + post_cell : NEURON section (required) + The postsynaptic cell that will receive the connection. + pre_opts : dictionary of options for the presynaptic cell (default: None) + see the synapses class for valid options and format. + post_opts : diction of options for the postsynaptic cell (default: None) + see synapses class for valid options and format. + \**kwds : (optional) + argmuments that are passed to the synapses class. + + Returns + ------- + the synapse object + + """ + if pre_opts is None: + pre_opts = {} + if post_opts is None: + post_opts = {} + + synapse = synapses.Synapse(self, pre_opts, post_cell, post_opts, **kwds) + self.outputs.append(synapse) + post_cell.inputs.append([synapse, post_opts, kwds]) + + return synapse + + def print_connections(self): + """ + This is mostly for debugging ... + """ + print("outputs: ", self.outputs) + print("inputs: ", self.inputs) + + def make_terminal(self, post_cell, **kwds): + """ + Create a synaptic terminal release mechanism suitable for output + from this cell to post_sec + This routine is a placeholder and should be replaced in the specific + cell class with code that performs the required actions for that class. + + Parameters + ---------- + post_cell : the target terminal cell (required) + + \**kwds : parameters passed to the terminal + + """ + raise NotImplementedError( + "Cannot make Terminal connecting %s => %s" + % (self.__class__.__name__, post_cell.__class__.__name__) + ) + + def make_psd(self, terminal, **kwds): + """ + Create a PSD suitable for synaptic input from pre_sec. + This routine is a placeholder and should be overridden in the specific + cell class with code that performs the required actions for that class. + + Parameters + ---------- + terminal : the terminal that connects to the PSD (required) + + \**kwds : parameters passed to the terminal + + """ + pre_cell = terminal.cell + raise NotImplementedError( + "Cannot make PSD connecting %s => %s" + % (pre_cell.__class__.__name__, self.__class__.__name__) + ) + + def make_glu_psd(self, post_sec, terminal, AMPA_gmax, NMDA_gmax, **kwds): + # Get AMPAR kinetic constants from database + params = data.get( + "sgc_ampa_kinetics", + species=self.species, + post_type=self.type, + field=["Ro1", "Ro2", "Rc1", "Rc2", "PA"], + ) + + return synapses.GluPSD( + post_sec, + terminal, + ampa_gmax=AMPA_gmax, + nmda_gmax=NMDA_gmax, + ampa_params=dict( + Ro1=params["Ro1"], + Ro2=params["Ro2"], + Rc1=params["Rc1"], + Rc2=params["Rc2"], + PA=params["PA"], + ), + **kwds + ) + + def make_gly_psd(self, post_sec, terminal, psdtype, **kwds): + # Get GLY kinetic constants from database + params = data.get( + "gly_kinetics", + species=self.species, + post_type=self.type, + field=["KU", "KV", "XMax"], + ) + psd = synapses.GlyPSD(post_sec, terminal, psdType=psdtype, **kwds) + return psd + + def make_exp2_psd( + self, post_sec, terminal, weight=0.01, loc=0.5, tau1=0.1, tau2=0.3, erev=0.0 + ): + return synapses.Exp2PSD( + post_sec, terminal, weight=weight, loc=loc, tau1=tau1, tau2=tau2, erev=erev + ) + + def print_status(self): + print("\nCell model: %s" % self.__class__.__name__) + print(self.__doc__) + print(" Model Status:") + print("-" * 24) + for s in self.status.keys(): + print("{0:>12s} : {1:<12s}".format(s, repr(self.status[s]))) + print("-" * 32) + + def cell_initialize(self, showinfo=False, vrange=None, **kwargs): + """ + Initialize this cell to it's "rmp" under current conditions + All sections in the cell are set to the same value + """ + if self.vm0 is None: + self.vm0 = self.find_i0(showinfo=showinfo, vrange=vrange, **kwargs) + for part in self.all_sections.keys(): + for sec in self.all_sections[part]: + sec.v = self.vm0 + + def get_mechs(self, section): + """ + return a list of the mechanisms that are present in a section + a mechanism is required to have a gbar variable. + This routine should be called at the end of every cell creation routine. + """ + u = dir(section()) + mechs = [] + for m in u: + if m[0:2] == "__": + continue + if m in [ + "cm", + "diam", + "k_ion", + "na_ion", + "next", + "point_processes", + "sec", + "v", + "x", + ]: + continue # skip non-mechanisms known to us + try: + gx = eval("section()." + m + ".gbar") + mechs.append(m) + except: + pass + self.mechs = mechs + return mechs + + def print_mechs(self, section): + """ + print the mechanisms that are inserted into the specified section, + and their densities (in uS/cm^2) + + """ + print("\n Installed mechanisms:") + self.get_mechs(section) + # print eval('section().nav11.gbar') + + print("somaarea: {:.3e}".format(self.somaarea)) + print("Mechanisms:", end="") + for s in self.mechs: + print(" {:>8s} ".format(s), end="") + print("") + for m in self.mechs: + try: + gx = eval("section()." + m + ".gbar") + erev = 0.0 + if m == "leak": + erev = eval("section()." + m + ".erev") + if m in ["jsrna", "na", "nacn", "nav11", "nacncoop", "napyr", "nap"]: + erev = eval("section().ena") + if m in ["klt", "kht", "ka"]: + erev = eval("section().e%s" % m) + if m in ["kis", "kif", "kdpyr", "kcnq"]: + erev = eval("section().ek") + if m in ["hcno", "ihvcn", "hcnobo", "ihpyr", "ihpyr_adj"]: + erev = eval("section()." + m + ".eh") + print( + "{0:>12s} : {2:8.1f} nS {1:7.3e} mho/cm2 {3:>5.1f} mV".format( + m, gx, mho2ns(gx, self.somaarea), erev + ) + ) + except: + print("{0:>12s} : ".format(m)) + print("-" * 32) + + def print_all_mechs(self): + print(self.get_all_mechs()) + + def get_all_mechs(self): + """ + return a string with all the mechanisms + """ + res = "\nAll mechanisms in all sections: \n" + for part in self.all_sections.keys(): + if len(self.all_sections[part]) == 0: + # res += 'Cell part: %s hs not sections' % part + continue + res += "Cell part: %s\n" % part + for sec in self.all_sections[part]: + res += " Section: %s\n" % sec.name() + res += " %s" % self.get_mechs(sec) + "\n" + for m in self.get_mechs(sec): + gx = eval("sec()." + m + ".gbar") + res += " %s: %f\n" % (m, gx) + return res + + def save_all_mechs(self): + """ + get and save all of the initial mechanisms and their + maximal conductances when the cell is created. + We use this to get and check values later when the run + is actually done. + Note: some cell constructions may require that save_all_mechs + be done again after the initial "build". In this case, + setting the cell's initial_mechanisms property to None must + be done to allow a new configuration of mechanisms to be saved. + + """ + if self.initial_mechanisms is not None: + raise ValueError( + "Cells: Attempting to save initial mechanisms more than once" + ) + self.initial_mechanisms = {} + for part in self.all_sections.keys(): + self.initial_mechanisms[part] = {} + # print('Cell part: %s' % part ) + for sec in self.all_sections[part]: + # print(' Section: ', sec) + # print(' ', self.get_mechs(sec)) + self.initial_mechanisms[part][sec] = {} + for m in self.get_mechs(sec): + gx = eval("sec()." + m + ".gbar") + # print(' %s: %f' % (m, gx)) + self.initial_mechanisms[part][sec][m] = gx + + def check_all_mechs(self): + """ + Check that all mechanisms are the same as when we initially created the cell + """ + check = {} + for part in self.all_sections.keys(): + if part not in self.initial_mechanisms.keys(): + raise ValueError("Cell part %s was not in the original cell") + check[part] = {} + for sec in self.all_sections[part]: + # print(' Section: ', sec) + # print(' ', self.get_mechs(sec)) + if sec not in self.initial_mechanisms[part].keys(): + raise ValueError("Cell section was not in the original cell: ", sec) + check[part][sec] = sec + for m in self.get_mechs(sec): + gx = eval("sec()." + m + ".gbar") + # print(' %s: %f' % (m, gx)) + if m not in self.initial_mechanisms[part][sec].keys(): + raise ValueError( + "Mechanism %s was not in cell part %s, section = " + % (m, part), + sec, + ) + if self.initial_mechanisms[part][sec][m] != gx: + raise ValueError( + "Conductance for mechanism %s in cell part %s has changed (%f, %f), section = " + % (m, part, self.initial_mechanisms[part][sec][m], gx), + sec, + ) + return True + + def get_cellpars(self, dataset, species="guineapig", cell_type="II"): + raise NotImplementedError( + "get_cellpars should be reimplemented in the individual cell modules" + ) + + def channel_manager(self, modelName=None, modelType=None): + """ + This routine defines channel density maps and distance map patterns + for each type of compartment in the cell. The maps + are used by the ChannelDecorator class (specifically, its private + \_biophys function) to decorate the cell membrane. + These settings are only used if the decorator is called; otherwise + for point cells, the species_scaling routine defines the channel + densities. + + Parameters + ---------- + modelType : string (default: 'None' + A string that defines the type of the model. + These are determined in the tables in the data directory, for ionchannels.py + + Returns + ------- + Nothing + + Notes + ----- + This routine defines the following variables for the class: + + * conductances (gBar) + * a channelMap (dictonary of channel densities in defined anatomical compartments) + * a current injection range for IV's (used for testing) + * a distance map, which defines how each conductance in a selected compartment + changes with distance from the soma. The current implementation includes both + linear and exponential gradients, + the minimum conductance at the end of the gradient, and the space constant or + slope for the gradient. + + """ + + dataset = "%s_channels" % modelName + decorationmap = dataset + "_compartments" + # print('dataset: {0:s} decorationmap: {1:s}'.format(dataset, decorationmap)) + cellpars = self.get_cellpars( + dataset, species=self.status["species"], modelType=modelType + ) + refarea = 1e-3 * cellpars.cap / self.c_m + # ? print ('cellpars: ' ) + cellpars.show() + # print(' species: ', self.status['species']) + # print('m# odelType: ', modelType) + # print('dataset: ', dataset) + table = data._db.get_table_info(dataset) + # table = data.get_table_info('mGBC_channels') + # print(dir(data.ionchannels)) + # print( data.print_table('mGBC_channels')) + + if len(table.keys()) == 0: + raise ValueError("data table %s lacks keys - does it exist?" % dataset) + chscale = data._db.get_table_info(decorationmap) + pars = {} + # retrive the conductances from the data set + # print ('table keys: ', table.keys()) + # print('table: ', table) + # print('chscale: ', chscale) + for g in table["field"]: + x = data._db.get( + dataset, species=self.status["species"], model_type=modelType, field=g + ) + if not isinstance(x, float): + continue + if "_gbar" in g: + pars[g] = x / refarea + else: + pars[g] = x + + self.channelMap = OrderedDict() + for c in chscale["compartment"]: + self.channelMap[c] = {} + for g in pars.keys(): + if g not in chscale["parameter"]: + # print ('Parameter %s not found in chscale parameters!' % g) + continue + scale = data._db.get( + decorationmap, + species=self.status["species"], + model_type=modelType, + compartment=c, + parameter=g, + ) + if "_gbar" in g: + self.channelMap[c][g] = pars[g] * scale + else: + self.channelMap[c][g] = pars[g] + + self.irange = np.linspace(-0.6, 1, 9) + self.distMap = { + "dend": { + "klt": {"gradient": "exp", "gminf": 0.0, "lambda": 50.0}, + "kht": {"gradient": "exp", "gminf": 0.0, "lambda": 50.0}, + "nav11": {"gradient": "exp", "gminf": 0.0, "lambda": 50.0}, + }, # linear with distance, gminf (factor) is multiplied by gbar + "dendrite": { + "klt": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "kht": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "nav11": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + }, # linear with distance, gminf (factor) is multiplied by gbar + "apic": { + "klt": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "kht": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "nav11": {"gradient": "exp", "gminf": 0.0, "lambda": 200.0}, + }, # gradients are: flat, linear, exponential + } + self.check_temperature() + return + + def i_currents(self, V): + """ + For the steady-state case, return the total current at voltage V + Used to find the zero current point + vrange brackets the interval + Implemented here are the basic known mechanisms. If you add or need + more mechanisms, they either need to be accomadated in this routine, + or this routine needs to be implemented (overridden) in the + specific cell class. + + """ + for part in self.all_sections.keys(): + for sec in self.all_sections[part]: + sec.v = V + h.celsius = self.status["temperature"] + h.t = 0.0 + h.finitialize(V) + h.fcurrent() + self.ix = {} + + if "na" in self.mechanisms: + # print dir(self.soma().na) + try: + self.ix["na"] = self.soma().na.gna * (V - self.soma().ena) + except: + self.ix["na"] = self.soma().nav11.gna * (V - self.soma().ena) + if "jsrna" in self.mechanisms: + self.ix["jsrna"] = self.soma().jsrna.gna * (V - self.soma().ena) + if "nav11" in self.mechanisms: + self.ix["nav11"] = self.soma().nav11.gna * (V - self.soma().ena) + if "nacn" in self.mechanisms: + self.ix["nacn"] = self.soma().nacn.gna * (V - self.soma().ena) + if "napyr" in self.mechanisms: + self.ix["napyr"] = self.soma().napyr.gna * (V - self.soma().ena) + if "nap" in self.mechanisms: + self.ix["nap"] = self.soma().nap.gna * (V - self.soma().ena) + if "nacncoop" in self.mechanisms: + self.ix["nacncoop"] = self.soma().nacncoop.gna * (V - self.soma().ena) + + if "klt" in self.mechanisms: + self.ix["klt"] = self.soma().klt.gklt * (V - self.soma().ek) + if "kht" in self.mechanisms: + self.ix["kht"] = self.soma().kht.gkht * (V - self.soma().ek) + if "ka" in self.mechanisms: + self.ix["ka"] = self.soma().ka.gka * (V - self.soma().ek) + if "kdpyr" in self.mechanisms: + self.ix["kdpyr"] = self.soma().kdpyr.gk * (V - self.soma().ek) + if "kcnq" in self.mechanisms: + self.ix["kcnq"] = self.soma().kdcnq.gk * (V - self.soma().ek) + if "kis" in self.mechanisms: + self.ix["kis"] = self.soma().kis.gk * (V - self.soma().ek) + if "kif" in self.mechanisms: + self.ix["kif"] = self.soma().kif.gk * (V - self.soma().ek) + + if "ihvcn" in self.mechanisms: + self.ix["ihvcn"] = self.soma().ihvcn.gh * (V - self.soma().ihvcn.eh) + if "ihpyr" in self.mechanisms: + self.ix["ihpyr"] = self.soma().ihpyr.gh * (V - self.soma().ihpyr.eh) + if "ihpyr_adj" in self.mechanisms: + self.ix["ihpyr_adj"] = self.soma().ihpyr_adj.gh * ( + V - self.soma().ihpyr_adj.eh + ) + if "hcno" in self.mechanisms: + raise ValueError("HCNO is not supported - use hcnobo instead") + # self.ix['hcno'] = self.soma().hcno.gh*(V - self.soma().hcno.eh) + if "hcnobo" in self.mechanisms: + self.ix["hcnobo"] = self.soma().hcnobo.gh * (V - self.soma().hcnobo.eh) + + if "leak" in self.mechanisms: + self.ix["leak"] = self.soma().leak.gbar * (V - self.soma().leak.erev) + # print self.status['name'], self.status['type'], V, self.ix + isum = np.sum([self.ix[i] for i in self.ix]) + # print 'conductances: ', self.ix.keys() + # print 'V, isum, values: ', V, isum, [self.ix[i] for i in self.ix] + return isum + + def find_i0(self, vrange=None, showinfo=False): + """ + find the root of the system of equations in vrange. + Finds RMP fairly accurately as zero current level for current conductances. + + Parameters + ---------- + vrange : list of 2 floats (default: [-70, -55]) + The voltage range over which the root search will be performed. + + showinfo : boolean (default: False) + a flag to print out which roots were found and which mechanisms were in the cell + + Returns + ------- + The voltage at which I = 0 in the vrange specified + """ + if vrange is None: + vrange = self.vrange + # print( vrange) + # print (self.i_currents(V=vrange[0]), self.i_currents(V=vrange[1])) + # v0 = scipy.optimize.brentq(self.i_currents, vrange[0], vrange[1], maxiter=10000) + # print( 'v0: ', v0) + try: + v0 = scipy.optimize.brentq( + self.i_currents, vrange[0], vrange[1], maxiter=10000 + ) + except: + print("find i0 failed:") + print(self.ix) + i0 = self.i_currents(V=vrange[0]) + i1 = self.i_currents(V=vrange[1]) + ivi = [] + ivv = [] + for v in np.arange(vrange[0], vrange[1], 0.5): + ivi.append(self.i_currents(V=v)) + ivv.append(v) + print("iv: ") + for i in range(len(ivi)): + print("%6.1f %9.4f" % (ivv[i], ivi[i])) + print( + "This means the voltage range for the search might be too large\nor too far away from the target" + ) + raise ValueError( + "vrange not good for %s : %f at %6.1f, %f at %6.1f, temp=%6.1f" + % (self.status["name"], i0, vrange[0], i1, vrange[1], h.celsius) + ) + # check to be sure all the currents that are needed are calculated + # can't do this until i_currents has populated self.ix, so do it now... + for m in self.mechanisms: + if m not in self.ix.keys(): + raise ValueError( + "Mechanism %s in cell is missing from i_currents calculation", m + ) + + if showinfo: + print( + "\n [soma] find_i0 Species: %s cell type: %s Temp %6.1f" + % (self.status["species"], self.status["modelType"], h.celsius) + ) + print(" *** found V0 = %f" % v0) + print(" *** and cell has mechanisms: ", self.mechanisms) + return v0 + + def compute_rmrintau(self, auto_initialize=True, vrange=None): + """ + Run the model for 2 msec after initialization - then + compute the inverse of the sum of the conductances to get Rin at rest + compute Cm*Rin to get tau at rest + + Parameters + ---------- + auto_initialize : boolean (default: True) + If true, forces initialization of cell in NEURON befor the computation. + + Returns + ------- + A dictionary containing: Rin (Mohm), tau (ms) and Vm (mV) + + """ + gnames = { # R&M 03 and related: + "nacn": "gna", + "na": "gna", + "jsrna": "gna", + "nav11": "gna", + "nacncoop": "gna", + "leak": "gbar", + "klt": "gklt", + "kht": "gkht", + "ka": "gka", + "ihvcn": "gh", + "hcno": "gh", + "hcnobo": "gh", + # pyramidal cell specific: + "napyr": "gna", + "nap": "gnap", + "kdpyr": "gk", + "kif": "gkif", + "kis": "gkis", + "ihpyr": "gh", + "ihpyr_adj": "gh", + "kcnq": "gk", + # cartwheel cell specific: + "bkpkj": "gbkpkj", + "hpkj": "gh", + "kpkj": "gk", + "kpkj2": "gk", + "kpkjslow": "gk", + "kpksk": "gk", + "lkpkj": "gbar", + "naRsg": "gna", + # SGC Ih specific: + "ihsgcApical": "gh", + "ihsgcBasalMiddle": "gh", + } + if auto_initialize: + self.cell_initialize(vrange=vrange) + custom_init() + self.computeAreas() + gsum = 0.0 + soma_sections = self.all_sections["soma"] + # 1e-8*np.pi*soma.diam*soma.L + somaarea = np.sum([1e-8 * np.pi * s.L * s.diam for s in soma_sections]) + for sec in soma_sections: + u = self.get_mechs(sec) + for m in u: + # gx = 'section().'+m+'.'+gnames[m] + gm = "%s_%s" % (gnames[m], m) + gsum += getattr(sec(), gm) + # eval(gx) + # print('{0:>12s} : gx '.format(m)) + # convert gsum from us/cm2 to nS using cell area + # print ('gsum, self.somaarea: ', gsum, self.somaarea) + gs = mho2ns(gsum, self.somaarea) + Rin = 1e3 / gs # convert to megohms + tau = Rin * self.totcap * 1e-3 # convert to msec + return {"Rin": Rin, "tau": tau, "v": self.soma(0.5).v} + + def set_soma_size_from_Cm(self, cap): + """ + Use soma capacitance to set the cell size. Area of the open cylinder is same as a sphere of + the same diameter. + Compute area and save total capacitance as well + """ + self.totcap = cap + self.somaarea = self.totcap * 1e-6 / self.c_m # pf -> uF, cm = 1uf/cm^2 nominal + lstd = 1e4 * ((self.somaarea / np.pi) ** 0.5) # convert from cm to um + self.soma.diam = lstd + self.soma.L = lstd + + def set_soma_size_from_Diam(self, diam): + """ + Use diameter to set the cell size. Area of the open cylinder is same as a sphere of + the same diameter. + Compute area and total capacitance as well + """ + self.somaarea = 1e-8 * 4.0 * np.pi * (diam / 2.0) ** 2 # in microns^2 + self.totcap = self.c_m * self.somaarea * 1e6 + # lstd = diam # 1E4 * ((self.somaarea / np.pi) ** 0.5) # convert from cm to um + self.soma.diam = diam + self.soma.L = diam + + def set_soma_size_from_Section(self, soma): + self.soma.diam = soma.diam + self.soma.L = soma.L + self.somaarea = 1e-8 * np.pi * soma.diam * soma.L + self.totcap = self.c_m * self.somaarea * 1e6 + + def print_soma_info(self): + print("-" * 40) + print("Soma Parameters: ") + print(" Area: ", self.somaarea) + print(" Cap: ", self.totcap) + print(" L: ", self.soma.L) + print(" diam: ", self.soma.diam) + print(" cm: ", self.c_m) + print("-" * 40) + + def distances(self, section=None): + self.distanceMap = {} + if section is None: + self.hr.h("access %s" % self.soma.name()) # reference point + else: + self.hr.h("access %s" % section.name()) + d = self.hr.h.distance() + for sec in self.all_sections: + s = self.all_sections[sec] + if len(s) > 0: + for u in s: + self.hr.h("access %s" % u.name()) + self.distanceMap[u.name()] = ( + self.hr.h.distance(0.5) - d + ) # should be distance from first point + + def computeAreas(self): + self.areaMap = {} + for sec in self.all_sections: # keys for names of section types + s = self.all_sections[sec] # get all the sections of that type + sectype = self.get_section_type(s) + if len(s) > 0: + self.areaMap[sec] = {} + for u in s: + self.areaMap[sec][u] = np.pi * u.diam * u.L + else: + pass + # print(' No section of type %s in cell' % sec) + + def add_axon( + self, + c_m=1.0, + R_a=150, + axonsf=1.0, + nodes=5, + debug=False, + dia=None, + len=None, + seg=None, + ): + """ + Add an axon to the soma with an initial segment (tapered), and multiple nodes of Ranvier + The size of the axon is determined by self.axonsf, which in turn is set by the species + The somaarea is used to scale the density of ion channels in the initial segment + """ + nnodes = range(nodes) + axnode = [] + internode = [] + Section = h.Section + initsegment = Section(cell=self.soma) + initsegment.connect(self.soma) + for i in nnodes: + axnode.append(Section(cell=self.soma)) + internode.append(Section(cell=self.soma)) + axnode[0].connect(initsegment) + for i in nnodes: + internode[i].connect(axnode[i]) + if i < nnodes[-1]: + axnode[i + 1].connect(internode[i]) + + # create an initial segment + ninitseg = 21 + initsegment.nseg = ninitseg + initsegment.diam = 4.0 * axonsf + initsegment.L = 36.0 * axonsf + initsegment.cm = c_m # c_m + initsegment.Ra = R_a # R_a + initsegment.insert("nacn") # uses a standard Rothman sodium channel + initsegment.insert("kht") + initsegment.insert("klt") + initsegment.insert("ihvcn") + initsegment.insert("leak") + gnamax = nstomho(6000.0, self.somaarea) + gnamin = 0.0 * gnamax + + gnastep = (gnamax - gnamin) / ninitseg # taper sodium channel density + for ip, inseg in enumerate(initsegment): + gna = gnamin + ip * gnastep + if debug: + print("Initial segment %d: gnabar = %9.6f" % (ip, gna)) + inseg.nacn.gbar = gna + inseg.klt.gbar = 0.2 * nstomho(200.0, self.somaarea) + inseg.kht.gbar = nstomho(150.0, self.somaarea) + inseg.ihvcn.gbar = 0.0 * nstomho(20.0, self.somaarea) + inseg.leak.gbar = nstomho(2.0, self.somaarea) + inseg.ena = self.e_na + inseg.ek = self.e_k + inseg.leak.erev = self.e_leak + + for i in nnodes: + axnode[i] = self.loadaxnodes(axnode[i], self.somaarea, eleak=self.e_leak) + internode[i] = self.loadinternodes( + internode[i], self.somaarea, eleak=self.e_leak + ) + + if debug: + print("<< {:s} Axon Added >>".format(self.__class__.__name__)) + h.topology() + self.add_section(initsegment, "initialsegment") + self.add_section(axnode, "axonnode") + self.add_section(internode, "internode") + + @staticmethod + def loadaxnodes(axnode, somaarea, nodeLength=2.5, nodeDiameter=2.0, eleak=-65): + v_potassium = -80 # potassium reversal potential + v_sodium = 50 # sodium reversal potential + Ra = 150 + cm = 1.0 + axnode.nseg = 1 + axnode.L = nodeLength + axnode.diam = nodeDiameter + axnode.Ra = Ra + axnode.cm = cm + axnode.insert("nacn") + axnode.insert("kht") + axnode.insert("klt") + axnode.insert("leak") + axnode.insert("ihvcn") + for ax in axnode: + ax.nacn.gbar = nstomho(1000.0, somaarea) + ax.kht.gbar = nstomho(150.0, somaarea) + ax.klt.gbar = nstomho(200.0, somaarea) + ax.ihvcn.gbar = 0 + ax.leak.gbar = nstomho(2.0, somaarea) + ax.ena = v_sodium + ax.ek = v_potassium + ax.leak.erev = eleak + return axnode + + @staticmethod + def loadinternodes( + internode, somaarea, internodeLength=1000, internodeDiameter=10, eleak=-65 + ): + v_potassium = -80 # potassium reversal potential + v_sodium = 50 # sodium reversal potential + Ra = 150 + cm = 0.002 + + internode.nseg = 20 + internode.L = internodeLength + internode.diam = internodeDiameter + internode.Ra = Ra + internode.cm = cm + internode.insert("nacn") + internode.insert("kht") + internode.insert("leak") + for inno in internode: + inno.leak.gbar = nstomho(0.002, somaarea) + inno.nacn.gbar = 0 * nstomho(500.0, somaarea) + inno.kht.gbar = 0 * nstomho(150.0, somaarea) + inno.ek = v_potassium + inno.ena = v_sodium + inno.leak.erev = eleak + return internode diff --git a/cnmodel/cells/dstellate.py b/cnmodel/cells/dstellate.py new file mode 100644 index 0000000..fb65b3a --- /dev/null +++ b/cnmodel/cells/dstellate.py @@ -0,0 +1,897 @@ +from __future__ import print_function +from neuron import h +from ..util import nstomho +from .cell import Cell +from ..util import Params +from .. import synapses +from .. import data + +__all__ = ["DStellate", "DStellateRothman", "DStellateEager"] + + +class DStellate(Cell): + + type = "dstellate" + + @classmethod + def create(cls, model="RM03", **kwds): + if model == "RM03": + return DStellateRothman(**kwds) + elif model == "Eager": + return DStellateEager(**kwds) + elif model == "dummy": + return DummyDStellate(**kwds) + else: + raise ValueError("DStellate type %s is unknown", type) + + def __init__(self): + Cell.__init__(self) + self.spike_source = ( + None + ) # used by DummyDStellate to connect VecStim to terminal + + def make_psd(self, terminal, psd_type, **kwds): + """ + Connect a presynaptic terminal to one post section at the specified location, with the fraction + of the "standard" conductance determined by gbar. + The default condition is designed to pass the unit test (loc=0.5) + + Parameters + ---------- + terminal : Presynaptic terminal (NEURON object) + + psd_type : either simple or multisite PSD for bushy cell + + kwds: dictionary of options. + Two are currently handled: + postsize : expect a list consisting of [sectionno, location (float)] + AMPAScale : float to scale the ampa currents + + """ + if ( + "postsite" in kwds + ): # use a defined location instead of the default (soma(0.5) + postsite = kwds["postsite"] + loc = postsite[1] # where on the section? + uname = ( + "sections[%d]" % postsite[0] + ) # make a name to look up the neuron section object + post_sec = self.hr.get_section(uname) # Tell us where to put the synapse. + else: + loc = 0.5 + post_sec = self.soma + + if psd_type == "simple": + if terminal.cell.type in ["sgc", "dstellate", "tuberculoventral"]: + weight = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="weight", + ) + tau1 = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="tau1", + ) + tau2 = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="tau2", + ) + erev = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="erev", + ) + return self.make_exp2_psd( + post_sec, + terminal, + weight=weight, + loc=loc, + tau1=tau1, + tau2=tau2, + erev=erev, + ) + else: + raise TypeError( + "Cannot make simple PSD for %s => %s" + % (terminal.cell.type, self.type) + ) + + elif psd_type == "multisite": + if terminal.cell.type == "sgc": + # Max conductances for the glu mechanisms are calibrated by + # running `synapses/tests/test_psd.py`. The test should fail + # if these values are incorrect + self.AMPAR_gmax = ( + data.get( + "sgc_synapse", + species=self.species, + post_type=self.type, + field="AMPAR_gmax", + ) + * 1e3 + ) + self.NMDAR_gmax = ( + data.get( + "sgc_synapse", + species=self.species, + post_type=self.type, + field="NMDAR_gmax", + ) + * 1e3 + ) + self.Pr = data.get( + "sgc_synapse", species=self.species, post_type=self.type, field="Pr" + ) + # adjust gmax to correct for initial Pr + self.AMPAR_gmax = self.AMPAR_gmax / self.Pr + self.NMDAR_gmax = self.NMDAR_gmax / self.Pr + # old values: + # AMPA_gmax = 0.22479596944138733*1e3 # factor of 1e3 scales to pS (.mod mechanisms) from nS. + # NMDA_gmax = 0.12281291946623739*1e3 + if "AMPAScale" in kwds: + self.AMPAR_gmax = ( + self.AMPAR_gmax * kwds["AMPAScale"] + ) # allow scaling of AMPA conductances + if "NMDAScale" in kwds: + self.NMDAR_gmax = self.NMDAR_gmax * kwds["NMDAScale"] + return self.make_glu_psd( + post_sec, terminal, self.AMPAR_gmax, self.NMDAR_gmax, loc=loc + ) + + elif terminal.cell.type == "dstellate": + # Get GLY kinetic constants from database + return self.make_gly_psd(post_sec, terminal, psdtype="glyfast", loc=loc) + elif terminal.cell.type == "tuberculoventral": + # Get GLY kinetic constants from database + return self.make_gly_psd(post_sec, terminal, psdtype="glyfast", loc=loc) + else: + raise TypeError( + "Cannot make PSD for %s => %s" % (terminal.cell.type, self.type) + ) + else: + raise ValueError("Unsupported psd type %s" % psd_type) + + def make_terminal(self, post_cell, term_type, **kwds): + if term_type == "simple": + return synapses.SimpleTerminal( + self.soma, post_cell, spike_source=self.spike_source, **kwds + ) + elif term_type == "multisite": + if post_cell.type in [ + "dstellate", + "tuberculoventral", + "pyramidal", + "bushy", + "tstellate", + ]: + nzones = data.get( + "dstellate_synapse", + species=self.species, + post_type=post_cell.type, + field="n_rsites", + ) + delay = data.get( + "dstellate_synapse", + species=self.species, + post_type=post_cell.type, + field="delay", + ) + else: + raise NotImplementedError( + "No knowledge as to how to connect D stellate cell to cell type %s" + % type(post_cell) + ) + pre_sec = self.soma + return synapses.StochasticTerminal( + pre_sec, + post_cell, + nzones=nzones, + spike_source=self.spike_source, + delay=delay, + **kwds + ) + else: + raise ValueError("Unsupported terminal type %s" % term_type) + + +class DStellateRothman(DStellate): + """ + VCN D-stellate model: + as a type I-II from Rothman and Manis, 2003 + """ + + def __init__( + self, + morphology=None, + decorator=None, + nach=None, + ttx=False, + species="guineapig", + modelType=None, + modelName=None, + debug=False, + ): + """ + initialize a radial stellate (D-stellate) cell, using the default parameters for guinea pig from + R&M2003, as a type I-II cell. + Modifications to the cell can be made by calling methods below. These include: + + * changing the sodium channel + * Changing "species" to mouse or cat (scales conductances) + * Shifting model type + + Parameters + ---------- + morphology : string (default: None) + Name of a .hoc file representing the morphology. This file is used to constructe + an electrotonic (cable) model. + If None (default), then a "point" (really, single cylinder) model is made, exactly according to RM03. + + decorator : Python function (default: None) + decorator is a function that "decorates" the morphology with ion channels according + to a set of rules. + If None, a default set of channels is inserted into the first soma section, and the + rest of the structure is "bare". + + nach : string (default: None) + nach selects the type of sodium channel that will be used in the model. A channel mechanism + by that name must exist. A value of None will set the channel to a default for the model (nacn). + + ttx : Boolean (default: False) + If ttx is True, then the sodium channel conductance is set to 0 everywhere in the cell. + This flag duplicates the effects of tetrodotoxin in the model. Currently, the flag is not implemented. + + species: string (default 'guineapig') + species defines the pattern of ion channel densities that will be inserted, according to + prior measurements in various species. Note that + if a decorator function is specified, this argument is ignored as the decorator will + specify the channel density. + + modelType: string (default: None) + modelType specifies the subtype of the cell model that will be used (e.g., "II", "II-I", etc). + modelType is passed to the decorator, or to species_scaling to adjust point (single cylinder) models. + + debug: boolean (default: False) + When True, there will be multiple printouts of progress and parameters. + + + Returns + ------- + Nothing + """ + + super(DStellateRothman, self).__init__() + if modelType == None: + modelType = "I-II" + if species == "guineapig": + modelName = "RM03" + temp = 22.0 + if nach == None: + nach = "nacn" + if species == "mouse": + temp = 34.0 + if modelName is None: + modelName = "XM13" + if nach is None: + nach = "na" + self.debug = debug + # if modelType == None: # allow us to pass None to get the default + # modelType = 'I-II' + # if nach == None: + # nach = 'na' + self.status = { + "soma": True, + "axon": False, + "dendrites": False, + "pumps": False, + "na": nach, + "species": species, + "modelType": modelType, + "modelName": modelName, + "ttx": ttx, + "name": "DStellate", + "morphology": morphology, + "decorator": decorator, + "temperature": None, + } + self.i_test_range = { + "pulse": [(-0.3, 0.3, 0.03), (-0.05, 0.0, 0.005)] + } # set range for ic command test + self.vrange = [-75.0, -55.0] + self.spike_threshold = ( + -40.0 + ) # matches threshold in released CNModel (set in base cell class) + + if morphology is None: + """ + instantiate a basic soma-only ("point") model + """ + soma = h.Section( + name="DStellate_Soma_%x" % id(self) + ) # one compartment of about 29000 um2 + soma.nseg = 1 + self.add_section(soma, "soma") + else: + """ + instantiate a structured model with the morphology as specified by + the morphology file + """ + self.set_morphology(morphology_file=morphology) + + # decorate the morphology with ion channels + if decorator is None: # basic model, only on the soma + self.mechanisms = ["klt", "kht", "ihvcn", "leak", nach] + for mech in self.mechanisms: + self.soma.insert(mech) + self.soma.ena = self.e_na + self.soma.ek = self.e_k + self.soma().leak.erev = self.e_leak + self.c_m = 0.9 + self.set_soma_size_from_Cm(12.0) + self.species_scaling( + silent=True, species=species, modelType=modelType + ) # set the default type II cell parameters + else: # decorate according to a defined set of rules on all cell compartments + self.decorate() + self.save_all_mechs() # save all mechanisms inserted, location and gbar values... + self.get_mechs(self.soma) + + if self.debug: + print("<< D-stellate: JSR Stellate Type I-II cell model created >>") + + def get_cellpars(self, dataset, species="guineapig", modelType="I-II"): + cellcap = data.get( + dataset, species=species, model_type=modelType, field="soma_Cap" + ) + chtype = data.get( + dataset, species=species, model_type=modelType, field="na_type" + ) + pars = Params(cap=cellcap, natype=chtype) + # pars.show() + + if self.status["modelName"] == "RM03": + for g in [ + "%s_gbar" % pars.natype, + "kht_gbar", + "klt_gbar", + "ka_gbar", + "ih_gbar", + "leak_gbar", + "leak_erev", + "ih_eh", + "e_k", + "e_na", + ]: + pars.additem( + g, data.get(dataset, species=species, model_type=modelType, field=g) + ) + if self.status["modelName"] == "XM13": + for g in [ + "%s_gbar" % pars.natype, + "kht_gbar", + "klt_gbar", + "ka_gbar", + "ihvcn_gbar", + "leak_gbar", + "leak_erev", + "ih_eh", + "e_k", + "e_na", + ]: + pars.additem( + g, data.get(dataset, species=species, model_type=modelType, field=g) + ) + if self.status["modelName"] == "mGBC": + for g in [ + "%s_gbar" % pars.natype, + "kht_gbar", + "klt_gbar", + "ka_gbar", + "ihvcn_gbar", + "leak_gbar", + "leak_erev", + ]: + pars.additem( + g, data.get(dataset, species=species, model_type=modelType, field=g) + ) + return pars + + def species_scaling(self, species="guineapig", modelType="I-II", silent=True): + """ + Adjust all of the conductances and the cell size according to the species requested. + + Parameters + ---------- + species : string (default: 'guineapig') + A string specifying the species used for scaling. Recognized values are + 'mouse', 'guineapig', and 'cat' (cat is just a larger version of the guineapig) + + modelType : string (default: 'I-II') + A string specifying the version of the model to use. + Current choices are 'I-II' (others need to be implemented) + + silent : boolean (default: True) + Flag for printing debugging information. + + """ + soma = self.soma + celltype = modelType + if species == "mouse": + # use conductance levels from Cao et al., J. Neurophys., 2007. + dataset = "XM13_channels" + self._valid_temperatures = (34.0,) + if self.status["temperature"] is None: + self.set_temperature(34.0) + self.c_m = 0.9 + pars = self.get_cellpars(dataset, species=species, modelType=modelType) + self.set_soma_size_from_Cm(pars.cap) + self.status["na"] = pars.natype + # pars.show() + self.adjust_na_chans(soma, gbar=pars.na_gbar, sf=1.0) + soma().kht.gbar = nstomho(pars.kht_gbar, self.somaarea) + soma().klt.gbar = nstomho(pars.klt_gbar, self.somaarea) + # soma().ka.gbar = nstomho(pars.ka_gbar, self.somaarea) + soma().ihvcn.gbar = nstomho(pars.ihvcn_gbar, self.somaarea) + soma().ihvcn.eh = pars.ih_eh # Rodrigues and Oertel, 2006 + soma().leak.gbar = nstomho(pars.leak_gbar, self.somaarea) + soma().leak.erev = pars.leak_erev + self.e_k = pars.e_k + self.e_na = pars.e_na + soma.ena = self.e_na + soma.ek = self.e_k + # soma().leak.erev = pars.leak_erev + self.axonsf = 0.5 + + elif species == "guineapig": # values from R&M 2003, Type II-I + dataset = "RM03_channels" + self.c_m = 0.9 + self._valid_temperatures = (22.0, 38.0) + if self.status["temperature"] is None: + self.set_temperature(22.0) + sf = 1.0 + if ( + self.status["temperature"] == 38.0 + ): # adjust for 2003 model conductance levels at 38 + sf = 3.03 # Q10 of 2, 22->38C. (p3106, R&M2003c) + self.i_test_range = {"pulse": (-0.3, 0.3, 0.03)} + self.vrange = [-75.0, -55.0] + pars = self.get_cellpars(dataset, species=species, modelType=modelType) + self.set_soma_size_from_Cm(pars.cap) + self.status["na"] = pars.natype + # pars.show() + self.adjust_na_chans(soma, gbar=pars.nacn_gbar, sf=sf) + soma().kht.gbar = nstomho(pars.kht_gbar, self.somaarea) + soma().klt.gbar = nstomho(pars.klt_gbar, self.somaarea) + # soma().ka.gbar = nstomho(pars.ka_gbar, self.somaarea) + soma().ihvcn.gbar = nstomho(pars.ih_gbar, self.somaarea) + soma().leak.gbar = nstomho(pars.leak_gbar, self.somaarea) + soma().leak.erev = pars.leak_erev + self.axonsf = 0.5 + + else: + raise ValueError( + "Species %s or species-modelType %s is not recognized for D-Stellate cells" + % (species, modelType) + ) + self.status["species"] = species + self.status["modelType"] = modelType + self.check_temperature() + # self.cell_initialize(showinfo=False) + if not silent: + print("set cell as: ", species) + print(" with Vm rest = %6.3f" % self.vm0) + + def adjust_na_chans(self, soma, sf=1.0, gbar=1000.0): + """ + adjust the sodium channel conductance + + Parameters + ---------- + soma : soma object (no default) + soma object whose sodium channel complement will have it's + conductances adjusted depending on the channel type + + gbar : float (default: 1000.) + The conductance to be set for the sodium channel + + debug : boolean (default: False) + Flag for printing the conductance value and Na channel model + + Returns + ------- + Nothing + """ + if self.status["ttx"]: + gnabar = 0.0 + else: + gnabar = nstomho(gbar, self.somaarea) * sf + nach = self.status["na"] + if nach == "jsrna": + soma().jsrna.gbar = gnabar + soma.ena = self.e_na + if self.debug: + print("jsrna gbar: ", soma().jsrna.gbar) + elif nach == "nav11": + soma().nav11.gbar = gnabar * 0.5 + soma.ena = self.e_na + soma().nav11.vsna = 4.3 + if self.debug: + print("bushy using inva11") + print("nav11 gbar: ", soma().nav11.gbar) + elif nach == "na": + soma().na.gbar = gnabar + soma.ena = self.e_na + if self.debug: + print("na gbar: ", soma().na.gbar) + elif nach == "nacn": + soma().nacn.gbar = gnabar + soma.ena = self.e_na + if self.debug: + print("nacn gbar: ", soma().nacn.gbar) + else: + raise ValueError( + "Dstellate setting Na channels: channel %s not known" % nach + ) + + def add_axon(self): + """ + Add a default axon from the generic cell class to the bushy cell (see cell class). + """ + Cell.add_axon(self, self.soma, self.somaarea, self.c_m, self.R_a, self.axonsf) + + def add_dendrites(self): + """ + Add simple unbranched dendrites to basic Rothman Type I-II model. + The dendrites have some kht and ih current + """ + cs = False # not implemented outside here - internal Cesium. + nDend = range(4) # these will be simple, unbranced, N=4 dendrites + dendrites = [] + for i in nDend: + dendrites.append(h.Section(cell=self.soma)) + for i in nDend: + dendrites[i].connect(self.soma) + dendrites[i].L = 300 # length of the dendrite (not tapered) + dendrites[i].diam = 1.25 # dendrite diameter + dendrites[i].nseg = 21 # # segments in dendrites + dendrites[i].Ra = 150 # ohm.cm + dendrites[i].insert("kht") + if cs is False: + dendrites[i]().kht.gbar = 0.005 # a little Ht + else: + dendrites[i]().kht.gbar = 0.0 + dendrites[i].insert("leak") # leak + dendrites[i]().leak.gbar = 0.0001 + dendrites[i].insert("ihvcn") # some H current + dendrites[i]().ihvcn.gbar = 0.0 # 0.001 + dendrites[i]().ihvcn.eh = -43.0 + self.maindend = dendrites + self.status["dendrites"] = True + self.add_section(self.maindend, "maindend") + + +class DummyDStellate(DStellate): + """ DStellate class with no cell body; this cell only replays a predetermined + spike train. Useful for testing, or replacing spike trains to determine + the importance of spike structures within a network. + """ + + def __init__(self, cf=None, species="mouse"): + """ + Parameters + ---------- + cf : float (default: None) + Required: the characteristic frequency for the DStellate + Really just for reference. + + """ + + DStellate.__init__(self) + self.vecstim = h.VecStim() + + # this causes the terminal to receive events from the VecStim: + self.spike_source = self.vecstim + + # just an empty section for holding the terminal + self.add_section(h.Section(), "soma") + self.status = { + "soma": True, + "axon": False, + "dendrites": False, + "pumps": False, + "na": None, + "species": species, + "modelType": "Dummy", + "modelName": "DummyDStellate", + "ttx": None, + "name": "DummyDStellate", + "morphology": None, + "decorator": None, + "temperature": None, + } + print("<< DStellate: Dummy DStellate Cell created >>") + + def set_spiketrain(self, times): + """ Set the times of spikes (in seconds) to be replayed by the cell. + """ + self._spiketrain = times + self._stvec = h.Vector(times) + self.vecstim.play(self._stvec) + + +class DStellateEager(DStellate): + """ + This is a model of the VCN D-Stellate cells as proposed by + Eager, M.A., Grayden, D.B., Burkitt, A.N., and Meffin, H., + "A neural circuit model of the ventral cochlear nucleus", + Internet: + http://citeseerx.ist.pus.edu/viewdoc/download?doi=10.1.79.9620.pdf&rep + =rep&type=pdf + also cited as: + Proceedings of the 10th Australian International Conference on + Speech Science and Technology, pp. 539-544, 2004. + It is based on the Rothman and Manis (2003c) model, + with small modifications. + Their model includes dendrites and an axon, which are added in this version + """ + + def __init__( + self, nach="na", ttx=False, species="guineapig", modelType="I-II", debug=False + ): + """ + Initialize the VCN D-stellate model of Eager et al. Some model parameters may be modified. + + Parameters + ---------- + nach : string (default: 'na') + Set the sodium channel model. Choices are 'na', 'nav11', 'jsrna' + + ttx : boolean (default: False) + ttx sets the sodium channel conductance to 0 + + species : string (default: 'guineapig') + species to use for conductance scaling + + modelType : string (default: 'I-II') + RM03 model type to use for conductances. + + debug : boolean (default: False) + Flag to use to enable print statements for debugging purposes. + + """ + super(DStellateEager, self).__init__() + + self.status = { + "soma": True, + "axon": False, + "dendrites": False, + "pumps": False, + "na": nach, + "species": species, + "modelType": modelType, + "ttx": ttx, + "name": "DStellateEager", + } + self.i_test_range = (-0.25, 0.25, 0.025) # set range for ic command test + + soma = h.Section(name="DStellateEager_Soma_%x" % id(self)) # one compartment + + soma.nseg = 1 + + if nach in ["nacn", "na"]: + soma.insert("na") + elif nach == "nav11": + soma.insert("nav11") + elif nach == "jsrna": + soma.insert("jsrna") + else: + raise ValueError("Sodium channel %s in type 1 cell not known" % nach) + self.debug = debug + soma.insert("kht") + soma.insert("klt") + soma.insert("ihvcn") + soma.insert("leak") + soma.ek = self.e_k + soma().leak.erev = self.e_leak + self.mechanisms = ["kht", "klt", "ihvcn", "leak", nach] + self.add_section(soma, "soma") + self.species_scaling( + silent=False, species=species, modelType=modelType + ) # set the default type II cell parameters + self.add_axon() # must follow species scaling so that area parameters are available + self.add_dendrites() # similar for dendrites + self.save_all_mechs() # save all mechanisms inserted, location and gbar values... + self.get_mechs(soma) + + if self.debug: + print("<< D-stellateEager: Eager DStellate Type I-II cell model created >>") + + def species_scaling(self, species="guineapig", modelType="I-II", silent=True): + """ + Adjust all of the conductances and the cell size according to the species requested. + + Parameters + ---------- + species : string (default: 'guineapig') + A string specifying the species used for scaling. Recognized values are + 'mouse', 'guineapig', and 'cat' (cat is just a larger version of the guineapig) + + modelType : string (default: 'I-II') + A string specifying the version of the model to use. + Current choices are 'I-II' (others need to be implemented) + + silent : boolean (default: True) + Flag for printing debugging information. + + """ + soma = self.soma + if species == "mouse" and modelType == "I-II": + # use conductance levels from Cao et al., J. Neurophys., 2007. + self.set_soma_size_from_Cm(25.0) + self.adjust_na_chans(soma, gbar=800.0) + soma().kht.gbar = nstomho(150.0, self.somaarea) + soma().klt.gbar = nstomho(20.0, self.somaarea) + soma().ihvcn.gbar = nstomho(2.0, self.somaarea) + soma().ihvcn.eh = -43 # Rodrigues and Oertel, 2006 + soma().leak.gbar = nstomho(2.0, self.somaarea) + self.axonsf = 0.5 + elif ( + species == "guineapig" and modelType == "I-II" + ): # values from R&M 2003, Type II-I + self.set_soma_size_from_Diam(25.0) + self.adjust_na_chans(soma, gbar=1000.0 * 0.75) + soma().kht.gbar = 0.02 # nstomho(150.0, self.somaarea) + soma().klt.gbar = 0.005 # nstomho(20.0, self.somaarea) + soma().ihvcn.gbar = 0.0002 # nstomho(2.0, self.somaarea) + soma().leak.gbar = 0.0005 # nstomho(2.0, self.somaarea) + self.axonsf = 1.0 + elif ( + species == "cat" and modelType == "I=II" + ): # a cat is a big guinea pig Type I + self.set_soma_size_from_Cm(35.0) + self.adjust_na_chans(soma) + soma().kht.gbar = nstomho(150.0, self.somaarea) + soma().klt.gbar = nstomho(20.0, self.somaarea) + soma().ihvcn.gbar = nstomho(2.0, self.somaarea) + soma().leak.gbar = nstomho(2.0, self.somaarea) + self.axonsf = 1.0 + else: + raise ValueError( + "Species %s or species-type %s is not recognized for D-StellateEager cells" + % (species, type) + ) + self.status["species"] = species + self.status["type"] = modelType + self.cell_initialize(showinfo=True) + if not silent: + print(" set cell as: ", species) + print(" with Vm rest = %6.3f" % self.vm0) + + def adjust_na_chans(self, soma, gbar=1000.0): + """ + adjust the sodium channel conductance + + Parameters + ---------- + soma : soma object (no default) + soma object whose sodium channel complement will have it's + conductances adjusted depending on the channel type + + gbar : float (default: 1000.) + The conductance to be set for the sodium channel + + Returns + ------- + Nothing + """ + + if self.status["ttx"]: + gnabar = 0.0 + else: + gnabar = nstomho(gbar, self.somaarea) + nach = self.status["na"] + if nach == "jsrna": + soma().jsrna.gbar = gnabar + soma.ena = self.e_na + if self.debug: + print("using jsrna with gbar: ", soma().jsrna.gbar) + elif nach == "nav11": + soma().nav11.gbar = gnabar * 0.5 + soma.ena = self.e_na + soma().nav11.vsna = 4.3 + if self.debug: + print("using inva11 with gbar:", soma().na.gbar) + print("nav11 gbar: ", soma().nav11.gbar) + elif nach == "na": + soma().na.gbar = gnabar + soma.ena = self.e_na + if self.debug: + print("using na with gbar: ", soma().na.gbar) + elif nach == "nach": + soma().nach.gbar = gnabar + soma.ena = self.e_na + if self.debug: + print(("uwing nacn with gbar: ", soma().nacn.gbar)) + else: + raise ValueError( + "DstellateEager setting Na channels: channel %s not known" % nach + ) + # print soma().na.gbar + + def add_axon(self): + """ + Adds an axon to the Eager. et al model + Cell.add_axon(self, nodes=1, c_m=self.c_m, R_a=self.R_a, axonsf=self.axonsf, dia=3.0, len=70, seg=2) + The Eager et al model just uses one cable, 70 microns long and 3 microns in dameter. + + Parameters + ---------- + None + + Returns + ------- + Nothing + """ + + naxons = 1 + axon = [] + for i in range(naxons): + axon.append(h.Section(cell=self.soma)) + for i in range(naxons): + axon[i].connect(self.soma) + axon[i].L = 70 + axon[i].diam = 3.0 + axon[i].Ra = 500 + axon[i].cm = 0.9 + axon[i].nseg = 2 + axon[i].insert("kht") + axon[i].insert("klt") + axon[i].insert("ihvcn") + axon[i].insert("leak") + axon[i].insert("na") + axon[i].ek = self.e_k + axon[i].ena = self.e_na + axon[i]().leak.erev = self.e_leak + axon[i]().na.gbar = 0.5 + axon[i]().klt.gbar = 0.005 + axon[i]().kht.gbar = 0.02 + axon[i]().ihvcn.gbar = 0.0002 + axon[i]().leak.gbar = 0.0005 + self.status["axon"] = True + self.add_section(axon, "axon") + + def add_dendrites(self): + """ + Adds dendrites to the Eager model. The Eager model uses simple passive dendrites. + + Parameters + ---------- + None + + Returns + ------- + Nothing + """ + + nDend = range(2) # these will be simple, unbranced, N=4 dendrites + dendrites = [] + for i in nDend: + dendrites.append(h.Section(cell=self.soma)) + for i in nDend: + dendrites[i].connect(self.soma) + dendrites[i].L = 1100 # length of the dendrite (not tapered) + dendrites[i].diam = 3.5 # dendrite diameter + dendrites[i].nseg = 5 # # segments in dendrites + dendrites[i].Ra = 1500 # ohm.cm + dendrites[i].insert("leak") # leak + dendrites[i]().leak.gbar = 0.00025 + dendrites[i]().leak.erev = self.e_leak + self.maindend = dendrites + self.status["dendrites"] = True + self.add_section(self.maindend, "maindend") diff --git a/cnmodel/cells/hh.py b/cnmodel/cells/hh.py new file mode 100644 index 0000000..3d12718 --- /dev/null +++ b/cnmodel/cells/hh.py @@ -0,0 +1,47 @@ +from __future__ import print_function +from neuron import h +import neuron as nrn +from ..util import nstomho + +from .cell import Cell + +__all__ = ["HH"] + + +class HH(Cell): + """ + Standard Hodgkin-Huxley mechanisms from NEURON + """ + + def __init__(self, debug=False, message=None): + super(HH, self).__init__() + + soma = h.Section( + name="HH_Soma_%x" % id(self) + ) # one compartment of about 29000 um2 + v_potassium = -80 # potassium reversal potential + v_sodium = 50 # sodium reversal potential + c_m = 1.0 + scalefactor = 1.0 # This determines the relative size of the cell + rinsf = 1.0 # input resistance adjustment (also current...) + totcap = 20.0 # scalefactor * 1.0 # cap in pF for cell + effcap = totcap # sometimes we change capacitance - that's effcap + somaarea = totcap * 1e-6 / c_m # pf -> uF, cm = 1uf/cm^2 nominal + lstd = 1e4 * ((somaarea / 3.14159) ** 0.5) # convert from cm to um + + soma.nseg = 1 + soma.diam = lstd + soma.L = lstd + + seg = soma + seg.insert("hh") + seg.insert("pas") + if debug: + if message is None: + print("<< Standard HH model created >>") + else: + print(message) + + self.add_section(soma, "soma") + + self.vm0 = -67.536 diff --git a/cnmodel/cells/msoprincipal.py b/cnmodel/cells/msoprincipal.py new file mode 100644 index 0000000..3e43685 --- /dev/null +++ b/cnmodel/cells/msoprincipal.py @@ -0,0 +1,516 @@ +from __future__ import print_function +from neuron import h + +from .cell import Cell + +# from .. import synapses +from ..util import nstomho +from ..util import Params +import numpy as np +from .. import data + +__all__ = ["MSO"] + + +class MSO(Cell): + + type = "mso" + + @classmethod + def create(cls, model="MSO-principal", **kwds): + if model == "MSO-principal": + return MSOPrincipal(**kwds) + else: + raise ValueError("MSO cell model %s is unknown", model) + + def make_psd(self, terminal, psd_type, **kwds): + """ + Connect a presynaptic terminal to one post section at the specified location, with the fraction + of the "standard" conductance determined by gbar. + The default condition is designed to pass the unit test (loc=0.5) + + Parameters + ---------- + terminal : Presynaptic terminal (NEURON object) + + psd_type : either simple or multisite PSD for MSO cell + + kwds: dictionary of options. + Two are currently handled: + postsite : expect a list consisting of [sectionno, location (float)] + AMPAScale : float to scale the ampa currents + + """ + if ( + "postsite" in kwds + ): # use a defined location instead of the default (soma(0.5) + postsite = kwds["postsite"] + loc = postsite[1] # where on the section? + uname = ( + "sections[%d]" % postsite[0] + ) # make a name to look up the neuron section object + post_sec = self.hr.get_section(uname) # Tell us where to put the synapse. + else: + loc = 0.5 + post_sec = self.soma + + if psd_type == "simple": + return self.make_exp2_psd(post_sec, terminal, loc=loc) + elif psd_type == "multisite": + if terminal.cell.type == "bushy": + # Max conductances for the glu mechanisms are calibrated by + # running `synapses/tests/test_psd.py`. The test should fail + # if these values are incorrect + self.AMPAR_gmax = ( + data.get( + "bushy_synapse", + species=self.species, + post_type=self.type, + field="AMPAR_gmax", + ) + * 1e3 + ) + self.NMDAR_gmax = ( + data.get( + "bushy_synapse", + species=self.species, + post_type=self.type, + field="NMDAR_gmax", + ) + * 1e3 + ) + self.Pr = data.get( + "bushy_synapse", + species=self.species, + post_type=self.type, + field="Pr", + ) + # adjust gmax to correct for initial Pr + self.AMPAR_gmax = self.AMPAR_gmax / self.Pr + self.NMDAR_gmax = self.NMDAR_gmax / self.Pr + if "AMPAScale" in kwds: # normally, this should not be done! + self.AMPAR_gmax = ( + self.AMPAR_gmax * kwds["AMPAScale"] + ) # allow scaling of AMPA conductances + if "NMDAScale" in kwds: + self.NMDAR_gmax = self.NMDAR_gmax * kwds["NMDAScale"] # and NMDA... + return self.make_glu_psd( + post_sec, terminal, self.AMPAR_gmax, self.NMDAR_gmax, loc=loc + ) + else: + raise TypeError( + "Cannot make PSD for %s => %s" % (terminal.cell.type, self.type) + ) + else: + raise ValueError("Unsupported psd type %s" % psd_type) + + +class MSOPrincipal(MSO): + """ + VCN MSO cell models. + Using Rothman and Manis, 2003abc (Type II) + MSO principal cell type + """ + + def __init__( + self, + morphology=None, + decorator=None, + nach=None, + ttx=False, + species="guineapig", + modelType=None, + debug=False, + temperature=None, + ): + """ + Create a MSO principal cell, using the default parameters for guinea pig from + R&M2003, as a type II cell. + Additional modifications to the cell can be made by calling methods below. + + Parameters + ---------- + morphology : string (default: None) + Name of a .hoc file representing the morphology. This file is used to constructe + an electrotonic (cable) model. + If None (default), then a "point" (really, single cylinder) model is made, exactly according to RM03. + + decorator : Python function (default: None) + decorator is a function that "decorates" the morphology with ion channels according + to a set of rules. + If None, a default set of channels is inserted into the first soma section, and the + rest of the structure is "bare". + + nach : string (default: None) + nach selects the type of sodium channel that will be used in the model. A channel mechanism + by that name must exist. The default channel is set to 'nacn' (R&M03) + + temperature : float (default: 22) + temperature to run the cell at. + + ttx : Boolean (default: False) + If ttx is True, then the sodium channel conductance is set to 0 everywhere in the cell. + This flag duplicates the effects of tetrodotoxin in the model. Currently, the flag is not implemented. + + temperature : float (default: None, sets to model default of 22) + temperature (deg C) to run the cell at. Must be a valid temperature for the model. + + species: string (default 'guineapig') + species defines the pattern of ion channel densities that will be inserted, according to + prior measurements in various species. Note that + if a decorator function is specified, this argument is ignored as the decorator will + specify the channel density. + + modelType: string (default: None) + modelType specifies the subtype of the cell model that will be used (e.g., "II", "II-I", etc). + modelType is passed to the decorator, or to species_scaling to adjust point (single cylinder) models. + + debug: boolean (default: False) + When True, there will be multiple printouts of progress and parameters. + + Returns + ------- + Nothing + + """ + super(MSO, self).__init__() + self.i_test_range = { + "pulse": (-1, 1, 0.05) + } # note that this gets reset with decorator according to channels + # Changing the default values will cause the unit tests to fail! + if modelType == None: + modelType = "principal" + if nach == None and species == "guineapig": + nach = "na" + if nach == None and species == "mouse": + nach = "na" + self.i_test_range = {"pulse": (-1, 1.2, 0.05)} + + self.status = { + "soma": True, + "axon": False, + "dendrites": False, + "pumps": False, + "hillock": False, + "initialsegment": False, + "myelinatedaxon": False, + "unmyelinatedaxon": False, + "na": nach, + "species": species, + "modelType": modelType, + "ttx": ttx, + "name": "MSO", + "morphology": morphology, + "decorator": decorator, + "temperature": temperature, + } + + self.spike_threshold = -40 + self.vrange = [-70.0, -55.0] # set a default vrange for searching for rmp + print("model type, species: ", modelType, species, nach) + if morphology is None: + """ + instantiate a basic soma-only ("point") model + """ + print("<< MSO model: Creating point principal cell >>") + soma = h.Section( + name="MSO_Soma_%x" % id(self) + ) # one compartment of about 29000 um2 + soma.nseg = 1 + self.add_section(soma, "soma") + else: + """ + instantiate a structured model with the morphology as specified by + the morphology file + """ + print( + "<< MSO principal cell model: Creating cell with morphology from %s >>" + % morphology + ) + self.set_morphology(morphology_file=morphology) + + # decorate the morphology with ion channels + if decorator is None: # basic model, only on the soma + self.mechanisms = ["klt", "kht", "ihvcn", "leak", nach] + for mech in self.mechanisms: + self.soma.insert(mech) + self.soma.ena = self.e_na + self.soma.ek = self.e_k + self.soma().ihvcn.eh = self.e_h + self.soma().leak.erev = self.e_leak + self.c_m = 0.9 + self.species_scaling( + silent=True, species=species, modelType=modelType + ) # set the default type II cell parameters + else: # decorate according to a defined set of rules on all cell compartments + self.decorate() + self.save_all_mechs() # save all mechanisms inserted, location and gbar values... + self.get_mechs(self.soma) + + if debug: + print(" << Created cell >>") + + def get_cellpars(self, dataset, species="guineapig", celltype="principal"): + cellcap = data.get( + dataset, species=species, cell_type=celltype, field="soma_Cap" + ) + chtype = data.get( + dataset, species=species, cell_type=celltype, field="soma_na_type" + ) + pars = Params(cap=cellcap, natype=chtype) + for g in ["soma_kht_gbar", "soma_klt_gbar", "soma_ih_gbar", "soma_leak_gbar"]: + pars.additem( + g, data.get(dataset, species=species, cell_type=celltype, field=g) + ) + return pars + + def species_scaling(self, species="guineapig", modelType="principal", silent=True): + """ + Adjust all of the conductances and the cell size according to the species requested. + This scaling should be used ONLY for point models, as no other compartments + are scaled. + + This scaling routine also sets the temperature for the model to a default value. Some models + can be run at multiple temperatures, and so a default from one of the temperatures is used. + The calling cell.set_temperature(newtemp) will change the conductances and reinitialize + the cell to the new temperature settings. + + Parameters + ---------- + species : string (default: 'guineapig') + name of the species to use for scaling the conductances in the base point model + Must be one of mouse, cat, guineapig + + modelType: string (default: 'principal') + definition of model type from RM03 models, principal cell for mso + + silent : boolean (default: True) + run silently (True) or verbosely (False) + + """ + # print '\nSpecies scaling: %s %s' % (species, type) + knownspecies = ["guineapig"] + + soma = self.soma + if modelType == "principal": + celltype = ( + "MSO-principal" + ) # There are other possiblities in the literature - this is just the main one + else: + raise ValueError("model type not recognized") + + if species == "guineapig": + print( + " Setting conductances for guinea pig %s MSO cell, based on Rothman and Manis, 2003 bushy cell" + % modelType + ) + self._valid_temperatures = (22.0, 38.0) + if self.status["temperature"] is None: + self.status["temperature"] = 22.0 + self.i_test_range = {"pulse": (-0.4, 0.4, 0.02)} + sf = 1.0 + if ( + self.status["temperature"] == 38.0 + ): # adjust for 2003 model conductance levels at 38 + sf = 2 # Q10 of 2, 22->38C. (p3106, R&M2003c) + # note that kinetics are scaled in the mod file. + dataset = "MSO_principal_channels" + pars = self.get_cellpars(dataset, species=species, celltype=celltype) + self.set_soma_size_from_Cm(pars.cap) + self.status["na"] = pars.natype + self.adjust_na_chans(soma, sf=sf) + soma().kht.gbar = nstomho(pars.soma_kht_gbar, self.somaarea) + soma().klt.gbar = nstomho(pars.soma_klt_gbar, self.somaarea) + soma().ihvcn.gbar = nstomho(pars.soma_ih_gbar, self.somaarea) + soma().leak.gbar = nstomho(pars.soma_leak_gbar, self.somaarea) + + self.axonsf = 0.57 + + else: + errmsg = ( + 'Species "%s" or model type "%s" is not recognized for MSO cells.' + % (species, modelType) + ) + errmsg += "\n Valid species are: \n" + for s in knownspecies: + errmsg += " %s\n" % s + errmsg += "-" * 40 + raise ValueError(errmsg) + + self.status["species"] = species + self.status["modelType"] = modelType + self.check_temperature() + # self.cell_initialize(vrange=self.vrange) # no need to do this just yet. + if not silent: + print(" set cell as: ", species) + print(" with Vm rest = %6.3f" % self.vm0) + + def channel_manager(self, modelType="MSO-principal"): + """ + This routine defines channel density maps and distance map patterns + for each type of compartment in the cell. The maps + are used by the ChannelDecorator class (specifically, its private + \_biophys function) to decorate the cell membrane. + These settings are only used if the decorator is called; otherwise + for point cells, the species_scaling routine defines the channel + densities. + + Parameters + ---------- + modelType : string (default: 'RM03') + A string that defines the type of the model. Currently, only 1 type is implemented: + RM03: Rothman and Manis, 2003 somatic densities based on guinea pig bushy cell + + Returns + ------- + Nothing + + Notes + ----- + This routine defines the following variables for the class: + + * conductances (gBar) + * a channelMap (dictonary of channel densities in defined anatomical compartments) + * a current injection range for IV's (used for testing) + * a distance map, which defines how each conductance in a selected compartment + changes with distance from the soma. The current implementation includes both + linear and exponential gradients, + the minimum conductance at the end of the gradient, and the space constant or + slope for the gradient. + + """ + + self.c_m = 1e-6 # default in units of F/cm^2 + if modelType == "MSO-principal": + # + # Create a model based on the Rothman and Manis 2003 conductance set from guinea pig + # + self.c_m = 0.9e-6 # default in units of F/cm^2 + totcap = 12.0e-12 # in units of F, from Rothman and Manis, 2003. + refarea = totcap / self.c_m # area is in cm^2 + # MSO Rothman-Manis, guinea pig type II + # model gave cell conductance in nS, but we want S/cm^2 for NEURON + # so conversion is 1e-9*nS = uS, and refarea is already in cm2 + self._valid_temperatures = (22.0, 38.0) + sf = 1.0 + if self.status["temperature"] == None: + self.status["temperature"] = 22.0 + if self.status["temperature"] == 38: + sf = 3.03 + self.gBar = Params( + nabar=sf * 1000.0e-9 / refarea, + khtbar=sf * 150.0e-9 / refarea, + kltbar=sf * 200.0e-9 / refarea, + ihbar=sf * 20.0e-9 / refarea, + leakbar=sf * 2.0e-9 / refarea, + ) + print("MSO principal channels gbar:\n", self.gBar.show()) + + self.channelMap = { + "axon": { + "nacn": self.gBar.nabar, + "klt": self.gBar.kltbar, + "kht": self.gBar.khtbar, + "ihvcn": 0.0, + "leak": self.gBar.leakbar / 2.0, + }, + "hillock": { + "nacn": self.gBar.nabar, + "klt": self.gBar.kltbar, + "kht": self.gBar.khtbar, + "ihvcn": 0.0, + "leak": self.gBar.leakbar, + }, + "initseg": { + "nacn": self.gBar.nabar, + "klt": self.gBar.kltbar, + "kht": self.gBar.khtbar, + "ihvcn": self.gBar.ihbar / 2.0, + "leak": self.gBar.leakbar, + }, + "soma": { + "nacn": self.gBar.nabar, + "klt": self.gBar.kltbar, + "kht": self.gBar.khtbar, + "ihvcn": self.gBar.ihbar, + "leak": self.gBar.leakbar, + }, + "dend": { + "nacn": self.gBar.nabar, + "klt": self.gBar.kltbar * 0.5, + "kht": self.gBar.khtbar * 0.5, + "ihvcn": self.gBar.ihbar / 3.0, + "leak": self.gBar.leakbar * 0.5, + }, + "apic": { + "nacn": self.gBar.nabar, + "klt": self.gBar.kltbar * 0.2, + "kht": self.gBar.khtbar * 0.2, + "ihvcn": self.gBar.ihbar / 4.0, + "leak": self.gBar.leakbar * 0.2, + }, + } + # self.irange = np.linspace(-1., 1., 21) + self.distMap = { + "dend": { + "klt": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "kht": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "nacn": {"gradient": "exp", "gminf": 0.0, "lambda": 100.0}, + }, # linear with distance, gminf (factor) is multiplied by gbar + "apic": { + "klt": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "kht": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "nacn": {"gradient": "exp", "gminf": 0.0, "lambda": 100.0}, + }, # gradients are: flat, linear, exponential + } + + else: + raise ValueError("model type %s is not implemented" % modelType) + self.check_temperature() + + def adjust_na_chans(self, soma, sf=1.0, gbar=1000.0, debug=False): + """ + adjust the sodium channel conductance + + Parameters + ---------- + soma : neuron section object + A soma object whose sodium channel complement will have its + conductances adjusted depending on the channel type + + gbar : float (default: 1000.) + The maximal conductance for the sodium channel + + debug : boolean (false): + Verbose printing + + Returns + ------- + Nothing : + + """ + + if self.status["ttx"]: + gnabar = 0.0 + else: + gnabar = nstomho(gbar, self.somaarea) * sf + nach = self.status["na"] + if nach == "jsrna": + soma().jsrna.gbar = gnabar + soma.ena = self.e_na + if debug: + print("jsrna gbar: ", soma().jsrna.gbar) + elif nach == "nav11": + soma().nav11.gbar = gnabar + soma.ena = 50 # self.e_na + # print('gnabar: ', soma().nav11.gbar, ' vs: 0.0192307692308') + soma().nav11.vsna = 4.3 + if debug: + print("MSO using inva11") + elif nach in ["na", "nacn"]: + soma().na.gbar = gnabar + soma.ena = self.e_na + if debug: + print("na gbar: ", soma().na.gbar) + else: + raise ValueError("Sodium channel %s is not recognized for MSO cells", nach) diff --git a/cnmodel/cells/octopus.py b/cnmodel/cells/octopus.py new file mode 100644 index 0000000..3d2d7bc --- /dev/null +++ b/cnmodel/cells/octopus.py @@ -0,0 +1,718 @@ +from __future__ import print_function +from neuron import h +from ..util import nstomho +from ..util import Params +import numpy as np +from .cell import Cell +from .. import data + +""" +Original hoc code from RMmodel.hoc +// including the "Octopus" cell: +proc set_Type2o() { + gbar_na = nstomho(1000) + gbar_kht = nstomho(150) + gbar_klt = nstomho(600) + gbar_ka = nstomho(0) + gbar_ih = nstomho(0) + gbar_hcno = nstomho(40) + gbar_leak = nstomho(2) + model = 6 + modelname = "Type IIo (Octopus)" + vm0 = -66.67 +} + +""" + +__all__ = ["Octopus", "OctopusRothman", "OctopusSpencer"] + + +class Octopus(Cell): + + type = "octopus" + + @classmethod + def create(cls, modelType="RM03", **kwds): + if modelType in ["RM03", "II-o"]: + return OctopusRothman(**kwds) + elif modelType == "Spencer": + return OctopusSpencer(**kwds) + else: + raise ValueError("Octopus cell type %s is unknown" % modelType) + + def make_psd(self, terminal, psd_type, **kwds): + """ + Connect a presynaptic terminal to one post section at the specified location, with the fraction + of the "standard" conductance determined by gbar. + The default condition is to try to pass the default unit test (loc=0.5) + + Parameters + ---------- + terminal : Presynaptic terminal (NEURON object) + + psd_type : either simple or multisite PSD for bushy cell + + kwds: dict of options. Two are currently handled: + postsize : expect a list consisting of [sectionno, location (float)] + AMPAScale : float to scale the ampa currents + + """ + if ( + "postsite" in kwds + ): # use a defined location instead of the default (soma(0.5) + postsite = kwds["postsite"] + loc = postsite[1] # where on the section? + uname = ( + "sections[%d]" % postsite[0] + ) # make a name to look up the neuron section object + post_sec = self.hr.get_section(uname) # Tell us where to put the synapse. + else: + loc = 0.5 + post_sec = self.soma + + if psd_type == "simple": + if terminal.cell.type in ["sgc"]: + weight = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="weight", + ) + tau1 = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="tau1", + ) + tau2 = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="tau2", + ) + erev = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="erev", + ) + return self.make_exp2_psd( + post_sec, + terminal, + weight=weight, + loc=loc, + tau1=tau1, + tau2=tau2, + erev=erev, + ) + else: + raise TypeError( + "Cannot make simple PSD for %s => %s" + % (terminal.cell.type, self.type) + ) + + elif psd_type == "multisite": + if terminal.cell.type == "sgc": + # Max conductances for the glu mechanisms are calibrated by + # running `synapses/tests/test_psd.py`. The test should fail + # if these values are incorrect + self.AMPAR_gmax = ( + data.get( + "sgc_synapse", + species=self.species, + post_type=self.type, + field="AMPAR_gmax", + ) + * 1e3 + ) + self.NMDAR_gmax = ( + data.get( + "sgc_synapse", + species=self.species, + post_type=self.type, + field="NMDAR_gmax", + ) + * 1e3 + ) + self.Pr = data.get( + "sgc_synapse", species=self.species, post_type=self.type, field="Pr" + ) + # adjust gmax to correct for initial Pr + self.AMPAR_gmax = self.AMPAR_gmax / self.Pr + self.NMDAR_gmax = self.NMDAR_gmax / self.Pr + # AMPA_gmax = 3.314707700918133*1e3 # factor of 1e3 scales to pS (.mod mechanisms) from nS. + # NMDA_gmax = 0.4531929783503451*1e3 + if "AMPAScale" in kwds: + self.AMPAR_gmax = ( + self.AMPAR_gmax * kwds["AMPAScale"] + ) # allow scaling of AMPA conductances + if "NMDAScale" in kwds: + self.NMDAR_gmax = self.NMDAR_gmax * kwds["NMDAScale"] + return self.make_glu_psd( + post_sec, terminal, self.AMPAR_gmax, self.NMDAR_gmax, loc=loc + ) + elif terminal.cell.type == "dstellate": + return self.make_gly_psd(post_sec, terminal, psdtype="glyslow", loc=loc) + else: + raise TypeError( + "Cannot make PSD for %s => %s" % (terminal.cell.type, self.type) + ) + else: + raise ValueError("Unsupported psd type %s" % psd_type) + + +class OctopusRothman(Octopus, Cell): + """ + VCN octopus cell model (point cell). + Rothman and Manis, 2003abc (Type II, with high gklt and hcno - octopus cell h current). + """ + + def __init__( + self, + morphology=None, + decorator=None, + nach=None, + ttx=False, + species="guineapig", + modelType=None, + debug=False, + ): + """ + initialize the octopus cell, using the default parameters for guinea pig from + R&M2003, as a type II cell with modified conductances. + Modifications to the cell can be made by calling methods below. + + Parameters + ---------- + morphology : string (default: None) + a file name to read the cell morphology from. If a valid file is found, a cell is constructed + as a cable model from the hoc file. + If None (default), the only a point model is made, exactly according to RM03. + + decorator : Python function (default: None) + decorator is a function that "decorates" the morphology with ion channels according + to a set of rules. + If None, a default set of channels aer inserted into the first soma section, and the + rest of the structure is "bare". + + nach : string (default: None) + nach selects the type of sodium channel that will be used in the model. A channel mechanism + by that name must exist. None implies the default channel (jsrna for this model). + + ttx : Boolean (default: False) + If ttx is True, then the sodium channel conductance is set to 0 everywhere in the cell. + Currently, this is not implemented. + + species: string (default 'guineapig') + species defines the channel density that will be inserted for different models. Note that + if a decorator function is specified, this argument is ignored. + + modelType: string (default: None) + modelType specifies the type of the model that will be used (e.g., "II", "II-I", etc). + modelType is passed to the decorator, or to species_scaling to adjust point models. + + debug: boolean (default: False) + debug is a boolean flag. When set, there will be multiple printouts of progress and parameters. + + Returns + ------- + Nothing + """ + + super(OctopusRothman, self).__init__() + if modelType == None: + modelType = "II-o" + if nach == None and species == "guineapig": + nach = "jsrna" + if nach == None and species == "mouse": + nach = "nacn" + self.status = { + "soma": True, + "axon": False, + "dendrites": False, + "pumps": False, + "na": nach, + "species": species, + "modelType": modelType, + "ttx": ttx, + "name": "Octopus", + "morphology": morphology, + "decorator": decorator, + "temperature": None, + } + self.i_test_range = {"pulse": (-4.0, 4.0, 0.2)} + self.spike_threshold = -50 + self.vrange = [-70.0, -57.0] # set a default vrange for searching for rmp + + if morphology is None: + """ + instantiate a basic soma-only ("point") model + """ + soma = h.Section( + name="Octopus_Soma_%x" % id(self) + ) # one compartment of about 29000 um2 + soma.nseg = 1 + self.add_section(soma, "soma") + else: + """ + instantiate a structured model with the morphology as specified by + the morphology file + """ + self.set_morphology(morphology_file=morphology) + + # decorate the morphology with ion channels + if decorator is None: # basic model, only on the soma + self.e_leak = -73.0 # from McGinley et al., 2016 + self.e_h = -38.0 # from McGinley et al. + self.R_a = 195 # McGinley et al. + if self.status["species"] == "mouse": + self.mechanisms = ["klt", "kht", "hcnobo", "leak", nach] + else: + self.mechanisms = ["klt", "kht", "ihvcn", "leak", nach] + for mech in self.mechanisms: + self.soma.insert(mech) + self.soma.ek = self.e_k + self.soma.ena = self.e_na + if self.status["species"] == "mouse": + self.soma().hcnobo.eh = self.e_h + else: + self.soma().ihvcn.eh = self.e_h + self.soma().leak.erev = self.e_leak + self.soma.Ra = self.R_a + self.species_scaling( + silent=True, species=species, modelType=modelType + ) # set the default type II cell parameters + else: # decorate according to a defined set of rules on all cell compartments + self.decorate() + self.save_all_mechs() # save all mechanisms inserted, location and gbar values... + self.get_mechs(self.soma) + + if debug: + print("<< octopus: octopus cell model created >>") + # print 'Cell created: ', self.status + + def species_scaling(self, species="guineapig", modelType="II-o", silent=True): + """ + Adjust all of the conductances and the cell size according to the species requested. + Used ONLY for point models. + + Parameters + ---------- + species : string (default: 'guineapig') + name of the species to use for scaling the conductances in the base point model + Must be guineapig + + modelType: string (default: 'II-o') + definition of model type from RM03 models, currently limited to type II-o + + silent : boolean (default: True) + run silently (True) or verbosely (False) + """ + soma = self.soma + + if species == "guineapig" and modelType == "II-o": + self.c_m = 0.9 + self.set_soma_size_from_Cm(25.0) + self._valid_temperatures = (22.0, 38.0) + if self.status["temperature"] is None: + self.set_temperature(22.0) + sf = 1.0 + if ( + self.status["temperature"] == 38.0 + ): # adjust for 2003 model conductance levels at 38 + sf = 3.03 # Q10 of 2, 22->38C. (p3106, R&M2003c) + # note that kinetics are scaled in the mod file. + # self.print_soma_info() + self.adjust_na_chans(soma, sf=sf) + soma().kht.gbar = sf * nstomho(150.0, self.somaarea) # 6.1 mmho/cm2 + soma().klt.gbar = sf * nstomho( + 1000.0, self.somaarea + ) # 40.7 mmho/cm2 3195? + soma().ihvcn.gbar = sf * nstomho( + 30.0, self.somaarea + ) # 7.6 mmho/cm2, cf. Bal and Oertel, Spencer et al. 25 u dia cell 40ns? + soma().leak.gbar = sf * nstomho(2.0, self.somaarea) + self.axonsf = 1.0 + elif species == "mouse" and modelType == "II-o": + self.set_soma_size_from_Cm(25.0) + self._valid_temperatures = (34.0,) + if self.status["temperature"] is None: + self.set_temperature(34.0) + # self.print_soma_info() + self.adjust_na_chans(soma, gbar=3000.0) + soma().kht.gbar = nstomho(150.0, self.somaarea) # 6.1 mmho/cm2 + soma().klt.gbar = nstomho(3196.0, self.somaarea) # 40.7 mmho/cm2 + soma().hcnobo.gbar = nstomho( + 40.0, self.somaarea + ) # 7.6 mmho/cm2, cf. Bal and Oertel, Spencer et al. 25 u dia cell + soma().leak.gbar = nstomho(2.0, self.somaarea) + self.axonsf = 1.0 + else: + raise ValueError( + 'Species "%s" or species-type "%s" is not recognized for octopus cells' + % (species, type) + ) + self.status["species"] = species + self.status["modelType"] = modelType + # self.cell_initialize(showinfo=True) + self.check_temperature() + if not silent: + print("set cell as: ", species) + print(" with Vm rest = %6.3f" % self.vm0) + + def adjust_na_chans(self, soma, sf=1.0, gbar=1000.0, debug=False): + """ + adjust the sodium channel conductance + + Parameters + ---------- + soma : neuron section object + a soma object whose sodium channel complement will have it's + conductances adjusted depending on the channel type + + gbar : float (default: 1000.) + the maximal conductance for the sodium channel + + debug : boolean (false): + verbose printing + + Returns + ------- + Nothing + """ + + if self.status["ttx"]: + gnabar = 0.0 + else: + gnabar = sf * nstomho(gbar, self.somaarea) # mmho/cm2 - 4244.1 moh - 4.2441 + nach = self.status["na"] + if nach == "jsrna": + soma().jsrna.gbar = gnabar + soma.ena = self.e_na + if debug: + print("octopus using jsrna, gbar: ", soma().jsrna.gbar) + elif nach == "nav11": + soma().nav11.gbar = gnabar + soma.ena = self.e_na + soma().nav11.vsna = 4.3 + if debug: + print("octopus using inva11, gbar:", soma().nav11.gbar) + elif nach in ["na", "nacn"]: + soma().nacn.gbar = gnabar + soma.ena = self.e_na + if debug: + print("octopus cell using na/nacn, gbar: ", soma().na.gbar) + else: + raise ValueError( + "Sodium channel %s is not recognized for octopus cells", nach + ) + + +class OctopusSpencer(Octopus, Cell): + """ + VCN octopus cell model (with dendrites). + Based on Spencer et al Front. Comput. Neurosci., 22 October 2012 + https://doi.org/10.3389/fncom.2012.00083 + """ + + def __init__( + self, + morphology=None, + decorator=None, + nach="jsrna", + ttx=False, + species="guineapig", + modelType=None, + debug=False, + ): + """ + initialize the octopus cell, using the parameters Spencer et al. 2012 + Modifications to the cell can be made by calling methods below. + + Parameters + ---------- + morphology : string (default: None) + a file name to read the cell morphology from. If a valid file is found, a cell is constructed + as a cable model from the hoc file. + If None (default), the only a point model is made, exactly according to RM03. + + decorator : Python function (default: None) + decorator is a function that "decorates" the morphology with ion channels according + to a set of rules. + If None, a default set of channels aer inserted into the first soma section, and the + rest of the structure is "bare". + + nach : string (default: 'na') + nach selects the type of sodium channel that will be used in the model. A channel mechanism + by that name must exist. + + ttx : Boolean (default: False) + If ttx is True, then the sodium channel conductance is set to 0 everywhere in the cell. + Currently, this is not implemented. + + species: string (default 'guineapig') + species defines the channel density that will be inserted for different models. Note that + if a decorator function is specified, this argument is ignored. + + modelType: string (default: None) + modelType specifies the type of the model that will be used (e.g., "II", "II-I", etc). + modelType is passed to the decorator, or to species_scaling to adjust point models. + + debug: boolean (default: False) + debug is a boolean flag. When set, there will be multiple printouts of progress and parameters. + + Returns + ------- + Nothing + """ + + super(OctopusSpencer, self).__init__() + if modelType == None: + modelType = "Spencer" + self.status = { + "soma": True, + "axon": False, + "dendrites": False, + "pumps": False, + "na": nach, + "species": species, + "modelType": modelType, + "ttx": ttx, + "name": "Octopus", + "morphology": morphology, + "decorator": decorator, + "temperature": None, + } + self.i_test_range = (-4.0, 6.0, 0.25) + self.spike_threshold = -50 + self.vrange = [-75.0, -63.0] # set a default vrange for searching for rmp + + if morphology is None: + """ + instantiate a basic soma-only ("point") model + """ + soma = h.Section( + name="Octopus_Soma_%x" % id(self) + ) # one compartment of about 29000 um2 + soma.nseg = 1 + self.add_section(soma, "soma") + self.set_soma_size_from_Section(self.soma) + + else: + """ + instantiate a structured model with the morphology as specified by + the morphology file + """ + self.set_morphology(morphology_file=morphology) + + # decorate the morphology with ion channels + if decorator is None: # basic model, only on the soma + self.e_leak = -62.0 # from Spencer et al., 2012 + self.e_h = -38.0 ## from Spencer et al., 2012 + self.R_a = 100.0 # from Spencer et al., 2012 + self.mechanisms = ["klt", "kht", "hcnobo", "leak", nach] + for mech in self.mechanisms: + self.soma.insert(mech) + self.soma.ek = -70.0 # self.e_k + self.soma.ena = 55.0 # self.e_na + self.soma().hcnobo.eh = self.e_h + self.soma().leak.erev = self.e_leak + self.soma.Ra = self.R_a + self.species_scaling( + silent=True, species=species, modelType=modelType + ) # set the default type II cell parameters + else: # decorate according to a defined set of rules on all cell compartments + self.decorate() + self.decorated.channelValidate(self, verify=True) + # print 'Mechanisms inserted: ', self.mechanisms + self.get_mechs(self.soma) + # self.cell_initialize(vrange=self.vrange) + + if debug: + print("<< octopus: octopus cell model created >>") + # print 'Cell created: ', self.status + + def channel_manager(self, modelType="Spencer"): + """ + This routine defines channel density maps and distance map patterns + for each type of compartment in the cell. The maps + are used by the ChannelDecorator class (specifically, it's private + \_biophys function) to decorate the cell membrane. + + Parameters + ---------- + modelType : string (default: 'Spencer') + A string that defines the type of the model. Currently, 1 type is implemented: + Spencer : Spencer et al Front. Comput. Neurosci. 2012 + + Returns + ------- + Nothing + + Notes + ----- + This routine defines the following variables for the class: + # conductances (gBar) + # a channelMap (dictonary of channel densities in defined anatomical compartments) + # a current injection range for IV's (when testing) + # a distance map, which defines how selected conductances in selected compartments + will change with distance. This includes both linear and exponential gradients, + the minimum conductance at the end of the gradient, and the space constant or + slope for the gradient. + + """ + + # + # Create a model based on the Spencer model + # Channel decoration and stick model from Figure 2 + # densities from Tables 2 and 3 + if modelType == "Spencer": + # print self.c_m + self.c_m = 0.9 + # self.set_soma_size_from_Section(self.soma) + totcap = self.totcap + refarea = self.somaarea # totcap / self.c_m # see above for units + # self.print_soma_info() + self._valid_temperatures = ( + 34.0, + ) # 34 for consistency with other mouse models, but + # Spencer data used "33". This affects very slightly + # the HCN channel conductance. + if self.status["temperature"] is None: + self.set_temperature(34.0) + self.gBar = Params( + nabar=0.0, # 0.0407, # S/cm2 + nabar_ais=0.42441, + kltbar_ais=0.0, + khtbar_ais=0.0, + ihbar_ais=0.0, + kltbar_soma=0.0407, + khtbar_soma=0.0061, + ihbar_soma=0.0076, + kltbar_dend=0.0027, + khtbar_dend=0.0, + ihbar_dend=0.0006, + khtbar_hillock=0.0, + kltbar_hillock=0.0, + ihbar_hillock=0.0, + leakbar=0.0020, + ) + + self.channelMap = { + "soma": { + "jsrna": self.gBar.nabar, + "klt": self.gBar.kltbar_soma, + "kht": self.gBar.khtbar_soma, + "hcnobo": self.gBar.ihbar_soma, + "leak": self.gBar.leakbar, + }, + "hillock": { + "jsrna": 0.0, + "klt": self.gBar.kltbar_hillock, + "kht": self.gBar.khtbar_hillock, + "hcnobo": self.gBar.ihbar_hillock, + "leak": self.gBar.leakbar, + }, + # axon initial segment: + "unmyelinatedaxon": { + "jsrna": self.gBar.nabar_ais, + "klt": self.gBar.kltbar_ais, + "kht": self.gBar.khtbar_ais, + "hcnobo": self.gBar.ihbar_ais, + "leak": self.gBar.leakbar, + }, + "primarydendrite": { + "jsrna": 0.0, + "klt": self.gBar.kltbar_dend, + "kht": self.gBar.khtbar_dend, + "hcnobo": self.gBar.ihbar_dend, + "leak": self.gBar.leakbar, + }, + } + + self.distMap = { + "primarydendrite": { + "klt": {"gradient": "flat", "gminf": 0.0, "lambda": 100.0}, + "kht": {"gradient": "flat", "gminf": 0.0, "lambda": 100.0}, + "hcnobo": {"gradient": "flat", "gminf": 0.0, "lambda": 100.0}, + } # all flat with distance + } + # reversal potential map + self.channelErevMap = { + "soma": { + "jsrna": 55.0, + "klt": -70, + "kht": -70, + "hcnobo": -38, + "leak": -62.0, + }, + "hillock": { + "jsrna": 55.0, + "klt": -70, + "kht": -70, + "hcnobo": -38, + "leak": -62.0, + }, + "unmyelinatedaxon": { + "jsrna": 55.0, + "klt": -70, + "kht": -70, + "hcnobo": -38, + "leak": -62.0, + }, + "primarydendrite": { + "jsrna": 55.0, + "klt": -70, + "kht": -70, + "hcnobo": -38, + "leak": -62.0, + }, + } + + else: + raise ValueError("model type %s is not implemented" % modelType) + self.check_temperature() + + def species_scaling(self, species="mouse", modelType="Spencer", silent=True): + """ + Adjust all of the conductances and the cell size according to the species requested. + Used ONLY for point models. + + Parameters + ---------- + species : string (default: 'guineapig') + name of the species to use for scaling the conductances in the base point model + Must be guineapig + + modelType: string (default: 'II-o') + definition of model type from RM03 models, currently limited to type II-o + + silent : boolean (default: True) + run silently (True) or verbosely (False) + """ + soma = self.soma + + if species == "mouse" and modelType == "Spencer": + print("Octopus: Mouse, Spencer point model - not a valid model") + self.set_soma_size_from_Cm(25.0) + self._valid_temperatures = (34.0,) + if self.status["temperature"] is None: + self.set_temperature(34.0) + self.print_soma_info() + # self.adjust_na_chans(soma) + # soma().kht.gbar = 0.0061 # nstomho(150.0, self.somaarea) # 6.1 mmho/cm2 + # soma().klt.gbar = 0.0407 # nstomho(3196.0, self.somaarea) # 40.7 mmho/cm2 + # soma().hcnobo.gbar = 0.0076 #nstomho(40.0, self.somaarea) # 7.6 mmho/cm2, cf. Bal and Oertel, Spencer et al. 25 u dia cell + # soma().leak.gbar = 0.0005 # nstomho(2.0, self.somaarea) + self.axonsf = 1.0 + else: + raise ValueError( + 'Species "%s" or species-type "%s" is not recognized for octopus cells' + % (species, type) + ) + self.status["species"] = species + self.status["modelType"] = modelType + self.cell_initialize(showinfo=True) + if not silent: + print("set cell as: ", species) + print(" with Vm rest = %6.3f" % self.vm0) diff --git a/cnmodel/cells/pyramidal.py b/cnmodel/cells/pyramidal.py new file mode 100644 index 0000000..3b2329d --- /dev/null +++ b/cnmodel/cells/pyramidal.py @@ -0,0 +1,482 @@ +from __future__ import print_function + +import numpy as np +from neuron import h + +from .cell import Cell +from .. import data +from ..util import Params +from ..util import nstomho + +__all__ = ["Pyramidal", "PyramidalKanold"] + + +class Pyramidal(Cell): + + type = "pyramidal" + + @classmethod + def create(cls, model="POK", **kwds): + if model == "POK": + return PyramidalKanold(**kwds) + else: + raise ValueError("Pyramidal model %s is unknown", model) + + def make_psd(self, terminal, psd_type, **kwds): + """ + Connect a presynaptic terminal to one post section at the specified location, with the fraction + of the "standard" conductance determined by gbar. + The default condition is to try to pass the default unit test (loc=0.5) + + Parameters + ---------- + terminal : Presynaptic terminal (NEURON object) + + psd_type : either simple or multisite PSD for bushy cell + + kwds: dict of options. Two are currently handled: + postsize : expect a list consisting of [sectionno, location (float)] + AMPAScale : float to scale the ampa currents + + """ + if ( + "postsite" in kwds + ): # use a defined location instead of the default (soma(0.5) + postsite = kwds["postsite"] + loc = postsite[1] # where on the section? + uname = ( + "sections[%d]" % postsite[0] + ) # make a name to look up the neuron section object + post_sec = self.hr.get_section(uname) # Tell us where to put the synapse. + else: + loc = 0.5 + post_sec = self.soma + + if psd_type == "simple": + if terminal.cell.type in [ + "sgc", + "dstellate", + "tuberculoventral", + "cartwheel", + ]: + weight = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="weight", + ) + tau1 = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="tau1", + ) + tau2 = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="tau2", + ) + erev = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="erev", + ) + return self.make_exp2_psd( + post_sec, + terminal, + weight=weight, + loc=loc, + tau1=tau1, + tau2=tau2, + erev=erev, + ) + else: + raise TypeError( + "Cannot make simple PSD for %s => %s" + % (terminal.cell.type, self.type) + ) + + elif psd_type == "multisite": + if terminal.cell.type == "sgc": + # Max conductances for the glu mechanisms are calibrated by + # running `synapses/tests/test_psd.py`. The test should fail + # if these values are incorrect + self.AMPAR_gmax = ( + data.get( + "sgc_synapse", + species=self.species, + post_type=self.type, + field="AMPAR_gmax", + ) + * 1e3 + ) + self.NMDAR_gmax = ( + data.get( + "sgc_synapse", + species=self.species, + post_type=self.type, + field="NMDAR_gmax", + ) + * 1e3 + ) + self.Pr = data.get( + "sgc_synapse", species=self.species, post_type=self.type, field="Pr" + ) + # adjust gmax to correct for initial Pr + self.AMPAR_gmax = self.AMPAR_gmax / self.Pr + self.NMDAR_gmax = self.NMDAR_gmax / self.Pr + if "AMPAScale" in kwds: + self.AMPA_gmax = ( + self.AMPA_gmax * kwds["AMPAScale"] + ) # allow scaling of AMPA conductances + if "NMDAScale" in kwds: + self.NMDA_gmax = self.NMDA_gmax * kwds["NMDAScale"] + return self.make_glu_psd( + post_sec, terminal, self.AMPAR_gmax, self.NMDAR_gmax, loc=loc + ) + elif terminal.cell.type == "dstellate": # WBI input -Voigt, Nelken, Young + return self.make_gly_psd(post_sec, terminal, psdtype="glyfast", loc=loc) + elif ( + terminal.cell.type == "tuberculoventral" + ): # TV cells talk to each other-Kuo et al. + return self.make_gly_psd(post_sec, terminal, psdtype="glyfast", loc=loc) + else: + raise TypeError( + "Cannot make PSD for %s => %s" % (terminal.cell.type, self.type) + ) + else: + raise ValueError("Unsupported psd type %s" % psd_type) + + +class PyramidalKanold(Pyramidal, Cell): + """ + DCN pyramidal cell + Kanold and Manis, 1999, 2001, 2005 + """ + + def __init__( + self, + morphology=None, + decorator=None, + nach=None, + ttx=False, + species="rat", + modelType=None, + debug=False, + ): + """ + initialize a pyramidal cell, based on the Kanold-Manis (2001) pyramidal cell model. + Modifications to the cell can be made by calling methods below. These include + converting to a model with modified size and conductances (experimental). + + Parameters + ---------- + morphology : string (default: None) + a file name to read the cell morphology from. If a valid file is found, a cell is constructed + as a cable model from the hoc file. + If None (default), the only a point model is made, exactly according to RM03. + + decorator : Python function (default: None) + decorator is a function that "decorates" the morphology with ion channels according + to a set of rules. + If None, a default set of channels is inserted into the first soma section, and the + rest of the structure is "bare". + + nach : string (default: None) + nach selects the type of sodium channel that will be used in the model. A channel mechanim + by that name must exist. None implies the default channel, 'napyr'. + + ttx : Boolean (default: False) + If ttx is True, then the sodium channel conductance is set to 0 everywhere in the cell. + Currently, this is not implemented. + + species: string (default 'guineapig') + species defines the channel density that will be inserted for different models. Note that + if a decorator function is specified, this argument is ignored (overridden by decorator). + + modelType: string (default: None) + modelType specifies the type of the model that will be used (e.g., "II", "II-I", etc). + modelType is passed to the decorator, or to species_scaling to adjust point models. + + debug: boolean (default: False) + debug is a boolean flag. When set, there will be multiple printouts of progress and parameters. + + Returns + ------- + Nothing + + """ + super(PyramidalKanold, self).__init__() + if modelType == None: + modelType = "POK" + if nach == None: + nach = "napyr" + self.status = { + "soma": True, + "axon": False, + "dendrites": False, + "pumps": False, + "na": nach, + "species": species, + "modelType": modelType, + "ttx": ttx, + "name": "Pyramidal", + "morphology": morphology, + "decorator": decorator, + "temperature": None, + } + + self.i_test_range = {"pulse": (-0.3, 0.401, 0.02)} + self.vrange = [-75.0, -60.0] + if morphology is None: + """ + instantiate a basic soma-only ("point") model + """ + soma = h.Section( + name="Pyramidal_Soma_%x" % id(self) + ) # one compartment of about 29000 um2 + soma.nseg = 1 + self.add_section(soma, "soma") + else: + """ + instantiate a structured model with the morphology as specified by + the morphology file + """ + self.set_morphology(morphology_file=morphology) + + # decorate the morphology with ion channels + if decorator is None: # basic model, only on the soma + self.mechanisms = [ + "napyr", + "kdpyr", + "kif", + "kis", + "ihpyr", + "leak", + "kcnq", + "nap", + ] + for mech in self.mechanisms: + try: + self.soma.insert(mech) + except ValueError: + print("WARNING: Mechanism %s not found" % mech) + self.soma().kif.kif_ivh = -89.6 + self.species_scaling( + silent=True, species=species, modelType=modelType + ) # set the default type I-c cell parameters + else: # decorate according to a defined set of rules on all cell compartments + self.decorate() + self.save_all_mechs() # save all mechanisms inserted, location and gbar values... + self.get_mechs(self.soma) + if debug: + print("<< PYR: POK Pyramidal Cell created >>") + + def get_cellpars(self, dataset, species="guineapig", celltype="II"): + cellcap = data.get( + dataset, species=species, cell_type=celltype, field="soma_Cap" + ) + chtype = data.get( + dataset, species=species, cell_type=celltype, field="soma_natype" + ) + pars = Params(cap=cellcap, natype=chtype) + for g in [ + "soma_napyr_gbar", + "soma_kdpyr_gbar", + "soma_kif_gbar", + "soma_kis_gbar", + "soma_kcnq_gbar", + "soma_nap_gbar", + "soma_ihpyr_gbar", + "soma_leak_gbar", + "soma_e_h", + "soma_leak_erev", + "soma_e_k", + "soma_e_na", + ]: + pars.additem( + g, data.get(dataset, species=species, cell_type=celltype, field=g) + ) + return pars + + def species_scaling(self, species="rat", modelType="I", silent=True): + """ + Adjust all of the conductances and the cell size according to the species requested. + Used ONLY for point models. + + Parameters + ---------- + species : string (default: 'rat') + name of the species to use for scaling the conductances in the base point model + Must be 'rat' + + modelType: string (default: 'I') + definition of model type from Kanold and Manis, 2001 + choices are 'I' or 'POK' (canonical model) or + 'II', a modified model with more physiological surface area and KCNQ channels + + silent : boolean (default: True) + run silently (True) or verbosely (False) + """ + if modelType in ["I", "POK"]: + celltype = "pyramidal" + elif modelType in ["II"]: + celltype = "pyramidal-II" + else: + celltype = modelType + + dataset = "POK_channels" + + soma = self.soma + if species in ["rat", "mouse"] and modelType in [ + "I", + "POK", + "II", + ]: # canonical K&M2001 model cell + self._valid_temperatures = (34.0,) + if self.status["temperature"] is None: + self.set_temperature(34.0) + pars = self.get_cellpars(dataset, species=species, celltype=celltype) + self.set_soma_size_from_Cm(pars.cap) + self.status["na"] = pars.natype + soma().napyr.gbar = nstomho(pars.soma_napyr_gbar, self.somaarea) + soma().nap.gbar = nstomho( + pars.soma_nap_gbar, self.somaarea + ) # does not exist in canonical model + soma().kdpyr.gbar = nstomho(pars.soma_kdpyr_gbar, self.somaarea) + soma().kcnq.gbar = nstomho( + pars.soma_kcnq_gbar, self.somaarea + ) # does not exist in canonical model. + soma().kif.gbar = nstomho(pars.soma_kif_gbar, self.somaarea) + soma().kis.gbar = nstomho(pars.soma_kis_gbar, self.somaarea) + soma().ihpyr.gbar = nstomho(pars.soma_ihpyr_gbar, self.somaarea) + # soma().ihpyr_adj.q10 = 3.0 # no temp scaling to sta + soma().leak.gbar = nstomho(pars.soma_leak_gbar, self.somaarea) + soma().leak.erev = pars.soma_leak_erev + soma().ena = pars.soma_e_na + soma().ek = pars.soma_e_k + soma().ihpyr.eh = pars.soma_e_h + + # elif species in 'rat' and modelType == 'II': + # """ + # Modified canonical K&M2001 model cell + # In this model version, the specific membrane capacitance is modified + # so that the overall membrane time constant is consistent with experimental + # measures in slices. However, this is not a physiological value. Attempts + # to use the normal 1 uF/cm2 value were unsuccessful in establishing the expected + # ~12 msec time constant. + # This model also adds a KCNQ channel, as described by Li et al., 2012. + # """ + # self.c_m = 6.0 + # self.set_soma_size_from_Diam(30.0) + # # self.set_soma_size_from_Cm(80.0) + # # print 'diameter: %7.1f' % self.soma.diam + # self._valid_temperatures = (34.,) + # if self.status['temperature'] is None: + # self.set_temperature(34.) + # self.refarea = self.somaarea + # soma().napyr.gbar = nstomho(550, self.refarea) + # soma().nap.gbar = nstomho(60.0, self.refarea) + # soma().kcnq.gbar = nstomho(2, self.refarea) # pyramidal cells have kcnq: Li et al, 2011 (Thanos) + # soma().kdpyr.gbar = nstomho(180, self.refarea) # Normally 80. + # soma().kif.gbar = nstomho(150, self.refarea) # normally 150 + # soma().kis.gbar = nstomho(40, self.refarea) # 40 + # soma().ihpyr.gbar = nstomho(2.8, self.refarea) + # soma().leak.gbar = nstomho(0.5, self.refarea) + # soma().leak.erev = -62. # override default values in cell.py + # soma().ena = 50.0 + # soma().ek = -81.5 + # soma().ihpyr.eh = -43 + # if not self.status['dendrites']: + # self.add_dendrites() + + else: + raise ValueError( + "Species %s or species-modelType %s is not implemented for Pyramidal cells" + % (species, modelType) + ) + + self.status["species"] = species + self.status["modelType"] = modelType + # self.cell_initialize(showinfo=True) + self.check_temperature() + if not silent: + print("set cell as: ", species, modelType) + print(" with Vm rest = %f" % self.vm0) + print(self.status) + for m in self.mechanisms: + print("%s.gbar = %f" % (m, eval("soma().%s.gbar" % m))) + + def i_currents(self, V): + """ + For the steady-state case, return the total current at voltage V + Used to find the zero current point + vrange brackets the interval + Overrides i_currents in cells.py because we have a different set of currents + to compute. + """ + for part in self.all_sections.keys(): + for sec in self.all_sections[part]: + sec.v = V + h.celsius = self.status["temperature"] + h.finitialize() + self.ix = {} + + if "napyr" in self.mechanisms: + self.ix["napyr"] = self.soma().napyr.gna * (V - self.soma().ena) + if "nap" in self.mechanisms: + self.ix["nap"] = self.soma().nap.gnap * (V - self.soma().ena) + if "kdpyr" in self.mechanisms: + self.ix["kdpyr"] = self.soma().kdpyr.gk * (V - self.soma().ek) + if "kif" in self.mechanisms: + self.ix["kif"] = self.soma().kif.gkif * (V - self.soma().ek) + if "kis" in self.mechanisms: + self.ix["kis"] = self.soma().kis.gkis * (V - self.soma().ek) + if "kcnq" in self.mechanisms: + self.ix["kcnq"] = self.soma().kcnq.gk * (V - self.soma().ek) + if "ihpyr" in self.mechanisms: + self.ix["ihpyr"] = self.soma().ihpyr.gh * (V - self.soma().ihpyr.eh) + if "ihpyr_adj" in self.mechanisms: + self.ix["ihpyr_adj"] = self.soma().ihpyr_adj.gh * ( + V - self.soma().ihpyr_adj.eh + ) + # leak + if "leak" in self.mechanisms: + self.ix["leak"] = self.soma().leak.gbar * (V - self.soma().leak.erev) + return np.sum([self.ix[i] for i in self.ix]) + + def add_dendrites(self): + """ + Add simple unbranched dendrite. + The dendrites have some kd, kif and ih current + """ + nDend = range(2) # these will be simple, unbranced, N=4 dendrites + dendrites = [] + for i in nDend: + dendrites.append(h.Section(cell=self.soma)) + for i in nDend: + dendrites[i].connect(self.soma) + dendrites[i].L = 250 # length of the dendrite (not tapered) + dendrites[i].diam = 1 + dendrites[i].cm = self.c_m + # h('dendrites[i].diam(0:1) = 2:1') # dendrite diameter, with tapering + dendrites[i].nseg = 21 # # segments in dendrites + dendrites[i].Ra = 150 # ohm.cm + dendrites[i].insert("napyr") + dendrites[i]().napyr.gbar = 0.00 + dendrites[i].insert("kdpyr") + dendrites[i]().kdpyr.gbar = 0.002 # a little Ht + dendrites[i].insert("kif") + dendrites[i]().kif.gbar = 0.0001 # a little Ht + dendrites[i].insert("leak") # leak + dendrites[i]().leak.gbar = 0.00001 + dendrites[i].insert("ihpyr_adj") # some H current + # mechanism missing so the ihvcn mechanism need to be inserted + dendrites[i].insert('ihvcn') + dendrites[i]().ihvcn.gbar = 0.0 # 0.00002 + dendrites[i]().ihvcn.eh = -43.0 + self.maindend = dendrites + self.status["dendrites"] = True + self.add_section(self.maindend, "maindend") diff --git a/cnmodel/cells/sgc.py b/cnmodel/cells/sgc.py new file mode 100644 index 0000000..f885bb2 --- /dev/null +++ b/cnmodel/cells/sgc.py @@ -0,0 +1,467 @@ +from __future__ import print_function +from neuron import h +from ..util import nstomho +from ..util import Params +import numpy as np +from .cell import Cell +from .. import synapses +from .. import an_model +from .. import data + +__all__ = ["SGC", "SGC_TypeI", "DummySGC"] + + +class SGC(Cell): + type = "sgc" + + @classmethod + def create(cls, model="I", species="mouse", **kwds): + if model == "dummy": + return DummySGC(**kwds) + elif model == "I": + return SGC_TypeI(species=species, **kwds) + else: + raise ValueError("SGC model %s is unknown", model) + + def __init__(self, cf=None, sr=None): + Cell.__init__(self) + self._cf = cf + self._sr = sr + self.spike_source = None # used by DummySGC to connect VecStim to terminal + + @property + def cf(self): + """ Center frequency + """ + return self._cf + + @property + def sr(self): + """ Spontaneous rate group. 1=low, 2=mid, 3=high + """ + return self._sr + + def make_terminal(self, post_cell, term_type, **kwds): + """Create a StochasticTerminal and configure it according to the + postsynaptic cell type. + """ + pre_sec = self.soma + + # Return a simple terminal unless a stochastic terminal was requested. + if term_type == "simple": + return synapses.SimpleTerminal( + pre_sec, post_cell, spike_source=self.spike_source, **kwds + ) + elif term_type == "multisite": + n_rsites = data.get( + "sgc_synapse", + species="mouse", + post_type=post_cell.type, + field="n_rsites", + ) + opts = {"nzones": n_rsites, "delay": 0, "dep_flag": 1} + opts.update(kwds) + # when created, depflag is set True (1) so that we compute the DKR D*F to get release + # this can be modified prior to the run by setting the terminal(s) so that dep_flag is 0 + # (no DKR: constant release probability) + term = synapses.StochasticTerminal( + pre_sec, post_cell, spike_source=self.spike_source, **opts + ) + + kinetics = data.get( + "sgc_ampa_kinetics", + species="mouse", + post_type=post_cell.type, + field=["tau_g", "amp_g"], + ) + term.set_params(**kinetics) + dynamics = data.get( + "sgc_release_dynamics", + species="mouse", + post_type=post_cell.type, + field=["F", "k0", "kmax", "kd", "kf", "taud", "tauf", "dD", "dF"], + ) + term.set_params(**dynamics) + return term + else: + raise ValueError("Unsupported terminal type %s" % term_type) + + +class DummySGC(SGC): + """ SGC class with no cell body; this cell only replays a predetermined + spike train. + """ + + def __init__(self, cf=None, sr=None, simulator=None): + """ + Parameters + ---------- + cf : float (default: None) + Required: the characteristic frequency for the SGC + + sr : int (default None) + required : Selects the spontaneous rate group from the + Zilany et al (2010) model. 1 = LSR, 2 = MSR, 3 = HSR + + simulator : 'cochlea' | 'matlab' | None (default None) + Sets the simulator interface that will be used. All models + currently use the Zilany et al. model, but the simulator can + be run though a Python-interface directly to the Matlab code + as publicy available, (simulator='matlab'), or can be run through + Rudnicki & Hemmert's Python interface to the simulator's C code + (simulator='cochlea'). + + """ + self._simulator = simulator + SGC.__init__(self, cf, sr) + self.vecstim = h.VecStim() + + # this causes the terminal to receive events from the VecStim: + self.spike_source = self.vecstim + + # just an empty section for holding the terminal + self.add_section(h.Section(), "soma") + self.status = { + "soma": True, + "axon": False, + "dendrites": False, + "pumps": False, + "na": None, + "species": None, + "modelType": "dummy", + "ttx": False, + "name": "DummysGC", + "morphology": None, + "decorator": None, + "temperature": None, + } + + def set_spiketrain(self, times): + """ Set the times of spikes (in seconds) to be replayed by the cell. + """ + self._spiketrain = times + self._stvec = h.Vector(times) + self.vecstim.play(self._stvec) + + def set_sound_stim(self, stim, seed, simulator=None): + """ Set the sound stimulus used to generate this cell's spike train. + """ + self._sound_stim = stim + spikes = self.generate_spiketrain(stim, seed, simulator) + self.set_spiketrain(spikes) + + def generate_spiketrain(self, stim, seed, simulator=None): + if simulator is None: + simulator = self._simulator + spikes = an_model.get_spiketrain( + cf=self.cf, sr=self.sr, seed=seed, stim=stim, simulator=simulator + ) + return spikes * 1000 + + +class SGC_TypeI(SGC): + """ + Spiral ganglion cell model + + """ + + def __init__( + self, + morphology=None, + decorator=None, + nach=None, + ttx=False, + species="guineapig", + modelType="bm", + cf=None, + sr=None, + debug=False, + ): + """ + Initialize a spiral ganglion Type I cell, based on a bushy cell model. + Modifications to the cell can be made by calling the methods below. These include + converting to a model with modified size and conductances (experimental), and + and changing the sodium channel conductances. + + Parameters + ---------- + morphology : string (default: None) + a file name to read the cell morphology from. If a valid file is found, a cell is constructed + as a cable model from the hoc file. + If None (default), the only a point model is made, exactly according to RM03. + + decorator : Python function (default: None) + decorator is a function that "decorates" the morphology with ion channels according + to a set of rules. + If None, a default set of channels aer inserted into the first soma section, and the + rest of the structure is "bare". + + nach : string (default: 'na') + nach selects the type of sodium channel that will be used in the model. A channel mechanim + by that name must exist. The default is jsrna (Rothman et al., 1993) + + ttx : Boolean (default: False) + If ttx is True, then the sodium channel conductance is set to 0 everywhere in the cell. + Currently, this is not implemented. + + species: string (default 'guineapig') + species defines the channel density that will be inserted for different models. Note that + if a decorator function is specified, this argument is ignored. + + modelType: string (default: None) + modelType specifies the type of the model that will be used. SGC model know about "a" (apical) + and "bm" (basal-middle) models, based on Liu et al., JARO, 2014. + modelType is passed to the decorator, or to species_scaling to adjust point models. + + cf : float (default: None) + The CF for the auditory nerve fiber that this SGC represents. + + sr : string (default: None) + The spontaneous rate group to which this fiber belongs. "LS", "MS", and "HS" are known values. + + debug: boolean (default: False) + debug is a boolean flag. When set, there will be multiple printouts of progress and parameters. + + Returns + ------- + Nothing + + """ + + super(SGC_TypeI, self).__init__(cf=cf, sr=sr) + if modelType == None: + modelType = "bm" # modelTypes are: a (apical), bm (basal middle) + if nach == None: + nach = "jsrna" + self.status = { + "soma": True, + "axon": False, + "dendrites": False, + "pumps": False, + "na": nach, + "species": species, + "modelType": modelType, + "ttx": ttx, + "name": "SGC", + "morphology": morphology, + "decorator": decorator, + "temperature": None, + } + + self.i_test_range = { + "pulse": [(-0.3, 0.3, 0.02), (-0.03, 0.0, 0.005)] + } # include finer range as well + self.vrange = [-75.0, -55.0] + if morphology is None: + """ + instantiate a basic soma-only ("point") model + """ + soma = h.Section( + name="SGC_Soma_%x" % id(self) + ) # one compartment of about 29000 um2 + soma.nseg = 1 + self.add_section(soma, "soma") + else: + """ + instantiate a structured model with the morphology as specified by + the morphology file + """ + self.set_morphology(morphology_file=morphology) + + # decorate the morphology with ion channels + if decorator is None: # basic model, only on the soma + self.mechanisms = [nach, "klt", "kht", "leak"] + if modelType == "a": + self.mechanisms.append("ihsgcApical") + elif modelType == "bm": + self.mechanisms.append("ihsgcBasalMiddle") + else: + raise ValueError("Type %s not known for SGC model" % modelType) + for mech in self.mechanisms: + self.soma.insert(mech) + self.soma.ek = self.e_k + self.soma().leak.erev = self.e_leak + self.species_scaling( + silent=True, species=species, modelType=modelType + ) # set the default type II cell parameters + else: # decorate according to a defined set of rules on all cell compartments + self.decorate() + self.save_all_mechs() # save all mechanisms inserted, location and gbar values... + self.get_mechs(self.soma) + if debug: + print("<< SGC: Spiral Ganglion Cell created >>") + + def get_cellpars(self, dataset, species="guineapig", celltype="sgc-a"): + cellcap = data.get( + dataset, species=species, cell_type=celltype, field="soma_Cap" + ) + chtype = data.get( + dataset, species=species, cell_type=celltype, field="soma_na_type" + ) + pars = Params(soma_Cap=cellcap, natype=chtype) + for g in [ + "soma_na_gbar", + "soma_kht_gbar", + "soma_klt_gbar", + "soma_ihap_gbar", + "soma_ihbm_gbar", + "soma_ihap_eh", + "soma_ihbm_eh", + "soma_leak_gbar", + "soma_leak_erev", + "soma_e_k", + "soma_e_na", + ]: + pars.additem( + g, data.get(dataset, species=species, cell_type=celltype, field=g) + ) + return pars + + def species_scaling(self, silent=True, species="guineapig", modelType="a"): + """ + Adjust all of the conductances and the cell size according to the species requested. + Used ONLY for point models. + + Parameters + ---------- + species : string (default: 'guineapig') + name of the species to use for scaling the conductances in the base point model + Must be one of mouse or guineapig + + modelType: string (default: 'a') + definition of HCN model type from Liu et al. JARO 2014: + 'a' for apical model + 'bm' for basal-middle model + + silent : boolean (default: True) + run silently (True) or verbosely (False) + + Returns + ------- + Nothing + + Notes + ----- + The 'guineapig' model uses the mouse HCN channel model, verbatim. This may not + be appropriate, given that the other conductances are scaled up. + + """ + + soma = self.soma + if modelType == "a": + celltype = "sgc-a" + elif modelType == "bm": + celltype = "sgc-bm" + else: + raise ValueError("SGC: unrecognized model type %s " % modelType) + + if species == "mouse": + self._valid_temperatures = (34.0,) + if self.status["temperature"] is None: + self.set_temperature(34.0) + par = self.get_cellpars( + "sgc_mouse_channels", species=species, celltype=celltype + ) + elif species == "guineapig": + # guinea pig data from Rothman and Manis, 2003, modelType II + self._valid_temperatures = (22.0,) + if self.status["temperature"] is None: + self.set_temperature(22.0) + par = self.get_cellpars( + "sgc_guineapig_channels", species=species, celltype=celltype + ) + + self.set_soma_size_from_Cm(par.soma_Cap) + self.adjust_na_chans(soma, gbar=par.soma_na_gbar) + soma().kht.gbar = nstomho(par.soma_kht_gbar, self.somaarea) + soma().klt.gbar = nstomho(par.soma_klt_gbar, self.somaarea) + if celltype == "sgc-a": + soma().ihsgcApical.gbar = nstomho(par.soma_ihap_gbar, self.somaarea) + soma().ihsgcApical.eh = par.soma_ihap_eh + elif celltype == "sgc-bm": + soma().ihsgcBasalMiddle.gbar = nstomho(par.soma_ihbm_gbar, self.somaarea) + soma().ihsgcBasalMiddle.eh = par.soma_ihbm_eh + else: + raise ValueError( + "Ihsgc modelType %s not recognized for species %s" % (celltype, species) + ) + soma().leak.gbar = nstomho(par.soma_leak_gbar, self.somaarea) + soma().leak.erev = par.soma_leak_erev + + self.status["species"] = species + self.status["modelType"] = modelType + self.check_temperature() + if not silent: + print("set cell as: ", species) + print(" with Vm rest = %f" % self.vm0) + + def adjust_na_chans(self, soma, gbar=1000.0, debug=False): + """ + adjust the sodium channel conductance + :param soma: a soma object whose sodium channel complement will have it's + conductances adjusted depending on the channel type + :return nothing: + """ + if self.status["ttx"]: + gnabar = 0.0 + else: + gnabar = nstomho(gbar, self.somaarea) + nach = self.status["na"] + if nach == "jsrna": + soma().jsrna.gbar = gnabar + soma.ena = self.e_na + if debug: + print("jsrna gbar: ", soma().jsrna.gbar) + elif nach == "nav11": + soma().nav11.gbar = gnabar * 0.5 + soma.ena = self.e_na + soma().nav11.vsna = 4.3 + if debug: + print("sgc using inva11") + print("nav11 gbar: ", soma().nav11.gbar) + elif nach in ["na", "nacn"]: + soma().na.gbar = gnabar + soma.ena = self.e_na + if debug: + print("na gbar: ", soma().na.gbar) + else: + raise ValueError("Sodium channel %s is not recognized for SGC cells", nach) + + def i_currents(self, V): + """ + For the steady-state case, return the total current at voltage V + Used to find the zero current point + vrange brackets the interval + Implemented here are the basic RM03 mechanisms + This function should be replaced for specific cell types. + """ + for part in self.all_sections.keys(): + for sec in self.all_sections[part]: + sec.v = V + + h.t = 0.0 + h.celsius = self.status["temperature"] + h.finitialize() + self.ix = {} + if "na" in self.mechanisms: + # print dir(self.soma().na) + self.ix["na"] = self.soma().na.gna * (V - self.soma().ena) + if "jsrna" in self.mechanisms: + # print dir(self.soma().na) + self.ix["jsrna"] = self.soma().jsrna.gna * (V - self.soma().ena) + if "klt" in self.mechanisms: + self.ix["klt"] = self.soma().klt.gklt * (V - self.soma().ek) + if "kht" in self.mechanisms: + self.ix["kht"] = self.soma().kht.gkht * (V - self.soma().ek) + if "ihsgcApical" in self.mechanisms: + self.ix["ihsgcApical"] = self.soma().ihsgcApical.gh * ( + V - self.soma().ihsgcApical.eh + ) + if "ihsgcBasalMiddle" in self.mechanisms: + self.ix["ihsgcBasalMiddle"] = self.soma().ihsgcBasalMiddle.gh * ( + V - self.soma().ihsgcBasalMiddle.eh + ) + if "leak" in self.mechanisms: + self.ix["leak"] = self.soma().leak.gbar * (V - self.soma().leak.erev) + # print self.status['name'], self.status['type'], V, self.ix + return np.sum([self.ix[i] for i in self.ix]) diff --git a/cnmodel/cells/tests/cell_data/SGC_rat_a.pk b/cnmodel/cells/tests/cell_data/SGC_rat_a.pk new file mode 100644 index 0000000..6636f68 --- /dev/null +++ b/cnmodel/cells/tests/cell_data/SGC_rat_a.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e60518d0332cd475f67e13e8f85e23b1b60dda4f252620b495bdfbc5dab43fe +size 7826 diff --git a/cnmodel/cells/tests/cell_data/SGC_rat_bm.pk b/cnmodel/cells/tests/cell_data/SGC_rat_bm.pk new file mode 100644 index 0000000..18d3b35 --- /dev/null +++ b/cnmodel/cells/tests/cell_data/SGC_rat_bm.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f0814086d71479adab9326978620e1af0ed153fdfc2c6f4fa0d2213c0b80131b +size 7729 diff --git a/cnmodel/cells/tests/cell_data/bushy-mouse-typeII.pk b/cnmodel/cells/tests/cell_data/bushy-mouse-typeII.pk new file mode 100644 index 0000000..50b349a --- /dev/null +++ b/cnmodel/cells/tests/cell_data/bushy-mouse-typeII.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5dbd4717983175a81d362bd01015cb28baa145d78c6c460dd7ec6456f9f46e72 +size 8103 diff --git a/cnmodel/cells/tests/cell_data/bushy_guineapig-typeII-I.pk b/cnmodel/cells/tests/cell_data/bushy_guineapig-typeII-I.pk new file mode 100644 index 0000000..15980c5 --- /dev/null +++ b/cnmodel/cells/tests/cell_data/bushy_guineapig-typeII-I.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34fbddf52a61283bd29622fe87e1fc8afc6f46160cdce3f0cdd581f89bfeba35 +size 7963 diff --git a/cnmodel/cells/tests/cell_data/bushy_guineapig-typeII.pk b/cnmodel/cells/tests/cell_data/bushy_guineapig-typeII.pk new file mode 100644 index 0000000..0cdff68 --- /dev/null +++ b/cnmodel/cells/tests/cell_data/bushy_guineapig-typeII.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:de245b95e0b1f66680ed1f79bc31739bce36aed9edd044d02b6effbd645e948e +size 8160 diff --git a/cnmodel/cells/tests/cell_data/cartwheel_rat_I.pk b/cnmodel/cells/tests/cell_data/cartwheel_rat_I.pk new file mode 100644 index 0000000..459f125 --- /dev/null +++ b/cnmodel/cells/tests/cell_data/cartwheel_rat_I.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f7c79982ffa921ba17690de6b31ff27be75936acde0fa72b5d52e0e4abc54da +size 5506 diff --git a/cnmodel/cells/tests/cell_data/dstellate_guineapig-typeI-II.pk b/cnmodel/cells/tests/cell_data/dstellate_guineapig-typeI-II.pk new file mode 100644 index 0000000..bbe549e --- /dev/null +++ b/cnmodel/cells/tests/cell_data/dstellate_guineapig-typeI-II.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:de64e933070f7c216d8f632cb56ee32b346bba282c24f453f818c686439b772a +size 8710 diff --git a/cnmodel/cells/tests/cell_data/dstellate_mouse-typeI-II.pk b/cnmodel/cells/tests/cell_data/dstellate_mouse-typeI-II.pk new file mode 100644 index 0000000..1ad0e76 --- /dev/null +++ b/cnmodel/cells/tests/cell_data/dstellate_mouse-typeI-II.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0e713ac67a7211e4d78c846bd8bdda4b738c49d5c50fb61c1974f12d45341937 +size 9506 diff --git a/cnmodel/cells/tests/cell_data/octopus_guineapig-typeII-o.pk b/cnmodel/cells/tests/cell_data/octopus_guineapig-typeII-o.pk new file mode 100644 index 0000000..5f16592 --- /dev/null +++ b/cnmodel/cells/tests/cell_data/octopus_guineapig-typeII-o.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e86a6fb8651d0ed0a33e30273d49b8358436bf169899ee9d2bcda454f450225e +size 7747 diff --git a/cnmodel/cells/tests/cell_data/pyramidal_rat_I.pk b/cnmodel/cells/tests/cell_data/pyramidal_rat_I.pk new file mode 100644 index 0000000..fb79f6b --- /dev/null +++ b/cnmodel/cells/tests/cell_data/pyramidal_rat_I.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ebe0523b9260f3b9a87fc6e535f38cb8f0b5840aea056fe8764943883782db7 +size 16581 diff --git a/cnmodel/cells/tests/cell_data/tstellate_guineapig-typeI-c.pk b/cnmodel/cells/tests/cell_data/tstellate_guineapig-typeI-c.pk new file mode 100644 index 0000000..9f2f9db --- /dev/null +++ b/cnmodel/cells/tests/cell_data/tstellate_guineapig-typeI-c.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2536a5ca43d2f46fa6e6bf786d520ac12815b742896a3272a227660a91fc2c1 +size 7863 diff --git a/cnmodel/cells/tests/cell_data/tstellate_guineapig-typeI-t.pk b/cnmodel/cells/tests/cell_data/tstellate_guineapig-typeI-t.pk new file mode 100644 index 0000000..703fa03 --- /dev/null +++ b/cnmodel/cells/tests/cell_data/tstellate_guineapig-typeI-t.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa5ddc40011269d7e4d00d70ac3053bd4d2d88293db5f8d6f9ae8225c3ed1bdc +size 8182 diff --git a/cnmodel/cells/tests/cell_data/tstellate_mouse-typeI-c.pk b/cnmodel/cells/tests/cell_data/tstellate_mouse-typeI-c.pk new file mode 100644 index 0000000..5d7b94d --- /dev/null +++ b/cnmodel/cells/tests/cell_data/tstellate_mouse-typeI-c.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2990652711db28fa846886f1399faecb4d4680fd8014cbc006636c215248263d +size 14815 diff --git a/cnmodel/cells/tests/cell_data/tuberculoventral_mouse_I.pk b/cnmodel/cells/tests/cell_data/tuberculoventral_mouse_I.pk new file mode 100644 index 0000000..6f7cbe0 --- /dev/null +++ b/cnmodel/cells/tests/cell_data/tuberculoventral_mouse_I.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f50fb610552b181dfd0130245ee41bcbe745d4fc856abfe7f5ad180e84773a5 +size 13267 diff --git a/cnmodel/cells/tests/test_cells.py b/cnmodel/cells/tests/test_cells.py new file mode 100644 index 0000000..858767a --- /dev/null +++ b/cnmodel/cells/tests/test_cells.py @@ -0,0 +1,227 @@ +import os, pickle, pprint +import numpy as np +import neuron + +import cnmodel +import cnmodel.cells as cells +from cnmodel.util import UserTester, reset +from cnmodel.protocols import IVCurve + +""" +Cell-type tests +""" + + +def test_bushy(): + reset(raiseError=False) + cell = cells.Bushy.create(species="guineapig", modelType="II") + CellTester("bushy_guineapig-typeII", cell) + + +def test_bushy21(): + reset(raiseError=False) + cell = cells.Bushy.create(species="guineapig", modelType="II-I") + CellTester("bushy_guineapig-typeII-I", cell) + + +def test_bushy_mouse(): + reset(raiseError=False) + cell = cells.Bushy.create(species="mouse", modelType="II") + CellTester("bushy-mouse-typeII", cell) + + +def test_tstellate(): + reset(raiseError=False) + cell = cells.TStellate.create(species="guineapig", modelType="I-c") + CellTester("tstellate_guineapig-typeI-c", cell) + + +def test_tstellate_mouse(): + reset(raiseError=False) + cell = cells.TStellate.create(species="mouse", modelType="I-c") + CellTester("tstellate_mouse-typeI-c", cell) + + +def test_tstellatet(): + reset(raiseError=False) + cell = cells.TStellate.create(species="guineapig", modelType="I-t") + CellTester("tstellate_guineapig-typeI-t", cell) + + +# not implemented yet +# def test_tstellatet_mouse(): +# reset(raiseError=False) +# cell = cells.TStellate.create(species='mouse', modelType='I-t') +# CellTester('tstellate_mouse-typeI-t', cell) + + +def test_dstellate(): + reset(raiseError=False) + cell = cells.DStellate.create(species="guineapig", modelType="I-II") + CellTester("dstellate_guineapig-typeI-II", cell) + + +def test_dstellate_mouse(): + reset(raiseError=False) + cell = cells.DStellate.create(species="mouse", modelType="I-II") + CellTester("dstellate_mouse-typeI-II", cell) + + +def test_octopus(): + reset(raiseError=False) + cell = cells.Octopus.create(species="guineapig", modelType="II-o") + CellTester("octopus_guineapig-typeII-o", cell) + + +def test_pyramidal(): + reset(raiseError=False) + cell = cells.Pyramidal.create(species="rat", modelType="I") + CellTester("pyramidal_rat_I", cell) + + +def test_tuberculoventral(): + reset(raiseError=False) + cell = cells.Tuberculoventral.create(species="mouse", modelType="TVmouse") + CellTester("tuberculoventral_mouse_I", cell) + + +def test_cartwheel(): + reset(raiseError=False) + cell = cells.Cartwheel.create(species="mouse", modelType="I") + CellTester("cartwheel_rat_I", cell) + + +def test_sgc_basal_middle(): + reset(raiseError=False) + cell = cells.SGC.create(species="mouse", modelType="bm") + CellTester("SGC_rat_bm", cell) + + +def test_sgc_apical(): + reset(raiseError=False) + cell = cells.SGC.create(species="mouse", modelType="a") + CellTester("SGC_rat_a", cell) + + +# +# Supporting functions +# + + +class CellTester(UserTester): + data_dir = "cell_data" + + def run_test(self, cell): + # run I/V test on cell + V0 = cell.find_i0(showinfo=True) + rmrintau = cell.compute_rmrintau(auto_initialize=False, vrange=None) + iv = IVCurve() + self.iv = iv + iv.run(cell.i_test_range, cell) + if self.audit: + iv.show(cell) + + info = dict( + temp=iv.temp, + icmd=iv.current_cmd, + spikes=iv.spike_times(), + rmp=iv.rest_vm(), + rm_taum=iv.input_resistance_tau(), + vpeak=iv.peak_vm(), + vss=iv.steady_vm(), + rmrintau=rmrintau, + ) + return info + + def assert_test_info(self, *args, **kwds): + try: + super(CellTester, self).assert_test_info(*args, **kwds) + finally: + if hasattr(self, "iv") and hasattr(self.iv, "win"): + self.iv.win.hide() + + +# def result_file(key): +# """ +# Return a file name to be used for storing / retrieving test results +# given *key*. +# """ +# path = os.path.dirname(__file__) +# return os.path.join(path, 'cell_data', key + '.pk') + +# def load_cell_info(key): +# """ +# Load prior test results for *key*. +# If there are no prior results, return None. +# """ +# fn = result_file(key) +# if os.path.isfile(fn): +# return pickle.load(open(fn, 'rb')) +# return None + +# def save_cell_info(info, key): +# """ +# Store test results for *key*. +# """ +# fn = result_file(key) +# dirname = os.path.dirname(fn) +# if not os.path.isdir(dirname): +# os.mkdir(dirname) +# pickle.dump(info, open(fn, 'wb')) + + +# The following is superseeded by the built in unit tests. +# def CellTester(key): +# """ +# Test *cell* and raise exception if the results do not match prior +# data. +# """ +# audit = cnmodel.AUDIT_TESTS + +## run I/V test on cell +# iv = IVCurve() +# iv.run(cell.i_test_range, cell) +# iv.show(cell) + +# try: +# info = dict( +# icmd=iv.current_cmd, +# spikes=iv.spike_times(), +# rmp=iv.rest_vm(), +# rm=iv.input_resistance(), +# vpeak=iv.peak_vm(), +# vss=iv.steady_vm(), +# ) + +# expect = load_cell_info(key) + +# if expect is not None: + +## Check test structures are the same +# assert len(info) == len(expect) +# for k in info: +# assert k in expect + +## Check data matches +# for k in info: +# if isinstance(info[k], list): +# assert len(info[k]) == len(expect[k]) +# for i in range(len(info[k])): +# assert np.allclose(info[k][i], expect[k][i]) +# else: +# assert np.allclose(info[k], expect[k]) +# else: +# if not audit: +# raise Exception("No prior test results for cell type '%s'. " +# "Run test.py --audit store new test data." % key) + +# print "\n=== New test results for %s: ===\n" % key +# pprint.pprint(info) +# print "Store new test results? [y/n]", +# yn = raw_input() +# if yn.lower().startswith('y'): +# save_cell_info(info, key) +# else: +# raise Exception("Rejected test results for '%s'" % key) +# finally: +# iv.win.hide() diff --git a/cnmodel/cells/tstellate.py b/cnmodel/cells/tstellate.py new file mode 100644 index 0000000..7b329c3 --- /dev/null +++ b/cnmodel/cells/tstellate.py @@ -0,0 +1,1089 @@ +from __future__ import print_function +from neuron import h +import numpy as np + +from .cell import Cell + +# from .. import synapses +from ..util import nstomho +from ..util import Params +from .. import data + +__all__ = ["TStellate", "TStellateRothman", "TStellateNav11"] + + +class TStellate(Cell): + + type = "tstellate" + + @classmethod + def create(cls, model="RM03", **kwds): + if model == "RM03": # original Rothman-Manis 2003, 22C, point cell, extendable + return TStellateRothman(**kwds) + elif model == "Nav11": # Xie-Manis, 2013, 37C, pointe cell, extendable + return TStellateNav11(**kwds) + else: + raise ValueError("TStellate type %s is unknown", type) + + def make_psd(self, terminal, psd_type, **kwds): + """ + Connect a presynaptic terminal to one post section at the specified location, with the fraction + of the "standard" conductance determined by gbar. + The default condition is to try to pass the default unit test (loc=0.5) + + Scaling is corrected by initial release probability now. + + Parameters + ---------- + terminal : Presynaptic terminal (NEURON object) + + psd_type : either simple or multisite PSD for bushy cell + + kwds: dict of options. + Available options: + postsize : expect a list consisting of [sectionno, location (float)] + AMPAScale : float to scale the ampa currents + + + """ + if ( + "postsite" in kwds + ): # use a defined location instead of the default (soma(0.5) + postsite = kwds["postsite"] + loc = postsite[1] # where on the section? + uname = ( + "sections[%d]" % postsite[0] + ) # make a name to look up the neuron section object + post_sec = self.hr.get_section(uname) # Tell us where to put the synapse. + else: + loc = 0.5 + post_sec = self.soma + # print('cells/tstellaty.py psd type: ', psd_type) + if psd_type == "simple": + if terminal.cell.type in ["sgc", "dstellate", "tuberculoventral"]: + weight = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="weight", + ) + tau1 = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="tau1", + ) + tau2 = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="tau2", + ) + erev = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="erev", + ) + return self.make_exp2_psd( + post_sec, + terminal, + weight=weight, + loc=loc, + tau1=tau1, + tau2=tau2, + erev=erev, + ) + else: + raise TypeError( + "Cannot make simple PSD for %s => %s" + % (terminal.cell.type, self.type) + ) + + # print('cells/tstellaty.py weight: ', weight) + elif psd_type == "multisite": + if terminal.cell.type == "sgc": + # Max conductances for the glu mechanisms are calibrated by + # running `synapses/tests/test_psd.py`. The test should fail + # if these values are incorrect + self.AMPAR_gmax = ( + data.get( + "sgc_synapse", + species=self.species, + post_type=self.type, + field="AMPAR_gmax", + ) + * 1e3 + ) + self.NMDAR_gmax = ( + data.get( + "sgc_synapse", + species=self.species, + post_type=self.type, + field="NMDAR_gmax", + ) + * 1e3 + ) + self.Pr = data.get( + "sgc_synapse", species=self.species, post_type=self.type, field="Pr" + ) + # adjust gmax to correct for initial Pr + self.AMPAR_gmax = self.AMPAR_gmax / self.Pr + self.NMDAR_gmax = self.NMDAR_gmax / self.Pr + # old values: + # AMPA_gmax = 0.22479596944138733*1e3 # factor of 1e3 scales to pS (.mod mechanisms) from nS. + # NMDA_gmax = 0.12281291946623739*1e3 + if "AMPAScale" in kwds: + self.AMPAR_gmax = ( + self.AMPAR_gmax * kwds["AMPAScale"] + ) # allow scaling of AMPA conductances + if "NMDAScale" in kwds: + self.NMDAR_gmax = self.NMDAR_gmax * kwds["NMDAScale"] + return self.make_glu_psd( + post_sec, terminal, self.AMPAR_gmax, self.NMDAR_gmax, loc=loc + ) + elif terminal.cell.type == "dstellate": + self.ds_gmax = ( + data.get( + "dstellate_synapse", + species=self.species, + post_type=self.type, + field="gly_gmax", + ) + * 1e3 + ) + # print('ds max: ', self.ds_gmax) + return self.make_gly_psd( + post_sec, terminal, psdtype="glyfast", loc=loc, gmax=self.ds_gmax + ) + elif terminal.cell.type == "tuberculoventral": + self.tv_gmax = ( + data.get( + "tuberculoventral_synapse", + species=self.species, + post_type=self.type, + field="gly_gmax", + ) + * 1e3 + ) + return self.make_gly_psd( + post_sec, terminal, psdtype="glyfast", loc=loc, gmax=self.tv_gmax + ) + else: + raise TypeError( + "Cannot make PSD for %s => %s" % (terminal.cell.type, self.type) + ) + else: + raise ValueError("Unsupported psd type %s" % psd_type) + + +class TStellateRothman(TStellate): + """ + VCN T-stellate base model. + Rothman and Manis, 2003abc (Type I-c, Type I-t) + """ + + def __init__( + self, + morphology=None, + decorator=None, + nach=None, + ttx=False, + temperature=None, + species="guineapig", + modelType=None, + modelName=None, + debug=False, + ): + """ + Initialize a planar stellate (T-stellate) cell, using the default parameters for guinea pig from + R&M2003, as a type I cell. + Modifications to the cell can be made by calling methods below. These include: + Converting to a type IA model (add transient K current) (species: guineapig-TypeIA). + Changing "species" to mouse or cat (scales conductances) + + Parameters + ---------- + morphology : string (default: None) + a file name to read the cell morphology from. If a valid file is found, a cell is constructed + as a cable model from the hoc file. + If None (default), the only a point model is made, exactly according to RM03. + + decorator : Python function (default: None) + decorator is a function that "decorates" the morphology with ion channels according + to a set of rules. + If None, a default set of channels aer inserted into the first soma section, and the + rest of the structure is "bare". + + nach : string (default: None) + nach selects the type of sodium channel that will be used in the model. A channel mechanism + by that name must exist. The default is 'nacn', from R&M2003. + + ttx : Boolean (default: False) + If ttx is True, then the sodium channel conductance is set to 0 everywhere in the cell. + Currently, this is not implemented. + + species: string (default 'guineapig') + species defines the channel density that will be inserted for different models. Note that + if a decorator function is specified, this argument is ignored. + + modelType: string (default: None) + modelType specifies the type of the model that will be used (e.g., "I-c", "I-t"). + modelType is passed to the decorator, or to species_scaling to adjust point models. + + debug: boolean (default: False) + debug is a boolean flag. When set, there will be multiple printouts of progress and parameters. + + Returns + ------- + Nothing + """ + + super(TStellateRothman, self).__init__() + self.i_test_range = {"pulse": (-0.15, 0.15, 0.01)} + if modelType is None: + modelType = "I-c" + if species == "guineapig": + modelName = "RM03" + temp = 22.0 + if nach == None: + nach = "nacn" + if species == "mouse": + temp = 34.0 + if modelName is None: + modelName = "XM13" + if nach == None: + nach = "nacn" + self.i_test_range = {"pulse": (-1.0, 1.0, 0.05)} + self.debug = debug + self.status = { + "species": species, + "cellClass": self.type, + "modelType": modelType, + "modelName": modelName, + "soma": True, + "axon": False, + "dendrites": False, + "pumps": False, + "na": nach, + "ttx": ttx, + "name": self.type, + "morphology": morphology, + "decorator": decorator, + "temperature": None, + } + self.c_m = 0.9e-6 # default in units of F/cm^2 + self.spike_threshold = ( + -40.0 + ) # matches threshold in released CNModel (set in base cell class) + self.vrange = [-70.0, -55.0] + self._valid_temperatures = (temp,) + if self.status["temperature"] == None: + self.status["temperature"] = temp + + if morphology is None: + """ + instantiate a basic soma-only ("point") model + """ + if self.debug: + print( + "<< TStellate model: Creating point cell, type={:s} >>".format( + modelType + ) + ) + soma = h.Section( + name="TStellate_Soma_%x" % id(self) + ) # one compartment of about 29000 um2 + soma.nseg = 1 + self.add_section(soma, "soma") + else: + """ + instantiate a structured model with the morphology as specified by + the morphology file + """ + if self.debug: + print("<< TStellate: Creating cell with morphology = %s>>" % morphology) + self.set_morphology(morphology_file=morphology) + + # decorate the morphology with ion channels + if decorator is None: # basic model, only on the soma + self.mechanisms = ["kht", "ka", "ihvcn", "leak", nach] + for mech in self.mechanisms: + self.soma.insert(mech) + self.soma.ek = self.e_k + self.soma.ena = self.e_na + self.soma().ihvcn.eh = self.e_h + self.soma().leak.erev = self.e_leak + self.species_scaling( + silent=True, species=species, modelType=modelType + ) # set the default type II cell parameters + else: # decorate according to a defined set of rules on all cell compartments + self.decorate() + + self.save_all_mechs() # save all mechanisms inserted, location and gbar values... + self.get_mechs(self.soma) + if self.debug: + print("<< T-stellate: JSR Stellate Type 1 cell model created >>") + + def get_cellpars(self, dataset, species="guineapig", modelType="I-c"): + cellcap = data.get( + dataset, species=species, model_type=modelType, field="soma_Cap" + ) + chtype = data.get( + dataset, species=species, model_type=modelType, field="na_type" + ) + pars = Params(cap=cellcap, natype=chtype) + # pars.show() + + if self.status["modelName"] == "RM03": + for g in [ + "%s_gbar" % pars.natype, + "kht_gbar", + "ka_gbar", + "ih_gbar", + "leak_gbar", + "leak_erev", + "ih_eh", + "e_k", + "e_na", + ]: + pars.additem( + g, data.get(dataset, species=species, model_type=modelType, field=g) + ) + if self.status["modelName"] == "XM13": + for g in [ + "%s_gbar" % pars.natype, + "kht_gbar", + "ka_gbar", + "ihvcn_gbar", + "leak_gbar", + "leak_erev", + "ih_eh", + "e_k", + "e_na", + ]: + pars.additem( + g, data.get(dataset, species=species, model_type=modelType, field=g) + ) + if self.status["modelName"] == "mGBC": + for g in [ + "%s_gbar" % pars.natype, + "kht_gbar", + "ka_gbar", + "ihvcn_gbar", + "leak_gbar", + "leak_erev", + "ih_eh", + "e_k", + "e_na", + ]: + pars.additem( + g, data.get(dataset, species=species, model_type=modelType, field=g) + ) + return pars + + def species_scaling(self, species="guineapig", modelType="I-c", silent=True): + """ + Adjust all of the conductances and the cell size according to the species requested. + Used ONLY for point models. + + This scaling routine also sets the temperature for the model to a default value. Some models + can be run at multiple temperatures, and so a default from one of the temperatures is used. + The calling cell.set_temperature(newtemp) will change the conductances and reinitialize + the cell to the new temperature settings. + + Parameters + ---------- + species : string (default: 'guineapig') + name of the species to use for scaling the conductances in the base point model + Must be one of mouse, cat, guineapig + + modelType: string (default: 'I-c') + definition of model type from RM03 models, type I-c or type I-t + + silent : boolean (default: True) + run silently (True) or verbosely (False) + """ + soma = self.soma + if modelType == "I-c": + celltype = "tstellate" + elif modelType == "I-t": + celltype = "tstellate-t" + else: + raise ValueError("model type not recognized") + + if species == "mouse": # and modelType == 'I-c': + # use conductance levels from Cao et al., J. Neurophys., 2007. + # model description in Xie and Manis 2013. Note that + # conductances were not scaled for temperature (rates were) + # so here we reset the default Q10's for conductance (g) to 1.0 + if self.debug: + print( + " Setting Conductances for mouse I-c Tstellate cell, (modified from Xie and Manis, 2013)" + ) + self.c_m = 0.9 # default in units of F/cm^2 + dataset = "XM13_channels" + self.vrange = [-75.0, -55.0] + self.set_soma_size_from_Cm(25.0) + self._valid_temperatures = (34.0,) + if self.status["temperature"] is None: + self.set_temperature(34.0) + + pars = self.get_cellpars(dataset, species=species, modelType=modelType) + # pars.show() + self.set_soma_size_from_Cm(pars.cap) + self.status["na"] = pars.natype + self.adjust_na_chans(soma, gbar=pars.nacn_gbar, sf=1.0) + soma().kht.gbar = nstomho(pars.kht_gbar, self.somaarea) + soma().ka.gbar = nstomho(pars.ka_gbar, self.somaarea) + soma().ihvcn.gbar = nstomho(pars.ihvcn_gbar, self.somaarea) + soma().ihvcn.eh = pars.ih_eh # Rodrigues and Oertel, 2006 + soma().leak.gbar = nstomho(pars.leak_gbar, self.somaarea) + soma().leak.erev = pars.leak_erev + self.e_k = pars.e_k + self.e_na = pars.e_na + soma.ena = self.e_na + soma.ek = self.e_k + self.axonsf = 0.5 + + elif species == "guineapig": + # and modelType == 'I-c': # values from R&M 2003, Type I + if self.debug: + print( + " Setting Conductances for Guinea Pig I-c, Rothman and Manis, 2003" + ) + dataset = "RM03_channels" + self.c_m = 0.9 # default in units of F/cm^2 + self.vrange = [-75.0, -55.0] + self._valid_temperatures = (22.0, 38.0) + if self.status["temperature"] is None: + self.set_temperature(22.0) + sf = 1.0 + if ( + self.status["temperature"] == 38.0 + ): # adjust for 2003 model conductance levels at 38 + sf = 3.03 # Q10 of 2, 22->38C. (p3106, R&M2003c) + # note that kinetics are scaled in the mod file. + pars = self.get_cellpars(dataset, species=species, modelType=modelType) + self.set_soma_size_from_Cm(pars.cap) + self.status["na"] = pars.natype + # pars.show() + self.adjust_na_chans(soma, gbar=pars.nacn_gbar, sf=sf) + soma().kht.gbar = nstomho(pars.kht_gbar, self.somaarea) + soma().ka.gbar = nstomho(pars.ka_gbar, self.somaarea) + soma().ihvcn.gbar = nstomho(pars.ih_gbar, self.somaarea) + soma().leak.gbar = nstomho(pars.leak_gbar, self.somaarea) + soma().leak.erev = pars.leak_erev + self.axonsf = 0.5 + + else: + raise ValueError( + "Species %s or species-type %s is not recognized for T-stellate cells" + % (species, type) + ) + + self.status["species"] = species + self.status["modelType"] = modelType + self.check_temperature() + + # def channel_manager(self, modelType='RM03'): + # """ + # This routine defines channel density maps and distance map patterns + # for each type of compartment in the cell. The maps + # are used by the ChannelDecorator class (specifically, called from it's private + # _biophys function) to decorate the cell membrane with channels. + # + # Parameters + # ---------- + # modelType : string (default: 'RM03') + # A string that defines the type of the model. Currently, 3 types are implemented: + # RM03: Rothman and Manis, 2003 somatic densities for guinea pig + # XM13: Xie and Manis, 2013, somatic densities for mouse + # XM13PasDend: XM13, but with only passive dendrites, no channels. + # + # Returns + # ------- + # Nothing + # + # Notes + # ----- + # + # This routine defines the following variables for the class: + # + # - conductances (gBar) + # - a channelMap (dictonary of channel densities in defined anatomical compartments) + # - a current injection range for IV's (when testing) + # - a distance map, which defines how selected conductances in selected compartments + # will change with distance. This includes both linear and exponential gradients, + # the minimum conductance at the end of the gradient, and the space constant or + # slope for the gradient. + # + # """ + # if modelType == 'RM03': + # totcap = 12.0E-12 # TStellate cell (type I) from Rothman and Manis, 2003, as base model + # refarea = totcap / self.c_m # see above for units + # # Type I stellate Rothman and Manis, 2003c + # self._valid_temperatures = (22., 38.) + # if self.status['temperature'] is None: + # self.set_temperature(22.) + # sf = 1.0 + # if self.status['temperature'] == 38.: # adjust for 2003 model conductance levels at 38 + # sf = 3.03 # Q10 of 2, 22->38C. (p3106, R&M2003c) + # self.gBar = Params(nabar=sf*1000.0E-9/refarea, + # khtbar=sf*150.0E-9/refarea, + # kltbar=sf*0.0E-9/refarea, + # ihbar=sf*0.5E-9/refarea, + # leakbar=sf*2.0E-9/refarea, + # ) + # + # self.channelMap = { + # 'axon': {'nacn': 0.0, 'klt': 0., 'kht': self.gBar.khtbar, + # 'ihvcn': 0., 'leak': self.gBar.leakbar / 4.}, + # 'hillock': {'nacn': self.gBar.nabar, 'klt': 0., 'kht': self.gBar.khtbar, + # 'ihvcn': 0., 'leak': self.gBar.leakbar, }, + # 'initseg': {'nacn': self.gBar.nabar, 'klt': 0., 'kht': self.gBar.khtbar, + # 'ihvcn': self.gBar.ihbar / 2., + # 'leak': self.gBar.leakbar, }, + # 'soma': {'nacn': self.gBar.nabar, 'klt': self.gBar.kltbar, + # 'kht': self.gBar.khtbar, 'ihvcn': self.gBar.ihbar, + # 'leak': self.gBar.leakbar, }, + # 'dend': {'nacn': self.gBar.nabar / 2.0, 'klt': 0., 'kht': self.gBar.khtbar * 0.5, + # 'ihvcn': self.gBar.ihbar / 3., 'leak': self.gBar.leakbar * 0.5, }, + # 'apic': {'nacn': 0.0, 'klt': 0., 'kht': self.gBar.khtbar * 0.2, + # 'ihvcn': self.gBar.ihbar / 4., + # 'leak': self.gBar.leakbar * 0.2, }, + # } + # self.irange = np.linspace(-0.1, 0.1, 7) + # self.distMap = {'dend': {'klt': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # 'kht': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}}, # linear with distance, gminf (factor) is multiplied by gbar + # 'apic': {'klt': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # 'kht': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}}, # gradients are: flat, linear, exponential + # } + # + # elif modelType == 'XM13': + # totcap = 25.0E-12 # Base model from Xie and Manis, 2013 for type I stellate cell + # refarea = totcap / self.c_m # see above for units + # self._valid_temperatures = (34.,) + # if self.status['temperature'] is None: + # self.set_temperature(34.) + # self.gBar = Params(nabar=1800.0E-9/refarea, + # khtbar=250.0E-9/refarea, + # kltbar=0.0E-9/refarea, + # ihbar=18.0E-9/refarea, + # leakbar=8.0E-9/refarea, + # ) + # self.channelMap = { + # 'axon': {'nav11': 0.0, 'klt': 0., 'kht': self.gBar.khtbar, + # 'ihvcn': 0., 'leak': self.gBar.leakbar / 4.}, + # 'hillock': {'nav11': self.gBar.nabar, 'klt': 0., 'kht': self.gBar.khtbar, + # 'ihvcn': 0., + # 'leak': self.gBar.leakbar, }, + # 'initseg': {'nav11': self.gBar.nabar, 'klt': 0., 'kht': self.gBar.khtbar, + # 'ihvcn': self.gBar.ihbar / 2., + # 'leak': self.gBar.leakbar, }, + # 'soma': {'nav11': self.gBar.nabar, 'klt': self.gBar.kltbar, + # 'kht': self.gBar.khtbar, 'ihvcn': self.gBar.ihbar, + # 'leak': self.gBar.leakbar, }, + # 'dend': {'nav11': self.gBar.nabar, 'klt': 0., 'kht': self.gBar.khtbar * 0.5, + # 'ihvcn': self.gBar.ihbar / 3., 'leak': self.gBar.leakbar * 0.5, }, + # 'apic': {'nav11': 0.0, 'klt': 0., 'kht': self.gBar.khtbar * 0.2, + # 'ihvcn': self.gBar.ihbar / 4., + # 'leak': self.gBar.leakbar * 0.2, }, + # } + # self.irange = np.linspace(-0.5, 0.5, 9) + # self.distMap = {'dend': {'klt': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # 'kht': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # 'nav11': {'gradient': 'exp', 'gminf': 0., 'lambda': 100.}}, # linear with distance, gminf (factor) is multiplied by gbar + # 'apic': {'klt': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # 'kht': {'gradient': 'linear', 'gminf': 0., 'lambda': 100.}, + # 'nav11': {'gradient': 'exp', 'gminf': 0., 'lambda': 100.}}, # gradients are: flat, linear, exponential + # } + # + # elif modelType == 'XM13PasDend': + # # bushy form Xie and Manis, 2013, based on Cao and Oertel mouse conductances + # # passive dendritestotcap = 26.0E-12 # uF/cm2 + # totcap = 26.0E-12 # uF/cm2 + # refarea = totcap / self.c_m # see above for units + # self._valid_temperatures = (34.,) + # if self.status['temperature'] is None: + # self.set_temperature(34.) + # self.gBar = Params(nabar=1000.0E-9/refarea, + # khtbar=150.0E-9/refarea, + # kltbar=0.0E-9/refarea, + # ihbar=0.5E-9/refarea, + # leakbar=2.0E-9/refarea, + # ) + # self.channelMap = { + # 'axon': {'nav11': self.gBar.nabar*0, 'klt': self.gBar.kltbar * 0.25, 'kht': self.gBar.khtbar, 'ihvcn': 0., + # 'leak': self.gBar.leakbar * 0.25}, + # 'hillock': {'nav11': self.gBar.nabar, 'klt': self.gBar.kltbar, 'kht': self.gBar.khtbar, 'ihvcn': 0., + # 'leak': self.gBar.leakbar, }, + # 'initseg': {'nav11': self.gBar.nabar*3, 'klt': self.gBar.kltbar*2, 'kht': self.gBar.khtbar*2, + # 'ihvcn': self.gBar.ihbar * 0.5, 'leak': self.gBar.leakbar, }, + # 'soma': {'nav11': self.gBar.nabar, 'klt': self.gBar.kltbar, 'kht': self.gBar.khtbar, + # 'ihvcn': self.gBar.ihbar, 'leak': self.gBar.leakbar, }, + # 'dend': {'nav11': self.gBar.nabar * 0.0, 'klt': self.gBar.kltbar*0 , 'kht': self.gBar.khtbar*0, + # 'ihvcn': self.gBar.ihbar*0, 'leak': self.gBar.leakbar*0.5, }, + # 'apic': {'nav11': self.gBar.nabar * 0.0, 'klt': self.gBar.kltbar * 0, 'kht': self.gBar.khtbar * 0., + # 'ihvcn': self.gBar.ihbar *0., 'leak': self.gBar.leakbar * 0.25, }, + # } + # self.irange = np.linspace(-1, 1, 21) + def get_distancemap(self): + return { + "dend": { + "klt": {"gradient": "linear", "gminf": 0.0, "lambda": 200.0}, + "kht": {"gradient": "llinear", "gminf": 0.0, "lambda": 200.0}, + "nav11": {"gradient": "linear", "gminf": 0.0, "lambda": 200.0}, + }, # linear with distance, gminf (factor) is multiplied by gbar + "apic": { + "klt": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "kht": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "nav11": {"gradient": "exp", "gminf": 0.0, "lambda": 200.0}, + }, # gradients are: flat, linear, exponential + } + # else: + # raise ValueError('model type %s is not implemented' % modelType) + # self.check_temperature() + + def adjust_na_chans(self, soma, sf=1.0, gbar=1000.0): + """ + Adjust the sodium channel conductance, depending on the type of conductance + + Parameters + ---------- + soma : NEURON section object (required) + This identifies the soma object whose sodium channel complement will have it's + conductances adjusted depending on the sodium channel type + gbar : float (default: 1000.) + The "maximal" conductance to be set in the model. + + Returns + ------- + Nothing + """ + if self.status["ttx"]: + gnabar = 0.0 + else: + gnabar = nstomho(gbar, self.somaarea) * sf + nach = self.status["na"] + if nach == "jsrna": + soma().jsrna.gbar = gnabar * sf + soma.ena = self.e_na + if self.debug: + print("jsrna gbar: ", soma().jsrna.gbar) + elif nach == "nav11": + soma().nav11.gbar = gnabar + soma.ena = self.e_na + soma().nav11.vsna = 4.3 + if self.debug: + print("tstellate using inva11") + print("nav11 gbar: ", soma().nav11.gbar) + print("nav11 vsna: ", soma().nav11.vsna) + elif nach == "na": + soma().nacn.gbar = gnabar + soma.ena = self.e_na + if self.debug: + print("na gbar: ", soma().na.gbar) + elif nach == "nacn": + soma().nacn.gbar = gnabar + soma.ena = self.e_na + if self.debug: + print("nacn gbar: ", soma().nacn.gbar) + else: + raise ValueError( + "tstellate setting Na channels: channel %s not known" % nach + ) + + def add_axon(self): + Cell.add_axon(self, self.soma, self.somaarea, self.c_m, self.R_a, self.axonsf) + + def add_dendrites(self): + """ + Add simple unbranched dendrites to basic Rothman Type I models. + The dendrites have some kht and ih current + """ + cs = False # not implemented outside here - internal Cesium. + nDend = range(4) # these will be simple, unbranced, N=4 dendrites + dendrites = [] + for i in nDend: + dendrites.append(h.Section(cell=self.soma)) + for i in nDend: + dendrites[i].connect(self.soma) + dendrites[i].L = 200 # length of the dendrite (not tapered) + dendrites[i].diam = 1.5 # dendrite diameter + dendrites[i].nseg = 21 # # segments in dendrites + dendrites[i].Ra = 150 # ohm.cm + dendrites[i].insert("kht") + if cs is False: + dendrites[i]().kht.gbar = 0.005 # a little Ht + else: + dendrites[i]().kht.gbar = 0.0 + dendrites[i].insert("leak") # leak + dendrites[i]().leak.gbar = 0.0001 + dendrites[i].insert("ihvcn") # some H current + dendrites[i]().ihvcn.gbar = 0.0 # 0.001 + dendrites[i]().ihvcn.eh = -43.0 + self.maindend = dendrites + self.status["dendrites"] = True + self.add_section(self.maindend, "maindend") + + +class TStellateNav11(TStellate): + """ + VCN T-stellate cell (Mouse) from Xie and Manis, 2013. + Using nav11 sodium channel model. + + """ + + def __init__( + self, + morphology=None, + decorator=None, + nach="nav11", + ttx=False, + species="mouse", + modelType=None, + debug=False, + ): + """ + Initialize a planar stellate (T-stellate) cell as a point model, using the default parameters for + mouse from Xie and Manis, 2013. + Modifications to the cell can be made by calling methods below. + Changing "species": This routine only supports "mouse" + *Note:* in the original model, the temperature scaling applied only to the rate constants, and not + to the conductance. Therefore, the conductances here need to be adjusted to compensate for the + way the mechanisms are currently implemented (so that they scale correctly to the values + used in Xie and Manis, 2013). This is done by setting q10g (the q10 for conductances) to 1 + before setting up the rest of the model parameters. For those conducantances in which a Q10 for + conductance is implemented, the value is typically 2. + + Parameters + ---------- + morphology : string (default: None) + a file name to read the cell morphology from. If a valid file is found, a cell is constructed + as a cable model from the hoc file. + If None (default), the only a point model is made, exactly according to RM03. + + decorator : Python function (default: None) + decorator is a function that "decorates" the morphology with ion channels according + to a set of rules. + If None, a default set of channels aer inserted into the first soma section, and the + rest of the structure is "bare". + + nach : string (default: 'nav11') + nach selects the type of sodium channel that will be used in the model. A channel mechanims + by that name must exist. + + ttx : Boolean (default: False) + If ttx is True, then the sodium channel conductance is set to 0 everywhere in the cell. + Currently, this is not implemented. + + species: string (default 'mouse') + species defines the channel density that will be inserted for different models. Note that + if a decorator function is specified, this argument is ignored. + + modelType: string (default: None) + modelType specifies the type of the model that will be used (e.g., "II", "II-I", etc). + modelType is passed to the decorator, or to species_scaling to adjust point models. + + debug: boolean (default: False) + debug is a boolean flag. When set, there will be multiple printouts of progress and parameters. + + Returns + ------- + Nothing + """ + + super(TStellateNav11, self).__init__() + if modelType == None: + modelType = "XM13" + self.status = { + "soma": True, + "axon": False, + "dendrites": False, + "pumps": False, + "na": nach, + "species": species, + "modelType": modelType, + "ttx": ttx, + "name": "TStellate", + "morphology": morphology, + "decorator": decorator, + } + + self.i_test_range = (-1, 1.0, 0.05) + + if morphology is None: + """ + instantiate a basic soma-only ("point") model + """ + print( + "<< TStellate Xie&Manis 2013 model: Creating point cell, type={:s} >>".format( + modelType + ) + ) + soma = h.Section( + name="TStellate_Soma_%x" % id(self) + ) # one compartment of about 29000 um2 + soma.nseg = 1 + self.add_section(soma, "soma") + else: + """ + instantiate a structured model with the morphology as specified by + the morphology file + """ + print("<< TStellate Xie&Manis 2013 model: Creating structured cell >>") + self.set_morphology(morphology_file=morphology) + + # decorate the morphology with ion channels + if decorator is None: # basic model, only on the soma + self.mechanisms = ["kht", "ka", "ihvcn", "leak", nach] + for mech in self.mechanisms: + self.soma.insert(mech) + self.soma.ek = self.e_k + self.soma.ena = self.e_na + self.soma().ihvcn.eh = self.e_h + self.soma().leak.erev = self.e_leak + self.soma().cm = 1.0 + self.species_scaling( + silent=True, species=species, modelType=modelType + ) # set the default type II cell parameters + else: # decorate according to a defined set of rules on all cell compartments + self.decorate() + + self.get_mechs(self.soma) + self.cell_initialize(vrange=self.vrange) + # self.print_mechs(self.soma) + if self.debug: + print("<< T-stellate: Xie&Manis 2013 cell model created >>") + + def species_scaling(self, species="mouse", modelType="I-c", silent=True): + """ + Adjust all of the conductances and the cell size according to the species requested. + Used ONLY for point models. + + Parameters + ---------- + species : string (default: 'guineapig') + name of the species to use for scaling the conductances in the base point model + Must be one of mouse, cat, guineapig + + modelType: string (default: 'I-c') + definition of model type from RM03 models, type I-c or type I-t + + silent : boolean (default: True) + run silently (True) or verbosely (False) + """ + soma = self.soma + if species == "mouse" and modelType == "XM13": + # use conductance levels from Cao et al., J. Neurophys., 2007. + # original temp for model: 32 C + print("Mouse Tstellate cell, Xie and Manis, 2013") + self.set_soma_size_from_Cm(25.0) + self.adjust_na_chans(soma, gbar=800.0) # inav11 does not scale conductance + self.e_k = -84.0 + self.e_na = 50.0 + soma.ek = self.e_k + soma.ena = self.e_na + soma().kht.gbar = nstomho(250.0, self.somaarea) + soma().ka.gbar = nstomho(0.0, self.somaarea) + soma().ihvcn.gbar = nstomho(18.0, self.somaarea) + soma().ihvcn.eh = -43 # Rodrigues and Oertel, 2006 + soma().leak.gbar = nstomho(8.0, self.somaarea) + soma().leak.erev = -65.0 + + else: + raise ValueError( + "Species %s or species-type %s is not recognized for T-stellate XM13 cells" + % (species, type) + ) + + self.status["species"] = species + self.status["modelType"] = modelType + # self.cell_initialize(showinfo=False) + # if not silent: + # print 'set cell as: ', species + # print ' with Vm rest = %f' % self.vm0 + + def channel_manager(self, modelType="XM13"): + """ + This routine defines channel density maps and distance map patterns + for each type of compartment in the cell. The maps + are used by the ChannelDecorator class (specifically, called from it's private + _biophys function) to decorate the cell membrane with channels. + + Parameters + ---------- + modelType : string (default: 'XM13') + A string that defines the type of the model. Currently, 3 types are implemented: + XM13: Xie and Manis, 2013, somatic densities for mouse + XM13PasDend: XM13, but with only passive dendrites, no channels. + + Returns + ------- + Nothing + + Notes + ----- + + This routine defines the following variables for the class: + + - conductances (gBar) + - a channelMap (dictonary of channel densities in defined anatomical compartments) + - a current injection range for IV's (when testing) + - a distance map, which defines how selected conductances in selected compartments + will change with distance. This includes both linear and exponential gradients, + the minimum conductance at the end of the gradient, and the space constant or + slope for the gradient. + + """ + if modelType == "XM13": + totcap = ( + 25.0e-12 + ) # Base model from Xie and Manis, 2013 for type I stellate cell + refarea = totcap / self.c_m # see above for units + self.gBar = Params( + nabar=800.0e-9 / refarea, + khtbar=250.0e-9 / refarea, + kltbar=0.0e-9 / refarea, + ihbar=18.0e-9 / refarea, + leakbar=8.0e-9 / refarea, + ) + self.channelMap = { + "axon": { + "nav11": 0.0, + "klt": 0.0, + "kht": self.gBar.khtbar, + "ihvcn": 0.0, + "leak": self.gBar.leakbar / 4.0, + }, + "hillock": { + "nav11": self.gBar.nabar, + "klt": 0.0, + "kht": self.gBar.khtbar, + "ihvcn": 0.0, + "leak": self.gBar.leakbar, + }, + "initseg": { + "nav11": self.gBar.nabar, + "klt": 0.0, + "kht": self.gBar.khtbar, + "ihvcn": self.gBar.ihbar / 2.0, + "leak": self.gBar.leakbar, + }, + "soma": { + "nav11": self.gBar.nabar, + "klt": self.gBar.kltbar, + "kht": self.gBar.khtbar, + "ihvcn": self.gBar.ihbar, + "leak": self.gBar.leakbar, + }, + "dend": { + "nav11": self.gBar.nabar, + "klt": 0.0, + "kht": self.gBar.khtbar * 0.5, + "ihvcn": self.gBar.ihbar / 3.0, + "leak": self.gBar.leakbar * 0.5, + }, + } + self.irange = np.linspace(-1.0, 1.0, 21) + self.distMap = { + "dend": { + "klt": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "kht": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "nav11": {"gradient": "exp", "gminf": 0.0, "lambda": 100.0}, + } # linear with distance, gminf (factor) is multiplied by gbar + } + + elif modelType == "XM13PasDend": + # bushy form Xie and Manis, 2013, based on Cao and Oertel mouse conductances + # passive dendrites + totcap = 26.0e-12 # uF/cm2 + refarea = totcap / self.c_m # see above for units + self.gBar = Params( + nabar=1000.0e-9 / refarea, + khtbar=150.0e-9 / refarea, + kltbar=0.0e-9 / refarea, + ihbar=0.5e-9 / refarea, + leakbar=2.0e-9 / refarea, + ) + self.channelMap = { + "axon": { + "nav11": self.gBar.nabar * 0, + "klt": self.gBar.kltbar * 0.25, + "kht": self.gBar.khtbar, + "ihvcn": 0.0, + "leak": self.gBar.leakbar * 0.25, + }, + "hillock": { + "nav11": self.gBar.nabar, + "klt": self.gBar.kltbar, + "kht": self.gBar.khtbar, + "ihvcn": 0.0, + "leak": self.gBar.leakbar, + }, + "initseg": { + "nav11": self.gBar.nabar * 3, + "klt": self.gBar.kltbar * 2, + "kht": self.gBar.khtbar * 2, + "ihvcn": self.gBar.ihbar * 0.5, + "leak": self.gBar.leakbar, + }, + "soma": { + "nav11": self.gBar.nabar, + "klt": self.gBar.kltbar, + "kht": self.gBar.khtbar, + "ihvcn": self.gBar.ihbar, + "leak": self.gBar.leakbar, + }, + "dend": { + "nav11": self.gBar.nabar * 0.0, + "klt": self.gBar.kltbar * 0, + "kht": self.gBar.khtbar * 0, + "ihvcn": self.gBar.ihbar * 0, + "leak": self.gBar.leakbar * 0.5, + }, + } + self.irange = np.linspace(-1, 1, 21) + self.distMap = { + "dend": { + "klt": {"gradient": "linear", "gminf": 0.0, "lambda": 200.0}, + "kht": {"gradient": "llinear", "gminf": 0.0, "lambda": 200.0}, + "nav11": {"gradient": "linear", "gminf": 0.0, "lambda": 200.0}, + } # linear with distance, gminf (factor) is multiplied by gbar + } + else: + raise ValueError("model type %s is not implemented" % modelType) + + def adjust_na_chans(self, soma, gbar=800.0): + """ + Adjust the sodium channel conductance, depending on the type of conductance + + Parameters + ---------- + soma : NEURON section object (required) + This identifies the soma object whose sodium channel complement will have it's + conductances adjusted depending on the sodium channel type + gbar : float (default: 800.) + The "maximal" conductance to be set in the model. + + Returns + ------- + Nothing + """ + if self.status["ttx"]: + gnabar = 0.0 + else: + gnabar = nstomho(gbar, self.somaarea) + nach = self.status["na"] + if nach == "nav11": + soma().nav11.gbar = gnabar + soma.ena = self.e_na + soma().nav11.vsna = 4.3 + if self.debug: + print("tstellate using inva11") + else: + raise ValueError( + "tstellate setting Na channels only supporting nav11: channel %s not known" + % nach + ) diff --git a/cnmodel/cells/tuberculoventral.py b/cnmodel/cells/tuberculoventral.py new file mode 100644 index 0000000..85d3eb1 --- /dev/null +++ b/cnmodel/cells/tuberculoventral.py @@ -0,0 +1,619 @@ +from __future__ import print_function +from neuron import h +import numpy as np + +# import neuron as nrn + +from .cell import Cell +from .. import synapses +from ..util import nstomho +from ..util import Params +from .. import data + +__all__ = ["Tuberculoventral"] + + +class Tuberculoventral(Cell): + + type = "tuberculoventral" + + @classmethod + def create(cls, model="TVmouse", **kwds): + if model in ["TVmouse", "I"]: + return Tuberculoventral(**kwds) + elif model == "dummy": + return DummyTuberculoventral(**kwds) + else: + raise ValueError("Tuberculoventral type %s is unknown", model) + + def __init__(self): + Cell.__init__(self) + self.spike_source = ( + None + ) # used by DummyTuberculoventral to connect VecStim to terminal + + def make_psd(self, terminal, psd_type, **kwds): + """ + Connect a presynaptic terminal to one post section at the specified location, with the fraction + of the "standard" conductance determined by gbar. + The default condition is to try to pass the default unit test (loc=0.5) + + Parameters + ---------- + terminal : Presynaptic terminal (NEURON object) + + psd_type : either simple or multisite PSD for bushy cell + + kwds: dict of options. Two are currently handled: + postsize : expect a list consisting of [sectionno, location (float)] + AMPAScale : float to scale the ampa currents + + """ + if ( + "postsite" in kwds + ): # use a defined location instead of the default (soma(0.5) + postsite = kwds["postsite"] + loc = postsite[1] # where on the section? + uname = ( + "sections[%d]" % postsite[0] + ) # make a name to look up the neuron section object + post_sec = self.hr.get_section(uname) # Tell us where to put the synapse. + else: + loc = 0.5 + post_sec = self.soma + + if psd_type == "simple": + if terminal.cell.type in ["sgc", "dstellate", "tuberculoventral"]: + weight = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="weight", + ) + tau1 = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="tau1", + ) + tau2 = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="tau2", + ) + erev = data.get( + "%s_synapse" % terminal.cell.type, + species=self.species, + post_type=self.type, + field="erev", + ) + return self.make_exp2_psd( + post_sec, + terminal, + weight=weight, + loc=loc, + tau1=tau1, + tau2=tau2, + erev=erev, + ) + else: + raise TypeError( + "Cannot make simple PSD for %s => %s" + % (terminal.cell.type, self.type) + ) + + elif psd_type == "multisite": + if terminal.cell.type == "sgc": + # Max conductances for the glu mechanisms are calibrated by + # running `synapses/tests/test_psd.py`. The test should fail + # if these values are incorrect + self.AMPAR_gmax = ( + data.get( + "sgc_synapse", + species=self.species, + post_type=self.type, + field="AMPAR_gmax", + ) + * 1e3 + ) + self.NMDAR_gmax = ( + data.get( + "sgc_synapse", + species=self.species, + post_type=self.type, + field="NMDAR_gmax", + ) + * 1e3 + ) + self.Pr = data.get( + "sgc_synapse", species=self.species, post_type=self.type, field="Pr" + ) + # adjust gmax to correct for initial Pr + self.AMPAR_gmax = self.AMPAR_gmax / self.Pr + self.NMDAR_gmax = self.NMDAR_gmax / self.Pr + if "AMPAScale" in kwds: + self.AMPA_gmax = ( + self.AMPA_gmax * kwds["AMPAScale"] + ) # allow scaling of AMPA conductances + if "NMDAScale" in kwds: + self.NMDA_gmax = self.NMDA_gmax * kwds["NMDAScale"] + return self.make_glu_psd( + post_sec, terminal, self.AMPAR_gmax, self.NMDAR_gmax, loc=loc + ) + elif terminal.cell.type == "dstellate": # WBI input -Voigt, Nelken, Young + return self.make_gly_psd(post_sec, terminal, psdtype="glyfast", loc=loc) + elif ( + terminal.cell.type == "tuberculoventral" + ): # TV cells talk to each other-Kuo et al. + return self.make_gly_psd(post_sec, terminal, psdtype="glyfast", loc=loc) + else: + raise TypeError( + "Cannot make PSD for %s => %s" % (terminal.cell.type, self.type) + ) + else: + raise ValueError("Unsupported psd type %s" % psd_type) + + def make_terminal(self, post_cell, term_type, **kwds): + pre_sec = self.soma + if term_type == "simple": + return synapses.SimpleTerminal( + pre_sec, post_cell, spike_source=self.spike_source, **kwds + ) + elif term_type == "multisite": + if post_cell.type in [ + "dstellate", + "tuberculoventral", + "pyramidal", + "bushy", + "tstellate", + ]: + nzones = data.get( + "tuberculoventral_synapse", + species=self.species, + post_type=post_cell.type, + field="n_rsites", + ) + delay = data.get( + "tuberculoventral_synapse", + species=self.species, + post_type=post_cell.type, + field="delay", + ) + else: + raise NotImplementedError( + "No knowledge as to how to connect tuberculoventral cell to cell type %s" + % type(post_cell) + ) + pre_sec = self.soma + return synapses.StochasticTerminal( + pre_sec, + post_cell, + nzones=nzones, + spike_source=self.spike_source, + delay=delay, + **kwds + ) + else: + raise ValueError("Unsupported terminal type %s" % term_type) + + +class Tuberculoventral(Tuberculoventral): + """ + Tuberculoventral Neuron (DCN) base model + Adapted from T-stellate model, using target parameters from Kuo et al. J. Neurophys. 2012 + """ + + def __init__( + self, + morphology=None, + decorator=None, + nach=None, + ttx=False, + species="mouse", + modelType=None, + debug=False, + ): + """ + Initialize a DCN Tuberculoventral cell, using the default parameters for guinea pig from + R&M2003, as a type I cell. + Modifications to the cell can be made by calling methods below. These include: + Converting to a type IA model (add transient K current) (species: guineapig-TypeIA). + Changing "species" to mouse or cat (scales conductances) + + Parameters + ---------- + morphology : string (default: None) + a file name to read the cell morphology from. If a valid file is found, a cell is constructed + as a cable model from the hoc file. + If None (default), the only a point model is made, exactly according to RM03. + + decorator : Python function (default: None) + decorator is a function that "decorates" the morphology with ion channels according + to a set of rules. + If None, a default set of channels aer inserted into the first soma section, and the + rest of the structure is "bare". + + nach : string (default: 'na') + nach selects the type of sodium channel that will be used in the model. A channel mechanims + by that name must exist. + + ttx : Boolean (default: False) + If ttx is True, then the sodium channel conductance is set to 0 everywhere in the cell. + Currently, this is not implemented. + + species: string (default 'guineapig') + species defines the channel density that will be inserted for different models. Note that + if a decorator function is specified, this argument is ignored. + + modelType: string (default: None) + modelType specifies the type of the model that will be used (e.g., "II", "II-I", etc). + modelType is passed to the decorator, or to species_scaling to adjust point models. + + debug: boolean (default: False) + debug is a boolean flag. When set, there will be multiple printouts of progress and parameters. + + Returns + ------- + Nothing + """ + super(Tuberculoventral, self).__init__() + if modelType == None: + modelType = "TVmouse" + if nach == None: + nach = "nacncoop" + self.debug = debug + self.status = { + "soma": True, + "axon": False, + "dendrites": False, + "pumps": False, + "na": nach, + "species": species, + "modelType": modelType, + "ttx": ttx, + "name": "Tuberculoventral", + "morphology": morphology, + "decorator": decorator, + "temperature": None, + } + + self.i_test_range = {"pulse": [(-0.35, 1.0, 0.05), (-0.04, 0.01, 0.01)]} + self.vrange = [-80.0, -60.0] # set a default vrange for searching for rmp + + if morphology is None: + """ + instantiate a basic soma-only ("point") model + """ + if self.debug: + print("<< Tuberculoventral model: Creating point cell >>") + soma = h.Section( + name="Tuberculoventral_Soma_%x" % id(self) + ) # one compartment of about 29000 um2 + soma.nseg = 1 + self.add_section(soma, "soma") + else: + """ + instantiate a structured model with the morphology as specified by + the morphology file + """ + if self.debug: + print("<< Tuberculoventral model: Creating structured cell >>") + self.set_morphology(morphology_file=morphology) + + # decorate the morphology with ion channels + if decorator is None: # basic model, only on the soma + self.mechanisms = ["kht", "ka", "ihvcn", "leak", nach] + for mech in self.mechanisms: + self.soma.insert(mech) + self.species_scaling( + silent=True, species=species, modelType=modelType + ) # adjust the default parameters + else: # decorate according to a defined set of rules on all cell compartments + self.decorate() + self.save_all_mechs() # save all mechanisms inserted, location and gbar values... + self.get_mechs(self.soma) + if self.debug: + print("<< Tuberculoventral cell model created >>") + + def get_cellpars(self, dataset, species="mouse", celltype="TVmouse"): + cellcap = data.get( + dataset, species=species, cell_type=celltype, field="soma_Cap" + ) + chtype = data.get( + dataset, species=species, cell_type=celltype, field="soma_na_type" + ) + pars = Params(soma_cap=cellcap, soma_na_type=chtype) + for g in [ + "soma_nacncoop_gbar", + "soma_kht_gbar", + "soma_ka_gbar", + "soma_ihvcn_gbar", + "soma_ihvcn_eh", + "soma_leak_gbar", + "soma_leak_erev", + "soma_e_k", + "soma_e_na", + ]: + pars.additem( + g, data.get(dataset, species=species, cell_type=celltype, field=g) + ) + return pars + + def species_scaling(self, species="guineapig", modelType="TVmouse", silent=True): + """ + Adjust all of the conductances and the cell size according to the species requested. + Used ONLY for point models. + + Parameters + ---------- + species : string (default: 'guineapig') + name of the species to use for scaling the conductances in the base point model + Must be one of mouse, cat, guineapig + + modelType: string (default: 'I-c') + definition of model type from RM03 models, type I-c or type I-t + + silent : boolean (default: True) + run silently (True) or verbosely (False) + """ + soma = self.soma + if self.debug: + print("modelType: ", modelType) + if modelType in ["TVmouse", "I"]: + celltype = "TVmouse" # modelType + modelType = "TVmouse" + else: + raise ValueError( + "Tuberuloventral: Model type %s not recognized" % modelType + ) + + if species == "mouse" and modelType in ["TVmouse", "I"]: + """#From Kuo 150 Mohm, 10 msec tau + Firing at 600 pA about 400 Hz + These values from brute_force runs, getting 380 Hz at 600 pA at 35C + Input resistance and vm is ok, time constnat is short + *** Rin: 168 tau: 7.8 v: -68.4 + Attempts to get longer time constant - cannot keep rate up. + """ + # Adapted from TStellate model type I-c' + self.vrange = [-80.0, -58.0] + self._valid_temperatures = (34.0,) + if self.status["temperature"] is None: + self.set_temperature(34.0) + + pars = self.get_cellpars("TV_channels", species="mouse", celltype=modelType) + self.set_soma_size_from_Cm(pars.soma_cap) + self.status["na"] = pars.soma_na_type + self.adjust_na_chans(soma, gbar=pars.soma_nacncoop_gbar, debug=self.debug) + soma().kht.gbar = nstomho(pars.soma_kht_gbar, self.somaarea) + soma().ka.gbar = nstomho(pars.soma_ka_gbar, self.somaarea) + soma().ihvcn.gbar = nstomho(pars.soma_ihvcn_gbar, self.somaarea) + soma().ihvcn.eh = pars.soma_ihvcn_eh + soma().leak.gbar = nstomho(pars.soma_leak_gbar, self.somaarea) + soma().leak.erev = pars.soma_leak_erev + self.e_leak = pars.soma_leak_erev + self.soma.ek = self.e_k = pars.soma_e_k + self.soma.ena = self.e_na = pars.soma_e_na + + self.axonsf = 0.5 + else: + raise ValueError( + "Species %s or species-type %s is not recognized for Tuberculoventralcells" + % (species, type) + ) + + self.status["species"] = species + self.status["modelType"] = modelType + self.check_temperature() + + def channel_manager(self, modelType="TVmouse"): + """ + This routine defines channel density maps and distance map patterns + for each type of compartment in the cell. The maps + are used by the ChannelDecorator class (specifically, it's private + _biophys function) to decorate the cell membrane. + + Parameters + ---------- + modelType : string (default: 'RM03') + A string that defines the type of the model. Currently, 3 types are implemented: + RM03: Rothman and Manis, 2003 somatic densities for guinea pig + XM13: Xie and Manis, 2013, somatic densities for mouse + XM13PasDend: XM13, but with only passive dendrites, no channels. + + Returns + ------- + Nothing + + Notes + ----- + + This routine defines the following variables for the class: + + - conductances (gBar) + - a channelMap (dictonary of channel densities in defined anatomical compartments) + - a current injection range for IV's (when testing) + - a distance map, which defines how selected conductances in selected compartments + will change with distance. This includes both linear and exponential gradients, + the minimum conductance at the end of the gradient, and the space constant or + slope for the gradient. + + """ + if modelType == "TVmouse": + print("decorate as tvmouse") + # totcap = 95.0E-12 # Tuberculoventral cell (type I), based on stellate, adjusted for Kuo et al. TV firing + self.set_soma_size_from_Section(self.soma) + totcap = self.totcap + refarea = self.somaarea # totcap / self.c_m # see above for units + self.gBar = Params( + nabar=1520.0e-9 / refarea, + khtbar=160.0e-9 / refarea, + kltbar=0.0e-9 / refarea, + kabar=65.0 / refarea, + ihbar=1.25e-9 / refarea, + leakbar=5.5e-9 / refarea, + ) + self.channelMap = { + "axon": { + "nacn": 0.0, + "klt": 0.0, + "kht": self.gBar.khtbar, + "ihvcn": 0.0, + "leak": self.gBar.leakbar / 4.0, + }, + "hillock": { + "nacn": self.gBar.nabar, + "klt": 0.0, + "kht": self.gBar.khtbar, + "ihvcn": 0.0, + "leak": self.gBar.leakbar, + }, + "initseg": { + "nacn": self.gBar.nabar, + "klt": 0.0, + "kht": self.gBar.khtbar, + "ihvcn": self.gBar.ihbar / 2.0, + "leak": self.gBar.leakbar, + }, + "soma": { + "nacn": self.gBar.nabar, + "klt": self.gBar.kltbar, + "kht": self.gBar.khtbar, + "ihvcn": self.gBar.ihbar, + "leak": self.gBar.leakbar, + }, + "dend": { + "nacn": self.gBar.nabar / 2.0, + "klt": 0.0, + "kht": self.gBar.khtbar * 0.5, + "ihvcn": self.gBar.ihbar / 3.0, + "leak": self.gBar.leakbar * 0.5, + }, + "apic": { + "nacn": 0.0, + "klt": 0.0, + "kht": self.gBar.khtbar * 0.2, + "ihvcn": self.gBar.ihbar / 4.0, + "leak": self.gBar.leakbar * 0.2, + }, + } + self.irange = np.linspace(-0.3, 0.6, 10) + self.distMap = { + "dend": { + "klt": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "kht": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + }, # linear with distance, gminf (factor) is multiplied by gbar + "apic": { + "klt": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + "kht": {"gradient": "linear", "gminf": 0.0, "lambda": 100.0}, + }, # gradients are: flat, linear, exponential + } + else: + raise ValueError("model type %s is not implemented" % modelType) + + def adjust_na_chans(self, soma, gbar=1000.0, debug=False): + """ + Adjust the sodium channel conductance, depending on the type of conductance + + Parameters + ---------- + soma : NEURON section object (required) + This identifies the soma object whose sodium channel complement will have it's + conductances adjusted depending on the sodium channel type + gbar : float (default: 1000.) + The "maximal" conductance to be set in the model. + debug : boolean (default: False) + A flag the prints out messages to confirm the operations applied. + + Returns + ------- + Nothing + """ + if self.status["ttx"]: + gnabar = 0.0 + else: + gnabar = nstomho(gbar, self.somaarea) + nach = self.status["na"] + if nach == "nacncoop": + soma().nacncoop.gbar = gnabar + soma().nacncoop.KJ = 2000.0 + soma().nacncoop.p = 0.25 + soma.ena = self.e_na + if debug: + print("nacncoop gbar: ", soma().nacncoop.gbar) + elif nach == "jsrna": + soma().jsrna.gbar = gnabar + soma.ena = self.e_na + if debug: + print("jsrna gbar: ", soma().jsrna.gbar) + elif nach == "nav11": + soma().nav11.gbar = gnabar * 0.5 + soma.ena = self.e_na + soma().nav11.vsna = 4.3 + if debug: + print("Tuberculoventral using inva11") + print("nav11 gbar: ", soma().nav11.gbar) + elif nach == "na": + soma().na.gbar = gnabar + soma.ena = self.e_na + if debug: + print("na gbar: ", soma().na.gbar) + elif nach == "nacn": + soma().nacn.gbar = gnabar + soma.ena = self.e_na + if debug: + print("nacn gbar: ", soma().nacn.gbar) + else: + raise ValueError( + "Tuberculoventral setting Na channels: channel %s not known" % nach + ) + + +class DummyTuberculoventral(Tuberculoventral): + """ Tuberculoventral cell class with no cell body; this cell only replays a predetermined + spike train. Useful for testing, or replacing spike trains to determine + the importance of spike structures within a network. + """ + + def __init__(self, cf=None, species="mouse"): + """ + Parameters + ---------- + cf : float (default: None) + Required: the characteristic frequency for the TV cell + Really just for reference. + + """ + + Tuberculoventral.__init__(self) + self.vecstim = h.VecStim() + + # this causes the terminal to receive events from the VecStim: + self.spike_source = self.vecstim + + # just an empty section for holding the terminal + self.add_section(h.Section(), "soma") + self.status = { + "soma": True, + "axon": False, + "dendrites": False, + "pumps": False, + "na": None, + "species": species, + "modelType": "Dummy", + "modelName": "DummyTuberculoventral", + "ttx": None, + "name": "DummyTuberculoventral", + "morphology": None, + "decorator": None, + "temperature": None, + } + print("<< Tuberculoventral: Dummy Tuberculoventral Cell created >>") + + def set_spiketrain(self, times): + """ Set the times of spikes (in seconds) to be replayed by the cell. + """ + self._spiketrain = times + self._stvec = h.Vector(times) + self.vecstim.play(self._stvec) diff --git a/cnmodel/custom_init.hoc b/cnmodel/custom_init.hoc new file mode 100755 index 0000000..7fdbbbd --- /dev/null +++ b/cnmodel/custom_init.hoc @@ -0,0 +1,23 @@ +INITDUR = 100 // # ms to reach steady state +DTSTEP = 0.1 +proc init() { local temp + //print "Using Custom Init" + finitialize(v_init) + t = -2*INITDUR // jump to a time "before" 0 + temp = cvode.active() + if (temp != 0) { // if cvode is on, turn it off + cvode.active(0) + dt = DTSTEP + } + while (t < -INITDUR) { + fadvance() + } + if (temp != 0) { cvode.active(1) } // turn cvode back on if necessary + t = 0 + if (cvode.active()) { + cvode.re_init() + } else { + fcurrent() + } + frecord_init() +} diff --git a/cnmodel/data/__init__.py b/cnmodel/data/__init__.py new file mode 100644 index 0000000..e623a56 --- /dev/null +++ b/cnmodel/data/__init__.py @@ -0,0 +1,18 @@ +""" +The cnmodel.data package contains information about ion channel densities, +connectivity, synaptic properties, and population distributions. These values +are used by the Cell, Synapse, Population, and related classes to determine +all model construction parameters. + +Values are stored in python strings that contain human-readable tables with +provenance documentation. +""" + + +from ._db import get, get_source, add_table_data, report_changes, setval + + +from . import connectivity +from . import synapses +from . import populations +from . import ionchannels diff --git a/cnmodel/data/_db.py b/cnmodel/data/_db.py new file mode 100644 index 0000000..f4eb7cf --- /dev/null +++ b/cnmodel/data/_db.py @@ -0,0 +1,321 @@ +# -*- encoding: utf-8 -*- +from __future__ import print_function +from collections import OrderedDict +import re + + +# Unified collection point for all empirically-determined biophysical +# values. Each value is a tuple (val, source). +DATA = OrderedDict() + + +def get(*args, **kwds): + """ Get a single value from the database using the supplied arguments + to query. + + Optionally, one keyword argument may be a list of values, in which case + a dict will be returned containing {listval: dbval} pairs for each value in + the list. + """ + return _lookup(0, *args, **kwds) + + +def get_source(*args, **kwds): + """ Get the source of a single value from the database using the supplied + arguments to query. + + Optionally, one keyword argument may be a list of values, in which case + a dict will be returned containing {listval: dbval} pairs for each value in + the list. + """ + return _lookup(1, *args, **kwds) + + +def print_table(table): + for k in DATA.keys(): + if table == k[0]: + print("data key: ", k) + print(DATA[k][0]) + + +def get_table_info(table): + """ + Return a dictionary of row and column names in the table + """ + tinfo = {} + for k in DATA.keys(): + if table == k[0]: + for p in k: + if not isinstance(p, tuple): + continue + if p[0] not in tinfo.keys(): + tinfo[p[0]] = [] + if p[1] not in tinfo[p[0]]: + tinfo[p[0]].append(p[1]) + return tinfo + + +def _lookup(ind, *args, **kwds): + key = mk_key(*args, **kwds) + if isinstance(key, dict): + data = {} + for k, key in key.items(): + data[k] = DATA[key][ind] + return data + else: + return DATA[key][ind] + + +def setval(val, *args, **kwds): + key = mk_key(*args, **kwds) + oldval = None + # change_flag = False + if key in DATA: + # change_flag = True # any attempt to change key will set this + oldval = DATA[key] # save the previous stored value + # raise RuntimeError("Data key '%s' has already been set." % str(key)) + DATA[key] = val + return oldval + + +def mk_key(*args, **kwds): + # Make a unique key (or list of keys) used to access values from the + # database. The generated key is independent of the order that arguments + # are specified. + # + # Optionally, one keyword argument may have a list of values, in which case + # the function will return a dict containing {listval: key} pairs for each + # value in the list. + listkey = None + for k, v in kwds.items(): + if isinstance(v, (list, tuple)): + if listkey is not None: + raise TypeError("May only specify a list of values for one key.") + listkey = k + + if listkey is None: + return _mk_key(*args, **kwds) + else: + keys = {} + for v in kwds[listkey]: + kwds[listkey] = v + keys[v] = _mk_key(*args, **kwds) + return keys + + +def _mk_key(*args, **kwds): + key = list(args) + list(kwds.items()) + key.sort(key=lambda a: a[0] if isinstance(a, tuple) else a) + return tuple(key) + + +def add_table_data(name, row_key, col_key, data, **kwds): + """ + Read data like:: + + Description + + ------------------------------------ + col1 col2 col3 + row1 1.2 [1] 0.9e-6 [1] 27 [2] + row2 1.7 [1] [3] + row3 0.93 [2] 0.3e-6 3 [2] + + ------------------------------------ + + [1] citation 1 + [2] citation 2 + [3] missing because. + + + """ + if isinstance(data, str) and "\xc2" in data: + raise TypeError( + "Data table <%s> appears to contain unicode characters but" + "was not defined as unicode." % name + ) + + lines = data.split("\n") + + # First, split into description, table, and sources using ----- lines + desc = [] + table = [] + while lines: + line = lines.pop(0) + # print ">", line + if re.match(r"\s*-+\s*$", line): + # print "match!" + break + desc.append(line) + while lines: + line = lines.pop(0) + # print ">", line + if re.match(r"\s*-+\s*$", line): + # print "match!" + break + table.append(line) + + # print desc + # print table + + # parse remaining lines as sources + sources = parse_sources(lines) + # print sources + + # + # parse table + # table might be empty, so take care of that first. + if table == []: + return [] # no changes + + while len(table[0].strip()) == 0: + table.pop(0) + + spaces = [c == " " for c in table[0]] + cols = [0] + [i for i in range(1, len(spaces)) if spaces[i - 1] and not spaces[i]] + cols = cols + [max(map(len, table)) + 1] + # print spaces + # print cols + # Make sure columns are obeyed strictly + for i, line in enumerate(table): + for j, c in enumerate(cols[1:]): + if len(line) < c: + continue + if line[c - 1] != " ": + print("Table line with error: \n ", line) + raise Exception( + "Table <%s> line: %d, column: %s does not obey column boundaries." + % (name, i, j) + ) + + # Break table into cells + cells = [] + for line in table: + if line.strip() != "": + cells.append( + [line[cols[i] : cols[i + 1]].strip() for i in range(len(cols) - 1)] + ) + # print cells + + # Extract row/column names + col_names = cells.pop(0)[1:] + row_names = [cells[i].pop(0) for i in range(len(cells))] + if len(set(row_names)) != len(row_names): + for n in set(row_names): + row_names.remove(n) + raise NameError("Duplicate row names: %s" % row_names) + + # Parse cell values + for i in range(len(cells)): + for j in range(len(cells[0])): + cell = cells[i][j].strip() + m = re.match(r"([^\[]*)(\[([^\]]+)\])?", cell) # match like "0.7 [3]" + if m is None: + raise ValueError( + "Table cell (%d, %d) has bad format: '%s'" % (i, j, cell) + ) + + # parse value + # If the value contains '±' then a tuple is returned containing the values + # on either side. + val, _, source = m.groups() + # val = unicode(val) # python 2 + val = str(val) # python 3 + if val.strip() == "": + val = None + else: + parts = val.split(u"±") + vals = [] + for p in parts: + try: + p = int(p) + except ValueError: + try: + p = float(p) + except ValueError: + try: + p = str( + p.strip() + ) # allow strings to identify mechanisms also + except ValueError: + raise ValueError( + "Table cell (%d, %d) value has bad format: '%s'" + % (i, j, val) + ) + vals.append(p) + if len(vals) == 1: + val = vals[0] + else: + val = tuple(vals) + + # parse source + if source is not None: + try: + source = sources[source] + except KeyError: + raise ValueError( + "Table cell (%d, %d) has unknown source key: '%s'" + % (i, j, source) + ) + + cells[i][j] = (val, source) + + changes = [] # a list of parameters that are changed if we are rewriting a table + for i, row in enumerate(row_names): + for j, col in enumerate(col_names): + kwds[row_key] = row + kwds[col_key] = col + oldval = setval(cells[i][j], name, **kwds) + if oldval is not None and oldval != cells[i][j]: + key = mk_key(name, **kwds) + changes.append( + {"key": key, "new": cells[i][j], "old": oldval, "name": name} + ) + # changes.append({'name': name, 'row': row, 'col': col, 'new': cells[i][j], 'old': oldval}) + return changes + + +def report_changes(changes): + """ + For changes to data tables, give user a readout + """ + if len(changes) > 0: + anychg = False + for ch in changes: + # print(' >>> Changing %s, %s from default (%s) to %s' % (ch['row'], ch['col'], str(ch['new'][0]), str(ch['old'][0]))) + if str(ch["old"][0]) != str(ch["new"][0]): + if anychg is False: + print( + "\nWarning: Data Table '%s' (in memory) has been modified!" + % changes[0]["name"] + ) + anychg = True + print( + " >>> Changing %s, from default (%s) to %s" + % (ch["key"], str(ch["old"][0]), str(ch["new"][0])) + ) + + +def parse_sources(lines): + sources = {} + key = None + val = [] + for l in lines: + l = l.lstrip() + m = re.match(r"\s*\[([^\]]+)\]\s+(.*)$", l) + if m is not None: + key = m.groups()[0] + sources[key] = m.groups()[1].strip() + else: + if key is None: + if l == "": + continue + raise ValueError( + "Incorrect sources format--got text without " + 'citation index: "%s".' % l + ) + sources[key] += "\n" + l + return sources + + +# parse_sources('''\n\n[1] source 1\n it's cool.\n[2] source 2 is not\n'''.split('\n')) diff --git a/cnmodel/data/connectivity.py b/cnmodel/data/connectivity.py new file mode 100644 index 0000000..085b6e9 --- /dev/null +++ b/cnmodel/data/connectivity.py @@ -0,0 +1,234 @@ +# -*- encoding: utf-8 -*- +from ._db import add_table_data + +#: Mouse synaptic convregence table +mouse_convergence = u""" + +Convergence defines the average number of presynaptic cells of a particular +type (rows) that synapse onto a single postsynaptic cell of a particular +type (columns). +This connectivity matrix is currently incomplete. +Note: Bushy and pyramidal cells are known to have no (or very few) +collaterals within the CN, and so they are not listed as presynaptic cells in +this table. Octopus cells have collaterals (including in granule cell domains), +and should be added to this table when more data are available (Golding et al., +J. Neurosci. 15: 3138, 1995) + +---------------------------------------------------------------------------------------------- + bushy tstellate dstellate octopus pyramidal tuberculoventral +sgc 3.3±0.6 [2] 6.5±1.0 [2] 35±0 [3] 60±0 [2] 48±0 [5] 24±0 [5] +dstellate 7 [1] 20 [1] 3 [1] 0 [4] 15 [5] 15 [5] +tstellate 0 [6] 0 [6] 0 [6] 0 [6] 0 [6] 0 [6] +tuberculoventral 6 6 0 0 [4] 21 [5] 0 [7] +pyramidal 0 0 0 0 0 0 +---------------------------------------------------------------------------------------------- + +[1] Guesses based on Campagnola & Manis 2014 + +[2] Cao, X. & Oertel, D. (2010). Auditory nerve fibers excite targets through + synapses that vary in convergence, strength, and short-term plasticity. + Journal of Neurophysiology, 104(5), 2308–20. + Xie and Manis (unpublished): max EPSC = 3.4 ± 1.5 nA with ~0.3 nA steps + (Cao and Oertel, 2010) = ~11 AN inputs. However neither we nor Cao and Oertel + see that many clear steps in the responses, so use lower bound. + +[3] Lower bound based on estimates from unpublished data Xie and Manis (2017) + Assumptions: No discernable step sizes when increasing shock intensity + at ANFs in radiate multipolars (dstellate) + Measured: 0.034 ± 15 nA sEPSC @ -70 mV + Measured: Maximal current from AN stim = 1.2 ± 0.7 nA @ -70 mV + Assuming that each AN provides 1 input, then N = ~35 + +[4] Octopus cells are devoid of inhibitory input (Golding et al., J. Neurosci., 1995) + +[5] Convergence from Hancock and Voigt, Ann. Biomed. Eng. 27, 1999 and Zheng and Voigt, + Ann. Biomed. Eng., 34, 2006. Numbers are based on models for cat and gerbil, + respectively. Adjusted to 1/2 to avoid overexciting TV cells in network model. + +[6] tstellate cells have collaterals within the CN. It has been proposed that they + provide auditory-driven input to the DCN (Oertel and Young, ), and also synapse + within the VCN (Oertel, SFN abstract). These parameters may need to be adjusted + once the convergence and strength is known. + +[7] In the models of Hancock and Voigt (1999) and Zheng and Voigt (2006), the TV cells + have no connections with each other. However, Kuo et al. (J. Neurophysiol., 2015) + did see connections between pairs of TV cells in the mouse. + +""" + +add_table_data( + "convergence", + row_key="pre_type", + col_key="post_type", + species="mouse", + data=mouse_convergence, +) + + +mouse_convergence_range = u""" + +The convergence range table describes, for each type of connection from +presynaptic (rows) to postsynaptic (columns), the variance in frequency of +presynaptic cells relative to the postsynaptic cell. + +All values are expressed as the sigma for a lognormal distribution scaled to +the CF of the postsynaptic cell. + +---------------------------------------------------------------------------------------------- + bushy tstellate dstellate octopus pyramidal tuberculoventral +sgc 0.05 [1] 0.1 [1] 0.4 [1] 0.5 [5] 0.1 [1] 0.1 [1] +dstellate 0.208 [2] 0.347 [2] 0.5 [1] 0 0.2 [1] 0.2 [1] +tstellate 0.1 [4] 0.1 [4] 0 0 0 0 +tuberculoventral 0.069 [3] 0.111 [3] 0 0 0.15 [1] 0 +pyramidal 0 0 0 0 0 0 +---------------------------------------------------------------------------------------------- + +[1] Guess based on axonal / dendritic morphology. + +[2] Calculated from Campagnola & Manis 2014 fig. 7C + Distribution widths are given in stdev(octaves), so we multiply by ln(2) to + get the sigma for a lognormal distribution. + DS->Bushy: ln(2) * 0.3 = 0.208 + DS->TStellate: ln(2) * 0.5 = 0.347 + +[3] Calculated from Campagnola & Manis 2014 fig. 9C + Distribution widths are given in stdev(octaves), so we multiply by ln(2) to + get the sigma for a lognormal distribution. + TV->Bushy: ln(2) * 0.10 = 0.069 + TV->TStellate: ln(2) * 0.16 = 0.111 + +[4] Guess based on very limited information in Campagnola & Manis 2014 fig. 12 + +[5] Octopus cells get a wide range of ANF input (but weak on a per input basis) + For example, see McGinley et al., 2012 or Spencer et al., 2012. + + +""" + +add_table_data( + "convergence_range", + row_key="pre_type", + col_key="post_type", + species="mouse", + data=mouse_convergence_range, +) + +# -------------------------------------------------------------------------------------------- +guineapig_convergence = u""" + +Convergence defines the average number of presynaptic cells of a particular +type (rows) that synapse onto a single postsynaptic cell of a particular +type (columns). +This connectivity matrix is currently incomplete. +Note: Bushy and pyramidal cells are known to have no (or very few) +collaterals within the CN, and so they are not listed as presynaptic cells in +this table. Octopus cells have collaterals (including in granule cell domains), +and should be added to this table when more data are available (Golding et al., +J. Neurosci. 15: 3138, 1995) + +This table is just a guess... using mouse data... + +---------------------------------------------------------------------------------------------- + bushy tstellate dstellate octopus pyramidal tuberculoventral mso +sgc 3.3±0.6 [2] 6.5±1.0 [2] 35±0 [3] 60±0 [2] 48±0 [5] 24±0 [5] 0 +bushy 0 0 0 0 0 0 12 [8] +dstellate 7 [1] 20 [1] 3 [1] 0 [4] 15 [5] 15 [5] 0 +tstellate 0 [6] 0 [6] 0 [6] 0 [6] 0 [6] 0 [6] 0 +tuberculoventral 6 6 0 0 [4] 21 [5] 0 [7] 0 +pyramidal 0 0 0 0 0 0 0 +---------------------------------------------------------------------------------------------- + +[1] Guesses based on Campagnola & Manis 2014 (using mouse data on guinea pig cells) + +[2] Cao, X. & Oertel, D. (2010). Auditory nerve fibers excite targets through + synapses that vary in convergence, strength, and short-term plasticity. + Journal of Neurophysiology, 104(5), 2308–20. + Xie and Manis (unpublished): max EPSC = 3.4 ± 1.5 nA with ~0.3 nA steps + (Cao and Oertel, 2010) = ~11 AN inputs. However neither we nor Cao and Oertel + see that many clear steps in the responses, so use lower bound. + +[3] Lower bound based on estimates from unpublished data Xie and Manis (2017) + Assumptions: No discernable step sizes when increasing shock intensity + at ANFs in radiate multipolars (dstellate) + Measured: 0.034 ± 15 nA sEPSC @ -70 mV + Measured: Maximal current from AN stim = 1.2 ± 0.7 nA @ -70 mV + Assuming that each AN provides 1 input, then N = ~35 + +[4] Octopus cells are devoid of inhibitory input (Golding et al., J. Neurosci., 1995) + +[5] Convergence from Hancock and Voigt, Ann. Biomed. Eng. 27, 1999 and Zheng and Voigt, + Ann. Biomed. Eng., 34, 2006. Numbers are based on models for cat and gerbil, + respectively. Adjusted to 1/2 to avoid overexciting TV cells in network model. + +[6] tstellate cells have collaterals within the CN. It has been proposed that they + provide auditory-driven input to the DCN (Oertel and Young, ), and also synapse + within the VCN (Oertel, SFN abstract). These parameters may need to be adjusted + once the convergence and strength is known. + +[7] In the models of Hancock and Voigt (1999) and Zheng and Voigt (2006), the TV cells + have no connections with each other. However, Kuo et al. (J. Neurophysiol., 2015) + did see connections between pairs of TV cells in the mouse. + +[8] Bushy convergence to MSO is a guess +""" + +add_table_data( + "convergence", + row_key="pre_type", + col_key="post_type", + species="guineapig", + data=guineapig_convergence, +) + + +guineapig_convergence_range = u""" + +The convergence range table describes, for each type of connection from +presynaptic (rows) to postsynaptic (columns), the variance in frequency of +presynaptic cells relative to the postsynaptic cell. + +All values are expressed as the sigma for a lognormal distribution scaled to +the CF of the postsynaptic cell. + +*** This table is just a guess - using data from mouse... **** + +------------------------------------------------------------------------------------------------------- + bushy tstellate dstellate octopus pyramidal tuberculoventral mso +sgc 0.05 [1] 0.1 [1] 0.4 [1] 0.5 [5] 0.1 [1] 0.1 [1] 0 +bushy 0 0 0 0 0 0 0.05 [6] +dstellate 0.208 [2] 0.347 [2] 0.5 [1] 0 0.2 [1] 0.2 [1] 0 +tstellate 0.1 [4] 0.1 [4] 0 0 0 0 0 +tuberculoventral 0.069 [3] 0.111 [3] 0 0 0.15 [1] 0 0 +pyramidal 0 0 0 0 0 0 0 +-------------------------------------------------------------------------------------------------------- + +[1] Guess based on axonal / dendritic morphology. + +[2] Calculated from Campagnola & Manis 2014 fig. 7C (Using mouse data on guinea pig cells) + Distribution widths are given in stdev(octaves), so we multiply by ln(2) to + get the sigma for a lognormal distribution. + DS->Bushy: ln(2) * 0.3 = 0.208 + DS->TStellate: ln(2) * 0.5 = 0.347 + +[3] Calculated from Campagnola & Manis 2014 fig. 9C (Using mouse data on guinea pig cells) + Distribution widths are given in stdev(octaves), so we multiply by ln(2) to + get the sigma for a lognormal distribution. + TV->Bushy: ln(2) * 0.10 = 0.069 + TV->TStellate: ln(2) * 0.16 = 0.111 + +[4] Guess based on very limited information in Campagnola & Manis 2014 fig. 12 + +[5] Octopus cells get a wide range of ANF input (but weak on a per input basis) + For example, see McGinley et al., 2012 or Spencer et al., 2012. + +[6] MSO convergence from bushy cells is a guess. + +""" + +add_table_data( + "convergence_range", + row_key="pre_type", + col_key="post_type", + species="guineapig", + data=guineapig_convergence_range, +) diff --git a/cnmodel/data/ionchannels.py b/cnmodel/data/ionchannels.py new file mode 100644 index 0000000..9691c7f --- /dev/null +++ b/cnmodel/data/ionchannels.py @@ -0,0 +1,582 @@ +# -*- encoding: utf-8 -*- +from ._db import add_table_data + +""" +Ion channel density tables +All of the ion channel densities for the models implemented in cnmodel +are (or should be) stated here, and should not be modified in the +cnmodel code itself. + +""" + +add_table_data( + "RM03_channels", + row_key="field", + col_key="model_type", + species="guineapig", + data=u""" + +This table describes the ion channel densities (and voltage shifts if necessary) +for different cell types in the original Rothman Manis 2003 model. +Data from Table 1, except for "octopus" cells, which is modified (see note 3) +map to cell: bushy-II bushy-II-I tstellate tstellate-t bushy-I-II octopus +----------------------------------------------------------------------------------------------------------------------------------- + II II-I I-c I-t I-II II-o + +nacn_gbar 1000. [1] 1000. [1] 1000. [1] 1000. [1] 1000. [2] 1000. [3] +kht_gbar 150.0 [1] 150.0 [1] 150.0 [1] 80.0 [1] 150.0 [2] 150.0 [3] +klt_gbar 200.0 [1] 35.0 [1] 0.0 [1] 0.0 [1] 20.0 [2] 1000. [3] +ka_gbar 0.0 [1] 0.0 [1] 0.0 [1] 65.0 [1] 0.0 [2] 0.0 [3] +ih_gbar 20.0 [1] 3.5 [1] 0.5 [1] 0.5 [1] 2.0 [2] 30.0 [3] +leak_gbar 2.0 [1] 2.0 [1] 2.0 [1] 2.0 [1] 2.0 [2] 2.0 [3] +leak_erev -65 [1] -65 [1] -65 [1] -65 [1] -65 [2] -65 [3] +na_type nacn [1] nacn [1] nacn [1] nacn [1] nacn [2] nacn [3] +ih_type ihvcn [1] ihvcn [1] ihvcn [1] ihvcn [1] ihvcn [2] ihvcn [3] +soma_Cap 12.0 [1] 12.0 [1] 12.0 [1] 12.0 [1] 12.0 [2] 25.0 [3] +e_k -84 [1] -84 [1] -84 [1] -84 [2] -84 [2] -84 [2] +e_na 50. [1] 50. [1] 50. [1] 50. [2] 50. [2] 50. [2] +ih_eh -43 [1] -43 [1] -43 [1] -43 [2] -43 [2] -43 [2] + +----------------------------------------------------------------------------------------------------------------------------------- + +[1] Rothman and Manis, 2003 + Age "adult", Temperature=22C + Units are nS. + +[2] Rothman and manis, 2003, model I-II + Some low-voltage K current, based on observations of + a single spike near threshold and regular firing for higher + currents (Xie and Manis, 2017) + +[3] Derived from Rothman and Manis, 2003, model II + Large amounts of low-voltage K current, and elevated HCN. Conductances + based on Rothman and Manis, 2003; concept from Cao and Oertel + +[4] Designation for elevated LTK and Ih for octopus cells + +""", +) + +add_table_data( + "XM13_channels", + row_key="field", + col_key="model_type", + species="mouse", + data=u""" + +This table describes the REFERENCE ion channel densities (and voltage shifts if necessary) +for different cell types based on the Xie and Manis 2013 models for mouse. + +The REFERENCE values are applied to "point" models, and to the soma of +compartmental models. +The names of the mechanisms must match a channel mechanism (Neuron .mod files) +and the following _(gbar, vshift, etc) must match an attribute of that channel +that can be accessed. + +----------------------------------------------------------------------------------------------------------------------------------- + II II-I I-c I-II I-t + +nav11_gbar 0000. [4] 0000. [4] 000. [4] 0. [4] 3000. [4] +nacn_gbar 1000. [1] 1000. [1] 3000. [1] 0000. [2] 0000. [1] +na_gbar 1000. [1] 1000. [1] 3000. [1] 1800. [2] 0000. [1] +kht_gbar 58.0 [1] 58.0 [1] 500.0 [1] 150.0 [2] 500.0 [1] +klt_gbar 80.0 [1] 20.0 [1] 0.0 [1] 14.0 [3] 0.0 [1] +ka_gbar 0.0 [1] 0.0 [1] 0.0 [1] 0.0 [2] 125.0 [1] +ihvcn_gbar 30.0 [1] 30.0 [1] 18.0 [1] 2.0 [2] 18.0 [1] +leak_gbar 2.0 [1] 2.0 [1] 8.0 [1] 2.0 [2] 8.0 [1] +leak_erev -65 [1] -65 [1] -65 [1] -65 [2] -65 [1] +na_type nacn [1] nav11 [1] nacn [1] na [3] nav11 [1] +ih_type ihvcn [1] ihvcn [1] ihvcn [1] ihvcn [2] ihvcn [1] +soma_Cap 26.0 [1] 26.0 [1] 25.0 [1] 25.0 [2] 25.0 [1] +nav11_vshift 4.3 [1] 4.3 [1] 4.3 [1] 4.3 [1] 4.3 [1] +e_k -84 [1] -84 [1] -84 [1] -70 [3] -84 [1] +e_na 50. [1] 50. [1] 50. [1] 55. [3] 50. [1] +ih_eh -43 [1] -43 [1] -43 [1] -43 [2] -43 [1] + +----------------------------------------------------------------------------------------------------------------------------------- + +[1] Uses channels from Rothman and Manis, 2003 + Conductances are for Mouse bushy cells + Xie and Manis, 2013 + Age "adult", Temperature=34C + Units are nS. + +[2] Rothman and manis, 2003, model I-II + Some low-voltage K current, based on observations of + a single spike near threshold and regular firing for higher + currents (Xie and Manis, 2017) + +[3] These values for the I-II (dstellate) are from the original checkpoint test + for cnmodel 12/2017. + +[4] nav11 channels were used in original Xie and Manis (2013) ms, but are not + used for mice in the master distribution of cnmodel, which used only the nacn + channels. + +""", +) + +add_table_data( + "XM13_channels_compartments", + row_key="parameter", + col_key="compartment", + species="mouse", + model_type="II", + data=u""" + +This table describes the ion channel densities relative to somatic densities, +e.g., relative to REFERENCE densities in the table XM13_channels. +and voltage shifts, for different compartments of the specified neuron, +Conductances will be calculated from the Model derived from Xie and Manis 2013 for mouse +(data table: mGVC_channels). + +------------------------------------------------------------------------------------------------------------------------------------------------------------------ + axon unmyelinatedaxon myelinatedaxon initialsegment hillock soma dendrite primarydendrite secondarydendrite + +nav11_gbar 3.0 [1] 3.0 [1] 0.0 [1] 5.0 [1] 5.0 [1] 1.0 [1] 0.5 [1] 0.50 [1] 0.25 [1] +kht_gbar 1.0 [1] 2.0 [1] 0.01 [1] 2.0 [1] 2.0 [1] 1.0 [1] 0.5 [1] 0.5 [1] 0.25 [1] +klt_gbar 1.0 [1] 1.0 [1] 0.01 [1] 1.0 [1] 1.0 [1] 1.0 [1] 0.5 [1] 0.5 [1] 0.25 [1] +ihvcn_gbar 0.0 [1] 0.0 [1] 0.0 [1] 0.5 [1] 0.0 [1] 1.0 [1] 0.5 [1] 0.5 [1] 0.5 [1] +leak_gbar 1.0 [1] 0.25 [1] 0.25e-3 [1] 1.0 [1] 1.0 [1] 1.0 [1] 0.5 [1] 0.5 [1] 0.5 [1] +leak_erev -65. [1] -65. [1] -65. [1] -65. [1] -65. [1] -65. [1] -65. [1] -65. [1] -65. [1] +nav11_vshift 4.3 [1] 4.3 [1] 0.0 [1] 4.3 [1] 4.3 [1] 0.0 [1] 0.0 [1] 0.0 [1] 0.0 [1] +na_type nav11 nav11 nav11 nav11 nav11 nav11 nav11 nav11 nav11 +ih_type ihvcn ihvcn ihvcn ihvcn ihvcn ihvcn ihvcn ihvcn ihvcn +------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +[1] Scaling is relative to soma scaling. Numbers are estimates based on general distribution from literature on cortical neurons. + + +""", +) + + +# ***** BEGINNING OF XM13_Channels for nacncoop version of model + + +add_table_data( + "XM13nacncoop_channels", + row_key="field", + col_key="model_type", + species="mouse", + data=u""" + +This table describes the REFERENCE ion channel densities (and voltage shifts if necessary) +for different cell types based on the Xie and Manis 2013 models for mouse, but using +the nacncoop mechanism (coooperative sodium channels) + +!!!!!!!!!!!! USAGE OF THIS TABLE SHOULD BE CONSIDERED EXPERIMENTAL !!!!!!!!!!!!!! + +The REFERENCE values are applied to "point" models, and to the soma of +compartmental models. +The names of the mechanisms must match a channel mechanism (Neuron .mod files) +and the following _(gbar, vshift, etc) must match an attribute of that channel +that can be accessed. + +----------------------------------------------------------------------------------------------------------------------------------- + II II-I I-c I-II I-t + +nacncoop_gbar 3000. [4] 1000. [4] 1000. [4] 1000. [4] 1000. [4] +kht_gbar 58.0 [1] 58.0 [1] 500.0 [1] 150.0 [2] 500.0 [1] +klt_gbar 80.0 [1] 20.0 [1] 0.0 [1] 14.0 [3] 0.0 [1] +ka_gbar 0.0 [1] 0.0 [1] 0.0 [1] 0.0 [2] 125.0 [1] +ihvcn_gbar 30.0 [1] 30.0 [1] 18.0 [1] 2.0 [2] 18.0 [1] +leak_gbar 2.0 [1] 2.0 [1] 8.0 [1] 2.0 [2] 8.0 [1] +leak_erev -65 [1] -65 [1] -65 [1] -65 [2] -65 [1] +na_type nacncoop [1] nacncoop [1] nacncoop [1] nacncoop [3] nacncoop [1] +ih_type ihvcn [1] ihvcn [1] ihvcn [1] ihvcn [2] ihvcn [1] +soma_Cap 26.0 [1] 26.0 [1] 25.0 [1] 25.0 [2] 25.0 [1] +nacncoop_vshift 0.0 [1] 0.0 [1] 0.0 [1] 0.0 [1] 0.0 [1] +e_k -84 [1] -84 [1] -84 [1] -70 [3] -84 [1] +e_na 50. [1] 50. [1] 50. [1] 55. [3] 50. [1] +ih_eh -43 [1] -43 [1] -43 [1] -43 [2] -43 [1] + +----------------------------------------------------------------------------------------------------------------------------------- + +[1] Uses channels from Xie and Manis, 2013 + Age "adult", Temperature=34C + Units are nS. + +[2] Rothman and manis, 2003, model I-II + Some low-voltage K current, based on observations of + a single spike near threshold and regular firing for higher + currents (Xie and Manis, 2017) + +[3] These values for the I-II (dstellate) are from the original checkpoint test + for cnmodel 12/2017. + +[4] nav11 channels were used in original Xie and Manis (2013) ms, + However, this version uses cooperative na channels for faster activation + +""", +) + +add_table_data( + "XM13nacncooop_channels_compartments", + row_key="parameter", + col_key="compartment", + species="mouse", + model_type="II", + data=u""" + +!!!!!!!!!!!! USAGE OF THIS TABLE SHOULD BE CONSIDERED EXPERIMENTAL !!!!!!!!!!!!!! + +This table describes the ion channel densities relative to somatic densities, +e.g., relative to REFERENCE densities in the table XM13_nacncoop_channels. +and voltage shifts, for different compartments of the specified neuron, +Conductances will be calculated from the Model derived from Xie and Manis 2013 for mouse + +------------------------------------------------------------------------------------------------------------------------------------------------------------------ + axon unmyelinatedaxon myelinatedaxon initialsegment hillock soma dendrite primarydendrite secondarydendrite + +nacncoop_gbar 3.0 [1] 3.0 [1] 0.0 [1] 5.0 [1] 5.0 [1] 1.0 [1] 0.5 [1] 0.50 [1] 0.25 [1] +kht_gbar 1.0 [1] 2.0 [1] 0.01 [1] 2.0 [1] 2.0 [1] 1.0 [1] 0.5 [1] 0.5 [1] 0.25 [1] +klt_gbar 1.0 [1] 1.0 [1] 0.01 [1] 1.0 [1] 1.0 [1] 1.0 [1] 0.5 [1] 0.5 [1] 0.25 [1] +ihvcn_gbar 0.0 [1] 0.0 [1] 0.0 [1] 0.5 [1] 0.0 [1] 1.0 [1] 0.5 [1] 0.5 [1] 0.5 [1] +leak_gbar 1.0 [1] 0.25 [1] 0.25e-3 [1] 1.0 [1] 1.0 [1] 1.0 [1] 0.5 [1] 0.5 [1] 0.5 [1] +leak_erev -65. [1] -65. [1] -65. [1] -65. [1] -65. [1] -65. [1] -65. [1] -65. [1] -65. [1] +nacncoop_vshift 0.0 [1] 0.0 [1] 0.0 [1] 0.0 [1] 0.0 [1] 0.0 [1] 0.0 [1] 0.0 [1] 0.0 [1] +na_type nacncoop nacncoop nacncoop nacncoop nacncoop nacncoop nacncoop nacncoop nacncoop +ih_type ihvcn ihvcn ihvcn ihvcn ihvcn ihvcn ihvcn ihvcn ihvcn +-------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +[1] Scaling is relative to soma scaling. Numbers are estimates based on general distribution from literature on cortical neurons. + + +""", +) + +# ***** END OF XM13_Channels for nacncoop version of model + +add_table_data( + "mGBC_channels", + row_key="field", + col_key="model_type", + species="mouse", + data=u""" + +This table describes the REFERENCE ion channel densities (and voltage shifts if necessary) +for different cell types based on the Xie and Manis 2013 models for mouse. + +The REFERENCE values are applied to "point" models, and to the soma of +compartmental models. +The names of the mechanisms must match a channel mechanism (Neuron .mod files) +and the following _(gbar, vshift, etc) must match an attribute of that channel +that can be accessed. + +----------------------------------------------------------------------------------------------------------------------------------- + II II-I I-c I-II I-t + +nav11_gbar 1600. [1] 1600. [1] 3000. [1] 1600. [2] 3000. [1] +kht_gbar 58.0 [1] 58.0 [1] 500.0 [1] 150.0 [2] 500.0 [1] +klt_gbar 80.0 [1] 14.0 [1] 0.0 [1] 20.0 [2] 0.0 [1] +ka_gbar 0.0 [1] 0.0 [1] 0.0 [1] 0.0 [2] 125.0 [1] +ihvcn_gbar 30.0 [1] 30.0 [1] 18.0 [1] 2.0 [2] 18.0 [1] +leak_gbar 2.0 [1] 2.0 [1] 8.0 [1] 2.0 [2] 8.0 [1] +leak_erev -65 [1] -65 [1] -65 [1] -65 [2] -65 [1] +na_type nav11 [1] nav11 [1] nav11 [1] nav11 [1] nav11 [1] +ih_type ihvcn [1] ihvcn [1] ihvcn [1] ihvcn [2] ihvcn [1] +soma_Cap 26.0 [1] 26.0 [1] 25.0 [1] 26.0 [2] 25.0 [1] +nav11_vshift 4.3 [1] 4.3 [1] 4.3 [1] 4.3 [1] 4.3 [1] +e_k -84 [1] -84 [1] -84 [1] -84 [2] -84 [1] +e_na 50. [1] 50. [1] 50. [1] 50. [2] 50. [1] +ih_eh -43 [1] -43 [1] -43 [1] -43 [2] -43 [1] + +----------------------------------------------------------------------------------------------------------------------------------- + +[1] Uses channels from Rothman and Manis, 2003, except for Na channels + Conductances are for Mouse bushy cells + Xie and Manis, 2013 + Age "adult", Temperature=34C + Units are nS. + +[2] Rothman and Manis, 2003, model I-II + Some low-voltage K current, based on observations of + a single spike near threshold and regular firing for higher + currents (Xie and Manis, 2017) + + +""", +) + + +add_table_data( + "mGBC_channels_compartments", + row_key="parameter", + col_key="compartment", + species="mouse", + model_type="II", + data=u""" + +This table describes the ion channel densities relative to somatic densities, +e.g., relative to REFERENCE densities in the table XM13_channels. +and voltage shifts, for different compartments of the specified neuron, +Conductances will be calculated from the Model for Xie and Manis 2013 for mouse +(data table: XM13_channels). + +------------------------------------------------------------------------------------------------------------------------------------------------------------------ + axon unmyelinatedaxon myelinatedaxon initialsegment hillock soma dendrite primarydendrite secondarydendrite + +nav11_gbar 3.0 [1] 3.0 [1] 0.0 [1] 3.0 [1] 2.0 [1] 1.0 [1] 0.25 [1] 0.25 [1] 0.25 [1] +kht_gbar 1.0 [1] 2.0 [1] 0.01 [1] 2.0 [1] 2.0 [1] 1.0 [1] 0.5 [1] 0.5 [1] 0.25 [1] +klt_gbar 1.0 [1] 1.0 [1] 0.01 [1] 1.0 [1] 1.0 [1] 1.0 [1] 0.5 [1] 0.5 [1] 0.25 [1] +ihvcn_gbar 0.0 [1] 0.0 [1] 0.0 [1] 0.5 [1] 0.0 [1] 1.0 [1] 0.5 [1] 0.5 [1] 0.5 [1] +leak_gbar 1.0 [1] 0.25 [1] 0.25e-3 [1] 1.0 [1] 1.0 [1] 1.0 [1] 0.5 [1] 0.5 [1] 0.5 [1] +leak_erev -65. [1] -65. [1] -65. [1] -65. [1] -65. [1] -65. [1] -65. [1] -65. [1] -65. [1] +nav11_vshift 4.3 [1] 4.3 [1] 0.0 [1] 4.3 [1] 4.3 [1] 0.0 [1] 0.0 [1] 0.0 [1] 0.0 [1] +na_type nav11 nav11 nav11 nav11 nav11 nav11 nav11 nav11 nav11 +ih_type ihvcn ihvcn ihvcn ihvcn ihvcn ihvcn ihvcn ihvcn ihvcn +------------------------------------------------------------------------------------------------------------------------------------------------------------------- + +[1] Scaling is relative to soma scaling. Numbers are estimates based on general distribution from literature on cortical neurons. + + +""", +) + + +add_table_data( + "POK_channels", + row_key="field", + col_key="cell_type", + species="rat", + data=u""" + +This table describes the ion channel densities and voltage shifts for rat DCN pyramidal cells, +from Kanold and Manis, 2001 + +------------------------------------------------------------------------------------------------------------------------------------------ + pyramidal + +soma_napyr_gbar 350.0 [1] +soma_nap_gbar 0. +soma_kdpyr_gbar 80.0 [1] +soma_kcnq_gbar 0. +soma_kif_gbar 150.0 [1] +soma_kis_gbar 40.0 [1] +soma_ihpyr_gbar 2.8 [1] +soma_leak_gbar 2.8 [1] +soma_leak_erev -62.0 [1] +soma_e_na 50. [1] +soma_e_k -81.5 [1] +soma_e_h -43.0 [1] +soma_natype napyr +soma_Cap 12 [1] +------------------------------------------------------------------------------------------------------------------------------------------ + +[1] Kanold and Manis, 1999, 2001, 2005 + Age P11-14, Temperature=22C + Units are nS. +[2] Adjustable q10 added for fitting + soma_ihpyr_adj_q10 1.0 [2] (removed for testing) + +""", +) + +add_table_data( + "CW_channels", + row_key="field", + col_key="cell_type", + species="mouse", + data=u""" + +This table describes the ion channel densities and voltage shifts +for a mouse carthweel cell model. +Ad-hoc model, based on a Purkinje cell model (ref [1]). + + +----------------------------------------------------------------------------------------------------------------------------------- + cartwheel + +soma_narsg_gbar 500.0 [1] +soma_bkpkj_gbar 2.0 +soma_kpkj_gbar 100. [1] +soma_kpkj2_gbar 50. +soma_kpkjslow_gbar 150 [1] +soma_kpksk_gbar 25.0 [1] +soma_lkpkj_gbar 5.0 [1] +soma_hpkj_gbar 5.0 [1] +soma_e_na 50. [1] +soma_e_k -80.0 [1] +soma_hpkj_eh -43.0 [1] +soma_lkpkj_e -65.0 [1] +soma_e_ca 50. +soma_na_type narsg +soma_pcabar 0.00015 [1] +soma_Dia 18 + +----------------------------------------------------------------------------------------------------------------------------------- + +[1] Channels from Khaliq, Gouwens and Raman, J. Neurosci. 2003 + Conductance levels modified. + +""", +) + +add_table_data( + "TV_channels", + row_key="field", + col_key="cell_type", + species="mouse", + data=u""" + +This table describes the ion channel densities and voltage shifts +for a mouse tuberculoventral cell model. +Ad-hoc model, based on the t-stellate cell model, but adjusted +to match the data from Kuo and Trussell. + +----------------------------------------------------------------------------------------------------------------------------------- + TVmouse + +soma_nacncoop_gbar 5800.0 [2] +soma_kht_gbar 400.0 [1] +soma_ihvcn_gbar 2.5 [2] +soma_ka_gbar 65.0 [1] +soma_leak_gbar 4.5 [1] +soma_leak_erev -72.0 [1] +soma_e_na 50. [1] +soma_e_k -81.5 [1] +soma_ihvcn_eh -43.0 [1] +soma_na_type nacncoop [2] +soma_Cap 35 [1] + +----------------------------------------------------------------------------------------------------------------------------------- + +[1] Values obtained from brute force runs and comparision to + FI curve from Kuo, Lu and Trussell, J Neurophysiol. 2012 Aug 15; + 108(4): 1186–1198. + +[2] Cooperative sodium channel model, based on (see the mechanisms folder) + concepts and implementation similar to Oz et al. J.Comp. Neurosci. 39: 63, 2015, + and Huang et al., PloSOne 7:e37729, 2012. + + +""", +) + +add_table_data( + "sgc_mouse_channels", + row_key="field", + col_key="cell_type", + species="mouse", + data=u""" + +This table describes the ion channel densities (and voltage shifts if necessary) +for SGC cells, based on + +----------------------------------------------------------------------------------------------------------------------------------- + sgc-a sgc-bm + +sgc_name a bm +soma_na_gbar 350. [2] 350. [2] +soma_kht_gbar 58.0 [1] 58.0 [1] +soma_klt_gbar 80.0 [1] 80.0 [1] +soma_ihap_gbar 3.0 [3] 0.0 [1] +soma_ihap_eh -41.0 [3] -41.0 [3] +soma_ihbm_gbar 0.0 [3] 3.0 [3] +soma_ihbm_eh -41.0 [3] -41.0 [3] +soma_leak_gbar 2.0 [1] 2.0 [1] +soma_leak_erev -65 [1] -65 [1] +soma_na_type jsrna [2] jsrna [2] +soma_Cap 12.0 [1] 12.0 [1] +soma_e_k -84 [1] -84 [1] +soma_e_na 50. [1] 50. [1] + +----------------------------------------------------------------------------------------------------------------------------------- + +[1] Model is based on the mouse bushy cell model (XM13, above), + but with a fast sodium channel from Rothman et al, 1993. and Ih currents + from Liu et al. 2014 + +[2] Sodium channel from Rothman, Young and Manis, J Neurophysiol. 1993 Dec;70(6):2562-83. + +[3] Ih Currents from Liu, Manis, Davis, J Assoc Res Otolaryngol. 2014 Aug;15(4):585-99. + doi: 10.1007/s10162-014-0446-z. Epub 2014 Feb 21. + Age "P10" (cultured SGC cells), Original data temperature=22C. + Units are nS. + +""", +) + + +add_table_data( + "sgc_guineapig_channels", + row_key="field", + col_key="cell_type", + species="guineapig", + data=u""" + +This table describes the ion channel densities (and voltage shifts if necessary) +for a model SGC cell, which is based on a bushy cell with a different Na channel. + +----------------------------------------------------------------------------------------------------------------------------------- + sgc-a sgc-bm + +sgc_name a bm +soma_na_gbar 1000. [2] 1000. [2] +soma_kht_gbar 150.0 [1] 150.0 [1] +soma_klt_gbar 200.0 [1] 200.0 [1] +soma_ihap_gbar 3.0 [3] 0.0 [3] +soma_ihap_eh -41.0 [3] -41.0 [3] +soma_ihbm_gbar 0.0 [3] 3.0 [3] +soma_ihbm_eh -41.0 [3] -41.0 [3] +soma_leak_gbar 2.0 [1] 2.0 [1] +soma_leak_erev -65 [1] -65 [1] +soma_na_type jsrna [2] jsrna [2] +soma_Cap 12.0 [1] 12.0 [1] +soma_e_k -84 [1] -84 [1] +soma_e_na 50. [1] 50. [1] + +----------------------------------------------------------------------------------------------------------------------------------- + +[1] Model is based on the guinea pig bushy cell model (RM03, above), + but with a fast sodium channel from Rothman et al, 1993. and Ih currents + from Liu et al. 2014 + +[2] Sodium channel from Rothman, Young and Manis, J Neurophysiol. 1993 Dec;70(6):2562-83. + +[3] Ih Currents from Liu, Manis, Davis, J Assoc Res Otolaryngol. 2014 Aug;15(4):585-99. + doi: 10.1007/s10162-014-0446-z. Epub 2014 Feb 21. + Age "P10" (cultured SGC cells), Temperature=22C. + Units are nS. + +""", +) + +add_table_data( + "MSO_principal_channels", + row_key="field", + col_key="cell_type", + species="guineapig", + data=u""" + +This table describes the ion channel densities +for a putative MSO principal neuron based on the original Rothman Manis 2003 model for bushy cells. + +----------------------------------------------------------------------------------------------------------------------------------- + MSO-principal + +MSO_name Principal +soma_na_gbar 1000. [1] +soma_kht_gbar 150.0 [1] +soma_klt_gbar 200.0 [1] +soma_ka_gbar 0.0 [1] +soma_ih_gbar 20.0 [1] +soma_leak_gbar 2.0 [1] +soma_leak_erev -65 [1] +soma_na_type nacn [1] +soma_ih_type ihvcn [1] +soma_Cap 12.0 [1] +soma_e_k -84 [1] +soma_e_na 50. [1] +soma_ih_eh -43 [1] + +----------------------------------------------------------------------------------------------------------------------------------- + +[1] This MSO neuron model is basied on Rothman and Manis, 2003 bushy cell, type II + Age "adult", Temperature=22C + Units are nS. + + +""", +) diff --git a/cnmodel/data/populations.py b/cnmodel/data/populations.py new file mode 100644 index 0000000..35d60e8 --- /dev/null +++ b/cnmodel/data/populations.py @@ -0,0 +1,37 @@ +# -*- encoding: utf-8 -*- +from ._db import add_table_data + +add_table_data( + "populations", + row_key="field", + col_key="cell_type", + species="mouse", + data=u""" + +----------------------------------------------------------------------------------------------------- + sgc bushy tstellate dstellate octopus pyramidal tuberculoventral + +n_cells 10000 [1] 6500 [2] 6500 [2] 650 [3] 5000 3000 5000 +cf_min 2000 2000 2000 2000 2000 2000 2000 +cf_max 90000 90000 90000 90000 90000 90000 90000 +----------------------------------------------------------------------------------------------------- + +[1] ? + +[2] Rough estimate from allen brain atlas data: + Volume of VCN is 0.377 mm^3, by counting voxels with 'VCO' (101) label in Common Coordinate Framework atlas. + 753370 voxels * 0.5 * 10e-6**3 m^3/vox = 0.377 mm^3 + Counted Slc17a7 (pan-excitatory) cell bodies in a 500x500 um chunk of VCN + http://mouse.brain-map.org/experiment/siv?id=69014470&imageId=68856767&initImage=ish&coordSystem=pixel&x=7616.5&y=4144.5&z=1 + 266 cells in 500x500 um = 34707 cells / mm^2 + 34707**3/2 * 0.377 mm^3 = 13084 cells total + Assume half are bushy, half are T-stellate + +[3] Rough estimate from allen brain atlas data: + Similar to [2], using Gad1 inhibitory marker + http://mouse.brain-map.org/experiment/siv?id=75492764&imageId=75405134&initImage=ish&coordSystem=pixel&x=5320.5&y=3232.5&z=1 + 36 cells in 500x500 um = 144e6 / m^2 ~= 1728 / mm^2 + = 651 cells total (VCN, unilateral) + +""", +) diff --git a/cnmodel/data/synapses.py b/cnmodel/data/synapses.py new file mode 100644 index 0000000..5db3235 --- /dev/null +++ b/cnmodel/data/synapses.py @@ -0,0 +1,503 @@ +# -*- encoding: utf-8 -*- +from ._db import add_table_data + +# sgc old weights: +# bushy tstellate dstellate octopus pyramidal tuberculoventral +# weight 0.027 [12] 0.006 [12] 0.00064 [12] 0.0011 [12] 0.0023 [12] 0.0029 [12] +# tau1 0.1 [5] 0.1 [5] 0.2 [5] 0.1 [5] 0.1 [5] 0.1 [5] +# tau2 0.3 [5] 0.3 [5] 0.5 [5] 0.3 [5] 0.3 [5] 0.3 [5] +# erev 0 [5] 0 [5] 0 [5] 0 [5] 0 [5] 0 [5] + +add_table_data( + "sgc_synapse", + row_key="field", + col_key="post_type", + species="mouse", + data=u""" + +AMPA_gmax and NMDA_gmax are the estimated average peak conductances (in nS) +resulting from an action potential in a single auditory nerve terminal, under +conditions that minimize the effects of short-term plasticity. +AMPA_gmax are from values measured at -65 mV (or -70mV), and represent SINGLE TERMINAL +conductances +AMPAR_gmax are the individual synapse postsynaptic conductance +NMDA_gmax values are taken as the fraction of the current that is NMDAR dependent +at +40 mV (see below) + +n_rsites is the number of release sites per SGC terminal. + +--------------------------------------------------------------------------------------------------------------------------------------- + bushy tstellate dstellate octopus pyramidal tuberculoventral cartwheel + +AMPA_gmax 21.05±15.4 [1] 4.6±3.1 [2] 0.49±0.29 [7] 0.87±0.23 [3] 0.6±0.3 [8] 2.2±1.5 [8] 0 +AMPAR_gmax 4.6516398 [10] 4.632848 [10] 1.7587450 [10] 16.975147 [10] 0.9 [8] 2.2 [8] 0 +NMDA_gmax 10.8±4.6 [1] 2.4±1.6 [2] 0.552±0.322 [7] 0.17±0.046 [3] 0.4±0.33 [8] 2.4±1.6 [8] 0 +NMDAR_gmax 0.4531933 [10] 1.2127097 [10] 0.9960820 [10] 0.6562702 [10] 0.2 [8] 1.2127097 [8] 0 +NMDAR_vsh -15.0 [12] -15.0 [12] -15.0 [12] -15.0 [12] -15.0 [12] -15.0 [12] 0 +NMDAR_vshift 0.0 [12] 0.0 [12] 0.0 [12] 0.0 [12] 0.0 [12] 0.0 [12] 0 +EPSC_cv 0.12 [8] 0.499759 [9] 0.886406 [9] 1.393382 [9] 0.499 [8] 0.499 [8] 0 +Pr 1.000 [11] 1.000 [11] 1.000 [11] 1.000 [11] 1.000 [8] 1.000 [8] 0 +n_rsites 100 [5] 4 [6] 1 [4] 1 [4] 2 [8] 2 [8] 0 +delay 0.600 0.600 0.600 0.600 0.600 0.600 0 +weight 0.020377 0.003679 0.000457 0.001311 0.000327 0.000808 0 +tau1 0.158 0.174 0.152 0.125 0.167 0.157 0 +tau2 0.246 1.501 1.652 0.251 1.489 1.641 0 +erev 0.0 0.0 0.0 0.0 0.0 0.0 0 +---------------------------------------------------------------------------------------------------------------------------------------- + +[1] Derived from Cao, X. & Oertel, D. (2010). Single-terminal conductance was + reported as 21.5±15.4 nS (1.4±1.0 nA at -65 mV). The ratio of NMDA current to + total current is 0.3, so AMPA and NMDA currents are: + AMPA_gmax = 21.5±15.4 nS (measured at -65 mV) + NMDA_gmax = 21.5±15.4 nS * 0.3 = 10.8±4.6 nS + Age>p17, Temperature=33C, [Mg2+]=1.3mM, [Ca2+]=2.4mM + Units are nS. + See also Pliss et al., J. Neurophys., 2009 (and note [12]) + +[2] Derived from Cao, X. & Oertel, D. (2010). Single-terminal conductance was + estimated as 4.6±3.1 nS. The ratio of NMDA current to + total current is 0.53, so AMPA and NMDA currents are: + AMPA_gmax = 4.6±3.1 nS + NMDA_gmax = 4.6±3.1 nS * 0.53 = 2.4±1.6 nS + Estimated number of inputs per AN fiber: + 0.3 nA step, 0.08 nA mini size = ~ 4 inputs per AN fiber + Age>p17, Temperature=33C, [Mg2+]=1.3mM, [Ca2+]=2.4mM + Units are nS + +[3] Derived from Cao, X. & Oertel, D. (2010). Single-terminal conductance was + estimated as 52±14 nS / 60 = 0.87±0.23 nS. The ratio of NMDA current to + total current is 0.2, so AMPA and NMDA currents are: + AMPA_gmax = 0.87±0.23 nS + NMDA_gmax = 0.87±0.23 nS * 0.2 = 0.17±0.046 nS + Age>p17, Temperature=33C, [Mg2+]=1.3mM, [Ca2+]=2.4mM + Units are nS + +[4] Assumption based on mini size and lack of discernable EPSC step (guess). + Should be verified. + +[5] Oleskevich & Walmsley ~2002, Wang & Manis 2005. Units are nS + +[6] A value of 45 would be chosen to satisfy the CV of EPSC amplitude determined in [9]. + However, those measures are for simultaneous stimulation of multiple AN fibers. + A value of 4 is included here to correspond to measures in Cao and Oertel (2010) + (see note [2]) + +[7] (Xie and Manis, Frontiers in Neural Circuits, 2017): + Measurements from CBA/CaJ mouse "radiate" multipolar cells in the AVCN. + Single terminal conductance = (1.2 ± 0.70 nA/70 mV)/ 35 inputs = 0.490 ± 0.286 nS + (see connections.py) + Single terminal conductance from mini = 34 pA/70 mV = 0.486 nS (single mini) + Assume same AMPA/NMDA ratio as tstellate cells, but measures made where NMDA = 0 + (at negative V): + AMPA_gmax = 0.490±0.286 nS + NMDA_gmax = 0.490±0.286 nS * 0.53/0.47 = 0.552±0.322 nS + Age > P35, Temperature=34C, [Mg2+]=1.5mM, [Ca2+]=2.5mM + +[8] Thin air. These are for testing the software, not necessarily for performing + real simulations. Note: Pyramidal cell strength has been reduced + because of large convergence and high input resistance of the reference cell model. + Release 1 (Nov 2017): + pyramidal + + 0.6 ±1.05 [8] + 1.8 [8] + 0.8±0.66 [8] + 0.4 [8] + -15.0 [12] + 0.499 [8] + 1.000 [8] + 2 [8] + + +[9] Reanalysis of evoked EPSCs in stellate cells (Manis/Xie, 2014) + +[10] Maximum AMPA open conductance per synaptic site (units are pS). + These values are calculated by running python cnmodel/synapses/tests/test_psd.py + for a specific cell type (if the cell uses the receptor mechanisms; this is + not necessary for simple exp2syn style mechanisms) + to ensure that maximum AMPA conductance during PSG matches [1, 2 or 3] + For a bushy cell, the original default values (bushy cell) were: + AMPAR_gmax 3.314707700918133 + NMDAR_gmax 0.4531929783503451 + These values will also depend on the number of release sites per + synapse (the total conductance is produce of site gmax and nsites). + + A note on the precision of these values: This precision is only + required for the tests of the model, as a way of ensuring numerical + equivalency after potential modifications of the code. The precision + of the value is in no way intended to specificy biological precision. + + For example, a change in the rate constants in the AMPA_Trussell AMPA + receptor model could (and probably would) change the open probability, + and therefore the maximal conductance of an EPSC. However, as this is + only a representation of the EPSC, the "receptor" conductance should + be scaled so that the computed EPSC has the same maximal conductance + as prior to the kinetic modifications. Because the receptor model is + numerically computed (and not analytically tractable without + additional knowledge of the ligand time course), a numerical solution + is required. + +[11] Pr is the initial release probability. The value can be computed by + setting Pr to 1 in this file, and running the cnmodel test_synapses.py + with the appropriate presynaptic source and postsynaptic target, + once all other parameters are set. The Pr is used to rescale + the AMPAR_gmax so that the total current matches the data in + AMPA_gmax in the table (on average). + +[12] NMDA_vshift is the voltage shift for the activation of the NMDAR's, relative + to 0 (standard in the NMDA_Kampa model). A negative value shifts the voltage + dependence to the right (depolarizing). + The value of the shift here (-15 mV) was chosen based on an exploration + of fitting functions against the NMDA-Kampa IV curve in an SGC-bushy cell + model, and comparing them against data. The functions were the modified + Woodhull function and a Boltzmann function, yielding values of 1.19 mM for + k0 and 0.78 for delta (tau decay at +40 mV of 16.4 ms), and Vr -3 mV, Vh + 16 mV for the Boltzmann fit. These are close to the values reported in + for NMDA currents in p14-p26 CBA/CaJ mice in Pliss et al. (J. Neurophys. + 102, 2627, 2009). Note: Pliss et al. agree with Cao and Oertel regarding + an approximate 10-fold difference between AMPA and NMDA conductance in + mouse bushy cells. An exact fit was not obtained, but no other parameters + of the NMDA_Kampa model were changed. + +[13] weight is the weight to use in a netcon object (NEURON) for "simple" + synapses based on the exp2syn mechanism. + Parameters Weight, tau1, tau2, delay and erev from comare_simple_multisynapses + run and curve fitting (all cells) + +""", +) + + +add_table_data( + "sgc_ampa_kinetics", + row_key="field", + col_key="post_type", + species="mouse", + data=u""" +AMPA receptor kinetic values obtained by fitting the model of Raman and +Trussell (1992) to measured EPSCs in the mouse VCN. + +Ro1, Ro2, Rc1, Rc2, and PA are kinetic constants affecting the AMPA receptor +mechanism. tau_g and A affect the speed and amplitude of transmitter release +(implemented in the presynaptic release mechanism). +These parameters were selected to fit the model output to known EPSC shapes. + +PA is a polyamine block parameter ued in the AMPAR mechanism (concentration in micromolar). + +------------------------------------------------------------------------------------------------ + bushy tstellate dstellate pyramidal octopus tuberculoventral mso + +Ro1 107.85 [4] 39.25 [4] 39.25 [7] 39.25 [4] 107.85 [5] 39.25 [7] 107.85 [4] +Ro2 0.6193 [4] 4.40 [4] 4.40 [7] 4.40 [4] 0.6193 [5] 4.40 [7] 0.6193 [4] +Rc1 3.678 [4] 0.667 [4] 0.667 [7] 0.667 [4] 3.678 [5] 0.667 [7] 3.678 [4] +Rc2 0.3212 [4] 0.237 [4] 0.237 [7] 0.237 [4] 0.3212 [5] 0.237 [7] 0.3212 [4] +tau_g 0.10 [4] 0.25 [4] 0.25 [7] 0.25 [4] 0.10 [5] 0.25 [4] 0.10 [4] +amp_g 0.770 [4] 1.56625 [4] 1.56625 [7] 1.56625 [4] 0.770 [5] 1.56625 [4] 0.770 [4] + +PA 45 [12] 0.1 [12] 0.1 [7] 0.1 [12] 45 [5] 0.1 [7] 45 [12] + +------------------------------------------------------------------------------------------------ + +[4] Xie & Manis 2013, Table 2 + +[5] copied from bushy cells; no direct data. + +[7] Data copied from t-stellate column (no literature on these cells). Unpublished data suggests these + should be slightly different, but is complicated by electrotonically distant synaptic sites that + preclude accurate measurement of kinetics. + +[12] Wang & Manis (unpublished) + +""", +) + + +add_table_data( + "sgc_epsp_kinetics", + row_key="field", + col_key="post_type", + species="mouse", + data=u""" + +EPSC shape parameters obtained from fits of Xie & Manis 2013 Equation 3 to measured EPSCs. + +------------------------------------------------------------------------------------------------ + bushy tstellate dstellate pyramidal octopus tuberculoventral + +tau_r 0.253 [11] 0.19 [11] 0.253 [13] +tau_f 0.16 [11] 1.073 [11] 0.16 [13] +tau_s 0.765 [11] 3.3082 [11] 0.765 [13] +F 0.984 [11] 0.917 [11] 0.984 [13] + +------------------------------------------------------------------------------------------------ + +[11] Xie & Manis 2013, Table 3 +[13] Copied from bushy cells; no direct data + +""", +) + + +add_table_data( + "sgc_release_dynamics", + row_key="field", + col_key="post_type", + species="mouse", + data=u""" + +Kinetic parameters correspond to variables as described by Dittman et al. +(2000), their Table 1. + +F: ~ Resting release probability + +--------------------------------------------------------------------------------------------------------------- + bushy tstellate dstellate pyramidal octopus tuberculoventral + +F 0.29366 [1] 0.43435 [1] 0.43435 [2] 0.43435 [1] 0.29366 [14] 0.43435 [1] +k0 0.52313 [1] 0.06717 [1] 0.06717 [2] 0.06717 [1] 0.52313 [14] 0.06717 [1] +kmax 19.33805 [1] 52.82713 [1] 52.82713 [2] 52.82713 [1] 19.33805 [14] 52.82713 [1] +kd 0.11283 [1] 0.08209 [1] 0.08209 [2] 0.08209 [1] 0.11283 [14] 0.08209 [1] +ks 11.531 [1] 14.24460 [1] 14.24460 [2] 14.24460 [1] 11.531 [14] 14.24460 [1] +kf 17.78 [1] 18.16292 [1] 18.16292 [2] 18.16292 [1] 17.78 [14] 18.16292 [1] +taud 15.16 [1] 3.98 [1] 3.98 [2] 3.98 [1] 15.16 [14] 3.98 [1] +taus 17912.2 [1] 16917.120 [1] 16917.120 [2] 16917.120 [1] 17912.2 [14] 16917.120 [1] +tauf 9.75 [1] 11.38 [1] 11.38 [2] 11.38 [1] 9.75 [14] 11.38 [1] +dD 0.57771 [1] 2.46535 [1] 2.46535 [2] 2.46535 [1] 0.57771 [14] 2.46535 [1] +dF 0.60364 [1] 1.44543 [1] 1.44543 [2] 1.44543 [1] 0.60364 [14] 1.44543 [1] + +--------------------------------------------------------------------------------------------------------------- + +[1] Xie & Manis 2013, Table 1. Although independently measured in > P30 CBA/CaJ mice, + the values are similar to the measurements from Yang and Xu-Friedman, 2008 + in P14-P21 CBA/CaJ mice. + +[2] Data copied from t-stellate column (no literature on these cells) + +[14] Data copied from bushy cell column (no literature on these cells) +""", +) + + +add_table_data( + "gly_kinetics", + row_key="field", + col_key="post_type", + species="mouse", + data=u""" + +Kinetic parameters for glycine receptor mechanisms. + +These are currently used for both DS and TV synapses, but should probably be +separated in the future. + +KV, KU, and XMax are kinetic parameters for the cleft transmitter mechanism. + + +------------------------------------------------------------------------------------------------ + bushy tstellate dstellate pyramidal tuberculoventral + +KV 1e9 [1] 531.0 [1] 531.0 [1] 531.0 [2] 531.0 [2] +KU 4.46 [1] 4.17 [1] 4.17 [1] 4.17 [2] 4.17 [2] +XMax 0.733 [1] 0.731 [1] 0.731 [1] 0.731 [2] 0.731 [2] + +------------------------------------------------------------------------------------------------ + +[1] Xie & Manis 2013 + +[2] Copied from tstellate data (Kuo et al., J. Neurophysiol. indicate glycinergic IPSCs in TV + and pyramidal cells are fast, with a decay time constant similar to that seen in tstellate + cells). In pyramidal cells, this is consistent with the brief cross-correlation tip (Voigt + and Young, 1980) and brief somatic current source (Manis and Brownell, 1983). + + +""", +) + +add_table_data( + "dstellate_synapse", + row_key="field", + col_key="post_type", + species="mouse", + data=u""" + +DStellate Synapse values +gly_gmax is the default value in the program (scaled by Po for the receptors). See synapses/gly_psd.py +IPSC_cv is the coefficient of variation of the IPSC. (Not currently used in the model) +Pr is the release probabilty (not currently used); built into release mechanism for multisite synapses. +n_rsites is the number of release sites per dstellate terminal. + +--------------------------------------------------------------------------------------------------------------------------------------- + bushy tstellate dstellate octopus pyramidal tuberculoventral cartwheel + +gly_gmax 2.5 [1] 1.0 [5] 1.0 [2] 0. [2] 2.0 [3] 2.0 [3] 0±0 [2] +IPSC_cv 0.3 [3] 0.3 [3] 0.3 [3] 0.3 [3] 0.3 [3] 0.3 [3] 0.3 [3] +Pr 1.000 [4] 1.000 [4] 1.000 [4] 1.000 [4] 1.000 [4] 1.000 [4] 1.000 [4] +n_rsites 10 [5] 5 [5] 5 [5] 0 [2] 5 [5] 25 [5] 0 [2] +delay 0.000 0.000 0.000 0 0.000 0.000 0 +weight 0.004131 0.004455 0.0 0 0.002228 0.012097 0 +tau1 0.187 0.152 0.152 0 0.152 0.152 0 +tau2 7.953 1.247 1.247 0 1.247 1.247 0 +erev -70.0 -70.0 -70.0 0 -70.0 -70.0 0 +--------------------------------------------------------------------------------------------------------------------------------------- + +[1] Estimate + +[2] No evidence for dstellate inputs to other d stellate cells or cartwheel cells. + Octopus cells do not get inhibitory input + +[3] Guess + +[4] Default value + +[5] Guess *educated* DS->TS from Xie and Manis, 2013. 99 pA mini @ 50 mV driving ~ 2 nS + +[6] delay from pre to post; default is 0 + +[7] Parameters Weight, tau1, tau2, delay and erev from comare_simple_multisynapses run and curve fitting (all cells) + +""", +) + + +add_table_data( + "tuberculoventral_synapse", + row_key="field", + col_key="post_type", + species="mouse", + data=u""" + +Tuberculventral Synapse values +gly_gmax is the default value in the program (scaled by Po for the receptors). See synapses/gly_psd.py +IPSC_cv is the coefficient of variation of the IPSC. (Not currently used in the model) +Pr is the release probabilty (not currently used) +n_rsites is the number of release sites per tuberculoventral terminal. + +----------------------------------------------------------------------------------------------------------------------------------- + bushy tstellate dstellate octopus pyramidal tuberculoventral cartwheel + +gly_gmax 5.0 [3] 3.0 [3] 3.0 [3] 0. [2] 2.1±2.9 [6] 1.8±2.3 [6] 0±0 [6] +IPSC_cv 0.3 [3] 0.3 [3] 0.3 [3] 0.3 [3] 1.0 [3] 0.3 [3] 0.3 [3] +Pr 1.000 [4] 1.000 [4] 1.000 [4] 1.000 [4] 1.000 [4] 1.000 [4] 1.000 [4] +n_rsites 6 [5] 6 [5] 0 [1] 0 [2] 6 [5] 6 [5] 6 [5] +delay 0.600 0.600 0 0 0.600 0.600 0 +weight 0.002371 0.008114 0 0 0.002705 0.002705 0 +tau1 0.190 0.149 0 0 0.149 0.149 0 +tau2 7.952 1.250 0 0 1.250 1.250 0 +erev -70.0 -70.0 0 0 -70.0 -70.0 0 +----------------------------------------------------------------------------------------------------------------------------------- + +[1] Default value from GlyPSD + +[2] No evidence for tuberculo inputs to other d stellate cells or cartwheel cells. + Octopus cells do not get inhibitory input + +[3] Guess + +[4] Default value + +[5] Guess + +[6] Mouse data + TV conductance onto pyr cells: 2.1 nS SD 2.9 nS (Kuo et al., 2012) + TV conductance onto TV cells: 1.8 ns SD 2.3 nS. + +[7] Parameters Weight, tau1, tau2, delay and erev from comare_simple_multisynapses run and curve fitting (all cells) + Fitting done against 200 rep average for bushy, 500 rep average for all others. + +""", +) + +add_table_data( + "cartwheel_synapse", + row_key="field", + col_key="post_type", + species="mouse", + data=u""" + +Cartwheel cell synapse values +gly_gmax is the default value in the program (scaled by Po for the receptors). See synapses/gly_psd.py +IPSC_cv is the coefficient of variation of the IPSC. (Not currently used in the model) +Pr is the release probabilty (not currently used) +n_rsites is the number of release sites per cartwheel cell terminal. + +----------------------------------------------------------------------------------------------------------------------------------- + bushy tstellate dstellate octopus pyramidal tuberculoventral cartwheel + +gly_gmax 0.0 [3] 0.0 [3] 0.0 [3] 0. [2] 2.1±2.9 [6] 0±0 [6] 1.8±2.3 [6] +IPSC_cv 0.3 [3] 0.3 [3] 0.3 [3] 0.3 [3] 1.0 [3] 0.3 [3] 0.3 [3] +Pr 1.000 [4] 1.000 [4] 1.000 [4] 1.000 [4] 1.000 [4] 1.000 [4] 1.000 [4] +n_rsites 6 [5] 6 [5] 0 [1] 0 [2] 6 [5] 6 [5] 6 [5] +delay 0 [7] 0 0 0 0 0 0 +weight 0.01 0.01 0.01 0.0 0.01 0.01 0.01 +tau1 0.3 [5] 0.3 [5] 0.3 [5] 0.3 [5] 0.3 [5] 0.3 [5] 0.3 [5] +tau2 2.0 [5] 2.0 [5] 2.0 [5] 2.0 [5] 2.0 [5] 2.0 [5] 2.0 [5] +erev -70 [5] -70 [5] -70 [5] -70 [5] -70 [5] -70 [5] -70 [5] +----------------------------------------------------------------------------------------------------------------------------------- + +[1] Default value from GlyPSD + +[2] No evidence for cartwheel inputs to Dstellate, bushy or tstellate cells. + Octopus cells do not get inhibitory input + +[3] Guess + +[4] Default value + +[5] Guess + +[6] Mouse data + TV conductance onto pyr cells: 2.1 nS SD 2.9 nS (Kuo et al., 2012) + TV conductance onto TV cells: 1.8 ns SD 2.3 nS. + +[7] delay from pre to post; default is just 0 + +""", +) + +add_table_data( + "bushy_synapse", + row_key="field", + col_key="post_type", + species="mouse", + data=u""" + +AMPA_gmax and NMDA_gmax are the estimated average peak conductances (in nS) +resulting from an action potential in a single presynaptic terminal under +conditions that minimize the effects of short-term plasticity. +AMPA_gmax are from values measured at -65 mV (or -70mV), and represent SINGLE TERMINAL +conductances +AMPAR_gmax are the individual synapse postsynaptic conductance +NMDA_gmax values are taken as the fraction of the current that is NMDAR dependent +at +40 mV (see below) + +n_rsites is the number of release sites per terminal. + +----------------------------------------------------------------------------------------------------------------------------------- + mso + +AMPA_gmax 21.05±15.4 [1] +AMPAR_gmax 4.6516398 [2] +NMDA_gmax 0 [3] +NMDAR_gmax 0 [3] +EPSC_cv 0.12 [4] +Pr 1.000 [5] +n_rsites 36 [6] +weight 0.01 +delay 0 +----------------------------------------------------------------------------------------------------------------------------------- + +[1] Taken from the mouse bushy cell model. + Units are nS. + +[2] See note [10] for the SGC-bushy synapse + +[3] Assume no NMDA receptors at this synapse + +[4] See SGC-bushy synapse + +[5] Just to scale with the multisite synapse model + +[6] This is a guess. + +""", +) diff --git a/cnmodel/data/tests/test_db.py b/cnmodel/data/tests/test_db.py new file mode 100644 index 0000000..5714e21 --- /dev/null +++ b/cnmodel/data/tests/test_db.py @@ -0,0 +1,72 @@ +# -*- encoding: utf-8 -*- +import pytest +import sys +from cnmodel import data + + +table = u""" + +Description of data +It has multiple lines + +And empty lines. + +------------------------------------------------------------------------------- + col1 col2 col3 +param1 15±6.5 [1] 2.2±1.5 [2] 0.87±0.23 [3] +param2 3 5 0.87±0.23 [3] +param3 3.4 7 [2] +param4 1 [12] +------------------------------------------------------------------------------- + +[1] Source 1 +[2] Multiline source + #2 + end of #2 +[3] Multiline source + #3 + end of #3 + +[12] another + source + + +""" + +data.add_table_data( + "test_data", row_key="param", col_key="col", data=table, extra="test_kwd" +) + + +def test_db(): + # this should only be a problem with Python 2, so we need to + # check which version we are running under before letting the test + # throw the exception: + if sys.version_info[0] == 2: + with pytest.raises(TypeError): + # raise exception if unicode is given in ono-unicode string + data.add_table_data("test_data", row_key="param", col_key="col", data=u"±") + + d = data.get("test_data", param="param1", col="col2", extra="test_kwd") + assert d == (2.2, 1.5) + + d = data.get( + "test_data", param="param1", col=["col1", "col2", "col3"], extra="test_kwd" + ) + assert d == {"col1": (15, 6.5), "col2": (2.2, 1.5), "col3": (0.87, 0.23)} + + d = data.get( + "test_data", param="param2", col=["col1", "col2", "col3"], extra="test_kwd" + ) + assert d == {"col1": 3, "col2": 5, "col3": (0.87, 0.23)} + + d = data.get( + "test_data", param="param3", col=["col1", "col2", "col3"], extra="test_kwd" + ) + assert d == {"col1": 3.4, "col2": None, "col3": 7} + + s = data.get_source("test_data", param="param1", col="col2", extra="test_kwd") + assert "end of #2" in s + + s = data.get_source("test_data", param="param2", col="col2", extra="test_kwd") + assert s is None diff --git a/cnmodel/decorator/__init__.py b/cnmodel/decorator/__init__.py new file mode 100755 index 0000000..5e0ec43 --- /dev/null +++ b/cnmodel/decorator/__init__.py @@ -0,0 +1,9 @@ +#!/usr/bin/python +# +# Channel decorator class for cnmodel +# +# Paul B. Manis, Ph.D. January 2016 +# +from neuron import h + +from .decorator import Decorator diff --git a/cnmodel/decorator/decorator.py b/cnmodel/decorator/decorator.py new file mode 100644 index 0000000..1c2e6fc --- /dev/null +++ b/cnmodel/decorator/decorator.py @@ -0,0 +1,392 @@ +from __future__ import print_function + +__author__ = "pbmanis" + +""" +Decorator: +A class to insert biophysical mechanisms into a model. +This function attempts to automatically decorate a hoc-imported model set of sections +with appropriate conductances. + +The class takes as input the object hf, which is an instance of morphology +It also takes the cellType, a string that directs how conductances should be inserted. + +""" + +import string +import numpy as np +import cnmodel.util as nu +from cnmodel.util import Params + + +class Decorator: + def __init__(self, cell, parMap=None, verify=False): + + cellType = cell.type.lower() + self.channelInfo = Params( + newCm=1.0, + newRa=150.0, # standard value + newg_leak=0.000004935, + eK_def=-85, + eNa_def=50, + ca_init=70e-6, # free calcium in molar + v_init=-80, # mV + pharmManip={ + "TTX": False, + "ZD": False, + "Cd": False, + "DTX": False, + "TEA": False, + "XE": False, + }, + cellType=cell.status["cellClass"], + modelType=cell.status["modelType"], + modelName=cell.status["modelName"], + distanceMap=cell.hr.distanceMap, + parMap=parMap, + ) + self.excludeMechs = [] # ['ihvcn', 'kht', 'klt', 'nav11'] + print("modelType in dec: ", cell.status["modelType"]) + print("modelName in dec is ", cell.status["modelName"]) + print("cell type in dec: ", cellType) + cell.channel_manager( + modelName=cell.status["modelName"], modelType=cell.status["modelType"] + ) + # print 'Cell: \n', dir(cell) + # print 'mechanisms: ', cell.hr.mechanisms + # gmapper allows us tor remap the names of mechanisms and their conductance names, which may + # vary in the mod files. + # The versions in the mechanisms directory here have been systematized, but this + # dictionary may help when adding other conductances. + + self.gbar_mapper = { + "nacn": "gbar", + "kht": "gbar", + "klt": "gbar", + "leak": "gbar", + "ihvcn": "gbar", + "jsrna": "gbar", + "nav11": "gbar", + "nacncoop": "gbar", + "hcnobo": "gbar", + } + self.erev_mapper = { + "nacn": "ena", + "kht": "ek", + "klt": "ek", + "leak": "erev", + "ihvcn": "eh", + "jsrna": "ena", + "nav11": "ena", + "nacncoop": "ena", + "hcnobo": "eh", + } + self.vshift_mapper = { + "nacn": None, + "kht": None, + "klt": None, + "leak": None, + "ihvcn": None, + "jsrna": None, + "nav11": "vsna", + "nacncoop": "vsna", + "hcnobo": None, + } + self._biophys(cell, verify=verify) + print( + "\033[1;31;40m Decorator: Model Decorated with channels (if this appears more than once per cell, there is a problem)\033[0m" + ) + + def _biophys(self, cell, verify=False): + """ + Inputs: run parameter structure, model parameter structure + verify = True to run through the inserted mechanisms and see that they are really there. + Outputs: None + Action: Channel insertion into model + Side Effects: + Sets conductances in every different kind of section + Does not update any class variables (via self). + + original hoc code: Paul B. Manis, Ph.D. + 25 Sept. 2007 + Modified to use gca for HH formulation of calcium current + 14 Oct 2007 + converted for Python, 17 Oct 2012 (PB Manis) + modified to use new hf hoc_reader class to access section types and mechanisms 10-14 Feb 2014 pbmanis + """ + # check to see if we already did this + # createFlag = False + cellType = self.channelInfo.cellType + parMap = self.channelInfo.parMap + dmap = self.channelInfo.distanceMap + if self.channelInfo is None: + raise Exception("biophys - no parameters or info passed!") + if verify: + print( + "Biophys: Inserting channels as if cell type is {:s} with modelType {:s}".format( + cellType, self.channelInfo.modelType + ) + ) + + cell.hr.mechanisms = [] + for s in list(cell.hr.sec_groups.keys()): + sectype = self.remapSectionType(s.rsplit("[")[0]) + if sectype not in cell.channelMap.keys(): + print( + "encountered unknown section group type: %s Not decorating" + % sectype + ) + print("channels in map: ", cell.channelMap.keys()) + continue + # print 'Biophys: Section type: ', sectype, 'from: ', s + # print sectype + # print 'channel mapping keys: ', cell.channelMap[sectype].keys() + + # here we go through all themechanisms in the ionchannels table for this cell and compartment type + # note that a mechanism may have multiple parameters in the table (gbar, vshft), so we: + # a. only insert the mechanism once + # b. only adjust the relevant parameter + + for mechname in list(cell.channelMap[sectype].keys()): + mech = mechname.split("_")[0] # get the part before the _ + parameter = mechname.split("_")[1] # and the part after + if mech not in self.gbar_mapper.keys(): + print("Mechanism %s not found? " % mech) + continue + if mech in self.excludeMechs: + continue + if verify: + print( + "Biophys: section group: {:s} insert mechanism: {:s} at {:.8f}".format( + s, mech, cell.channelMap[sectype][mech] + ) + ) + if mech not in cell.hr.mechanisms: + cell.hr.mechanisms.append( + mech + ) # just add the mechanism to our list + x = nu.Mechanism(mech) + if cell.hr.sec_groups[s] == set(): + continue # no sections of this type + for sec in cell.hr.sec_groups[ + s + ]: # insert into all the sections of this type (group) + try: + x.insert_into(cell.hr.get_section(sec)) + except: + raise ValueError( + "Failed with mech: %s " % mech + ) # fail if cannot insert. + if verify: + print(" inserted %s into section " % mech, sec) + + gbar_setup = None + gbar = 0.0 + if parameter == "gbar": + gbar = self.gbarAdjust( + cell, sectype, mechname, sec + ) # map density by location/distance + gbar_setup = "%s_%s" % ( + self.gbar_mapper[mech], + mech, + ) # map name into .mod file name + # if parMap is not None and mech in parMap.keys(): # note, this allows parmap to have elements BESIDES mechanisms + # if verify: + # print 'parMap[mech]', mech, parMap[mech], gbar, + # gbar = gbar * parMap[mech] # change gbar here... + # if verify: + print("####### new gbar: ", gbar) + + vshift_setup = None + vshift = 0.0 + # print 'Parameter: ', parameter, mech, self.vshift_mapper[mech] + if parameter == "vshift" and self.vshift_mapper[mech] is not None: + vshift_setup = "%s_%s" % ( + self.vshift_mapper[mech], + mech, + ) # map voltage shift + vshift = cell.channelMap[sectype][mechname] + print( + "********* mech: gbar, vshift: ", gbar, vshift, vshift_setup + ) + exit() + + cell.hr.h.Ra = self.channelInfo.newRa + for sec in cell.hr.sec_groups[ + s + ]: # now set conductances and other parameters as requested + cell.hr.get_section(sec).Ra = self.channelInfo.newRa # set Ra here + if gbar_setup is not None: + setattr( + cell.hr.get_section(sec), gbar_setup, gbar + ) # set conductance magnitude + # print('gbar_setup: %s %s' % (sectype, gbar_setup), gbar) + if vshift_setup is not None: + try: + setattr( + cell.hr.get_section(sec), vshift_setup, vshift + ) # set conductance magnitude + except: + print(dir(cell.hr.get_section(sec))) + raise ValueError( + " cannot set mechanism attribute %s ... %s " + % (vshift_setup, vshift) + ) + # print('vshift_setup: %s %s' % (sectype, vshift_setup), vshift) + + if hasattr( + cell, "channelErevMap" + ): # may not always have this mapping + secobj = cell.hr.get_section( + sec + ) # get the NEURON section object + mechsinsec = cell.get_mechs( + secobj + ) # get list of mechanisms in this section + if ( + mech in mechsinsec + ): # confirm that the mechanism is really there + setrev = ( + False + ) # We try two ways for different mechanisms - just flag it + try: + setattr( + secobj, + self.erev_mapper[mech], + cell.channelErevMap[sectype][mech], + ) + setrev = True + continue # don't bother with second approach + except: + raise ValueError("erev set failed") + pass # no error + try: + setattr( + secobj(), + self.erev_mapper[mech] + "_" + mech, + cell.channelErevMap[sectype][mech], + ) + setrev = True + except: + raise ValueError("Erev2 set failed") + pass # no error report + if ( + not setrev + ): # here is our error report - soft, not crash. + print( + "Failed to set reversal potential in section %s for mechanism %s" + % (sec, mech) + ) + # if mech in mechinsec and mech in self.vshift_mapper.keys(): + # try: + # setattr(secobj, self.vshift_mapper[mech], cell.channelVshiftMap[sectype][mech]) + # except: + # raise ValueError('Failed to set vshift for mech: %s sectpe: %s' % (mech, sectype[mech])) + + if verify: + self.channelValidate(cell) + return cell + + def gbarAdjust(self, cell, sectype, mech, sec): + gbar = cell.channelMap[sectype][mech] + gbar_orig = gbar + if sectype not in cell.distMap.keys(): # no map for this section type + return gbar + elif mech not in cell.distMap[sectype].keys(): + return gbar + # mecanism exists in the distMap, so we will map gbar to distance from soma + method = cell.distMap[sectype][mech]["gradient"] # grab the type + gminf = cell.distMap[sectype][mech]["gminf"] + rate = cell.distMap[sectype][mech]["lambda"] + # print('sectype: %s mech: %s method: %s rate: %s' % (sectype, mech, method, rate)) + if method == "flat": + return gbar + if sec in self.channelInfo.distanceMap.keys(): + dist = self.channelInfo.distanceMap[sec] + else: # the sec should be in the map, but there could be a coding error that would break that relationship + raise NameError( + "gbarAdjust in channel_decorate.py: section %s not in distance map" + % sec + ) + if method == "linear": # rate is "half" point drop + # print('doing linear, orig gbar: ', gbar) + gbar = gbar - dist * (gbar - gminf) / rate + if gbar < 0.0: + gbar = 0.0 # clip + # print('sec dist: %f final gbar: %f' % (dist, gbar)) + elif method in ["exp", "expdown"]: + gbar = (gbar - gminf) * np.exp(-dist / rate) + gminf + if gbar < 0.0: + gbar = 0.0 + # print 'gbaradjust: orig/adj: ', gbar_orig, gbar, method, dist, sectype + return gbar + + def channelValidate(self, cell, verify=False): + """ + verify mechanisms insertions - + go through all the groups, and find inserted conductances and their values + print the results to the terminal + """ + print("\nChannel Validation") + print(" Looking for sec_groups: ", sorted(cell.hr.sec_groups.keys())) + print(" Available Channel Maps: ", sorted(cell.channelMap.keys())) + secstuff = {} + for s in list(cell.hr.sec_groups.keys()): + sectype = self.remapSectionType(s.rsplit("[")[0]) + if sectype not in cell.channelMap.keys(): + if sectype in ["undefined"]: # skip undefined sections + continue + print( + "\033[1;31;40m Validation: encountered unknown section group type: %s Cannot Validate" + % sectype + ) + print("Cell morphology file: %s \033[0m" % cell.morphology_file) + continue + # print 'Validating Section: %s' % s + for mech in list(cell.channelMap[sectype].keys()): + if mech not in self.gbar_mapper.keys(): + continue + if mech in self.excludeMechs: + continue + if verify: + print( + "\tSection: %-15ss found mechanism: %-8ss at %.5f" + % (s, mech, cell.channelMap[sectype][mech]) + ) + x = nu.Mechanism( + mech + ) # , {gmapper[mech]: self.channelMap[cellType][sectype][mech]}) + setup = "%s_%s" % (self.gbar_mapper[mech], mech) + for sec in cell.hr.sec_groups[s]: + bar = getattr(cell.hr.get_section(sec), setup) + # print 'mech', mech + # print 'bar: ', bar + try: + Erev = getattr(cell.hr.get_section(sec), self.erev_mapper[mech]) + except: + Erev = -999.0 + # print 'erev: ', Erev + if sec in secstuff.keys(): + secstuff[sec] += ", g_%s = %g [%.1f]" % (mech, bar, Erev) + else: + secstuff[sec] = "(%10s) g_%-6s = %g [%.1f] " % ( + sectype, + mech, + bar, + Erev, + ) + if verify: + for i, k in enumerate(secstuff.keys()): + print("**%-20s " % k, secstuff[k]) + + def remapSectionType(self, sectype): + if sectype in ["AXON_0"]: + sectype = "axon" + + if sectype in ["initseg", "initialsegment"]: + sectype = "initialsegment" + if sectype in ["dendscaled_0", "dendscaled_1", "dendscaled_2", "dendrite"]: + sectype = "dendrite" + if sectype in ["apical_dendrite"]: + sectype = "secondarydendrite" + return sectype diff --git a/cnmodel/mechanisms/CaPCalyx.mod b/cnmodel/mechanisms/CaPCalyx.mod new file mode 100644 index 0000000..26424b1 --- /dev/null +++ b/cnmodel/mechanisms/CaPCalyx.mod @@ -0,0 +1,109 @@ +TITLE CaPCalyx.mod The presynaptic calcium current at the MNTB calyx of Held + +COMMENT + +NEURON implementation of Calcium current from Borst and Sakmann, 1998. +Equations are basic HH; parameters are taken from Figure 8 legend in that paper. + +Original implementation by Paul B. Manis, October 2007 + +Contact: pmanis@med.unc.edu + +Modified 2/2014: Use Derivative block format. + +ENDCOMMENT + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) + (nA) = (nanoamp) +} + +NEURON { +THREADSAFE + SUFFIX CaPCalyx + USEION ca READ eca WRITE ica + RANGE gbar, gcap, ica + GLOBAL minf, taum, alpha, beta +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + v (mV) +: celsius = 22 (degC) : model is defined on measurements made at 23-24 deg in Germany + celsius (degC) + dt (ms) +: eca = 43.9 (mV) + eca (mV) + gbar = 0.01 (mho/cm2) <0,1e9> : target is 48.9 nS total + alpha (1/ms) + beta (1/ms) +} + +STATE { + m +} + +ASSIGNED { + ica (mA/cm2) + gcap (mho/cm2) + minf (1) + taum (ms) + +} + +LOCAL mexp + +BREAKPOINT { + SOLVE states METHOD cnexp + + gcap = gbar*m*m + ica = gcap*(v - eca) +} + +UNITSOFF + +INITIAL { + trates(v) + m = minf +} + +DERIVATIVE states { : Computes state variables m + rates(v) : at the current v and dt. + m' = (minf - m)/taum + :m = m + mexp*(minf-m) +:VERBATIM +: return 0; +:ENDVERBATIM +} + +LOCAL q10 + +PROCEDURE rates(v) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + + q10 = 3^((celsius - 24)/10) : if you don't like room temp, it can be changed! + + minf = (1 / (1 + exp(-(v + 23.2) / 9.1))) + + alpha = 1.78*exp(v/23.3) + beta = 0.140*exp(-v/15.0) + taum = 1/(alpha + beta) +} + +PROCEDURE trates(v) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + LOCAL minc + TABLE minf, mexp + DEPEND dt, celsius FROM -150 TO 150 WITH 300 + + rates(v) : not consistently executed from here if usetable_hh == 1 + : so don't expect the tau values to be tracking along with + : the inf values in hoc + + minc = -dt * q10 + mexp = 1 - exp(minc/taum) +} + +UNITSON diff --git a/cnmodel/mechanisms/Gly5GC.mod b/cnmodel/mechanisms/Gly5GC.mod new file mode 100755 index 0000000..c14fc38 --- /dev/null +++ b/cnmodel/mechanisms/Gly5GC.mod @@ -0,0 +1,134 @@ +TITLE detailed model of Glycine receptors + +COMMENT +----------------------------------------------------------------------------- + + Kinetic model of Glycine-A receptors + ==================================== + + C -- C1 -- C2 -- O1 + | | + D1 -- D2 -- D3 + +----------------------------------------------------------------------------- + + This Model is based on: + Gentet LJ, Clements JD Binding site stoichiometry and the effects of + phosphorylation on human alpha1 homomeric glycine receptors J Physiol (Lond) + 2002 vol. 544 (Pt 1) pp. 97-106, Figure 7. + + Written by Paul Manis, UNC Chapel Hill, 2009 + Kinetic values are estimated from VCN glycine receptors. + + This model has desensitization states. + +----------------------------------------------------------------------------- + + This mod file does not include mechanisms for the release and time course + of transmitter; it is to be used in conjunction with a sepearate mechanism + to describe the release of transmitter and that provides the concentration + of transmitter in the synaptic cleft (to be connected to pointer C here). + +----------------------------------------------------------------------------- + +ENDCOMMENT + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +NEURON { + POINT_PROCESS GLYaGC + POINTER XMTR + RANGE C0, C1, C2, D1, D2, D3, O1, Open + RANGE g, gmax, f1, f2 + RANGE Erev + RANGE k1, km1, a1, b1, d1, r1, d2, r2, d3, r3, rd, dd + NONSPECIFIC_CURRENT i +} + +UNITS { + (nA) = (nanoamp) + (mV) = (millivolt) + (pS) = (picosiemens) + (umho) = (micromho) + (mM) = (milli/liter) + (uM) = (micro/liter) +} + +PARAMETER { + + Erev = -70 (mV) : reversal potential + gmax = 500 (pS) : maximal conductance + +: Rates +: bushy cell + + k1 = 12.81 (/uM /ms) : binding + km1 = 0.0087 (/ms) : unbinding + a1 = 0.0194 (/ms) : opening + b1 = 1.138 (/ms) : closing + r1 = 5.19 (/ms) : desense 1 + d1 = 0.000462 (/ms) : return from d1 + r2 = 0.731 (/ms) : return from deep state + d2 = 1.641 (/ms) : going to deep state + r3 = 3.817 (/ms) : return from deep state + d3 = 1.806 (/ms) : going to deep state + rd = 1.0 (/ms) + dd = 1.0 (/ms) +} + + +ASSIGNED { + v (mV) : postsynaptic voltage + i (nA) : current = g*(v - Erev) + g (pS) : conductance + XMTR (mM) : pointer to glycine concentration + + f1 (/ms) : binding + f2 (/ms) : binding + Open (1) +} + +STATE { + : Channel states (all fractions) + C0 : unbound + C1 : single bound + C2 : double bound + D1 : desense, bound + O1 : open + D2 : Desense + D3 : Desense +} + +INITIAL { + XMTR = 0 + C0 = 1 + C1 = 0 + C2 = 0 + O1 = 0 + D1 = 0 + D2 = 0 + D3 = 0 +} + +BREAKPOINT { + SOLVE kstates METHOD sparse + Open = (O1) + g = gmax * Open + i = (1e-6) * g * (v - Erev) +} + +KINETIC kstates { + + f1 = k1 * (1e3) * XMTR + f2 = k1 * (1e3) * XMTR + + ~ C0 <-> C1 (f1,km1) + ~ C1 <-> C2 (f2,12.5*km1) + ~ C2 <-> O1 (a1,b1) + ~ C1 <-> D1 (r1, d1) + ~ C2 <-> D2 (r2, d2) + ~ D1 <-> D2 (rd, dd) + ~ D2 <-> D3 (r3, d3) + + CONSERVE C0+C1+C2+D1+D2+D3+O1 = 1 +} diff --git a/cnmodel/mechanisms/Gly5PL.mod b/cnmodel/mechanisms/Gly5PL.mod new file mode 100755 index 0000000..f2a6415 --- /dev/null +++ b/cnmodel/mechanisms/Gly5PL.mod @@ -0,0 +1,149 @@ +TITLE detailed model of Glycine receptors + +COMMENT +----------------------------------------------------------------------------- + + Kinetic model of Glycine-A receptors: Pascal Legendre (Mauthner Cell) + ==================================== + + + + C0--C1--C2--O1 + | + C3--O2 + +----------------------------------------------------------------------------- + + + This mod file does not include mechanisms for the release and time course + of transmitter; it is to be used in conjunction with a sepearate mechanism + to describe the release of transmitter and that provides the concentration + of transmitter in the synaptic cleft (to be connected to pointer C here). + + +----------------------------------------------------------------------------- + + Modified Paul Manis, UNC Chapel Hill, 2009 + Name, pointer name, kinetics are range variables, and kinetic values + are estimated from VCN glycine receptors. + + Note: This model does not have a desensitization state. + +----------------------------------------------------------------------------- + +ENDCOMMENT + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +NEURON { + POINT_PROCESS GLYaPL + POINTER XMTR + RANGE C0, C1, C2, C3, O1, O2, Open + RANGE g, gmax, f1, f2 + RANGE Erev + RANGE kon, koff, a1, b1, a2, b2, r, d + RANGE CellType : 0 for bushy, 1 for stellate + NONSPECIFIC_CURRENT i +} + +UNITS { + (nA) = (nanoamp) + (mV) = (millivolt) + (pS) = (picosiemens) + (umho) = (micromho) + (mM) = (milli/liter) + (uM) = (micro/liter) +} + +PARAMETER { + + Erev = -70 (mV) : reversal potential + gmax = 500 (pS) : maximal conductance + CellType = 1 (1) : define cell type parameters + +: Rates + +: Stellate cell fit (1/1/10; excellent fit) + +: kon = 0.0236 (/uM /ms) : binding +: koff = 2.4 (/ms) : unbinding +: a1 = 1.707 (/ms) : opening +: b1 = 8.95 (/ms) : closing +: a2 = 0.325 (/ms) : opening +: b2 = 5.871 (/ms) : closing +: r = 2.019 (/ms) : return from deep state +: d = 28.87 (/ms) : going to deep state + +:if psdtype == 'glyfast': fit from 3/5/2010. error = 0.174 maxopen = 0.0385 +: See synapses.py + a1 = 1.000476 (/ms) : opening + a2 = 0.137903 (/ms) : opening + b1 = 1.700306 (/ms) : closing + koff = 13.143132 (/ms) : unbinding + kon = 0.038634 (/ms) : binding + r = 0.842504 (/ms) : return from deep state + b2 = 8.051435 (/ms) : closing + d = 12.821820 (/ms) : going to deep state + +} + + +ASSIGNED { + v (mV) : postsynaptic voltage + i (nA) : current = g*(v - Erev) + g (pS) : conductance + XMTR (mM) : pointer to glycine concentration + + f1 (/ms) : binding + f2 (/ms) : binding + koff2 (/ms) + Open (1) +} + +STATE { + : Channel states (all fractions) + C0 : unbound + C1 : single bound + C2 : double bound + C3 : bound but closed state to O2 + O1 : open + O2 : open +} + +INITIAL { + + XMTR = 0.0 + C0 = 1 + C1 = 0 + C2 = 0 + C3 = 0 + O1 = 0 + O2 = 0 +} + +BREAKPOINT { + SOLVE kstates METHOD sparse +:VERBATIM +: if (CGly > 0.0) { +: fprintf(stderr, "t = %f Xmtr = %f\n", t, XMTR); +: } +: ENDVERBATIM + Open = (O1 + O2) + g = gmax * Open + i = (1e-6) * g * (v - Erev) +} + +KINETIC kstates { + + f1 = 2.0 * kon * (1e3) * XMTR + f2 = kon * (1e3) * XMTR + koff2 = 2.0 * koff + + ~ C0 <-> C1 (f1,koff) + ~ C1 <-> C2 (f2,koff2) + ~ C2 <-> O1 (a1,b1) + ~ C2 <-> C3 (d, r) + ~ C3 <-> O2 (a2,b2) + + CONSERVE C0+C1+C2+C3+O1+O2 = 1 +} diff --git a/cnmodel/mechanisms/Gly5State.mod b/cnmodel/mechanisms/Gly5State.mod new file mode 100755 index 0000000..3820cfc --- /dev/null +++ b/cnmodel/mechanisms/Gly5State.mod @@ -0,0 +1,147 @@ +TITLE detailed model of Glycine receptors + +COMMENT +----------------------------------------------------------------------------- + + Kinetic model of Glycine-A receptors + ==================================== + + + + C -- C1 -- C2 + | | + O1 O2 + +----------------------------------------------------------------------------- + + + This mod file does not include mechanisms for the release and time course + of transmitter; it is to be used in conjunction with a sepearate mechanism + to describe the release of transmitter and that provides the concentration + of transmitter in the synaptic cleft (to be connected to pointer C here). + +----------------------------------------------------------------------------- + + Based on models + + Destexhe, A., Mainen, Z.F. and Sejnowski, T.J. Kinetic models of + synaptic transmission. In: Methods in Neuronal Modeling (2nd edition; + edited by Koch, C. and Segev, I.), MIT press, Cambridge, 1998, pp. 1-25. + + (electronic copy available at http://cns.iaf.cnrs-gif.fr) + + Written by Alain Destexhe, Laval University, 1995 + +----------------------------------------------------------------------------- + + Modified Paul Manis, UNC Chapel Hill, 2009 + Changed name, pointer name, kinetics are range variables, and kinetic values + are estimated from VCN glycine receptors. + + This model does not have a desensitization state. + +----------------------------------------------------------------------------- + +ENDCOMMENT + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +NEURON { + POINT_PROCESS GLYa5 + POINTER XMTR + RANGE C0, C1, C2, O1, O2, Open + RANGE g, gmax, f1, f2 + RANGE Erev + RANGE kf1, kf2, kb1, kb2, a1, b1, a2, b2 + NONSPECIFIC_CURRENT i +} + +UNITS { + (nA) = (nanoamp) + (mV) = (millivolt) + (pS) = (picosiemens) + (umho) = (micromho) + (mM) = (milli/liter) + (uM) = (micro/liter) +} + +PARAMETER { + + Erev = -70 (mV) : reversal potential + gmax = 500 (pS) : maximal conductance + +: Rates + +: from fits to averaged ipsc data, stellate cells 1/1/10 + +: kf1 = 0.002930 (/uM /ms) : binding +: kf2 = 0.005936 (/uM /ms) : binding +: kb1 = 2.793 (/ms) : unbinding +: kb2 = 1.445 (/ms) : unbinding +: a1 = 1e-6 (/ms) : opening +: b1 = 129.0 (/ms) : closing +: a2 = 5.10 (/ms) : opening +: b2 = 2.79 (/ms) : closing + +: from fits to averaged ipsc data, bushy cells 1/1/10 + + kf1 = 0.0278 (/uM /ms) : binding + kf2 = 1e-6 (/uM /ms) : binding + kb1 = 0.000054 (/ms) : unbinding + kb2 = 0.000855 (/ms) : unbinding + a1 = 1e-6 (/ms) : opening + b1 = 129.0 (/ms) : closing + a2 = 5.10 (/ms) : opening + b2 = 2.79 (/ms) : closing + +} + + +ASSIGNED { + v (mV) : postsynaptic voltage + i (nA) : current = g*(v - Erev) + g (pS) : conductance + XMTR (mM) : pointer to glycine concentration + + f1 (/ms) : binding + f2 (/ms) : binding + Open (1) +} + +STATE { + : Channel states (all fractions) + C0 : unbound + C1 : single bound + C2 : double bound + O1 : open + O2 : open +} + +INITIAL { + C0 = 1 + C1 = 0 + C2 = 0 + O1 = 0 + O2 = 0 + XMTR = 0.0 +} + +BREAKPOINT { + SOLVE kstates METHOD sparse + Open = (O1 + O2) + g = gmax * Open + i = (1e-6) * g * (v - Erev) +} + +KINETIC kstates { + + f1 = kf1 * (1e3) * XMTR + f2 = kf2 * (1e3) * XMTR + + ~ C0 <-> C1 (f1,kb1) + ~ C1 <-> C2 (f2,kb2) + ~ C1 <-> O1 (a1,b1) + ~ C2 <-> O2 (a2,b2) + + CONSERVE C0+C1+C2+O1+O2 = 1 +} diff --git a/cnmodel/mechanisms/Gly6S.mod b/cnmodel/mechanisms/Gly6S.mod new file mode 100755 index 0000000..e796ee3 --- /dev/null +++ b/cnmodel/mechanisms/Gly6S.mod @@ -0,0 +1,131 @@ +TITLE Model of glycine receptors + +COMMENT +----------------------------------------------------------------------------- + + Kinetic model of glycine receptors + =============================== + + 6-state gating model with + 2 open states provide dual exponential response. + + O1 + | + C0 -- C1 -- C2 -- O2 + | + D1 + +----------------------------------------------------------------------------- + + This mod file does not include mechanisms for the release and time course + of transmitter; it is to be used in conjunction with a sepearate mechanism + to describe the release of transmitter and that provides the concentration + of transmitter in the synaptic cleft (to be connected to pointer C here). + + Default parameters are set for a miniature EPSC. + + +----------------------------------------------------------------------------- + +Paul B. Manis, Ph.D. 28 Dec 2009 + +----------------------------------------------------------------------------- +ENDCOMMENT + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +NEURON { + POINT_PROCESS Gly6S + POINTER XMTR + RANGE C0, C1, C2, D1, O1, O2, Open + RANGE Erev + RANGE Rb, Ru1, Ru2, Rd, Rr, Ro1, Rc1, Ro2, Rc2 + RANGE g, rb, gmax + RANGE CellType : 0 is bushy, 1 is stellate + NONSPECIFIC_CURRENT i +} + +UNITS { + (nA) = (nanoamp) + (mV) = (millivolt) + (pS) = (picosiemens) + (umho) = (micromho) + (mM) = (milli/liter) + (uM) = (micro/liter) +} + +PARAMETER { + + Erev = -70 (mV) : reversal potential + gmax = 500 (pS) : maximal conductance + CellType = 0 (1) : Cell type definition. +: Rates +: Bushy cell IPSCs: (rates can be changed externally) +: Set per Fits 8 March 2010 (see Synapses.py as well) + Rd = 1.177999 (/ms) : desensitization + Rr = 0.000005 (/ms) : resensitization + Rb = 0.009403 (/mM /ms): binding + : diffusion limited + Ru2 = 0.000086 (/ms) : unbinding (2nd site) + Ro1 = 0.187858 (/ms) : opening (fast) + Ro2 = 1.064426 (/ms) : opening (slow) + Ru1 = 0.028696 (/ms) : unbinding (1st site) + Rc1 = 0.103625 (/ms) : closing + Rc2 = 1.730578 (/ms) : closing + +} + +ASSIGNED { + v (mV) : postsynaptic voltage + i (nA) : current = g*(v - Erev) + g (pS) : conductance + XMTR (mM) : pointer to glutamate concentration + rbind (/ms) : binding + Open (1) +} + +STATE { + : Channel states (all fractions) + C0 : unbound + C1 : single gly bound + C2 : double gly bound + D1 : double gly bound, desensitized + O1 : double gly bound, open state 1 + O2 : double gly bound, open state 2 +} + +INITIAL { + + XMTR = 0 + C0 = 1 + C1 = 0 + C2 = 0 + D1 = 0 + O1 = 0 + O2 = 0 +} + +BREAKPOINT { + SOLVE kstates METHOD sparse +:VERBATIM +: if (XMTR > 0.1) { +: fprintf(stderr, "t = %f XMTR = %f\n", t, XMTR); +: } +: ENDVERBATIM + Open = (O1 + O2) + g = gmax * Open + i = (1e-6)*g*(v-Erev) +} + + +KINETIC kstates { + + rbind = Rb * (1e3) * XMTR + + ~ C0 <-> C1 (rbind,Ru1) + ~ C1 <-> C2 (rbind*2.0,Ru2) + ~ C2 <-> O1 (Ro1,Rc1) + ~ C2 <-> D1 (Rd,Rr) + ~ C2 <-> O2 (Ro2,Rc2) + CONSERVE C0+C1+C2+D1+O1+O2 = 1 +} diff --git a/cnmodel/mechanisms/Iclamp2.mod b/cnmodel/mechanisms/Iclamp2.mod new file mode 100644 index 0000000..74d15ff --- /dev/null +++ b/cnmodel/mechanisms/Iclamp2.mod @@ -0,0 +1,64 @@ +COMMENT + +Iclamp2.mod: Electrode current injection, revised for our own use +I specifically needed more step changes in a single waveform than +were provided by the default code. This routine gives us 5 levels: +holding, 3 steps, and a final (holding?) level. + +This version generates a pulse of duration at amplitude I for +onset times in the vector onset[STEP] and durations in dur[STEP] +Each pulse is independent and pulses _could_ overlap. + +Since this is an electrode current, positive values of I depolarize the cell +and in the presence of the extracellular mechanism there will be a change +in vext since I is not a transmembrane current but a current injected +directly to the inside of the cell. + +(modified and borrowed extensively from other Neuron code, +2001-2002. Paul B. Manis) + +ENDCOMMENT + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +DEFINE NSTEP 5 : maximum number of steps supported in this mechanism + +NEURON { + POINT_PROCESS IClamp2 + RANGE onset, dur, amp, i + ELECTRODE_CURRENT i +} +UNITS { + (nA) = (nanoamp) +} +PARAMETER { +} + +ASSIGNED { + i (nA) + index + onset[NSTEP] (ms) + dur[NSTEP] (ms) + amp[NSTEP] (nA) + pu +} + +INITIAL { + i = 0 (nA) + index = 0 + pu = 0 +} +: +: at each onset time, a pulse of duration dur is generated. +: + +BREAKPOINT { + i = 0 + FROM index = 0 TO NSTEP-1 { + if(t > onset[index]) { + if(t < (dur[index]+onset[index])) { + i = i + amp[index] : allows overlap + } : end of if condition + } :end of second if condition + } : end of "FROM" (for) loop +} : end of breakpoint diff --git a/cnmodel/mechanisms/NMDA.mod b/cnmodel/mechanisms/NMDA.mod new file mode 100644 index 0000000..54cb110 --- /dev/null +++ b/cnmodel/mechanisms/NMDA.mod @@ -0,0 +1,142 @@ +TITLE NMDA receptor--one of the two input stimulation of our model + +: This mechanism is taken from the Neuron data base "exp2syn.mod" +: The original comment are below between "COMMENT" and "ENDCOMMENT". +: +: Our modifications: +: +: 1.We added a single receptor conductance factor: "g_max=0.000045 (uS)". +: An event of weight 1 generates a peak conductance of 1*g_max. +: The weight is equal to the number of ampa receptors open at peak conductance +: +: 2.The NMDA receptors are simulated using a slow rise time constant +: and a double-expontial decay time constant + +: The kinetic rate constants and channel conductance are taken from Franks KM, Bartol TM and Sejnowski TJ +: A Monte Carlo model reveals independent signaling at central glutamatergic synapses +: J Biophys (2002) 83(5):2333-48 +: and Spruston N, Jonas P and Sakmann B +: Dendritic glutamate receptor channels in rat hippocampal CA3 and CA1 neurons +: J Physiol (1995) 482(2): 325-352 +: correctd for physiological tempterature with Q10 from Hestrin S, Sah P and Nicoll RA +: Mechanisms generating the time course of dual component excitatory synaptic currents +: recorded in hippocampal slices +: Neuron (1990) 5: 247-253 +: +: Written by Lei Tian on 04/12/06 + + + +COMMENT +Two state kinetic scheme synapse described by rise time tau1, +and decay time constant tau2. The normalized peak condunductance is 1. +Decay time MUST be greater than rise time. + +The solution of A->G->bath with rate constants 1/tau1 and 1/tau2 is + A = a*exp(-t/tau1) and + G = a*tau2/(tau2-tau1)*(-exp(-t/tau1) + exp(-t/tau2)) + where tau1 < tau2 + +If tau2-tau1 -> 0 then we have a alphasynapse. +and if tau1 -> 0 then we have just single exponential decay. + +The factor is evaluated in the +initial block such that an event of weight 1 generates a +peak conductance of 1. + +Because the solution is a sum of exponentials, the +coupled equations can be solved as a pair of independent equations +by the more efficient cnexp method. + +ENDCOMMENT + + +NEURON { +THREADSAFE + POINT_PROCESS nmda + RANGE tau1, tau2, tau3, e, i, g_max, g, A, B, C ,k + NONSPECIFIC_CURRENT i + GLOBAL total,i2,g2 +: EXTERNAL Area_canmda +} + +UNITS { + (nA) = (nanoamp) + (mA) = (milliamp) + (mV) = (millivolt) + (uS) = (microsiemens) +} + +PARAMETER { + tau1 = 3.18 (ms) <1e-9,1e9> :rise time constant + tau2 = 57.14 (ms) <1e-9,1e9> :decay time constant + tau3 = 2000 (ms) <1e-9,1e9> :decay time constant + + g_max= 0.000045 (uS) : single channel conductance + e = 0 (mV) + mg = 1 (mM) + + Area (cm2) + k = 1e-06 (mA/nA) + Area_canmda = 1 +} + +ASSIGNED { + v (mV) + i (nA) + factor + total (uS) + g (uS) + + g2 (uS) : plot 'g' and 'i' in "nmda.mod". + i2 (mA/cm2) : global variables read in "canmda.mod" as 'inmda' and 'gnmda' to give us +} + +STATE { + A (uS) + B (uS) + C (uS) +} + +INITIAL { + LOCAL t_peak + total = 0 + if (tau1/tau2 > .9999) { + tau1 = .9999*tau2 + } + A = 0 + B = 0 + C = 0 + + factor=0.8279 :from matlab to make the peak of the conductance curve shape to be 1*weight (then multiply with g_max) + factor = 1/factor + + Area = Area_canmda +} + +BREAKPOINT { + SOLVE state METHOD cnexp + + g = g_max*(B*0.8+C*0.2-A) + i = g*(v - e)*1/(1+(exp(0.08(/mV) * -v)*(mg / 0.69))) + + g2=g :global variable can be read in 'canmda.mod' + i2=i*k/Area :to get a current in 'mA/cm2' and send it to 'canmda.mod' +} + +DERIVATIVE state { + A' = -A/tau1 + B' = -B/tau2 + C' = -C/tau3 +} + +NET_RECEIVE(weight (uS)) { + state_discontinuity(A, weight*factor) + state_discontinuity(B, weight*factor) + state_discontinuity(C, weight*factor) + total = total+weight + +} + + + diff --git a/cnmodel/mechanisms/NMDA_Kampa.mod b/cnmodel/mechanisms/NMDA_Kampa.mod new file mode 100644 index 0000000..cfd4526 --- /dev/null +++ b/cnmodel/mechanisms/NMDA_Kampa.mod @@ -0,0 +1,212 @@ +TITLE kinetic NMDA receptor model + +COMMENT +----------------------------------------------------------------------------- + + Kinetic model of NMDA receptors + =============================== + + 10-state gating model: + Kampa et al. (2004) J Physiol + + U -- Cl -- O + \ | \ \ + \ | \ \ + UMg -- ClMg - OMg + | | + D1 | + | \ | + D2 \ | + \ D1Mg + \ | + D2Mg +----------------------------------------------------------------------------- + + Based on voltage-clamp recordings of NMDA receptor-mediated currents in + nucleated patches of rat neocortical layer 5 pyramidal neurons (Kampa 2004), + this model was fit with AxoGraph directly to experimental recordings in + order to obtain the optimal values for the parameters. + +----------------------------------------------------------------------------- + + This mod file does not include mechanisms for the release and time course + of transmitter; it should to be used in conjunction with a separate mechanism + to describe the release of transmitter and timecourse of the concentration + of transmitter in the synaptic cleft (to be connected to pointer XMTR here). + +----------------------------------------------------------------------------- + + See details of NEURON kinetic models in: + + Destexhe, A., Mainen, Z.F. and Sejnowski, T.J. Kinetic models of + synaptic transmission. In: Methods in Neuronal Modeling (2nd edition; + edited by Koch, C. and Segev, I.), MIT press, Cambridge, 1996. + + + Written by Bjoern Kampa in 2004 + Lightly modified, Paul Manis 2010. + Note that data were taken at 23 deg C + Q10 was taken from native receptors: + Korinek M, Sedlacek M, Cais O, Dittert I, Vyklicky L Jr. Temperature +dependence of N-methyl-D-aspartate receptor channels and N-methyl-D-aspartate +receptor excitatory postsynaptic currents. Neuroscience. 2010 Feb +3;165(3):736-48. Epub 2009 Oct 31. PubMed PMID: 19883737. + +----------------------------------------------------------------------------- +ENDCOMMENT + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +NEURON { +THREADSAFE + + POINT_PROCESS NMDA_Kampa + POINTER XMTR + RANGE U, Cl, D1, D2, Open, MaxOpen, UMg, ClMg, D1Mg, D2Mg, OMg + RANGE g, gmax, vshift, Erev, rb, rmb, rmu, rbMg,rmc1b,rmc1u,rmc2b,rmc2u + GLOBAL mg, Rb, Ru, Rd1, Rr1, Rd2, Rr2, Ro, Rc, Rmb, Rmu + GLOBAL RbMg, RuMg, Rd1Mg, Rr1Mg, Rd2Mg, Rr2Mg, RoMg, RcMg + GLOBAL Rmd1b,Rmd1u,Rmd2b,Rmd2u,rmd1b,rmd1u,rmd2b,rmd2u + GLOBAL Rmc1b,Rmc1u,Rmc2b,Rmc2u + GLOBAL vmin, vmax, valence, memb_fraction + NONSPECIFIC_CURRENT i +} + +UNITS { + (nA) = (nanoamp) + (mV) = (millivolt) + (pS) = (picosiemens) + (umho) = (micromho) + (mM) = (milli/liter) + (uM) = (micro/liter) +} + +PARAMETER { + + Erev = 5 (mV) : reversal potential + gmax = 500 (pS) : maximal conductance + mg = 1 (mM) : external magnesium concentration + vmin = -120 (mV) + vmax = 100 (mV) + valence = -2 : parameters of voltage-dependent Mg block + memb_fraction = 0.8 + vshift = 0.0 (mV) + Q10 = 2.0 : temperature sensitivity (see above) + + : Maximum open probability with Mode=0 (no rectification). + : This is determined empirically by holding XMTR at a large + : value and v=40mV for 100 timesteps and measuring the + : maximum value of Open. + MaxOpen = 0.01988893957 (1) + +: Rates + + Rb = 10e-3 (/uM /ms) : binding + Ru = 5.6e-3 (/ms) : unbinding + Ro = 10e-3 (/ms) : opening + Rc = 273e-3 (/ms) : closing +: Rd1 = 2.2e-3 (/ms) : fast desensitisation + Rd1 = 0.1 (/ms) : fast desensitisation + Rr1 = 1.6e-3 (/ms) : fast resensitisation +: Rd2 = 0.43e-3 (/ms) : slow desensitisation + Rd2 = 1e-4 (/ms) : slow desensitisation + Rr2 = 0.5e-3 (/ms) : slow resensitisation + Rmb = 0.05e-3 (/uM /ms) : Mg binding Open + Rmu = 12800e-3 (/ms) : Mg unbinding Open + Rmc1b = 0.00005e-3 (/uM /ms) : Mg binding Closed + Rmc1u = 2.438312e-3 (/ms) : Mg unbinding Closed + Rmc2b = 0.00005e-3 (/uM /ms) : Mg binding Closed2 + Rmc2u = 5.041915e-3 (/ms) : Mg unbinding Closed2 + Rmd1b = 0.00005e-3 (/uM /ms) : Mg binding Desens1 + Rmd1u = 2.98874e-3 (/ms) : Mg unbinding Desens1 + Rmd2b = 0.00005e-3 (/uM /ms) : Mg binding Desens2 + Rmd2u = 2.953408e-3 (/ms) : Mg unbinding Desens2 + RbMg = 10e-3 (/uM /ms) : binding with Mg + RuMg = 17.1e-3 (/ms) : unbinding with Mg + RoMg = 10e-3 (/ms) : opening with Mg + RcMg = 548e-3 (/ms) : closing with Mg + Rd1Mg = 2.1e-3 (/ms) : fast desensitisation with Mg + Rr1Mg = 0.87e-3 (/ms) : fast resensitisation with Mg + Rd2Mg = 0.26e-3 (/ms) : slow desensitisation with Mg + Rr2Mg = 0.42e-3 (/ms) : slow resensitisation with Mg +} + +ASSIGNED { + v (mV) : postsynaptic voltage + i (nA) : current = g*(v - Erev) + g (pS) : conductance + XMTR (mM) : pointer to glutamate concentration + + rb (/ms) : binding, [glu] dependent + rmb (/ms) : blocking V and [Mg] dependent + rmu (/ms) : unblocking V and [Mg] dependent + rbMg (/ms) : binding, [glu] dependent + rmc1b (/ms) : blocking V and [Mg] dependent + rmc1u (/ms) : unblocking V and [Mg] dependent + rmc2b (/ms) : blocking V and [Mg] dependent + rmc2u (/ms) : unblocking V and [Mg] dependent + rmd1b (/ms) : blocking V and [Mg] dependent + rmd1u (/ms) : unblocking V and [Mg] dependent + rmd2b (/ms) : blocking V and [Mg] dependent + rmd2u (/ms) : unblocking V and [Mg] dependent + + qfac : Q10 + celsius (degC) +} + +STATE { + : Channel states (all fractions) + U : unbound + Cl : closed + D1 : desensitised 1 + D2 : desensitised 2 + Open : open + UMg : unbound with Mg + ClMg : closed with Mg + D1Mg : desensitised 1 with Mg + D2Mg : desensitised 2 with Mg + OMg : open with Mg +} + +INITIAL { + U = 1 + qfac = Q10^((celsius-23)/10 (degC))} + +BREAKPOINT { + SOLVE kstates METHOD sparse + + g = gmax * Open / MaxOpen + i = (1e-6) * g * (v - Erev) +} + +KINETIC kstates { + + rb = Rb * (1e3) * XMTR + rbMg = RbMg * (1e3) * XMTR + rmb = Rmb * mg * (1e3) * exp((v-40+vshift) * valence * memb_fraction /25 (mV)) + rmu = Rmu * exp((-1)*(v-40+vshift) * valence * (1-memb_fraction) /25 (mV)) + rmc1b = Rmc1b * mg * (1e3) * exp((v-40+vshift) * valence * memb_fraction /25 (mV)) + rmc1u = Rmc1u * exp((-1)*(v-40+vshift) * valence * (1-memb_fraction) /25 (mV)) + rmc2b = Rmc2b * mg * (1e3) * exp((v-40+vshift) * valence * memb_fraction /25 (mV)) + rmc2u = Rmc2u * exp((-1)*(v-40+vshift) * valence * (1-memb_fraction) /25 (mV)) + rmd1b = Rmd1b * mg * (1e3) * exp((v-40+vshift) * valence * memb_fraction /25 (mV)) + rmd1u = Rmd1u * exp((-1)*(v-40+vshift) * valence * (1-memb_fraction) /25 (mV)) + rmd2b = Rmd2b * mg * (1e3) * exp((v-40+vshift) * valence * memb_fraction /25 (mV)) + rmd2u = Rmd2u * exp((-1)*(v-40+vshift) * valence * (1-memb_fraction) /25 (mV)) + + ~ U <-> Cl (rb*qfac,Ru*qfac) + ~ Cl <-> Open (Ro*qfac,Rc*qfac) + ~ Cl <-> D1 (Rd1*qfac,Rr1*qfac) + ~ D1 <-> D2 (Rd2*qfac,Rr2*qfac) + ~ Open <-> OMg (rmb*qfac,rmu*qfac) + ~ UMg <-> ClMg (rbMg*qfac,RuMg*qfac) + ~ ClMg <-> OMg (RoMg*qfac,RcMg*qfac) + ~ ClMg <-> D1Mg (Rd1Mg*qfac,Rr1Mg*qfac) + ~ D1Mg <-> D2Mg (Rd2Mg*qfac,Rr2Mg*qfac) + ~ U <-> UMg (rmc1b*qfac,rmc1u*qfac) + ~ Cl <-> ClMg (rmc2b*qfac,rmc2u*qfac) + ~ D1 <-> D1Mg (rmd1b*qfac,rmd1u*qfac) + ~ D2 <-> D2Mg (rmd2b*qfac,rmd2u*qfac) + + CONSERVE U+Cl+D1+D2+Open+UMg+ClMg+D1Mg+D2Mg+OMg = 1 +} diff --git a/cnmodel/mechanisms/adex.mod b/cnmodel/mechanisms/adex.mod new file mode 100644 index 0000000..3b505fa --- /dev/null +++ b/cnmodel/mechanisms/adex.mod @@ -0,0 +1,125 @@ +: AdEx GIF model + +: This implementation is for the equations in: +: Naud R, Marcille N, Clopath C, Gerstner W. Firing patterns in the adaptive +: exponential integrate-and-fire model. Biol Cybern. 2008 Nov;99(4-5):335-47. doi: +: 10.1007/s00422-008-0264-7. Epub 2008 Nov 15. PubMed PMID: 19011922; PubMed +: Central PMCID: PMC2798047. + +: Which in turn is based on: +: Brette R, Gerstner W. Adaptive exponential integrate-and-fire model as an +: effective description of neuronal activity. J Neurophysiol. 2005 +: Nov;94(5):3637-42. Epub 2005 Jul 13. PubMed PMID: 16014787. +: +: Paul B. Manis +: 9 Nov 2017, Washington DC +: + + +NEURON { +: ARTIFICIAL_CELL AdEx + SUFFIX AdEx + RANGE gl, el, delt, vt, vr, w, b, cm, is, a, tauw + RANGE refract, Vm + NONSPECIFIC_CURRENT i + : m plays the role of voltage +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + cm = 200 (pF) + el = -70 (mV) : leak (RMP) + gl = 10 (nS) : resting input R + delt = 2 (mV) : spike threshold sharpness + vt = -50 (mV) + vr = -58 (mV): reset value after a spike + a = 2 (nS) + b = 0 (pA) + is = 0 (pA) + tauw = 30 (ms) + refract = 1 (ms) +} + +ASSIGNED { + i (mA/cm2) + t0(ms) : time of last spike + refractory : flag indicating when in a refractory period +} + +STATE { + w + Vm +} + +INITIAL { + Vm = el + t0 = t + w = 0 + + refractory = 0 : 0-integrates input, 1-refractory +} + +BREAKPOINT { + SOLVE states METHOD cnexp + + if (refractory == 0 && Vm <= 0.) { + states() + } + if (refractory == 1) { + if ((t-t0) >= refract){ + refractory = 0 + Vm = vr + states() + } + else { + Vm = 0. + } + } + if (refractory == 0 && Vm > 0.) { + refractory = 1 + t0 = t + Vm = 0. + w = w + b + } +} + + +DERIVATIVE states { : update adaptation variable w + LOCAL eterm, et + w' = (a*(Vm - el) - w)/tauw + eterm = (Vm-vt)/delt + if (eterm > 700 ) { : prevent overflow of the exponential term + : (it would be better to estimate the value... but for this + : implementation, not necessary as this will be the term + : that drives the model to spike - after that V is reset + : so the time evolution no longer matters) + et = 700. + } + else { + et = exp(eterm) + } + Vm' = ( -gl*(Vm-el) + gl*delt*et + is - w)/cm +} + + +COMMENT +NET_RECEIVE (w) { + if (refractory == 0) { : inputs integrated only when excitable + i = -gl*(v-el) + gl*delt*exp((Vm-vt)/delt) - w + m = i/cm + t0 = t + states() + if (m > 0) { + refractory = 1 + m = 0 + net_send(refractory, refractory) + net_event(t) + } + } else if (flag == 1) { : ready to integrate again + t0 = t + refractory = 0 + m = vr + } +} +ENDCOMMENT \ No newline at end of file diff --git a/cnmodel/mechanisms/ampa_trussell.mod b/cnmodel/mechanisms/ampa_trussell.mod new file mode 100644 index 0000000..206dc34 --- /dev/null +++ b/cnmodel/mechanisms/ampa_trussell.mod @@ -0,0 +1,224 @@ +TITLE Model of AMPA receptors + +COMMENT +----------------------------------------------------------------------------- + + Kinetic model of AMPA receptors + =============================== + + 6-state gating model: + (scheme 1 from Raman and Trussell, Neuron 9:173-186, 1992) + 2 open states provide dual exponential response. + + O1 + | + C -- C1 -- C2 -- O2 + | + D + +----------------------------------------------------------------------------- + + This mod file does not include mechanisms for the release and time course + of transmitter; it is to be used in conjunction with a separate mechanism + to describe the release of transmitter and that provides the concentration + of transmitter in the synaptic cleft (to be connected to pointer C here). + + Default parameters are set for a miniature EPSC. + +----------------------------------------------------------------------------- + Code based on Destexhe's ampa5.mod + + B. Graham, Dept. of Computing Science & Maths, University of Stirling + (Contact: b.graham@cs.stir.ac.uk) + (previously IANC, Division of Informatics, University of Edinburgh) + + CNS 2000 Version (19/11/02) + +----------------------------------------------------------------------------- + + Further modified: + + Paul Manis (Otolaryngology/HNS and Cell and Molecular Physiology, + UNC Chapel Hill. contact: pmanis@med.unc.edu) + + 3/15/2005 Modifications: + + 1. Added Q10/qfac to allow temperature scaling. All rates in the state model + are changed by the same factor. A Q10 of 1.5 gives a decay tau (single + exponential fit using Praxis algorithm in NEURON; using ampa_kinetics.hoc) + of about 850 usec at 22 deg C and 570 usec at 33 deg C. These are consistent + with the Raman and Trussell 1992 measurements in avians. The 850 usec is a + bit fast for an EPSC, and could probably be tuned by adjustment of some of + the parameters below. + + 2. Brought several variables out to global (rather than range) so that we + can change them - Q10 and gmax in particular. note that gmax is in pS. Only + local conductance etc. is in specified as RANGE. + + 3. Max open probability is less than unity, so a gmax of 2500 yields 100 pA + at -60 mV. Therefore scaling by mini size must take this into account. + + 3/28/2005 Paul B. Manis + Added rectification to AMPA R. Rectification is controlled by + polyamine-style block of receptor. See Donevan and Rogawski, 1995; Washburn + et al., 1997. The equations used here are from Washburn et al. The values + given in the equation at the break point were determined from EPSCs in 5 + 21-d old DBA mice. Blocker = 45 (uM), Kd = 31.32, zd = 1.029. Note that this + should also reduce the maximal conductance. Mode: if 1, use rectifying; if + 0, use non-rectifying. Default is 1 + + This point process uses XMTR as the transmitter concentration to operate on + the receptor kinetics. XMTR should be provided by another process that + controls release (e.g., COH calyx of Held, etc). An advantage of this is + that whatever release process is present, glutamate accumulates in the + cleft, and can drive desensitization etc. + +----------------------------------------------------------------------------- +ENDCOMMENT + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +NEURON { +THREADSAFE + POINT_PROCESS AMPATRUSSELL + POINTER XMTR + RANGE C0, C1, C2, D, O1, O2 + + RANGE Rb, Ru1, Ru2, Rd, Rr, Ro1, Rc1, Ro2, Rc2, Open, MaxOpen + GLOBAL vmin, vmax + GLOBAL Q10, Mode + GLOBAL zd, Kd0 + RANGE g, rb, gmax, PA, Erev + NONSPECIFIC_CURRENT i +} + +UNITS { + (nA) = (nanoamp) + (mV) = (millivolt) + (pS) = (picosiemens) + (umho) = (micromho) + (mM) = (milli/liter) + (uM) = (micro/liter) +} + +PARAMETER { + + Erev = 7 (mV) : reversal potential + gmax = 10 (pS) : maximal conductance + vmin = -120 (mV) + vmax = 100 (mV) + Q10 = 1.5 : temperature sensitivity + Mode = 0 : flag to control rectification calculation + +: polyamine block parameters (Wang & Manis unpublished data) + zd = 1.032 + PA = 45 + Kd0 = 31.e-6 + +: Rates + + Rb = 13 (/mM /ms): binding + : diffusion limited (DO NOT ADJUST) + Ru1 = 0.3 (/ms) : unbinding (1st site) + Ru2 = 200 (/ms) : unbinding (2nd site) + Rd = 30.0 (/ms) : desensitization (WAS30.0) + Rr = 0.02 (/ms) : resensitization + Ro1 = 100 (/ms) : opening (fast) + Rc1 = 2 (/ms) : closing + Ro2 = 2 (/ms) : opening (slow) + Rc2 = 0.25 (/ms) : closing + + Open = 0 (1) : total of all open states + + : Maximum open probability with Mode=0 (no rectification). + : This is determined empirically by holding XMTR at a large + : value for 100 timesteps and measuring the maximum value + : of Open. + MaxOpen = 0.72418772400 (1) + + aflag = 1 : Flag for control of printout of initial values..... + +} + +ASSIGNED { + v (mV) : postsynaptic voltage + i (nA) : current = g*(v - Erev) + g (pS) : conductance + g0 (pS) : conductance for voltage-dependent block by polyamines + gvdep (pS) : voltage-dependence of conductance + XMTR (mM) : pointer to glutamate concentration + rb (/ms) : binding + qfac : q10 factor for rate scaling + celsius (degC) + +} + +STATE { + : Channel states (all fractions) + C0 : unbound + C1 : single glu bound + C2 : double glu bound + D : single glu bound, desensitized + O1 : open state 1 + O2 : open state 2 +} + +INITIAL { + usetable = 0 + C0=1 + C1=0 + C2=0 + D=0 + O1=0 + O2=0 + Open = 0 + qfac = Q10^((celsius-22)/10) +: VERBATIM +: fprintf(stdout, "AMPA.MOD gmax: %f Q10 = %f celsius = %f\n", gmax, Q10, celsius); +: ENDVERBATIM + gvdepcalc(v) +} + +BREAKPOINT { + SOLVE kstates METHOD sparse + : VERBATIM + : fprintf(stderr, "kstates @ t=%7.2f Rb: %f XMTR: %f: gmax: %f, o1: %f o2: %f\n", t, Rb, XMTR, gmax, O1, O2); + : ENDVERBATIM + + gvdepcalc(v) + Open = O1 + O2 + g = gmax * Open / MaxOpen + if ( Mode == 1) { + g0 = 1.0 + 0.6*exp((v-50)/40) : eq. 5 of Washburn et al., 1997, slightly modified + gvdep = g0*(1/(1+PA/(Kd0*exp(-zd*v/25.3)))) + i = (1e-6) * g * gvdep * (v - Erev) + } + else { + i = (1e-6)*g*(v-Erev) + } +} + +KINETIC kstates { + + rb = Rb * XMTR + + ~ C0 <-> C1 (rb*qfac,Ru1*qfac) + ~ C1 <-> C2 (rb*qfac,Ru2*qfac) + ~ C2 <-> D (Rd*qfac,Rr*qfac) + ~ C2 <-> O1 (Ro1*qfac,Rc1*qfac) + ~ C2 <-> O2 (Ro2*qfac,Rc2*qfac) + CONSERVE C0+C1+C2+D+O1+O2 = 1 +} + +LOCAL g0 +PROCEDURE gvdepcalc(v) { + TABLE gvdep DEPEND PA, Kd0, zd FROM -100 TO 100 WITH 200 + : VERBATIM + : fprintf(stderr, "gvdepcalc starts "); + : ENDVERBATIM + g0 = 1.0 + 0.6*exp((v-50)/40) : eq. 5 of Washburn et al., 1997, slightly modified + gvdep = g0*(1/(1+PA/(Kd0*exp(-zd*v/25.3)))) + : VERBATIM + : fprintf(stderr, "& ends\n"); + : ENDVERBATIM +} diff --git a/cnmodel/mechanisms/atm.mod b/cnmodel/mechanisms/atm.mod new file mode 100644 index 0000000..1a7bbe8 --- /dev/null +++ b/cnmodel/mechanisms/atm.mod @@ -0,0 +1,129 @@ +: ATM GIF model + +: This implementation the adaptive theshold model (ATM) is for the equations in: +: Fontaine, B., Benichourx, V., Joris, P.X., and Brette, R. Prediciting +: spike timing in hhigy synchronous auditory neurons at different sound +: levels. J. Neurophysiol. 110: 1672-1688, 2013. + +: Which in turn is based on: +: Brette R, Gerstner W. Adaptive exponential integrate-and-fire model as an +: effective description of neuronal activity. J Neurophysiol. 2005 +: Nov;94(5):3637-42. Epub 2005 Jul 13. PubMed PMID: 16014787. +: +: Paul B. Manis +: 2 December 2017, Chapel Hill, NC +: +: Incomplete version + +NEURON { +: ARTIFICIAL_CELL ATM + SUFFIX ATM + RANGE gl, el, delt, vt, vr, alpha, beta, cm, is, a, tauw + RANGE refract, Vm + NONSPECIFIC_CURRENT i + : m plays the role of voltage +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + cm = 200 (pF) + el = -70 (mV) : leak (RMP) + gl = 10 (nS) : resting input R + delt = 2 (mV) : spike threshold sharpness + vr = -58 (mV): reset value after a spike + a = 2 (1) + b = 2 (1) + beta = 0 (1) + alpha = 0 + is = 0 (pA) + taut = 30 (ms) : threshold tau + refract = 1 (ms) +} + +ASSIGNED { + i (mA/cm2) + t0 (ms) : time of last spike + refractory : flag indicating when in a refractory period +} + +STATE { + w + Vm + vt +} + +INITIAL { + Vm = el + t0 = t + a = 0 + b = 0 + + refractory = 0 : 0-integrates input, 1-refractory +} + +BREAKPOINT { + SOLVE states METHOD cnexp + + if (refractory == 0 && Vm <= 0.) { + states() + } + if (refractory == 1) { + if ((t-t0) >= refract){ + refractory = 0 + Vm = vr + states() + } + else { + Vm = 0. + } + } + if (refractory == 0 && Vm > 0.) { + refractory = 1 + t0 = t + Vm = 0. + w = w + b + } +} + + +DERIVATIVE states { : update adaptation variable w + LOCAL eterm, et + vt' = (a*i - vt)/taut +COMMENT + eterm = (Vm-vt)/delt + if (eterm > 700 ) { : prevent overflow of the exponential term + : (it would be better to estimate the value... but for this + : implementation, not necessary as this will be the term + : that drives the model to spike - after that V is reset + : so the time evolution no longer matters) + et = 700. + } + else { + et = exp(eterm) + } +ENDCOMMENT + Vm' = gl*( -(Vm-el) + i)/cm +} + + +COMMENT +NET_RECEIVE (w) { + if (refractory == 0) { : inputs integrated only when excitable + i = -gl*(v-el) + gl*delt*exp((Vm-vt)/delt) - w + m = i/cm + t0 = t + states() + if (m > 0) { + refractory = 1 + m = 0 + net_send(refractory, refractory) + net_event(t) + } + } else if (flag == 1) { : ready to integrate again + t0 = t + refractory = 0 + m = vr + } +} +ENDCOMMENT \ No newline at end of file diff --git a/cnmodel/mechanisms/bkpkj.mod b/cnmodel/mechanisms/bkpkj.mod new file mode 100644 index 0000000..bccab47 --- /dev/null +++ b/cnmodel/mechanisms/bkpkj.mod @@ -0,0 +1,98 @@ +: BK-type Purkinje calcium-activated potassium current +: Created 8/19/02 - nwg + +NEURON { + THREADSAFE + SUFFIX bkpkj + USEION k READ ek WRITE ik + USEION ca READ cai + RANGE gbar, ik, gbkpkj + GLOBAL minf, mtau, hinf, htau, zinf, ztau + GLOBAL m_vh, m_k, mtau_y0, mtau_vh1, mtau_vh2, mtau_k1, mtau_k2 + GLOBAL z_coef, ztau + GLOBAL h_y0, h_vh, h_k, htau_y0, htau_vh1, htau_vh2, htau_k1, htau_k2 +} + +UNITS { + (mV) = (millivolt) + (mA) = (milliamp) + (mM) = (milli/liter) +} + +PARAMETER { + v (mV) + gbar = 0.007 (mho/cm2) + + m1 (ms) + m_vh = -28.9 (mV) + m_k = 6.2 (mV) + mtau_y0 = 0.505 (ms) : 0.000505 (s) + mtau_vh1 = -33.3 (mV) + mtau_k1 = -10 (mV) + mtau_vh2 = 86.4 (mV) + mtau_k2 = 10.1 (mV) + + z_coef = 0.001 (mM) + ztau = 1 (ms) + + h_y0 = 0.085 + h_vh = -32 (mV) + h_k = 5.8 (mV) + htau_y0 = 1.9 (ms) : 0.0019 (s) + htau_vh1 = -54.2 (mV) + htau_k1 = -12.9 (mV) + htau_vh2 = 48.5 (mV) + htau_k2 = 5.2 (mV) + + ek (mV) + cai (mM) +} + +ASSIGNED { + gbkpkj (mho/cm2) + minf + mtau (ms) + hinf + htau (ms) + zinf + + ik (mA/cm2) +} + +STATE { + m FROM 0 TO 1 + z FROM 0 TO 1 + h FROM 0 TO 1 +} + +BREAKPOINT { + SOLVE states METHOD cnexp + gbkpkj = gbar * m * m * m * z * z * h + ik = gbkpkj * (v - ek) +} + +DERIVATIVE states { + rates(v) + + m' = (minf - m) / mtau + h' = (hinf - h) / htau + z' = (zinf - z) / ztau +} + +PROCEDURE rates(Vm (mV)) { + LOCAL v + v = Vm + 5 + minf = 1 / (1 + exp(-(v - (m_vh)) / m_k)) + m1 = mtau_y0 + (1. (ms)/(exp((v+ mtau_vh1)/mtau_k1))) + mtau = m1 + (1. (ms)) * exp((v+mtau_vh2)/mtau_k2) + zinf = 1/(1 + z_coef / cai) + hinf = h_y0 + (1-h_y0) / (1+exp((v - h_vh)/h_k)) + htau = (htau_y0 + (1 (ms))/(exp((v + htau_vh1)/htau_k1)+exp((v+htau_vh2)/htau_k2))) +} + +INITIAL { + rates(v) + m = minf + z = zinf + h = hinf +} diff --git a/cnmodel/mechanisms/cabpump.mod b/cnmodel/mechanisms/cabpump.mod new file mode 100644 index 0000000..e18c0c7 --- /dev/null +++ b/cnmodel/mechanisms/cabpump.mod @@ -0,0 +1,157 @@ +TITLE Calcium ion accumulation and diffusion with pump +: The internal coordinate system is set up in PROCEDURE coord_cadifus() +: and must be executed before computing the concentrations. +: The scale factors set up in this procedure do not have to be recomputed +: when diam or DFree are changed. +: The amount of calcium in an annulus is ca[i]*diam^2*vol[i] with +: ca[0] being the second order correct concentration at the exact edge +: and ca[NANN-1] being the concentration at the exact center + +? interface +NEURON { +THREADSAFE + SUFFIX cadifpmp + USEION ca READ cao, ica WRITE cai, ica + RANGE ica_pmp, last_ica_pmp, k1, k2, k3, k4, DFree + GLOBAL vol, pump0 +} + +DEFINE NANN 10 + +UNITS { + (mV) = (millivolt) + (molar) = (1/liter) + (mM) = (millimolar) + (um) = (micron) + (mA) = (milliamp) + (mol) = (1) + FARADAY = (faraday) (coulomb) + PI = (pi) (1) + R = (k-mole) (joule/degC) +} + +PARAMETER { + DFree = 0.6 (um2/ms) <0,1e9> + beta = 50 <0, 1e9> + + k1 = 5e8 (/mM-s) <0, 1e10>:optional mm formulation + k2 = .25e6 (/s) <0, 1e10> + k3 = .5e3 (/s) <0, 1e10> + k4 = 5e0 (/mM-s) <0, 1e10> + pump0 = 3e-14 (mol/cm2) <0, 1e9> : set to 0 in hoc if this pump not wanted +} + +ASSIGNED { + celsius (degC) + diam (um) + v (millivolt) + cao (mM) + cai (mM) + ica (mA/cm2) + vol[NANN] (1) : gets extra cm2 when multiplied by diam^2 + ica_pmp (mA/cm2) + area1 (um2) + c1 (1+8 um5/ms) + c2 (1-10 um2/ms) + c3 (1-10 um2/ms) + c4 (1+8 um5/ms) + ica_pmp_last (mA/cm2) +} + +CONSTANT { + volo = 1 (liter) +} + +STATE { + ca[NANN] (mM) <1e-6> : ca[0] is equivalent to cai + pump (mol/cm2) <1e-15> + pumpca (mol/cm2) <1e-15> +} + +INITIAL {LOCAL total + parms() + FROM i=0 TO NANN-1 { + ca[i] = cai + } + pumpca = cai*pump*c1/c2 + total = pumpca + pump + if (total > 1e-9) { + pump = pump*(pump/total) + pumpca = pumpca*(pump/total) + } + ica_pmp = 0 + ica_pmp_last = 0 +} + +BREAKPOINT { + SOLVE state METHOD sparse + ica_pmp_last = ica_pmp + ica = ica_pmp +: printf("Breakpoint t=%g v=%g cai=%g ica=%g\n", t, v, cai, ica) +} + +LOCAL frat[NANN] : gets extra cm when multiplied by diam + +PROCEDURE coord() { + LOCAL r, dr2 + : cylindrical coordinate system with constant annuli thickness to + : center of cell. Note however that the first annulus is half thickness + : so that the concentration is second order correct spatially at + : the membrane or exact edge of the cell. + : note ca[0] is at edge of cell + : ca[NANN-1] is at center of cell + r = 1/2 :starts at edge (half diam) + dr2 = r/(NANN-1)/2 :half thickness of annulus + vol[0] = 0 + frat[0] = 2*r + FROM i=0 TO NANN-2 { + vol[i] = vol[i] + PI*(r-dr2/2)*2*dr2 :interior half + r = r - dr2 + frat[i+1] = 2*PI*r/(2*dr2) :exterior edge of annulus + : divided by distance between centers + r = r - dr2 + vol[i+1] = PI*(r+dr2/2)*2*dr2 :outer half of annulus + } +} + +KINETIC state { +: printf("Solve begin t=%g v=%g cai=%g ica_pmp=%g\n", t, v, cai, ica_pmp) + COMPARTMENT i, (1+beta)*diam*diam*vol[i]*1(um) {ca} + COMPARTMENT (1e10)*area1 {pump pumpca} + COMPARTMENT volo*(1e15) {cao} +? kinetics + ~ pumpca <-> pump + cao (c3, c4) + ica_pmp = (1e-4)*2*FARADAY*(f_flux - b_flux)/area1 + : all currents except pump + ~ ca[0] << (-(ica-ica_pmp_last)*PI*diam*1(um)*(1e4)*frat[0]/(2*FARADAY)) + :diffusion + FROM i=0 TO NANN-2 { + ~ ca[i] <-> ca[i+1] (DFree*frat[i+1]*1(um), DFree*frat[i+1]*1(um)) + } + :pump + ~ ca[0] + pump <-> pumpca (c1, c2) + cai = ca[0] : this assignment statement is used specially by cvode +: printf("Solve end cai=%g ica=%g ica_pmp=%g ica_pmp_last=%g\n", +: cai, ica, ica_pmp,ica_pmp_last) +} + +PROCEDURE parms() { + coord() + area1 = 2*PI*(diam/2) * 1(um) + c1 = (1e7)*area1 * k1 + c2 = (1e7)*area1 * k2 + c3 = (1e7)*area1 * k3 + c4 = (1e7)*area1 * k4 +} + +FUNCTION ss() (mM) { + SOLVE state STEADYSTATE sparse + ss = cai +} + +COMMENT +At this time, conductances (and channel states and currents are +calculated at the midpoint of a dt interval. Membrane potential and +concentrations are calculated at the edges of a dt interval. With +secondorder=2 everything turns out to be second order correct. +ENDCOMMENT diff --git a/cnmodel/mechanisms/cadiff.mod b/cnmodel/mechanisms/cadiff.mod new file mode 100644 index 0000000..53c78f6 --- /dev/null +++ b/cnmodel/mechanisms/cadiff.mod @@ -0,0 +1,50 @@ +: Ca diffusion in a Purkinje cell +: Created 8/15/02 - nwg + +NEURON { + SUFFIX cadiff + USEION ca READ ica, cai WRITE cai + RANGE ca + GLOBAL depth, beta +} + +UNITS { + (mV) = (millivolt) + (mA) = (milliamp) + (mM) = (milli/liter) + (um) = (micron) +} + +CONSTANT { + F = 9.6485e4 (coul) +} + +PARAMETER { + cai (mM) + dt (ms) + + depth = 0.1 (um) + beta = 1 (/ms) +} + +ASSIGNED { + ica (mA/cm2) +} + +STATE { + ca (mM) +} + +INITIAL { + ca = 0.0001 +} + +BREAKPOINT { + ca = ca + (10000.0) * dt * ( ( -1/(2*F)*ica / (depth)) - (0.0001) * beta * ca ) + + if ( ca < 1e-4 ) {: minimum 100 nM Ca + ca = 1e-4 + } + + cai = ca +} diff --git a/cnmodel/mechanisms/cadyn.mod b/cnmodel/mechanisms/cadyn.mod new file mode 100644 index 0000000..e61bc98 --- /dev/null +++ b/cnmodel/mechanisms/cadyn.mod @@ -0,0 +1,100 @@ +TITLE decay of submembrane calcium concentration +: +: Internal calcium concentration due to calcium currents and pump. +: Differential equations. +: +: This file contains two mechanisms: +: +: 1. Simple model of ATPase pump with 3 kinetic constants (Destexhe 1992) +: +: Cai + P <-> CaP -> Cao + P (k1,k2,k3) +: +: A Michaelis-Menten approximation is assumed, which reduces the complexity +: of the system to 2 parameters: +: kt = * k3 -> TIME CONSTANT OF THE PUMP +: kd = k2/k1 (dissociation constant) -> EQUILIBRIUM CALCIUM VALUE +: The values of these parameters are chosen assuming a high affinity of +: the pump to calcium and a low transport capacity (cfr. Blaustein, +: TINS, 11: 438, 1988, and references therein). +: +: For further information about this this mechanism, see Destexhe, A. +: Babloyantz, A. and Sejnowski, TJ. Ionic mechanisms for intrinsic slow +: oscillations in thalamic relay neurons. Biophys. J. 65: 1538-1552, 1993. +: +: +: 2. Simple first-order decay or buffering: +: +: Cai + B <-> ... +: +: which can be written as: +: +: dCai/dt = (cainf - Cai) / taur +: +: where cainf is the equilibrium intracellular calcium value (usually +: in the range of 200-300 nM) and taur is the time constant of calcium +: removal. The dynamics of submembranal calcium is usually thought to +: be relatively fast, in the 1-10 millisecond range (see Blaustein, +: TINS, 11: 438, 1988). +: +: All variables are range variables +: +: Written by Alain Destexhe, Salk Institute, Nov 12, 1992 +: + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +NEURON { + SUFFIX cadyn + USEION ca READ ica, cai WRITE cai + RANGE depth,kt,kd,cainf,taur +} + +UNITS { + (molar) = (1/liter) : moles do not appear in units + (mM) = (millimolar) + (um) = (micron) + (mA) = (milliamp) + (msM) = (ms mM) +} + +CONSTANT { + FARADAY = 96489 (coul) : moles do not appear in units +} + +PARAMETER { + depth = .1 (um) : depth of shell + taur = 1e10 (ms) : remove first-order decay + cainf = 1.4e-1 (mM) + kt = 1e-4 (mM/ms) + kd = 1e-4 (mM) +} + +STATE { + cai (mM) +} + +INITIAL { + cai = kd +} + +ASSIGNED { + ica (mA/cm2) + drive_channel (mM/ms) + drive_pump (mM/ms) +} + +BREAKPOINT { + SOLVE state METHOD cnexp +} + +DERIVATIVE state { + + drive_channel = - (10000) * ica / (2 * FARADAY * depth) + + if (drive_channel <= 0.) { drive_channel = 0. } : cannot pump inward + + drive_pump = -kt * cai / (cai + kd ) : Michaelis-Menten + + cai' = drive_channel + drive_pump + (cainf-cai)/taur +} + diff --git a/cnmodel/mechanisms/cap.mod b/cnmodel/mechanisms/cap.mod new file mode 100644 index 0000000..8d81c76 --- /dev/null +++ b/cnmodel/mechanisms/cap.mod @@ -0,0 +1,86 @@ +: HH P-type Calcium current +: Created 8/13/02 - nwg + +NEURON { + THREADSAFE + SUFFIX cap + USEION ca READ cai, cao WRITE ica + RANGE pcabar, ica + RANGE minf, mtau + RANGE monovalConc, monovalPerm +} + +UNITS { + (mV) = (millivolt) + (mA) = (milliamp) + (mM) = (milli/liter) + F = 9.6485e4 (coul) + R = 8.3145 (joule/degC) +} + +PARAMETER { + v (mV) + celsius (degC) + + pcabar = 0.00005 (cm/s) + monovalConc = 140 (mM) + monovalPerm = 0 + + cai (milli/liter) + cao (milli/liter) +} + +ASSIGNED { + ica (mA/cm2) + minf + mtau (ms) + T (degC) + E (volts) +} + +STATE { + m +} + +INITIAL { + rates(v) + m = minf +} + +BREAKPOINT { + SOLVE states METHOD cnexp + ica = (1e3) * pcabar * m * ghk(v, cai, cao, 2) +} + +DERIVATIVE states { + rates(v) + m' = (minf - m)/mtau +} + +FUNCTION ghk( v(mV), ci(mM), co(mM), z) (coul/cm3) { LOCAL Ci + T = celsius + 273.19 : Kelvin + E = (1e-3) * v + Ci = ci + (monovalPerm) * (monovalConc) : Monovalent permeability + if (fabs(1-exp(-z*(F*E)/(R*T))) < 1e-6) { : denominator is small -> Taylor series + ghk = (1e-6) * z * F * (Ci-co*exp(-z*(F*E)/(R*T)))*(1-(z*(F*E)/(R*T))) + } else { + ghk = (1e-6) * z^2*(E*F^2)/(R*T)*(Ci-co*exp(-z*(F*E)/(R*T)))/(1-exp(-z*(F*E)/(R*T))) + } +} + +PROCEDURE rates (v (mV)) { + UNITSOFF + minf = 1/(1+exp(-(v - (-19)) / 5.5)) + mtau = (mtau_func(v)) * 1e3 + UNITSON +} + +FUNCTION mtau_func( v (mV) ) (ms) { + UNITSOFF + if (v > -50) { + mtau_func = .000191 + .00376*exp(-((v-(-41.9))/27.8)^2) + } else { + mtau_func = .00026367 + .1278 * exp(.10327*v) + } + UNITSON +} diff --git a/cnmodel/mechanisms/capmp.mod b/cnmodel/mechanisms/capmp.mod new file mode 100644 index 0000000..ca4c0cf --- /dev/null +++ b/cnmodel/mechanisms/capmp.mod @@ -0,0 +1,71 @@ +NEURON { + SUFFIX capmp + USEION ca READ cao, ica, cai WRITE cai, ica + RANGE tau, width, cabulk, ica, pump0 +} + +UNITS { + (um) = (micron) + (molar) = (1/liter) + (mM) = (millimolar) + (uM) = (micromolar) + (mA) = (milliamp) + (mol) = (1) + FARADAY = (faraday) (coulomb) +} + +PARAMETER { + width = 0.1 (um) + tau = 1 (ms) + k1 = 5e8 (/mM-s) + k2 = 0.25e6 (/s) + k3 = 0.5e3 (/s) + k4 = 5e0 (/mM-s) + cabulk = 0.1 (uM) + pump0 = 3e-14 (mol/cm2) +} + +ASSIGNED { + cao (mM) : 2 + cai (mM) : 100e-6 + ica (mA/cm2) + ica_pmp (mA/cm2) + ica_pmp_last (mA/cm2) +} + +STATE { + cam (uM) <1e-6> + pump (mol/cm2) <1e-16> + capump (mol/cm2) <1e-16> +} + +INITIAL { + ica = 0 + ica_pmp = 0 + ica_pmp_last = 0 + SOLVE pmp STEADYSTATE sparse +} + +BREAKPOINT { + SOLVE pmp METHOD sparse + ica_pmp_last = ica_pmp + ica = ica_pmp +} + +KINETIC pmp { + ~ cabulk <-> cam (width/tau, width/tau) + ~ cam + pump <-> capump ((1e7)*k1, (1e10)*k2) + ~ capump <-> cao + pump ((1e10)*k3, (1e10)*k4) + ica_pmp = (1e-7)*2*FARADAY*(f_flux - b_flux) + + : ica_pmp_last vs ica_pmp needed because of STEADYSTATE calculation + ~ cam << (-(ica - ica_pmp_last)/(2*FARADAY)*(1e7)) + + CONSERVE pump + capump = (1e13)*pump0 + COMPARTMENT width {cam} : volume has dimensions of um + COMPARTMENT (1e13) {pump capump} : area is dimensionless + COMPARTMENT 1(um) {cabulk} + COMPARTMENT (1e3)*1(um) {cao} + + cai = (0.001)*cam +} diff --git a/cnmodel/mechanisms/capump.mod b/cnmodel/mechanisms/capump.mod new file mode 100644 index 0000000..a300f46 --- /dev/null +++ b/cnmodel/mechanisms/capump.mod @@ -0,0 +1,32 @@ +NEURON { + SUFFIX capump + USEION ca READ cai WRITE ica + RANGE vmax, kmp, ica + } + + UNITS { + (uM) = (micro/liter) + (mM) = (milli/liter) + (mA) = (milliamp) + } + + PARAMETER { + vmax = .0667 (mA/cm2) <0, 1e6>: at 6.3 deg, Q10 = 3 + kmp = .2 (uM) <0, 1e6> + } + + ASSIGNED { + celsius (degC) + ica (mA/cm2) + cai (mM) + } + + LOCAL Q, s_celsius + + BREAKPOINT { + if (s_celsius*1(degC) != celsius) { + s_celsius = celsius + Q = 3^((celsius - 6.3)/10 (degC)) + } + ica = vmax*Q*cai/(cai + (.001)*kmp) / 5.18 +} \ No newline at end of file diff --git a/cnmodel/mechanisms/cleftXmtr.mod b/cnmodel/mechanisms/cleftXmtr.mod new file mode 100755 index 0000000..fba6643 --- /dev/null +++ b/cnmodel/mechanisms/cleftXmtr.mod @@ -0,0 +1,88 @@ +COMMENT +cleftXmtr + +This is simple state model that generates "cleft" transmitter, through +the following scheme: + +A netreceive block receives the driving event. This forces XV (the vesicle +state) to be set to XMax to mimic the release of a vesicle. +Then: +XV --> XC --> XU +where XV is the vesicle transmitter, XC is the cleft transmitter and +XU is transmitter that has been taken up. The forward rates are finite, and the +reverse rates are 0 (XU is an absorbing state) + +The forward rate kv1 mimics simple first-order diffusion across the cleft +The forward rate ku1 mimics simple first-order uptake from the cleft + +The concentration XC is available to the program as Xmtr. +XMax is the max cleft concentration of transmitter. + +Because vesicle release events at a single presynaptic terminal can be nearly +simultaneous, it is important that this mechanism does not have a refractory +period. We also assume that the uptake mechanism is not saturable. + +Paul B. Manis, Ph.D. +UNC Chapel Hill +3 Jan 2010 + +ENDCOMMENT + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +DEFINE NSTEP 5 + +NEURON { + POINT_PROCESS cleftXmtr + POINTER pre + RANGE KV, KU, XMax + RANGE CXmtr, preThresh +} +UNITS { + (nA) = (nanoamp) +} + +PARAMETER { : Parameters are chosen from best fit to stellate cell data in VCN + KV = 531 (/ms) <0,1e9> : release rate from vesicle + KU = 4.17 (/ms) <0,1e3> : uptake rate + XMax = 0.731 (mM) + preThresh = 0 +} + +ASSIGNED { + pre + CXmtr (mM) + preLast (1) + tLast +} + +STATE { + XV : Vesicle transmitter (just released) + XC : Cleft transmitter (e.g., at receptor) + XU : Uptake state (dead state... ) +} + +INITIAL { + XV = 0 + XC = 0 (mM) + XU = 0 + CXmtr = 0.0 + preLast = 0.0 + tLast = 0.0 +} + +BREAKPOINT { + SOLVE kstates METHOD sparse + CXmtr = XC*XMax +} + +KINETIC kstates { + ~ XV <-> XC (KV, 0.0) + ~ XC <-> XU (KU, 0.0) + : note that this mechanism has no CONSERVATION : XU can accumulate as much + : as needed. +} + +NET_RECEIVE(conc (mM)) { : detect and cause a release event + XV = XV + 1 +} diff --git a/cnmodel/mechanisms/gly.mod b/cnmodel/mechanisms/gly.mod new file mode 100755 index 0000000..df4cb2a --- /dev/null +++ b/cnmodel/mechanisms/gly.mod @@ -0,0 +1,65 @@ +TITLE Gly synapse + +COMMENT + MODIFIED to be a faster GLY synapse, taken from GABA synapse + Paul B. Manis - 7 Feb 2000 + + simple alpha-synapse that generates a single PSP + ********************************************* + reference: McCormick, Wang & Huguenard (1993) + Cerebral Cortex 3(5), 387-398 + found in: cat reticular nucleus of thalamus + ********************************************* + Assembled for MyFirstNEURON by Arthur Houweling + + +ENDCOMMENT + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +NEURON { + POINT_PROCESS GlySynapse + USEION cl READ ecl VALENCE 1 + : negative valence not accepted by nrnivmodl + RANGE onset, gmaxIPSP, e, g, i, w + NONSPECIFIC_CURRENT i +} + +UNITS { + (nA) = (nanoamp) + (mV) = (millivolt) + (nS) = (nanomho) +} + +PARAMETER { + onset= 25 (ms) + gmaxIPSP= 0 (nS) + w= 1 : weight factor for gmaxIPSP + ecl (mV) + v (mV) + celsius (degC) +} + +ASSIGNED { + i (nA) + g (nS) + tadj +} + +UNITSOFF +INITIAL { + tadj = 3^((celsius-23.5)/10) +} + +BREAKPOINT { LOCAL tt + tt= (t-onset)*tadj + if ((t>onset)&&(tt<740)) { + : the exp() function does not accept arguments smaller than -745 + g = w*gmaxIPSP * exp(-tt/15) * (1-exp(-tt/0.5))/0.84 + } + else {g = 0} + : -ecl because negative valences can not be specified + i = g * (v-(-ecl)) +} +UNITSON + diff --git a/cnmodel/mechanisms/gly2.mod b/cnmodel/mechanisms/gly2.mod new file mode 100755 index 0000000..54cefb5 --- /dev/null +++ b/cnmodel/mechanisms/gly2.mod @@ -0,0 +1,196 @@ +COMMENT +----------------------------------------------------------------------------- +Simple synaptic mechanism derived for first order kinetics of +binding of transmitter to postsynaptic receptors. + +A. Destexhe & Z. Mainen, The Salk Institute, March 12, 1993. +Last modif. Sept 8, 1993. + +Reference: + +Destexhe, A., Mainen, Z. and Sejnowski, T.J. An efficient method for +computing synaptic conductances based on a kinetic model of receptor binding. +Neural Computation, 6: 14-18, 1994. +----------------------------------------------------------------------------- + +During the arrival of the presynaptic spike (detected by threshold +crossing), it is assumed that there is a brief pulse (duration=Cdur) +of neurotransmitter C in the synaptic cleft (the maximal concentration +of C is Cmax). Then, C is assumed to bind to a receptor Rc according +to the following first-order kinetic scheme: + +Rc + C ---(Alpha)--> Ro (1) + <--(Beta)--- + +where Rc and Ro are respectively the closed and open form of the +postsynaptic receptor, Alpha and Beta are the forward and backward +rate constants. If R represents the fraction of open gates Ro, +then one can write the following kinetic equation: + +dR/dt = Alpha * C * (1-R) - Beta * R (2) + +and the postsynaptic current is given by: + +Isyn = gmax * R * (V-Erev) (3) + +where V is the postsynaptic potential, gmax is the maximal conductance +of the synapse and Erev is the reversal potential. + +If C is assumed to occur as a pulse in the synaptic cleft, such as + +C _____ . . . . . . Cmax + | | + _____| |______ . . . 0 + t0 t1 + +then one can solve the kinetic equation exactly, instead of solving +one differential equation for the state variable and for each synapse, +which would be greatly time consuming... + +Equation (2) can be solved as follows: + +1. during the pulse (from t=t0 to t=t1), C = Cmax, which gives: + + R(t-t0) = Rinf + [ R(t0) - Rinf ] * exp (- (t-t0) / Rtau ) (4) + +where + Rinf = Alpha * Cmax / (Alpha * Cmax + Beta) +and + Rtau = 1 / (Alpha * Cmax + Beta) + +2. after the pulse (t>t1), C = 0, and one can write: + + R(t-t1) = R(t1) * exp (- Beta * (t-t1) ) (5) + +There is a pointer called "pre" which must be set to the variable which +is supposed to trigger synaptic release. This variable is usually the +presynaptic voltage but it can be the presynaptic calcium concentration, +or other. Prethresh is the value of the threshold at which the release is +initiated. + +Once pre has crossed the threshold value given by Prethresh, a pulse +of C is generated for a duration of Cdur, and the synaptic conductances +are calculated accordingly to eqs (4-5). Another event is not allowed to +occur for Deadtime milliseconds following after pre rises above threshold. + +The user specifies the presynaptic location in hoc via the statement + connect pre_GABA[i] , v.section(x) + +where x is the arc length (0 - 1) along the presynaptic section (the currently +specified section), and i is the synapse number (Which is located at the +postsynaptic location in the usual way via + postsynaptic_section {loc_GABA(i, x)} +Notice that loc_GABA() must be executed first since that function also +allocates space for the synapse. +----------------------------------------------------------------------------- + GLY SYNAPSE (GLY receptors) + + currently parameters are same as GABA-A until I get the Harty data in here + P. Manis 2/10/2000 + +----------------------------------------------------------------------------- +ENDCOMMENT + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +NEURON { + POINT_PROCESS GLY2 + POINTER pre + RANGE C, R, R0, R1, g, gmax, Erev, lastrelease, Prethresh + NONSPECIFIC_CURRENT i + GLOBAL Cmax, Cdur, Alpha, Beta, Deadtime, Rinf, Rtau +} +UNITS { + (nA) = (nanoamp) + (mV) = (millivolt) + (umho) = (micromho) + (mM) = (milli/liter) +} + +PARAMETER { + + Cmax = 1 (mM) : max transmitter concentration + Cdur = 1 (ms) : transmitter duration (rising phase) + Alpha = 0.53 (/ms mM) : forward (binding) rate + Beta = 0.18 (/ms) : backward (unbinding) rate + Erev = -80 (mV) : reversal potential + Prethresh = 0 : voltage level nec for release + Deadtime = 1 (ms) : mimimum time between release events + gmax (umho) : maximum conductance +} + +ASSIGNED { + v (mV) : postsynaptic voltage + i (nA) : current = g*(v - Erev) + g (umho) : conductance + C (mM) : transmitter concentration + R : fraction of open channels + R0 : open channels at start of release + R1 : open channels at end of release + Rinf : steady state channels open + Rtau (ms) : time constant of channel binding + pre : pointer to presynaptic variable + lastrelease (ms) : time of last spike +} + +INITIAL { + R = 0 + C = 0 + R0 = 0 + R1 = 0 + Rinf = Cmax*Alpha / (Cmax*Alpha + Beta) + Rtau = 1 / ((Alpha * Cmax) + Beta) + lastrelease = -999 +} + +BREAKPOINT { + SOLVE release + g = gmax * R + i = g*(v - Erev) +} + +PROCEDURE release() { LOCAL q + :will crash if user hasn't set pre with the connect statement + + q = ((t - lastrelease) - Cdur) : time since last release ended + + : ready for another release? + if (q > Deadtime) { + if (pre > Prethresh) { : spike occured? + C = Cmax : start new release + R0 = R + lastrelease = t + } + + } else if (q < 0) { : still releasing? + + : do nothing + + } else if (C == Cmax) { : in dead time after release + R1 = R + C = 0. + } + + if (C > 0) { : transmitter being released? + + R = Rinf + (R0 - Rinf) * exptable (- (t - lastrelease) / Rtau) + + } else { : no release occuring + + R = R1 * exptable (- Beta * (t - (lastrelease + Cdur))) + } + + VERBATIM + return 0; + ENDVERBATIM +} + +FUNCTION exptable(x) { + TABLE FROM -10 TO 10 WITH 2000 + + if ((x > -10) && (x < 10)) { + exptable = exp(x) + } else { + exptable = 0. + } +} diff --git a/cnmodel/mechanisms/hcno.mod b/cnmodel/mechanisms/hcno.mod new file mode 100644 index 0000000..337b2e1 --- /dev/null +++ b/cnmodel/mechanisms/hcno.mod @@ -0,0 +1,101 @@ +TITLE h current for Octopus cells of Cochlear Nucleus +: From Bal and Oertel (2000) +: M.Migliore Oct. 2001 +: Modified, P. Manis July 2014. + +NEURON { + THREADSAFE + SUFFIX hcno + NONSPECIFIC_CURRENT i + RANGE gbar, eh, gh + GLOBAL hinf, tau1, tau2 +} + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) + (pS) = (picosiemens) + (um) = (micron) + R = (k-mole)(joule/degC) + F = (faraday)(kilocoulombs) +} + +PARAMETER { + gbar = 0.0005 (mho/cm2) + + vhalf1 = -50 (mV) : v 1/2 for forward + vhalf2 = -84 (mV) : v 1/2 for backward + gm1 = 0.3 :(mV) : slope for forward + gm2 = 0.6 : (mV) : slope for backward + zeta1 = 3 : (/ms) + zeta2 = 3 : (/ms) + a01 = 0.008 (/ms) + a02 = 0.0029 (/ms) + frac = 0.0 + c0 = 273.16 (degC) + thinf = -66 (mV) : inact inf slope + qinf = 7 (mV) : inact inf slope + q10tau = 4.5 : from Magee (1998) + v (mV) + q10g = 2.0 : Rothman... +} + + +ASSIGNED { + celsius (degC) + i (mA/cm2) + gh (mho/cm2) + eh (mV) : must be explicitly def. in hoc + hinf + tau1 (ms) + tau2 (ms) + qg () : computed q10 for gnabar based on q10g + q10 () + ssih +} + + +STATE { h1 h2 } + +BREAKPOINT { + SOLVE states METHOD derivimplicit + gh = qg*gbar*(h1*frac + h2*(1.0-frac)) + i = gh * (v - eh) +} + +INITIAL { + qg = q10g^((celsius-33.0)/10.0 (degC)) :note original measurements made at 33 C + q10 = q10tau^((celsius - 22.0)/10.0 (degC)) : if you don't like room temp, it can be changed! + rates(v) + h1=hinf + h2=hinf + ssih = 0. +} + +DERIVATIVE states { + rates(v) + h1' = (hinf - h1)/tau1 + h2' = (hinf - h2)/tau2 +} + +PROCEDURE rates(v (mV)) { + tau1 = bet1(v)/(q10*a01*(1.0+alp1(v))) + tau2 = bet2(v)/(q10*a02*(1.0+alp2(v))) + hinf = 1.0/(1.0+exp((v-thinf)/qinf)) +} + +FUNCTION alp1(v(mV)) { + alp1 = exp(1e-3*zeta1*(v-vhalf1)*F/(R*(c0+celsius))) +} + +FUNCTION bet1(v(mV)) { + bet1 = exp(1.e-3*zeta1*gm1*(v-vhalf1)*F/(R*(c0+celsius))) +} + +FUNCTION alp2(v(mV)) { + alp2 = exp(1.e-3*zeta2*(v-vhalf2)*F/(R*(c0+celsius))) +} + +FUNCTION bet2(v(mV)) { + bet2 = exp(1.e-3*zeta2*gm2*(v-vhalf2)*F/(R*(c0+celsius))) +} diff --git a/cnmodel/mechanisms/hcno_bo.mod b/cnmodel/mechanisms/hcno_bo.mod new file mode 100644 index 0000000..8da7466 --- /dev/null +++ b/cnmodel/mechanisms/hcno_bo.mod @@ -0,0 +1,103 @@ +TITLE h current for Octopus cells of Cochlear Nucleus +: From Bal and Oertel (2000) + +: Modified, P. Manis July 2014, 2017 +: Parameters from McGinley et al. paper + +NEURON { + THREADSAFE + SUFFIX hcnobo + NONSPECIFIC_CURRENT i + RANGE gbar, eh, gh, q10tau + GLOBAL hinf, tau1, tau2 +} + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) + (pS) = (picosiemens) + (um) = (micron) + R = (k-mole)(joule/degC) + F = (faraday)(kilocoulombs) +} + +PARAMETER { + gbar = 0.0005 (mho/cm2) + + vhalf1 = -70 (mV) : -50 (mV) : v 1/2 for forward + vhalf2 = -84 (mV) : v 1/2 for backward + gm1 = 0.3 :(mV) : slope for forward + gm2 = 0.6 : (mV) : slope for backward + zeta1 = 3 : (/ms) +: zeta2 = 3 : (/ms) + a01 = 4.8e-3 (/ms) : was 0.008 + a02 = 2.9e-3 (/ms) : was 0.0029 (/ms) + frac = 0.8 + c0 = 273.16 (degC) + thinf = -72.4 (mV) : inact inf slope + qinf = 5.3 (mV) : inact inf slope + q10tau = 4.5 : from Magee (1998) + v (mV) +} + + +ASSIGNED { + celsius (degC) + i (mA/cm2) + gh (mho/cm2) + eh (mV) : must be explicitly def. in hoc + hinf + tau1 (ms) + tau2 (ms) + q10 () + ssih + ct +} + + +STATE { h1 h2 } + +BREAKPOINT { + SOLVE states METHOD cnexp + : SOLVE states METHOD derivimplicit + gh = gbar*(h1*frac + h2*(1.0-frac)) + i = gh * (v - eh) +} + +INITIAL { + ct = 1e-3*zeta1*F/(R*(c0+celsius)) + + q10 = q10tau^((celsius - 33.0)/10.0 (degC)) : Measurements at 33 + rates(v) + h1=hinf + h2=hinf + ssih = 0. +} + +DERIVATIVE states { + rates(v) + h1' = (hinf - h1)/tau1 + h2' = (hinf - h2)/tau2 +} + +PROCEDURE rates(v (mV)) { + tau1 = bet1(v)/(q10*a01*(1.0+alp1(v))) + tau2 = bet2(v)/(q10*a02*(1.0+alp2(v))) + hinf = 1.0/(1.0+exp((v-thinf)/qinf)) +} + +FUNCTION alp1(v(mV)) { + alp1 = exp((v-vhalf1)*ct) +} + +FUNCTION bet1(v(mV)) { + bet1 = exp(gm1*(v-vhalf1)*ct) +} + +FUNCTION alp2(v(mV)) { + alp2 = exp((v-vhalf2)*ct) +} + +FUNCTION bet2(v(mV)) { + bet2 = exp(gm2*(v-vhalf2)*ct) +} diff --git a/cnmodel/mechanisms/iStim.mod b/cnmodel/mechanisms/iStim.mod new file mode 100755 index 0000000..f0c78ab --- /dev/null +++ b/cnmodel/mechanisms/iStim.mod @@ -0,0 +1,48 @@ +COMMENT +iStim + +This is a point current injection (like an electrode). +Positive values of the amplitude depolarize the cell +and in the presence of the extracellular mechanism there will be a change +in vext since i is not a transmembrane current but a current injected +directly to the inside of the cell. + +This is meant to be used with Vector Play... +ENDCOMMENT + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +DEFINE NSTEP 5 + +NEURON { + THREADSAFE + POINT_PROCESS iStim + RANGE dur, delay, iMax + ELECTRODE_CURRENT i +} +UNITS { + (nA) = (nanoamp) +} +PARAMETER { + dur (ms) <0,1e9> + delay (ms) <0,1e9> + iMax (nA) +} +ASSIGNED { +i (nA) +} + +INITIAL { + i = 0 +} + +BREAKPOINT { +COMMENT +if(t < delay || t > (delay+dur)) { + i = 0 + } + if(t >= delay && t <= (delay+dur)) { + i = iMax + } +ENDCOMMENT +} diff --git a/cnmodel/mechanisms/ihpkj.mod b/cnmodel/mechanisms/ihpkj.mod new file mode 100644 index 0000000..6575898 --- /dev/null +++ b/cnmodel/mechanisms/ihpkj.mod @@ -0,0 +1,56 @@ +: Ih current +: Created 8/6/02 - nwg + +NEURON { + THREADSAFE + SUFFIX hpkj + NONSPECIFIC_CURRENT i + RANGE gbar, gh, eh + GLOBAL ninf, ntau +} + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) + (S) = (siemens) +} + +PARAMETER { + v (mV) + + gbar = .0001 (S/cm2) + + eh = -30 (mV) +} + +ASSIGNED { + gh (mho/cm2) + i (mA/cm2) + ninf + ntau (ms) +} + +STATE { + n +} + +INITIAL { + rates(v) + n = ninf +} + +BREAKPOINT { + SOLVE states METHOD cnexp + gh = gbar * n + i = gh*(v - eh) +} + +DERIVATIVE states { + rates(v) + n' = (ninf - n)/ntau +} + +PROCEDURE rates(v (mV)) { + ninf = 1/(1+exp((v+90.1(mV))/9.9(mV))) + ntau = (1000) * (0.19 (s) + 0.72 (s)*exp(-((v-(-81.5(mV)))/11.9(mV))^2)) +} \ No newline at end of file diff --git a/cnmodel/mechanisms/ihpyr.mod b/cnmodel/mechanisms/ihpyr.mod new file mode 100644 index 0000000..7684ded --- /dev/null +++ b/cnmodel/mechanisms/ihpyr.mod @@ -0,0 +1,134 @@ +TITLE ihpyr.mod DCN pyramidal cell model H-current + +COMMENT + +This model is part a Dorsal Cochlear Nucleus Pyramidal point cell +based on kinetic data from Kanold and Manis (1999) and Kanold's dissertation (1999) + +-- 15 Jan 1999 P. Manis + +Added export of start states for some variables to do perturbation tests +These start values replace the "inf" values used in the initialization procedure +Note that if the start variable is set to a value less than 0, +then the default initialization will be done. Typically I use a value of -1 for this flagging +Note also that it is possible to set the initial values > 1 but this is meaningless in terms of +the present equations. +-- 5 Feb 1999 P. Manis + +Added Patrick's version of ih as ihpyr +Model is from Destexhe and Babloyantz 1993; Destexhe et al. 1993 + + +2/10/02. P. Manis. +7/23/2014 P. Manis - separated from pyr.mod. + +ENDCOMMENT + + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) +} + + +NEURON { + THREADSAFE + SUFFIX ihpyr + USEION na READ ena WRITE ina + USEION k READ ek WRITE ik + NONSPECIFIC_CURRENT i +: USEION h READ eh WRITE ih VALENCE 1 + RANGE eh +: + RANGE gh, kh_m_inf, kh_n_inf, aih, gbar, ghvshift + RANGE kh_m_tau, kh_n_tau + +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + v (mV) + celsius (degC) + dt (ms) + ek (mV) : = -81.5 (mV) + ena (mV) : = 50.0 (mV) + gbar = 0.00025 (mho/cm2) <0,1e9> + ghvshift = 0 (mV) + eh (mV) : = -43.0(mV) +} + +STATE { + khm khn +} + +ASSIGNED { + gh (mho/cm2) + ina (mA/cm2) + ik (mA/cm2) + ih (mA/cm2) + i (mA/cm2) + kh_m_inf kh_n_inf + kh_m_tau kh_n_tau + aih +} + +BREAKPOINT { + SOLVE states METHOD cnexp + aih = khm*khn + gh = gbar*aih + ih = gh*(v - eh) + i = ih +} + +UNITSOFF + +INITIAL { + rates(v) + khm = kh_m_inf + khn = kh_n_inf +} + + +DERIVATIVE states { + rates(v) + khm' = (kh_m_inf - khm) / kh_m_tau + khn' = (kh_n_inf - khn) / kh_n_tau +} + + +LOCAL q10 + +PROCEDURE rates(v(mV)) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + q10 = 3^((celsius - 22)/10 (degC)) + + :"kh" adaptation of Destexhe hyp-activated cation current by Patrick Kanold + kh_m_inf = kh_m(v) + kh_n_inf = kh_n(v) + kh_m_tau = kh_mt(v) + kh_n_tau = kh_nt(v) +} + +: Make these as functions so we can view them from hoc, although this +: may slow things down a bit + + +FUNCTION kh_m(x (mV)) { + kh_m = 1/(1+exp((x+68.9+ghvshift)/6.5)) +} + +FUNCTION kh_n(x (mV)) { + kh_n = 1/(1+exp((x+68.9+ghvshift)/6.5)) : same as kh_m, but for completeness, compute this +} + +FUNCTION kh_mt(v (mV)) { + kh_mt = exp((v+183.6+ghvshift)/15.24) +} + +FUNCTION kh_nt(v (mV)) { + kh_nt = exp((v+158.6+ghvshift)/11.2)/(1+exp((v+75+ghvshift)/5.5)) +} + + + diff --git a/cnmodel/mechanisms/ihpyr_adj.mod b/cnmodel/mechanisms/ihpyr_adj.mod new file mode 100644 index 0000000..8bc96fb --- /dev/null +++ b/cnmodel/mechanisms/ihpyr_adj.mod @@ -0,0 +1,142 @@ +TITLE ihpyr_adj.mod DCN pyramidal cell model H-current + +COMMENT + +This model is part a Dorsal Cochlear Nucleus Pyramidal point cell +based on kinetic data from Kanold and Manis (1999) and Kanold's dissertation (1999) + +-- 15 Jan 1999 P. Manis + +Added export of start states for some variables to do perturbation tests +These start values replace the "inf" values used in the initialization procedure +Note that if the start variable is set to a value less than 0, +then the default initialization will be done. Typically I use a value of -1 for this flagging +Note also that it is possible to set the initial values > 1 but this is meaningless in terms of +the present equations. +-- 5 Feb 1999 P. Manis + +Added Patrick's version of ih as ihpyr +Model is from Destexhe and Babloyantz 1993; Destexhe et al. 1993 + + +2/10/02. P. Manis. +7/23/2014 P. Manis - separated from pyr.mod. + +7/23/2018 P. Manis - created "ihpyr_adj" +ihpyr_adj has an adjustable q10 for fitting against experimental data + +ENDCOMMENT + + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) +} + + +NEURON { + THREADSAFE + SUFFIX ihpyr_adj + USEION na READ ena WRITE ina + USEION k READ ek WRITE ik + NONSPECIFIC_CURRENT i +: USEION h READ eh WRITE ih VALENCE 1 + RANGE eh +: + RANGE gh, kh_m_inf, kh_n_inf, aih, gbar, ghvshift + RANGE kh_m_tau, kh_n_tau + GLOBAL q10, q10f + +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + v (mV) + celsius (degC) + dt (ms) + ek (mV) : = -81.5 (mV) + ena (mV) : = 50.0 (mV) + gbar = 0.00025 (mho/cm2) <0,1e9> + ghvshift = 0 (mV) + eh (mV) : = -43.0(mV) + q10 = 3.0 (1) +} + +STATE { + khm khn +} + +ASSIGNED { + gh (mho/cm2) + ina (mA/cm2) + ik (mA/cm2) + ih (mA/cm2) + i (mA/cm2) + kh_m_inf kh_n_inf + kh_m_tau kh_n_tau + aih + q10f (1) +} + +BREAKPOINT { + SOLVE states METHOD cnexp + aih = khm*khn + gh = gbar*aih + ih = gh*(v - eh) + i = ih +} + +UNITSOFF + +INITIAL { + rates(v) + khm = kh_m_inf + khn = kh_n_inf +} + + +DERIVATIVE states { + rates(v) + khm' = (kh_m_inf - khm) / kh_m_tau + khn' = (kh_n_inf - khn) / kh_n_tau +} + + +: LOCAL q10f + +PROCEDURE rates(v(mV)) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + q10f = q10^((celsius - 22)/10 (degC)) + + :"kh" adaptation of Destexhe hyp-activated cation current by Patrick Kanold + : adding q10 does not shift activation curves + kh_m_inf = kh_m(v) + kh_n_inf = kh_n(v) + : adding the q10 just changes the rate for the taus (1/(a+b)) + kh_m_tau = kh_mt(v)/q10f + kh_n_tau = kh_nt(v)/q10f +} + +: Make these as functions so we can view them from hoc, although this +: may slow things down a bit + + +FUNCTION kh_m(x (mV)) { + kh_m = 1/(1+exp((x+68.9+ghvshift)/6.5)) +} + +FUNCTION kh_n(x (mV)) { + kh_n = 1/(1+exp((x+68.9+ghvshift)/6.5)) : same as kh_m, but for completeness, compute this +} + +FUNCTION kh_mt(v (mV)) { + kh_mt = exp((v+183.6+ghvshift)/15.24) +} + +FUNCTION kh_nt(v (mV)) { + kh_nt = exp((v+158.6+ghvshift)/11.2)/(1+exp((v+75+ghvshift)/5.5)) +} + + + diff --git a/cnmodel/mechanisms/ihsgc_apical.mod b/cnmodel/mechanisms/ihsgc_apical.mod new file mode 100755 index 0000000..65cc09d --- /dev/null +++ b/cnmodel/mechanisms/ihsgc_apical.mod @@ -0,0 +1,155 @@ +TITLE ihsgc-apical.mod - Spiral Ganglion Cell Ih current for Apical Region + +COMMENT +Ih for Spiral ganglion cells. +Kinetcs are based on average fits to mouse SGCs, +This model is for just the apical cell group. +Data used to establish the kinetic parameters were collected by +Qing Liu and Robin Davis (Rutgers). +Data were taken at room temperature. +Kinetic parameters were extracted by curve fitting for fast and +slow components from activation and deactivation (using +the program Ihfit4b.py). + +Implementation by Paul B. Manis, January-April, 2012. +Revised December 2013, January 2014. + # of parameters in the fit were decreased (tau uses one v and scale factor). +Parameters are shown in the tables in Liu et al., JARO 2014. + +March 13, 2014: Corrected version with boltzmax for slow component +July 2014: made threadsafe, changed solver + +pmanis@med.unc.edu + +Note: vshift parameter is nominally 0. This parameter can +shift the entire activation and rate curves, keeping them +in register for each component of the conductance. + +ENDCOMMENT + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) + (nA) = (nanoamp) +} + +NEURON { + THREADSAFE + SUFFIX ihsgcApical + NONSPECIFIC_CURRENT i + RANGE gbar, gh, ih, eh, vshift + RANGE vh, k, vhs, ks + RANGE rinf, rtau, sinf, stau +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + v (mV) + celsius = 22 (degC) + dt (ms) + gbar = 0.00318 (mho/cm2) <0,1e9> + eh = -41 (mV) + +: Parameters from kinetic analysis +: Format for NEURON MOD file: + +: (Run on date = 2014-01-01 12:55:35.786524 ) + +: lmfit, Constrained model t(v) = DC + 1/(a * exp((v+vh)/k1) + a*exp(-(v+vh)/k2)) +: A. Fast component (Fast trace): + +: Boltzmann: + vh = -101.831 (mV) + k = 12.431 (mV) + vshift = 0.0 (mV) + afast = 0.4225 : fraction that is fast. + +: Tau + taufac = 1.0 (1) + taumin = 0 (ms) + tausc1 = 0.00445778 (/ms) : (ms) + vtau1 = 87.0705 (mV) + kfac1 = 53.0338 (mV) + kfac2 = 21.5365 (mV) + + +: B. Slow component (Cyan trace): +: (Run on date = 2014-01-01 12:55:35.786883 ) + +: Boltzmann: + svh1 = -86.762 (mV) + sk1 = 4.430 (mV) : double boltzmann + svh2 = -115.227 (mV) + sk2 = 9.675 (mV) + svshift = 0.0 (mV) + sba2 = 0.400557 : relative amplitude slow component 2 compared to slow 1 (slow2/(slow2+slow1)) + aslow = 0.5775 : total slow + boltzmax = 0.5019571 : normalization factor + : (computed numerically in Sage to make double boltz max = 1.0) + +: stau + staufac = 1.0 (1) + staumin = 0 (ms) + stausc1 = 0.00093656 (/ms) : (ms) + svtau1 = 89.6097 (mV) + skfac1 = 25.392 (mV) + skfac2 = 26.4195 (mV) + +} + +STATE { + r + s +} + +ASSIGNED { + gh (mho/cm2) + i (mA/cm2) + ih (mA/cm2) + rinf + rtau (ms) + sinf + stau (ms) + q10 () +} + + +BREAKPOINT { + SOLVE states METHOD cnexp + gh = gbar*(afast*(r^2)+aslow*s) : Balance between fast and slow determined by afast and aslow + ih = gh*(v - eh) + i = ih +} + +INITIAL { + q10 = 3.0^((celsius - 22.0)/10.0 (degC)) : adjust for temperature... + rates(v) + r = rinf + s = sinf +} + +DERIVATIVE states { + rates(v) + r' = (rinf - r)/rtau + s' = (sinf - s)/stau +} + +LOCAL rt, st +PROCEDURE rates(v (mV)) { : Computes rate and activation at voltage = v. + +: fast component - standard HH-like kinetics. + rinf = 1.0 / (1+exp((v - vh + vshift) / k))^0.5 + rt = tausc1*exp((v + vtau1 + vshift) / kfac1) + tausc1*exp(-(v + vtau1 + vshift) / kfac2) + rtau = (taumin + taufac/rt) + +: slow component +: double boltzman activation function (decreasing conductance), unequal sharing. + sinf = 1. / (1 + exp((v - svh1 + vshift) / sk1)) + st = 1. / (1 + exp((v - svh2 + vshift) / sk2)) + sinf = (1-sba2)*sinf - sba2*st + sinf = sinf/boltzmax : make sinf [0..1] + stau = staufac / (stausc1*exp((v + svtau1 + vshift) / skfac1) + stausc1*exp(-(v + svtau1 + vshift) / skfac2)) + stau = (stau + staumin) +} + diff --git a/cnmodel/mechanisms/ihsgc_basalmiddle.mod b/cnmodel/mechanisms/ihsgc_basalmiddle.mod new file mode 100755 index 0000000..b034154 --- /dev/null +++ b/cnmodel/mechanisms/ihsgc_basalmiddle.mod @@ -0,0 +1,154 @@ +TITLE ihsgc-basalmiddle.mod - Spiral Ganglion Cell Ih current for basal and middle Regions + +COMMENT +Ih for Spiral ganglion cells. +Kinetcs are based on average fits to mouse SGCs, +This model is for the basal and middle cell groups (averaged). +Data used to establish the kinetic parameters were collected by +Qing Liu and Robin Davis (Rutgers). +Data were taken at room temperature. +Kinetic parameters were extracted by curve fitting for fast and +slow components from activation and deactivation (using +the program Ihfit4b.py). + +Implementation by Paul B. Manis, January-April, 2012. +Revised December 2013, January 2014. + # of parameters in the fit were decreased (tau uses one v and scale factor). +Parameters are shown in the tables in Liu et al., JARO 2014. + +March 13, 2014: Corrected version with boltzmax for slow component +July 2014: made threadsafe, changed solver + +pmanis@med.unc.edu + +Note: vshift parameter is nominally 0. This parameter can +shift the entire activation and rate curves, keeping them +in register for each component of the conductance. + +ENDCOMMENT + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) + (nA) = (nanoamp) +} + +NEURON { + THREADSAFE + SUFFIX ihsgcBasalMiddle + NONSPECIFIC_CURRENT i + RANGE gbar, gh, ih, eh, vshift + RANGE vh, k, vhs, ks + RANGE rinf, rtau, sinf, stau +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + v (mV) + celsius = 22 (degC) + dt (ms) + gbar = 0.00318 (mho/cm2) <0,1e9> + eh = -41 (mV) + +: Parameters from kinetic analysis +: Formatted for NEURON MOD file +: (Run on date = 2014-01-01 12:52:22.776598 ) + +: lmfit, Constrained model t(v) = DC + 1/(a * exp((v+vh)/k1) + a*exp(-(v+vh)/k2)) +: A. Fast component (Fast trace): + +: Boltzmann: + vh = -105.298 (mV) + k = 12.359 (mV) + vshift = 0.0 (mV) + afast = 0.4471 : fraction that is fast. + +: Tau + taufac = 1.0 (1) + taumin = 0 (ms) + tausc1 = 0.00417518 (/ms) + vtau1 = 87.0836 (mV) + kfac1 = 28.1667 (mV) + kfac2 = 21.4809 (mV) + + +: B. Slow component: +: (Run on date = 2014-01-01 12:52:22.777259 ) +: Boltzmann: + svh1 = -91.860 (mV) + sk1 = 4.883 (mV) : double boltzmann + svh2 = -110.209 (mV) + sk2 = 3.927 (mV) + svshift = 0.0 (mV) + sba2 = 0.337216 : relative amplitude slow component 2 compared to slow 1 (slow2/(slow2+slow1)) + aslow = 0.5529 : total slow + boltzmax = 0.5551729 : normalization factor + : (computed numerically in Sage to make double boltz max = 1.0) + +: stau + staufac = 1.0 (1) + staumin = 0 (ms) + stausc1 = 0.00104354 (/ms) + svtau1 = 105.816 (mV) + skfac1 = 40.0291 (mV) + skfac2 = 20.2273 (mV) + +} + +STATE { + r + s +} + +ASSIGNED { + gh (mho/cm2) + i (mA/cm2) + ih (mA/cm2) + rinf + rtau (ms) + sinf + stau (ms) + q10 () +} + + +BREAKPOINT { + SOLVE states METHOD cnexp + gh = gbar*(afast*(r^2)+aslow*s) : Balance between fast and slow determined by afast and aslow + ih = gh*(v - eh) + i = ih +} + + +INITIAL { + q10 = 3.0^((celsius - 22.0)/10.0 (degC)) : adjust for temperature... + rates(v) + r = rinf + s = sinf +} + +DERIVATIVE states { : Updates state variables r and s + rates(v) : at the current voltage + r' = (rinf - r )/rtau + s' = (sinf - s)/stau +} + +LOCAL rt, st +PROCEDURE rates(v (mV)) { : Computes rate and activation at voltage = v. + +: fast component - standard HH-like kinetics. + rinf = 1.0 / (1+exp((v - vh + vshift) / k))^0.5 + rt = tausc1*exp((v + vtau1 + vshift) / kfac1) + tausc1*exp(-(v + vtau1 + vshift) / kfac2) + rtau = (taumin + taufac/rt) + +: slow component +: double boltzman activation function (decreasing conductance), unequal sharing. + sinf = 1. / (1 + exp((v - svh1 + vshift) / sk1)) + st = 1. / (1 + exp((v - svh2 + vshift) / sk2)) + sinf = (1-sba2)*sinf - sba2*st + sinf = sinf/boltzmax : make sinf [0..1] + + stau = staufac / (stausc1*exp((v + svtau1 + vshift) / skfac1) + stausc1*exp(-(v + svtau1 + vshift) / skfac2)) + stau = (stau + staumin) +} diff --git a/cnmodel/mechanisms/ihvcn.mod b/cnmodel/mechanisms/ihvcn.mod new file mode 100644 index 0000000..c10d4e0 --- /dev/null +++ b/cnmodel/mechanisms/ihvcn.mod @@ -0,0 +1,79 @@ +TITLE jsr.mod VCN conductances + +COMMENT +Ih for VCN neurons - average from several studies in auditory neurons + +Implementation by Paul B. Manis, April (JHU) and Sept, (UNC)1999. +revised 2/28/04 pbm + +pmanis@med.unc.edu + +Modifed implementation; includes all temperature scaling, passes modlunit +7/10/2014 pbm + +ENDCOMMENT + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) + (nA) = (nanoamp) +} + +NEURON { + THREADSAFE + SUFFIX ihvcn + NONSPECIFIC_CURRENT i + RANGE gbar, gh, i, eh + GLOBAL rinf, rtau +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + v (mV) + dt (ms) + gbar = 0.00318 (mho/cm2) <0,1e9> + q10tau = 3.0 +} + +STATE { + r +} + +ASSIGNED { + celsius (degC) + gh (mho/cm2) + eh (mV) + i (mA/cm2) + rinf + rtau (ms) + q10 () +} + +BREAKPOINT { + SOLVE states METHOD cnexp + + gh = gbar*r + i = gh*(v - eh) +} + +INITIAL { + q10 = q10tau^((celsius - 22)/10 (degC)) : if you don't like room temp, it can be changed! + rates(v) + r = rinf +} + +DERIVATIVE states { :Computes state variables m, h, and n + rates(v) : at the current v and dt. + r' = (rinf - r)/rtau +} + +PROCEDURE rates(v (mV)) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + + rinf = 1 / (1+exp((v + 76) / 7 (mV))) + rtau = (100000 (ms)/ (237*exp((v+60) / 12 (mV)) + 17*exp(-(v+60) / 14 (mV)))) + 25 + rtau = rtau/q10 + +} + diff --git a/cnmodel/mechanisms/inav11.mod b/cnmodel/mechanisms/inav11.mod new file mode 100755 index 0000000..4b3c454 --- /dev/null +++ b/cnmodel/mechanisms/inav11.mod @@ -0,0 +1,188 @@ +: +: ichanWT2005.mod +: +: Alan Goldin Lab, University of California, Irvine +: Jay Lickfett - Last Modified: 6 July 2005 +: +: This file is the Nav1.1 wild-type channel model described in: +: +: Barela et al. An Epilepsy Mutation in the Sodium Channel SCN1A That Decreases +: Channel Excitability. J. Neurosci. 26(10): p. 2714-2723 +: +: +: The model is derived from the one described in: +: +: Spampanato et al. (2004a) Increased Neuronal Firing in Computer Simulations +: of Sodium Channel Mutations that Cause Generalized Epilepsy with Febrile Seizures Plus. +: Journal of Neurophysiology 91:2040-2050 +: +: and +: +: Spampanato et al. (2004b) A Novel Epilepsy Mutation +: in the Sodium Channel SCN1A Identifies a Cytoplasmic Domain for +: Beta Subunit Interaction. J. Neurosci. 24(44):10022-10034 +: + +: delayed rectifier removed (p.b.manis 2/22/2009) + + + + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) + (uF) = (microfarad) + (molar) = (1/liter) + (nA) = (nanoamp) + (mM) = (millimolar) + (um) = (micron) + (S) = (siemens) + FARADAY = 96520 (coul) + R = 8.3134 (joule/degC) + +} + + +NEURON { + THREADSAFE + SUFFIX nav11 + USEION na READ ena WRITE ina VALENCE 1 + RANGE gna + RANGE gbar + RANGE minf, mtau, hinf, htau, sinf, stau, inat, m, h, s + RANGE vsna : voltage shift parameter +} + + +INDEPENDENT {t FROM 0 TO 100 WITH 100 (ms)} + + +PARAMETER { + vsna = 4.3 (mV) + celsius (degC) + dt (ms) + ena (mV) + :enat = 50 (mV) + gbar = 0.1 (mho/cm2) + q10 = 3.0 (1) +} + + +ASSIGNED { + + v (mV) + gna (mho/cm2) + ina (mA/cm2) + minf hinf sinf + mtau (ms) htau (ms) stau (ms) + mexp hexp sexp +: vsna (mV) +} + + +STATE { + m h s +} + + +BREAKPOINT { + SOLVE states METHOD cnexp + gna = gbar*m*m*m*h*s + ina = gna*(v - ena) +} + + +UNITSOFF + + +INITIAL { + + trates(v) + + m = minf + h = hinf + s = sinf + +} + + +DERIVATIVE states { : Computes state variables m, h, s and n + : at the current v and dt. + rates(v) + m' = (minf - m)/mtau + h' = (hinf - h)/htau + s' = (sinf - s)/stau + +} + + +LOCAL qt + + +PROCEDURE rates(v (mV)) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + + LOCAL alpha, beta, sum + qt = q10^((celsius - 22)/10) : original recordings in Barela et al made at "room temperature" + + + : "m" sodium activation system + minf = f_minf(v) + mtau = f_mtau(v)/qt + + : "h" sodium fast inactivation system + hinf = f_hinf(v) + htau = f_htau(v)/qt + + : "s" sodium slow inactivation system + sinf = f_sinf(v) + stau = f_stau(v)/qt + +} + + +PROCEDURE trates(v (mV)) { :Build table with rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + LOCAL tinc + + TABLE minf, mexp, hinf, hexp, sinf, sexp, mtau, htau, stau + DEPEND dt, celsius FROM -100 TO 100 WITH 200 + + rates(v) : not consistently executed from here if usetable_hh == 1 + : so don't expect the tau values to be tracking along with + : the inf values in hoc + + tinc = -dt : * q10 q10 is handled in rates, above + mexp = 1 - exp(tinc/mtau) + hexp = 1 - exp(tinc/htau) + sexp = 1 - exp(tinc/stau) +} + +FUNCTION f_minf(v (mV)) { + f_minf = 1/(1+exp(-(v+27.4+vsna)*4.7*0.03937)) + + } +FUNCTION f_mtau(v (mV)) { + f_mtau = 0.15 + } + +FUNCTION f_hinf(v (mV)) { + f_hinf = 1/(1+exp((v+41.9+vsna)/6.7)) + } + +FUNCTION f_htau(v (mV)) { + f_htau = 23.12*exp(-0.5*((v+77.58+vsna)/43.92)^2) + } + + +FUNCTION f_sinf(v (mV)) { + f_sinf = 1/(1+exp((v+46.0+vsna)/6.6)) + } + +FUNCTION f_stau(v (mV)) { + f_stau = 1000*140.4*exp(-0.5*((v+71.3+vsna)/30.9)^2) + } + + +UNITSON + diff --git a/cnmodel/mechanisms/jsrnaf.mod b/cnmodel/mechanisms/jsrnaf.mod new file mode 100644 index 0000000..a8aad08 --- /dev/null +++ b/cnmodel/mechanisms/jsrnaf.mod @@ -0,0 +1,136 @@ +TITLE jsrnaf.mod VCN Na conductance, fast model + +COMMENT +gnaf is the modified form used in his +1993 M.S. thesis (as in Rothman et al., J. Neurophysiol. 70:2562, 1993), +with rapid recovery from inactivation for potentials below rest. + +Implementation by Paul B. Manis, April and Sept, 1999. +ENDCOMMENT + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) + (nA) = (nanoamp) +} + +? interface +NEURON { +THREADSAFE + SUFFIX jsrna + USEION na READ ena WRITE ina + RANGE gbar + RANGE gna, vsna + RANGE minf, hinf, mtau, htau +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + v (mV) + dt (ms) + ena = 55 (mV) + gbar = 0.25 (mho/cm2) <0,1e9> + vsna = 0 (mV) + q10 = 3.0 (1) +} + +STATE { + m h +} + +ASSIGNED { + gna (mho/cm2) + ina (mA/cm2) + minf hinf + mtau (ms) htau (ms) + celsius (degC) +} + +LOCAL mexp, hexp + +? currents +BREAKPOINT { + SOLVE states METHOD cnexp + gna = gbar*(m^3)*h + ina = gna*(v - ena) +} + +UNITSOFF + +INITIAL { + trates(v) + m = minf + h = hinf +} + +DERIVATIVE states { :Computes state variables m, h, and n + trates(v) : at the current v and dt. + m' = (minf - m)/mtau + h' = (hinf - h)/htau +} + +LOCAL qt + +PROCEDURE rates(v (mV)) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. +LOCAL alpha, beta, sum + + qt = q10^((celsius - 22)/10 (degC)) : R&M'03 used 3 + +: Note qt temperature here cancels in minf (a/(a+b)) +:"m" sodium activation system - JSR + alpha = -0.36*qt*vtrap((v+49),-3) + beta = 0.4*qt*vtrap((v+58),20) + sum = alpha + beta + mtau = 1/sum + minf = alpha/sum + +:"h" sodium inactivation system - JSR + alpha = 2.4*qt/(1+exp((v+68-vsna)/3 (mV))) + 0.8*qt/(1+exp(v+61.3-vsna)) + beta = 3.6*qt/(1+exp(-(v+21-vsna)/10 (mV))) + sum = alpha + beta + htau = 1/sum + hinf = alpha/sum + + + + +: jsr modified sodium channel - defined in terms of alpha and beta this time +: am = (0.36*q10*(v+49))/(1-exp(-((v+49)/3))) +: am = -(0.36*q10*vtrap(-(v+49),3)) +: bm = -(0.40*q10*(v+58))/(1-exp((v+58)/20)) +: bm = (0.40*q10*vtrap((v+58),20)) +: ah = ((2.4*q10)/(1+exp((v+68)/3))) + (0.8*qten/(1+exp(v+61.3))) +: bh = (3.6*q10)/(1+exp(-(v+21)/10)) + +: minf = am/(am+bm) +: hinf = ah/(ah+bh) + +: mtau = 1/(am+bm) +: htau = 1/(ah+bh) + +} + +PROCEDURE trates(v (mV)) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + LOCAL tinc + + rates(v) : not consistently executed from here if usetable_hh == 1 + : so don't expect the tau values to be tracking along with + : the inf values in hoc + + tinc = -dt : * q10 # handled in rates now + mexp = 1 - exp(tinc/mtau) + hexp = 1 - exp(tinc/htau) +} + +FUNCTION vtrap(x,y) { :Traps for 0 in denominator of rate eqns. + if (fabs(x/y) < 1e-6) { + vtrap = y*(1 - x/y/2) + }else{ + vtrap = x/(exp(x/y) - 1) + } +} + + diff --git a/cnmodel/mechanisms/ka.mod b/cnmodel/mechanisms/ka.mod new file mode 100644 index 0000000..c8cf1cf --- /dev/null +++ b/cnmodel/mechanisms/ka.mod @@ -0,0 +1,104 @@ +TITLE klt.mod The low threshold conductance of cochlear nucleus neurons + +COMMENT + +NEURON implementation of Jason Rothman's measurements of VCN conductances. + +This file implements the transient potassium current found in ventral cochlear +nucleus "Type I" cells, which are largely "stellate" or "multipolar" cells (Manis and +Marx, 1991; Rothman and Manis, 2003a,b; Manis et al, 1996). The current is likely + mediated by Kv4.2 potassium channel subunits, but this has not been directly +demonstrated. The specific implementation is described in Rothman and Manis, J. +Neurophysiol. 2003, in the appendix. Measurements were made from isolated +neurons from adult guinea pig, under reasonably stringent voltage clamp conditions. + The measured current is sensitive to 4-aminopyridine. +Original implementation by Paul B. Manis, April (JHU) and Sept, (UNC)1999. + +File split implementaiton, April 1, 2004. + +Contact: pmanis@med.unc.edu + +ENDCOMMENT + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) + (nA) = (nanoamp) +} + +NEURON { + THREADSAFE + SUFFIX ka + USEION k READ ek WRITE ik + RANGE gbar, gka, ik + GLOBAL ainf, binf, cinf, atau, btau, ctau +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + v (mV) + dt (ms) + gbar = 0.00477 (mho/cm2) <0,1e9> + q10tau = 3.0 + q10g = 2.0 +} + +STATE { + a b c +} + +ASSIGNED { + celsius (degC) : model is defined on measurements made at room temp in Baltimore + ik (mA/cm2) + ek (mV) + gka (mho/cm2) + ainf binf cinf + atau (ms) btau (ms) ctau (ms) + qg () : computed q10 for gnabar based on q10g + q10 () +} + +LOCAL aexp, bexp, cexp + +BREAKPOINT { + SOLVE states METHOD cnexp + + gka = gbar*(a^4)*b*c + ik = gka*(v - ek) + +} + + +INITIAL { + qg = q10g^((celsius-22)/10 (degC)) + q10 = q10tau^((celsius - 22)/10 (degC)) : if you don't like room temp, it can be changed! + rates(v) + a = ainf + b = binf + c = cinf +} + +DERIVATIVE states { :Computes state variables m, h, and n + rates(v) : at the current v and dt. + a' = (ainf - a)/atau + b' = (binf - b)/btau + c' = (cinf - c)/ctau +} + + +PROCEDURE rates(v (mV)) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + + ainf = (1 / (1 + exp(-1*(v + 31) / 6 (mV))))^0.25 + binf = 1 / (1 + exp((v + 66) / 7 (mV)))^0.5 + cinf = 1 / (1 + exp((v + 66) / 7 (mV)))^0.5 + + atau = (100 (ms)/ (7*exp((v+60) / 14 (mV)) + 29*exp(-(v+60) / 24 (mV)))) + 0.1 + atau = atau/q10 + btau = (1000 (ms) / (14*exp((v+60) / 27 (mV)) + 29*exp(-(v+60) / 24 (mV)))) + 1 + btau = btau/q10 + ctau = (90 (ms)/ (1 + exp((-66-v) / 17 (mV)))) + 10 + ctau = ctau/q10 +} + diff --git a/cnmodel/mechanisms/kcnq.mod b/cnmodel/mechanisms/kcnq.mod new file mode 100644 index 0000000..e71e6fa --- /dev/null +++ b/cnmodel/mechanisms/kcnq.mod @@ -0,0 +1,72 @@ +TITLE KCNQ potassium channel for GPe neuron + +COMMENT + modeled by Gunay et al., 2008 + implemented in NEURON by Kitano, 2011 +Threadsafe and unit checking, P.B. Manis, 2014 + + ENDCOMMENT + +UNITS { + (mV) = (millivolt) + (mA) = (milliamp) +} + +NEURON { + THREADSAFE + SUFFIX kcnq + USEION k READ ek WRITE ik + RANGE gbar, gk, iKCNQ +} + +PARAMETER { + v (mV) + dt (ms) + gbar = 0.001 (mho/cm2) + iKCNQ = 0.0 (mA/cm2) + ek (mV) + + theta_m = -61.0 (mV) + k_m = 19.5 (mV) + tau_m0 = 6.7 (ms) + tau_m1 = 100.0 (ms) + phi_m = -61.0 (mV) + sigma_m0 = 35.0 (mV) + sigma_m1 = -25.0 (mV) +} + +STATE { + m +} + +ASSIGNED { + ik (mA/cm2) + gk (mho/cm2) + minf + taum (ms) +} + +BREAKPOINT { + SOLVE states METHOD cnexp + gk = gbar*m*m*m*m + ik = gk * (v-ek) + iKCNQ = ik +} + + +INITIAL { + settables(v) + m = minf +} + +DERIVATIVE states { + settables(v) + m' = (minf - m)/taum +} + +PROCEDURE settables(v (mV)) { + TABLE minf, taum FROM -100 TO 100 WITH 400 + + minf = 1.0 / (1.0 + exp((theta_m - v)/k_m)) + taum = tau_m0 + (tau_m1 - tau_m0)/(exp((phi_m - v)/sigma_m0) + exp((phi_m - v)/sigma_m1)) +} diff --git a/cnmodel/mechanisms/kdpyr.mod b/cnmodel/mechanisms/kdpyr.mod new file mode 100644 index 0000000..2e1334b --- /dev/null +++ b/cnmodel/mechanisms/kdpyr.mod @@ -0,0 +1,92 @@ +TITLE kdpyr.mod DCN pyramidal cell model, delayed rectifier + +COMMENT + +This is part of a model implements a Dorsal Cochlear Nucleus Pyramidal point cell +based on kinetic data from Kanold and Manis (1999) and Kanold's dissertation (1999) + +-- 15 Jan 1999 P. Manis + +Added export of start states for some variables to do perturbation tests +These start values replace the "inf" values used in the initialization procedure +Note that if the start variable is set to a value less than 0, +then the default initialization will be done. Typically I use a value of -1 for this flagging +Note also that it is possible to set the initial values > 1 but this is meaningless in terms of +the present equations. +-- 5 Feb 1999 P. Manis + +ENDCOMMENT + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) +} + +NEURON { + THREADSAFE + SUFFIX kdpyr + USEION k READ ek WRITE ik + RANGE gbar, gk : delayed rectifier + RANGE ntau: time constants delayed rectifier + RANGE kd_avh + +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + v (mV) + celsius (degC) + dt (ms) + ek (mV) : = -81.5 (mV) + gbar = 0.006667 (mho/cm2) <0,1e9> + ntau = 0.5 (ms) <0.1,100> + kd_avh = -40 (mV) + } + +STATE { + n +} + +ASSIGNED { + gk (mho/cm2) + ik (mA/cm2) + ninf +} + +LOCAL nexp + +BREAKPOINT { + SOLVE states METHOD cnexp + gk = gbar*n*n + ik = gk*(v - ek) +} + +INITIAL { + rates(v) + n = ninf +} + +DERIVATIVE states { + rates(v) + n' = (ninf - n) / ntau +} + +LOCAL q10 + +PROCEDURE rates(v(mV)) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + LOCAL alpha, beta, sum + TABLE ninf, ntau DEPEND celsius FROM -200 TO 100 WITH 400 + + q10 = 3^((celsius - 22)/10 (degC)) + : "n" potassium activation system + ninf = kd_m(v) +} + +: Make these as functions so we can view them from hoc, although this +: may slow things down a bit +FUNCTION kd_m(x (mV)) { : potassium activation + kd_m = 1/(1+exp(-(x-kd_avh)/(3 (mV)))) : flat time constants +} + diff --git a/cnmodel/mechanisms/kht.mod b/cnmodel/mechanisms/kht.mod new file mode 100644 index 0000000..9f8aa21 --- /dev/null +++ b/cnmodel/mechanisms/kht.mod @@ -0,0 +1,111 @@ +TITLE kht.mod The high threshold conductance of cochlear nucleus neurons + +COMMENT + +NEURON implementation of Jason Rothman's measurements of VCN conductances. + +This file implements the high threshold potassium current found in several brainstem + nuclei of the auditory system, including the spherical and globular bushy cells + (Manis and Marx, 1991; Rothman and Manis, 2003a,b) and multipolar (stellate) + cells of the ventral cochlear nucleus, principal cells of the medial + nucleus of the trapzoid body (Brew and Forsythe, 1995, Wang and Kaczmarek, + 1997) and neurons of the medial superior olive. The current is likely mediated by + Kv3.1 potassium channel subunits. The specific + implementation is described in Rothman and Manis, J. Neurophysiol. 2003, in the + appendix. Measurements were made from isolated neurons from adult guinea pig, + under reasonably stringent voltage clamp conditions. The measured current is + sensitive to 4-aminopyridine and TEA, but is spared by mamba snake toxi + dendrotoxin I. + + +Similar conductrances are found in the homologous neurons of the avian auditory +system (Reyes and Rubel; Zhang and Trussell; Rathouz and Trussell), and the +conductance described here, in the absence of more detailed kinetic measurements +, is probably suitable for use in modeling that system. + + +Original implementation by Paul B. Manis, April (JHU) and Sept, (UNC)1999. + +File split implementation, February 28, 2004. + +Contact: pmanis@med.unc.edu + +ENDCOMMENT + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) + (nA) = (nanoamp) +} + +NEURON { + THREADSAFE + SUFFIX kht + USEION k READ ek WRITE ik + RANGE gbar, gkht, ik, q10g + GLOBAL ninf, pinf, ntau, ptau +} + +:INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} +ASSIGNED { + celsius (degC) : model is defined on measurements made at room temp in Baltimore: 22 degC + ik (mA/cm2) + ek (mV) + gkht (mho/cm2) + pinf ninf + ptau (ms) + ntau (ms) + qg () : computed q10 for gnabar based on q10g + q10 () +} + +PARAMETER { + v (mV) + dt (ms) + gbar = 0.01592 (mho/cm2) <0,1e9> + nf = 0.85 <0,1> :proportion of n vs p kinetics + q10tau = 3.0 + q10g = 2.0 +} + +STATE { + n p +} + +LOCAL nexp, pexp + +BREAKPOINT { + SOLVE states METHOD cnexp + + gkht = qg*gbar*(nf*(n^2) + (1-nf)*p) + ik = gkht*(v - ek) +} + +INITIAL { + qg = q10g^((celsius-22)/10 (degC)) + q10 = q10tau^((celsius - 22)/10 (degC)) + rates(v) + p = pinf + n = ninf +} + +DERIVATIVE states { :Computes state variables m, h, and n + rates(v) : at the current v and dt. + n' = (ninf - n)/ntau + p' = (pinf - p)/ptau +} + +PROCEDURE rates(v (mV)) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + + ninf = (1 + exp(-(v + 15) / 5 (mV)))^-0.5 + pinf = 1 / (1 + exp(-(v + 23) / 6 (mV))) + + ntau = (100 (ms)/ (11*exp((v+60) / 24 (mV)) + 21*exp(-(v+60) / 23 (mV)))) + 0.7 + ntau = ntau/q10 + ptau = (100 (ms)/ (4*exp((v+60) / 32 (mV)) + 5*exp(-(v+60) / 22 (mV)))) + 5 + ptau = ptau/q10 + +} + + diff --git a/cnmodel/mechanisms/kif.mod b/cnmodel/mechanisms/kif.mod new file mode 100644 index 0000000..14694c9 --- /dev/null +++ b/cnmodel/mechanisms/kif.mod @@ -0,0 +1,128 @@ +TITLE kif.mod DCN pyramidal cell model fast transient current + +COMMENT + +This model implements a fast transient potassium current from +Dorsal Cochlear Nucleus Pyramidal cells +based on kinetic data from Kanold and Manis (1999) and Kanold's dissertation (1999) + -- 15 Jan 1999 P. Manis + 2/10/02. P. Manis. + Pulled from pyr.mod 7/24/2014 +ENDCOMMENT + + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) +} + + NEURON { + SUFFIX kif + USEION k READ ek WRITE ik + + RANGE gkif, kif_a_inf, kif_i_inf : fast inactivating potassium current + RANGE akif, gbar + RANGE kif_a_tau, kif_i_tau + RANGE kif_a_start, kif_i_start + RANGE kif_ivh, kif_avh, kif_hivh +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + v (mV) + celsius (degC) + dt (ms) + ek (mV) : = -81.5 (mV) + ena (mV) : = 50.0 (mV) + gbar = 0.0125 (mho/cm2) <0,1e9> + + kif_ivh = -89.6 (mV) + kif_avh = -57.0 (mV) + kif_hivh = -87.0 (mV) + kif_a_start = -1 (1) + kif_i_start = -1 (1) + } + +STATE { + kifa kifi +} + +ASSIGNED { + gkif (mho/cm2) + ik (mA/cm2) + kif_a_inf (1) + kif_i_inf (1) + kif_a_tau (ms) + kif_i_tau (ms) + akif () + q10 () +} + + +BREAKPOINT { + SOLVE states METHOD cnexp + akif = kifa*kifa*kifa*kifa*kifi + gkif = gbar*akif + ik = gkif*(v - ek) +} + +INITIAL { + q10 = 3^((celsius - 22)/10 (degC)) + rates(v) + if(kif_a_start < 0) { : if xx_(i/a)_start is > 0, then perturbation is done at onset of computations. + kifa = kif_a_inf + } else { + kifa = kif_a_start + } + if(kif_i_start < 0) { + kifi = kif_i_inf + } else { + kifi = kif_i_start + } +} + +DERIVATIVE states { + rates(v) + kifa' = (kif_a_inf - kifa) / kif_a_tau + kifi' = (kif_i_inf - kifi) / kif_i_tau +} + + +PROCEDURE rates(v(mV)) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. +: LOCAL alpha, beta, sum +: TABLE kif_a_inf, kif_a_tau, kif_i_inf, kif_i_tau DEPEND celsius, kif_avh, kif_ivh FROM -200 TO 100 WITH 400 + : "kif" fast inactivation potassium channel - activation and inactivation + kif_a_inf = kif_m(v) + kif_i_inf = kif_h(v) + kif_a_tau = kif_mt(v) + kif_i_tau = kif_ht(v) + } + +: Make these as functions so we can view them from hoc, although this +: may slow things down a bit + +FUNCTION kif_m(v ) { : ikif activation + kif_m = 1.0/(1+exp(-(v-kif_avh)/25.8 (mV))) +} + +FUNCTION kif_h(v (mV)) { : ikif inactivation + kif_h = 1.0/(1+exp((v-kif_ivh)/6.7 (mV))) +} + +FUNCTION kif_mt(v (mV)) (ms) { : ikif activation tau + LOCAL x + x = 0.15 * exp((v-kif_avh)/10 (mV)) + 0.3 *exp(-(v-kif_avh)/10 (mV)) + x = 0.5 + (1.0 /x) + kif_mt = (x * 1.0 (ms))/q10 +} + +FUNCTION kif_ht(v (mV)) (ms) { : ikif inactivation tau + LOCAL x + x = 0.015 * exp((v-kif_hivh)/20 (mV))+0.03*exp(-(v-kif_hivh)/20 (mV)) + x = 10 + (1./x) + kif_ht = (x * 1.0 (ms)) /q10 +} + + diff --git a/cnmodel/mechanisms/kir.mod b/cnmodel/mechanisms/kir.mod new file mode 100755 index 0000000..b567cf8 --- /dev/null +++ b/cnmodel/mechanisms/kir.mod @@ -0,0 +1,108 @@ +TITLE KIR channel +COMMENT +Reference: Steephen JE, Manchanda R (2009) Differences in biophysical +properties of nucleus accumbens medium spiny neurons emerging from +inactivation of inward rectifying potassium currents. J Comput Neurosci [PubMed] + +Found on ModelDB, 1/21/2013 PBManis + + +ENDCOMMENT + +NEURON { + SUFFIX KIR + USEION k READ ek WRITE ik + RANGE g, ik, gbar + GLOBAL minf, mtau +} + +UNITS { + (mA) = (milliamp) + (uA) = (microamp) + (mV) = (millivolt) + (mS) = (millimho) +} + +PARAMETER { + celsius (degC) + ek (mV) + gbar = 1.4e-4 (mho/cm2) <0,1e9> + m_vh = -82 (mV) : half activation + m_ve = 13 (mV) : slope +} + +ASSIGNED { + v (mV) + g (mho/cm2) + ik (mA/cm2) + minf (1) + mtau (ms) + qt (1) +} + +STATE { + m +} + +BREAKPOINT { + SOLVE states METHOD cnexp + g = gbar*m + ik = g*(v - ek) +} + +INITIAL { + qt = 3^((celsius-35)/10) + rates(v) + m = minf +} + +DERIVATIVE states { + rates(v) + m' = (minf-m)/mtau +} + +FUNCTION_TABLE tabmtau(v(mV)) (ms) + +: rates() computes rate and other constants at present v +: call once from hoc to initialize inf at resting v + +PROCEDURE rates(v(mV)) { +: mtau = tabmtau(v) + mtau = tabmtau(v)/qt + minf = 1/(1 + exp((v - m_vh)/m_ve)) +} + +COMMENT +/* TABLES +The tables here are built as vecs in hoc, and then loaded into the mod file arrays before use... + + * + * Steephen, J. E., & Manchanda, R. (2009). Differences in biophysical properties of nucleus accumbens medium spiny neurons emerging from inactivation of inward rectifying potassium currents. J Comput Neurosci, + * doi:10.1007/s10827-009-0161-7 + */ + +//KIR +objref vecmtau_KIR, vecv_KIR +vecmtau_KIR = new Vector() +vecv_KIR = new Vector() +vecv_KIR.indgen(-120, 0, 10) +vecmtau_KIR.append(7.465, 7.465, 7.465, 8, 9.435, 10.755, 12.12, 13.795, 15.385, 14.285, 11.765, 8.89, 8) // At 35 deg C +table_tabmtau_KIR(&vecmtau_KIR.x[0], vecv_KIR.size, &vecv_KIR.x[0]) + +//inKIR +objref vecv_inKIR, vechinf_inKIR, vechtau_inKIR, vecv_tau_inKIR +vecv_tau_inKIR = new Vector() +vechtau_inKIR= new Vector() +vecv_tau_inKIR.append(-120,-90, -50) +vechtau_inKIR.append(7.767, 15, 25.333) // At 35 deg C +table_tabhtau_inKIR(&vechtau_inKIR.x[0],vecv_tau_inKIR.size, &vecv_tau_inKIR.x[0]) + +vecv_inKIR = new Vector() +vechinf_inKIR = new Vector() +vecv_inKIR.append(-120,-90, -50) +vechinf_inKIR.append(0, 0.13, 1) +table_tabhinf_inKIR(&vechinf_inKIR.x[0], vecv_inKIR.size, &vecv_inKIR.x[0]) +table_tabmtau_inKIR(&vecmtau_KIR.x[0], vecv_KIR.size, &vecv_KIR.x[0]) + +ENDCOMMENT + diff --git a/cnmodel/mechanisms/kis.mod b/cnmodel/mechanisms/kis.mod new file mode 100644 index 0000000..42d844f --- /dev/null +++ b/cnmodel/mechanisms/kis.mod @@ -0,0 +1,123 @@ +TITLE kis.mod DCN pyramidal cell model Slow transient K current + +COMMENT + + +This model implements the slow transient potassium current from +Dorsal Cochlear Nucleus Pyramidal cells +based on kinetic data from Kanold and Manis (1999) and Kanold's dissertation (1999) + +-- 15 Jan 1999 P. Manis + +2/10/02, 7/24/2014. P. Manis. + +ENDCOMMENT + + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) +} + + +NEURON { + THREADSAFE + SUFFIX kis + USEION k READ ek WRITE ik + RANGE gkis, kis_a_inf, kis_i_inf : fast inactivating potassium current + RANGE akis, gbar + RANGE kis_a_tau, kis_i_tau + RANGE kis_a_start, kis_i_start +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + v (mV) + celsius (degC) + dt (ms) + ek (mV) : = -81.5 (mV) + ena (mV) : = 50.0 (mV) + gbar = 0.0033333 (mho/cm2) <0,1e9> + + kis_ivh = -40.9 (mV) + kis_avh = -38.4 (mV) + kis_a_start = -1 + kis_i_start = -1 +} + +STATE { + kisa kisi +} + +ASSIGNED { + gkis (mho/cm2) + ik (mA/cm2) + kis_a_inf kis_i_inf + kis_a_tau (ms) + kis_i_tau (ms) + akis + q10 () +} + +BREAKPOINT { + SOLVE states METHOD cnexp + akis = kisa*kisa*kisa*kisa*kisi + gkis = gbar*akis + ik = gkis*(v - ek) +} + +INITIAL { + q10 = 3^((celsius - 22)/10 (degC)) + rates(v) + if(kis_a_start < 0) { : if xx_(i/a)_start is > 0, then perturbation is done at onset of computations. + kisa = kis_a_inf + } else { + kisa = kis_a_start + } + if(kis_i_start < 0) { + kisi = kis_i_inf + } else { + kisi = kis_i_start + } +} + + +DERIVATIVE states { + rates(v) + kisa' = (kis_a_inf - kisa) / kis_a_tau + kisi' = (kis_i_inf - kisi) / kis_i_tau +} + +PROCEDURE rates(v (mV)) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + + : "kis" fast inactivation potassium channel - activation and inactivation + kis_a_inf = kis_m(v) + kis_i_inf = kis_h(v) + kis_a_tau = kis_mt(v) + kis_i_tau = kis_ht(v) +} + +: Make these as functions so we can view them from hoc, although this +: may slow things down a bit + +FUNCTION kis_m(v (mV)) { : ikis activation + kis_m = 1/(1+exp(-(v-kis_avh)/23.7 (mV))) +} + +FUNCTION kis_h(v (mV)) { : ikis inactivation + kis_h = 1/(1+exp((v-kis_ivh)/9 (mV))) +} + +FUNCTION kis_mt(v (mV)) (ms) { : ikis activation tau + LOCAL x + x = 0.15*exp((v-kis_avh)/10 (mV)) + 0.3*exp(-(v-kis_avh)/10 (mV)) + x = 0.5 + (1.0 /x) + kis_mt = (x * 1.0 (ms))/q10 +} + +FUNCTION kis_ht(v (mV)) (ms) { : ikis inactivation tau + kis_ht = 200 (ms) +} + diff --git a/cnmodel/mechanisms/klt.mod b/cnmodel/mechanisms/klt.mod new file mode 100644 index 0000000..082ae89 --- /dev/null +++ b/cnmodel/mechanisms/klt.mod @@ -0,0 +1,109 @@ +TITLE klt.mod The low threshold conductance of cochlear nucleus neurons + +COMMENT + +NEURON implementation of Jason Rothman's measurements of VCN conductances. + +This file implements the low threshold potassium current found in several brainstem + nuclei of the auditory system, including the spherical and globular bushy cells + (Manis and Marx, 1991; Rothman and Manis, 2003a,b) and octopus cells (Bal and + Oertel, 2000) of the ventral cochlear nucleus, principal cells of the medial + nucleus of the trapzoid body (Brew and Forsythe, 1995, Wang and Kaczmarek, + 1997) and neurons of the medial superior olive. The current is likely mediated by + heteromultimers of Kv1.1 and Kv1.2 potassium channel subunits. The specific + implementation is described in Rothman and Manis, J. Neurophysiol. 2003, in the + appendix. Measurements were made from isolated neurons from adult guinea pig, + under reasonably stringent voltage clamp conditions. The measured current is + sensitive to the mamba snake toxin dendrotoxin-I. + + +Similar conductrances are found in the homologous neurons of the avian auditory +system (Reyes and Rubel; Zhang and Trussell; Rathouz and Trussell), and the +conductance described here, in the absence of more detailed kinetic measurements +, is probably suitable for use in modeling that system. + + +Original implementation by Paul B. Manis, April (JHU) and Sept, (UNC)1999. + +File split implementation, February 28, 2004. + +Contact: pmanis@med.unc.edu + +ENDCOMMENT + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) + (nA) = (nanoamp) +} + +NEURON { + THREADSAFE + SUFFIX klt + USEION k READ ek WRITE ik + RANGE gbar, gklt, ik, q10g + GLOBAL winf, zinf, wtau, ztau +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + v (mV) + dt (ms) + gbar = 0.01592 (mho/cm2) <0,1e9> + zss = 0.5 <0,1> : steady state inactivation of glt + q10tau = 3.0 + q10g = 2.0 +} + +STATE { + w z +} + +ASSIGNED { + celsius (degC) : model is defined on measurements made at room temp in Baltimore + ik (mA/cm2) + ek (mV) + gklt (mho/cm2) + winf zinf + wtau (ms) ztau (ms) + qg () : computed q10 for gnabar based on q10g + q10 () +} + +LOCAL wexp, zexp + +BREAKPOINT { + SOLVE states METHOD cnexp + + gklt = qg*gbar*(w^4)*z + ik = gklt*(v - ek) +} + +INITIAL { + qg = q10g^((celsius-22)/10 (degC)) + q10 = q10tau^((celsius - 22)/10 (degC)) : if you don't like room temp, it can be changed! + rates(v) + w = winf + z = zinf +} + +DERIVATIVE states { :Computes state variables m, h, and n + rates(v) : at the current v and dt. + w' = (winf - w)/wtau + z' = (zinf - z)/ztau +} + + +PROCEDURE rates(v (mV)) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + + winf = (1 / (1 + exp(-(v + 48) / 6 (mV))))^0.25 + zinf = zss + ((1-zss) / (1 + exp((v + 71) / 10 (mV)))) + + wtau = (100 (ms)/ (6*exp((v+60) / 6 (mV)) + 16*exp(-(v+60) / 45 (mV)))) + 1.5 + wtau = wtau/q10 + ztau = (1000 (ms)/ (exp((v+60) / 20 (mV)) + exp(-(v+60) / 8 (mV)))) + 50 + ztau = ztau/q10 +} + diff --git a/cnmodel/mechanisms/kpkj.mod b/cnmodel/mechanisms/kpkj.mod new file mode 100644 index 0000000..e0d035b --- /dev/null +++ b/cnmodel/mechanisms/kpkj.mod @@ -0,0 +1,94 @@ +: HH TEA-sensitive Purkinje potassium current +: Created 8/5/02 - nwg + +NEURON { + THREADSAFE + SUFFIX kpkj + USEION k READ ek WRITE ik + RANGE gbar, ik, gk + GLOBAL minf, hinf, mtau, htau +} + +UNITS { + (mV) = (millivolt) + (mA) = (milliamp) +} + +PARAMETER { + v (mV) + + gbar = .004 (mho/cm2) + + mivh = -24 (mV) + mik = 15.4 (mV) + mty0 = .00012851 (s) + mtvh1 = 100.7 (mV) + mtk1 = 12.9 (mV) + mtvh2 = -56.0 (mV) + mtk2 = -23.1 (mV) + + hiy0 = .31 + hiA = .78 + hivh = -5.802 (mV) + hik = 11.2 (mV) + + ek (mV) +} + +ASSIGNED { + gk (mho/cm2) + ik (mA/cm2) + minf + mtau (ms) + hinf + htau (ms) +} + +STATE { + m + h +} + +INITIAL { + rates(v) + m = minf + h = hinf +} + +BREAKPOINT { + SOLVE states METHOD cnexp + gk = gbar * m^3 * h + ik = gk * (v - ek) +} + +DERIVATIVE states { + rates(v) + m' = (minf - m) / mtau + h' = (hinf - h) / htau +} + +PROCEDURE rates( Vm (mV)) { + LOCAL v + v = Vm + 11 (mV) : Account for Junction Potential + minf = 1/(1+exp(-(v-mivh)/mik)) + mtau = mtau_func(v) + hinf = hiy0 + hiA/(1+exp((v-hivh)/hik)) + htau = 1000 * htau_func(v) +} + +FUNCTION mtau_func (v (mV)) (ms) { + if (v < -35 (mV)) { + mtau_func = (1000)*(3.4225e-5+.00498*exp(-v/-28.29 (mV)))*3 (s) + } else { + mtau_func = (1000)*(mty0 + 1(s)/(exp((v+mtvh1)/mtk1)+exp((v+mtvh2)/mtk2))) + } +} + +FUNCTION htau_func(Vm (mV)) (ms) { + if ( Vm > 0) { + htau_func = (1000)*(0.0012 (s) + 0.0023(s)*exp(-0.141 *Vm / 1 (mV))) + } else { + htau_func = (1000)*(1.2202e-05(s) + .012(s) * exp(-((Vm-(-56.3 (mV)))/49.6 (mV))^2)) + } +} + \ No newline at end of file diff --git a/cnmodel/mechanisms/kpkj2.mod b/cnmodel/mechanisms/kpkj2.mod new file mode 100644 index 0000000..da6bacf --- /dev/null +++ b/cnmodel/mechanisms/kpkj2.mod @@ -0,0 +1,67 @@ +: HH Low TEA-sensitive Purkinje potassium current +: Created 8/7/02 - nwg + +NEURON { + THREADSAFE + SUFFIX kpkj2 + USEION k READ ek WRITE ik + RANGE gbar, ik, gk + GLOBAL ninf, ntau +} + +UNITS { + (mV) = (millivolt) + (mA) = (milliamp) +} + +PARAMETER { + v (mV) + gbar = .002 (mho/cm2) + + nivh = -24 (mV) + nik = 20.4 (mV) + + ek (mV) +} + +ASSIGNED { + gk (mho/cm2) + ik (mA/cm2) + ninf (1) + ntau (ms) +} + +STATE { + n +} + +INITIAL { + rates(v) + n = ninf +} + +BREAKPOINT { + SOLVE states METHOD cnexp + gk = gbar * n^4 + ik = gk * (v - ek) +} + +DERIVATIVE states { + rates(v) + n' = (ninf - n) / ntau +} + +PROCEDURE rates(Vm (mV)) { + LOCAL v + v = Vm + 11 : Account for Junction Potential + ninf = 1/(1+exp(-(v-nivh)/nik)) + ntau = 1000 * ntau_func(v) +} + +FUNCTION ntau_func(v (mV)) (ms) { + if (v < -20) { + ntau_func = 0.000688 (ms) + 1 (ms)/(exp((v+64.2 (mV))/6.5 (mV))+exp((v-141.5 (mV))/-34.8 (mV))) + } else { + ntau_func = 0.00016 (ms) + 0.0008 (ms) *exp(-0.0267 * v /(1 (mV))) + } +} diff --git a/cnmodel/mechanisms/kpkjslow.mod b/cnmodel/mechanisms/kpkjslow.mod new file mode 100644 index 0000000..42ca378 --- /dev/null +++ b/cnmodel/mechanisms/kpkjslow.mod @@ -0,0 +1,63 @@ +: HH Slow TEA-insensitive Purkinje potassium current +: Created 8/7/02 - nwg + +NEURON { + THREADSAFE + SUFFIX kpkjslow + USEION k READ ek WRITE ik + RANGE gbar, ik, gk + GLOBAL ninf, ntau +} + +UNITS { + (mV) = (millivolt) + (mA) = (milliamp) +} + +PARAMETER { + v (mV) + gbar = 0.004 (mho/cm2) + + nivh = -16.5 (mV) + nik = 18.4 (mV) + + ek (mV) +} + +ASSIGNED { + gk (mho/cm2) + ik (mA/cm2) + ninf + ntau (ms) +} + +STATE { + n +} + +INITIAL { + rates(v) + n = ninf +} + +BREAKPOINT { + SOLVE states METHOD cnexp + gk = gbar * n^4 + ik = gk * (v - ek) +} + +DERIVATIVE states { + rates(v) + n' = (ninf - n) / ntau +} + +PROCEDURE rates(Vm (mV)) { + LOCAL v + v = Vm + 11 : Account for Junction Potential + ninf = 1/(1+exp(-(v-nivh)/nik)) + ntau = 1000 * ntau_func(v) +} + +FUNCTION ntau_func(v (mV)) (ms){ + ntau_func = 0.000796 (ms) + 1 (ms)/(exp((v+73.2 (mV))/11.7 (mV))+exp((v-306.7 (mV))/-74.2(mV))) +} \ No newline at end of file diff --git a/cnmodel/mechanisms/kpksk.mod b/cnmodel/mechanisms/kpksk.mod new file mode 100644 index 0000000..dac0ea6 --- /dev/null +++ b/cnmodel/mechanisms/kpksk.mod @@ -0,0 +1,111 @@ +TITLE Slow Ca-dependent potassium current +: +: Ca++ dependent K+ current IC responsible for slow AHP +: Differential equations +: +: Model based on a first order kinetic scheme +: +: + n cai <-> (alpha,beta) +: +: Following this model, the activation fct will be half-activated at +: a concentration of Cai = (beta/alpha)^(1/n) = cac (parameter) +: +: The mod file is here written for the case n=2 (2 binding sites) +: --------------------------------------------- +: +: This current models the "slow" IK[Ca] (IAHP): +: - potassium current +: - activated by intracellular calcium +: - NOT voltage dependent +: +: A minimal value for the time constant has been added +: +: Ref: Destexhe et al., J. Neurophysiology 72: 803-818, 1994. +: +: Modifications by Arthur Houweling for use in MyFirstNEURON + + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +NEURON { + THREADSAFE + SUFFIX kpksk + USEION k READ ek WRITE ik + USEION ca READ cai + RANGE m_inf, tau_m, gbar, gk + GLOBAL beta, cac + RANGE ik +} + + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) + (molar) = (1/liter) + (mM) = (millimolar) +} + + +PARAMETER { + v (mV) + celsius (degC) + dt (ms) + ek (mV) + cai (mM) + gbar = .01 (mho/cm2) + beta = 0.002 (1/ms) : backward rate constant + cac = 0.010 (mM) : middle point of activation fct + taumin = 0.1 (ms) : minimal value of the time cst +} + + +STATE { + m +} + +ASSIGNED { + ik (mA/cm2) + gk (mho/cm2) + m_inf + tau_m (ms) + tadj () +} + +BREAKPOINT { + SOLVE states :METHOD euler + gk = gbar * m*m + ik = gk * (v - ek) +} + +:DERIVATIVE states { +: evaluate_fct(v,cai) +: +: m'= (m_inf-m) / tau_m +:} + +PROCEDURE states() { + evaluate_fct(v,cai) + + m= m + (1-exp(-dt/tau_m))*(m_inf-m) +} + +INITIAL { +: +: activation kinetics are assumed to be at 22 deg. C +: Q10 is assumed to be 3 +: + tadj = 3 ^ ((celsius-22.0)/10 (degC)) + + evaluate_fct(v,cai) + m = m_inf +} + +PROCEDURE evaluate_fct(v(mV),cai(mM)) { LOCAL car + + car = (cai/cac)^2 + + m_inf = car / ( 1 + car ) + tau_m = 1 / beta / (1 + car) / tadj + + if(tau_m < taumin) { tau_m = taumin } : min value of time cst +} diff --git a/cnmodel/mechanisms/leak.mod b/cnmodel/mechanisms/leak.mod new file mode 100644 index 0000000..867c7c8 --- /dev/null +++ b/cnmodel/mechanisms/leak.mod @@ -0,0 +1,32 @@ +TITLE passive (leak) membrane channel + +UNITS { + (mV) = (millivolt) + (mA) = (milliamp) +} + +NEURON { + THREADSAFE + SUFFIX leak + NONSPECIFIC_CURRENT i + RANGE gbar, erev, i +} + +PARAMETER { + v (mV) + gbar = 0.001 (mho/cm2) + erev = -65 (mV) +} + +ASSIGNED { + i (mA/cm2) +} + +INITIAL { + +} +BREAKPOINT { + i = gbar*(v - erev) +} + + diff --git a/cnmodel/mechanisms/multisite.mod b/cnmodel/mechanisms/multisite.mod new file mode 100644 index 0000000..022500a --- /dev/null +++ b/cnmodel/mechanisms/multisite.mod @@ -0,0 +1,379 @@ +TITLE Multisite synapse + +COMMENT +----------------------------------------------------------------------------- +Multi-site synapse with independent release sites. Each site operates independently +and releases a vesicle upon presynaptic depolarization with a probability +determined by the history of activity, using the Dittman and Regehr (1998, 2000) +model. + +Revised from coh2.mod, coh3.mod, and coh4.mod. +The Dittman and Regeher (1998, 2000) release model with +facilitation closely fits Auditory Nerve data from mouse over +a wide range of frequencies. +The model DOES NOT include the postsynaptic receptors or desensitization, since +these should be treated separately (couple XMTR to an AMPA receptor model, +such as the Trussell-Raman model) + +Range variables: +nZones: is the number of active zones simulated in this calyx model. Each zone + can be connected to a separate PSD. +F (0.4): The base release probability +k0 (1/1.75): /s, baseline recovery rate from depletion (slow rate) +kmax (1/0.025): /s, maximal recovery rate from depletion (fast rate) +td (0.05) : time constant for fast calcium-dependent recovery, sec +kd (0.7) : affinity of fast recovery process for calcium sensor +kf (0.5) : affinity of facilitation process +tf (0.01) : rate of facilitation process (slow) seconds +dD (0.02): calcium that drives recovery (ca influx per AP) +dF (0.02): calcium that drives facilitation + +Added latency and variable delay (latstd, latency standard deviation in msec) +around the mean spike time. 4/5/2011 pbm. + +Version 4 uses a log-normal distribution to determine release latencies. +The calculation is built-in instead of being passed through an array. +The lognormal distribution describes the individual vesicle release time +course at this synapse as measured by Isaacson and Walmsley, 1996. Note that +they used a gamma distribution in some plots, but the lognormal distribution +seems to fit their published data at least as well. +The parameters of the distribution, as well as the release latency, +are controlled by an exponential function whose parameters are initialized at +run time. +10/19/2011 Paul B. Manis, UNC Chapel Hill + +ENDCOMMENT + +DEFINE MAX_ZONES 1000 : maximum number of zones in this model +DEFINE EVENT_N 10000 : number of entries in the Event Distribution (e.g., as sampled) + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +NEURON { + THREADSAFE + POINT_PROCESS MultiSiteSynapse + RANGE F, k0, kmax, taud, kd, tauf, kf + RANGE nZones, multisite, rseed, latency, latstd, debug + RANGE dD, dF, XMTR, glu, CaDi, CaFi + RANGE Fn, Dn + RANGE TTotal + RANGE nRequests, nReleases + RANGE Identifier : just a number so we can report which instance is active + RANGE tau_g, amp_g + : Distributions for stochastic release and testing (Sept, Oct, 2011): + RANGE EventLatencies, EventTime : returns the first EVENT_N latencies and absolute times at which they were used + RANGE ev_index : count in the EventLatencies (in case we are "short") + : parameters for latency shift during repetitive stimulation (Oct 19, 2011) + RANGE Dep_Flag : Depression flag (0 to remove depression; 1 to allow DKR control of facilitation and depression) + RANGE Lat_Flag, Lat_t0, Lat_A0, Lat_tau : Lat_Flag = 0 means fixed latency (set by "latency" above) + : otherwise, latency = latency for t < Lat_t0 + : latency = latency + Lat_A0*(1-exp(-(t-Lat_t0)/Lat_tau)) + : parameters for lognorm distribution shift during repetitive stimulation (Oct 19, 2011) + RANGE LN_Flag, LN_t0, LN_A0, LN_tau : LN_Flag = 0 means fixed sigma as well + : otherwise, sigma = latstd for t < LN_t0 + : sigma = latstd + LN_A0*(1-exp(-(t-LN_t0)/LN_tau)) + + : externally assigned pointers to RNG functions + POINTER uniform_rng : for deciding the number of active synapses when multisite==0 +} + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) + (mM) = (milli/liter) + (uM) = (micro/liter) +} + +PARAMETER { + dt (ms) + amp_g = 1.0 (mM) : amplitude of transmitter pulse + tau_g = 0.5 (ms) : duration of transmitter pulse + dD = 0.02 (1) : calcium influx driving recovery per AP + dF = 0.02 (1) : calcium influx driving facilitation per AP + F = 0.5 (1) : basal facilitation + k0 = 0.0005714(/ms) : slow recovery from depletion (1.0/1.75) + kmax = 0.040 (/ms) : fast recovery from depletion (1/0.025) + taud = 50.0 (ms) : time constant for fast calcium dependent recovery + kd = 0.7 (1) : affinity of fast recovery process for calcium sensor + tauf = 10.0 (ms) : rate of slow facilitation process + kf = 0.5 (1) : affinity of slow facilitation process + : taus = 1 (ms) : defined by DKR but not used here + : ks = 0.5 (1) + : glu = 1 (mM) + rseed (1) : random number generator seed (for SCOP module) + latency = 0.0 (ms) + latstd = 0.0 (ms) + + : Time course of latency shift in release during repetitive stimulation + Lat_Flag = 0 (1) : 0 means fixed latency, 1 means lognormal distribution + Lat_t0 = 0.0 (ms) : minimum time since simulation start before changes in latency are calculated + Lat_A0 = 0.0 (ms) : size of latency shift from t0 to infinity + Lat_tau = 100.0 (ms) : rate of change of latency shift (from fit of a+b(1-exp(-t/tau))) + : Statistical control of log-normal release shape over time during repetitive stimulation + LN_Flag = 0 (1) : 0 means fixed values for all time + LN_t0 = 0.0 (ms) : : minimum time since simulation start before changes in distribution are calculated + LN_A0 = 0.0 (ms) : size of change in sigma from t0 to infinity + LN_tau = 100.0 (ms) : rate of change of sigma over time (from fit of a+b*(1-exp(-t/tau))) + + : control flags - if debug is 1, show all, if 2, just "some" + debug = 0 + Identifier = 0 + Dep_Flag = 1 (1) : 1 means use depression calculations; 0 means always set release probability to F +} + +ASSIGNED { + : Externally set assignments + nZones (1) : number of zones in the model + multisite (1) : whether zones are modeled individually (1) or as a single, variable-amplitude zone (0) + nRequests (1) + nReleases (1) + EventLatencies[EVENT_N] (0) + EventTime[EVENT_N] (0) + tRelease[MAX_ZONES] (ms) : time of last release + + : Internal calculated variables + Fn (1) + Dn (1) + CaDn (1) + CaFn (1) + CaDi (1) + CaFi (1) + eta (1) + tSpike (ms) : time of last spike + tstep(ms) + TTotal(0) + tspike (ms) + latzone (ms) + vesicleLatency (ms) + sigma (ms) + gindex (0) + ev_index (0) + scrand (0) + + uniform_rng +} + +: Function prototypes needed to assign RNG function pointers +VERBATIM +double nrn_random_pick(void* r); +void* nrn_random_arg(int argpos); +ENDVERBATIM + +: Return a pick from uniform distribution. +: (distribution parameters are set externally) +FUNCTION rand_uniform() { +VERBATIM + _lrand_uniform = nrn_random_pick(_p_uniform_rng); +ENDVERBATIM +} + +: Function to allow RNG to be externally set +PROCEDURE setUniformRNG() { +VERBATIM + { + void** pv = (void**)(&_p_uniform_rng); + *pv = nrn_random_arg(1); + } +ENDVERBATIM +} + + +STATE { + XMTR[MAX_ZONES] (mM) : per-zone neurotransmitter concentration + N_ACTIVE[MAX_ZONES] (1) : number of zones actively releasing +} + +INITIAL { +: VERBATIM +: fprintf(stdout, "MultiSiteSynapse: Calyx #%d Initialized with Random Seed: %d\n", (int)Identifier, (int)rseed); +: ENDVERBATIM + + TTotal = 0 + nRequests = 0 + nReleases = 0 + set_seed(rseed) + tSpike = -1e9 + latzone = 0.0 + sigma = 0.0 + vesicleLatency = 0.0 + gindex = 0 + ev_index = 0 + scrand = 0.0 + CaDi = 1.0 + CaFi = 0.0 + CaDn = 1.0 + CaFn = 0.0 + Fn = F + Dn = 1.0 + FROM i = 0 TO (nZones-1) { + XMTR[i] = 0 + N_ACTIVE[i] = 1 + tRelease[i] = tSpike + } + update_dkr(t-tSpike) +} + +BREAKPOINT { + SOLVE release +} + +LOCAL tz, n_relzones, amp +PROCEDURE release() { + : Once released, the transmitter packet has a defined smooth time course in the "cleft" + : represented by the product of rising and falling exponentials. + : update glutamate in cleft + if (multisite == 1) { + : Update glutamate waveform for each active release zone + n_relzones = nZones + } + else { + : Update aggregate glutamate waveform for only the first release zone + n_relzones = 1 + } + + FROM i = 0 TO (nZones-1) { : for each zone in the synapse + if (t >= tRelease[i] && t < tRelease[i] + 5.0 * tau_g) { + tz = t - tRelease[i] : time since onset of release + : calculate glutamate waveform (Xie & Manis 2013 Supplementary Eq. 1) + XMTR[i] = amp_g * (1.0-exp(-tz/(tau_g/3.0))) * exp(-(tz-(tau_g/3.0))/tau_g) + } + else { + XMTR[i] = 0 + } + } +} + + +PROCEDURE update_dkr(tstep (ms)) { + : update the facilitation and depletion variables + : from the Dittman-Regehr model. + : Updates are done with each new presynaptic AP event. + if(tstep > 0.0) { + CaDi = CaDi + dD + CaFi = CaFi + dF + CaDn = CaDi * exp (-tstep/taud) + CaFn = CaFi * exp (-tstep/tauf) + eta = (kd/CaDi + 1.0)/(kd/CaDi + exp(-tstep/taud)) + eta = eta^(-(kmax-k0)*taud) + Dn = 1.0-(1.0-(1.0-Fn)*Dn)*exp(-k0*tstep)*eta + Fn = F + (1.0-F)/(1.0+kf/CaFn) + CaDi = CaDn + CaFi = CaFn + } + if (Dep_Flag == 0) { : no depression + Dn = 1.0 : set to 1 + Fn = F : set to initial value to set release probability constant + } +: VERBATIM +: if (debug >= 2 ){ +: fprintf(stdout, "update start t = %f ts=%f: F=%7.2f CaDi = %g CaFi = %g\n", \ +: t, tstep, F, CaDi, CaFi); +: fprintf(stdout, " vars: taud=%g: tauf=%g kd = %g kmax= %g\n", taud, tauf, kd, kmax); +: fprintf(stdout, " CaDi = %g CaFi = %g\n", CaDi, CaFi); +: fprintf(stdout, " CaDn = %g CaFn = %g\n", CaDn, CaFn); +: fprintf(stdout, " eta: %g\n", eta); +: fprintf(stdout, " Fn=%7.2f Dn: %7.2f CaDi = %g CaFi = %g,\n", \ +: Fn, Dn, CaDi, CaFi); +: } +: ENDVERBATIM +} + + +NET_RECEIVE(weight) { + : A spike has been received; process synaptic release + + : First, update DKR state to determine new release probability + update_dkr(t - tSpike) + tSpike = t : save the time of spike + + TTotal = 0 : reset total transmitter from this calyx for each release + nRequests = nRequests + 1 : count the number of inputs that we received + + : Next, process vesicle release using new release probability + if (multisite == 1) { + release_multisite() + } + else { + release_singlesite() + } +} + + +PROCEDURE release_multisite() { + : Vesicle release procedure for multi-site terminal. + : Loops over multiple zones using release probability Fn*Dn to decide whether + : each site will release, and selecting an appropriate release latency. + + : The synapse can release one vesicle per AP per zone, with a probability 0 0.0) { + latzone = normrand(0.0, latstd) : set a latency for the zone with one draw from the distribution + latzone = exp(latzone) - 1.0 + vesicleLatency : the latency should not be too short.... + } + else { + latzone = vesicleLatency : fixed value + } + } + else { + sigma = latstd + LN_A0*(1-exp(-(t-LN_t0)/LN_tau)) : time-dependent std shift + latzone = normrand(0.0, sigma) + latzone = exp(latzone)-1.0 + vesicleLatency + } + if (latzone < 0.0) { : this is to be safe... must have causality. + latzone = 0.0 + } + if (ev_index < EVENT_N) { : save event distribution list for verification + EventLatencies[ev_index] = latzone + EventTime[ev_index] = t + ev_index = ev_index + 1 + } + + : release time for this event + tRelease[i] = t + latzone + } + } + } +} + + +PROCEDURE release_singlesite() { + LOCAL pr + tRelease[0] = t + pr = Fn * Dn + FROM i = 0 TO (nZones-1) { + if (rand_uniform() < pr) { + TTotal = TTotal + 1 : count total releases this trial. + } + } + : Tell PSD to multiply its final current by the number of active zones + N_ACTIVE[0] = TTotal + printf("Release: %f\n", TTotal) +} diff --git a/cnmodel/mechanisms/na.mod b/cnmodel/mechanisms/na.mod new file mode 100644 index 0000000..e9ba278 --- /dev/null +++ b/cnmodel/mechanisms/na.mod @@ -0,0 +1,100 @@ +TITLE na.mod A sodium channel for cochlear nucleus neurons + +COMMENT + +NEURON implementation of Jason Rothman's measurements of VCN conductances. + +This file implements the average brain sodium current used in the Rothman model. +In the absence of direct measurements in the VCN, this is a fair assumption. +The model differs from the one used in Rothman et al, (1993) in that the steep +voltage dependence of recovery from inactivation in that model is missing. This +may affect the refractory period. To use the other model, use najsr.mod instead. + +Original implementation by Paul B. Manis, April (JHU) and Sept, (UNC)1999. + +File split implementaiton, April 1, 2004. + +Contact: pmanis@med.unc.edu + +Modifed implementation; includes all temperature scaling, passes modlunit +7/10/2014 pbm + +ENDCOMMENT + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) + (nA) = (nanoamp) +} + +NEURON { + THREADSAFE + SUFFIX na + USEION na READ ena WRITE ina + RANGE gbar, gna, ina + GLOBAL hinf, minf, htau, mtau +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + v (mV) + dt (ms) + ena (mV) + gbar = 0.07958 (mho/cm2) <0,1e9> + q10tau = 3.0 + q10g = 2.0 + +} + +STATE { + m h +} + +ASSIGNED { + celsius (degC) : model is defined on measurements made at room temp in Baltimore + ina (mA/cm2) + gna (mho/cm2) + minf hinf + mtau (ms) htau (ms) + qg () : computed q10 for gnabar based on q10g + q10 () + +} + +LOCAL mexp, hexp + +BREAKPOINT { + SOLVE states METHOD cnexp + + gna = qg*gbar*(m^3)*h + ina = gna*(v - ena) +} + +INITIAL { + qg = q10g^((celsius-22)/10 (degC)) + q10 = q10tau^((celsius - 22)/10 (degC)) : if you don't like room temp, it can be changed! + rates(v) + m = minf + h = hinf +} + +DERIVATIVE states { :Computes state variables m, h, and n + rates(v) : at the current v and dt. + m' = (minf - m)/mtau + h' = (hinf - h)/htau +} + +PROCEDURE rates(v (mV)) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + +: average sodium channel + minf = 1 / (1+exp(-(v + 38) / 7 (mV))) + hinf = 1 / (1+exp((v + 65) / 6 (mV))) + + mtau = (10 (ms)/ (5*exp((v+60) / 18 (mV)) + 36*exp(-(v+60) / 25 (mV)))) + 0.04 + mtau = mtau/q10 + htau = (100 (ms)/ (7*exp((v+60) / 11 (mV)) + 10*exp(-(v+60) / 25 (mV)))) + 0.6 + htau = htau/q10 +} + diff --git a/cnmodel/mechanisms/nacn.mod b/cnmodel/mechanisms/nacn.mod new file mode 100755 index 0000000..c979504 --- /dev/null +++ b/cnmodel/mechanisms/nacn.mod @@ -0,0 +1,103 @@ +TITLE nacn.mod A sodium conductance for a ventral cochlear nucleus neuron model + +COMMENT + +NEURON implementation of Jason Rothman's measurements of VCN conductances. + +This file implements the average brain sodium current used in the Rothman model. +In the absence of direct measurements in the VCN, this is a fair assumption. +The model differs from the one used in Rothman et al, (1993) in that the steep +voltage dependence of recovery from inactivation in that model is missing. This +may affect the refractory period. To use the other model, use najsr.mod instead. + +Original implementation by Paul B. Manis, April (JHU) and Sept, (UNC)1999. + +File split implementaiton, April 1, 2004. + + Does not pass modlunit. +Should work at 22C and scales by Rothman and Manis, 2003c for temperature + +Contact: pmanis@med.unc.edu + +ENDCOMMENT + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) + (nA) = (nanoamp) +} + +NEURON { + THREADSAFE + SUFFIX nacn + USEION na READ ena WRITE ina + RANGE gbar, gna, ina + GLOBAL hinf, minf, htau, mtau +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + v (mV) + celsius (degC) : 22 (degC) model is defined on measurements made at room temp in Baltimore + dt (ms) + ena (mV) + gbar = 0.07958 (mho/cm2) <0,1e9> + q10tau = 3.0 : q10 for rates +} + +STATE { + m h +} + +ASSIGNED { + ina (mA/cm2) + gna (mho/cm2) + minf hinf + mtau (ms) htau (ms) + q10 () + + } + +LOCAL mexp, hexp + +BREAKPOINT { + SOLVE states METHOD cnexp + gna = gbar*(m^3)*h + ina = gna*(v - ena) +} + +UNITSOFF + +INITIAL { + rates(v) + m = minf + h = hinf +} + +DERIVATIVE states { :Computes state variables m, h, and n + rates(v) : at the current v and dt. + m' = (minf - m)/mtau : m = m + mexp*(minf-m) + h' = (hinf - h)/htau : h = h + hexp*(hinf-h) + +} + +LOCAL qt + +PROCEDURE rates(v) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + + q10 = q10tau^((celsius - 22)/10) : if you don't like room temp, it can be changed! + +: average sodium channel + minf = 1 / (1+exp(-(v + 38) / 7)) + hinf = 1 / (1+exp((v + 65) / 6)) + + mtau = (10 / (5*exp((v+60) / 18) + 36*exp(-(v+60) / 25))) + 0.04 + mtau = mtau/q10 + htau = (100 / (7*exp((v+60) / 11) + 10*exp(-(v+60) / 25))) + 0.6 + htau = htau/q10 +} + + +UNITSON diff --git a/cnmodel/mechanisms/nacncoop.mod b/cnmodel/mechanisms/nacncoop.mod new file mode 100644 index 0000000..da36e7a --- /dev/null +++ b/cnmodel/mechanisms/nacncoop.mod @@ -0,0 +1,138 @@ +TITLE nacn.mod A sodium conductance for a ventral cochlear nucleus neuron model + +COMMENT + +NEURON implementation of Jason Rothman's measurements of VCN conductances. + +This file implements a modified version of the average brain sodium current + used in the Rothman and Manis 2003 models. + +The model differs from the one used in Rothman et al, (1993) in that the steep +voltage dependence of recovery from inactivation in that model is missing. This +may affect the refractory period. To use the other model, use jsrnaf.mod instead. + +Original implementation by Paul B. Manis, April 1999 (JHU) and Sept 1999 (UNC-CH). + +File split implementation, April 1, 2004. + + +Version nacncoop implements a cooperative sodium channel model built on the kinetics +of the original nacn model (R&M2003c). The motivation is to make a sodium channel with +faster activation kinetics, by introducing cooperativity between a subset of channels. +The model is based on concepts and implementation similar to Oz et al. +J.Comp. Neurosci. 39: 63, 2015, and Huang et al., PloSOne 7:e37729, 2012. +The cooperative channels are modeled with the same kinetics as the non-cooperative +channels, but are treated as a separate subset (fraction: p). The cooperativity is +introduced by shifting the voltage "seen" by the channels by KJ*m^3*h, which moves +the channels to a faster regime (essentially, they experience a depolarized membrane +potential that depends on their current gating state, relative to the main population +of channels). + +A subpopulation of Na channels (p [0..1]) experiences a small voltage-dependent shift +in the gating kinetics. The shift is determined by KJ + +This version does not have all the temperature scaling. Does not pass modlunit. +Should work at 22C, appears to work at other temperatures ok. + +Contact: pmanis@med.unc.edu + +ENDCOMMENT + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) + (nA) = (nanoamp) +} + +NEURON { + THREADSAFE + SUFFIX nacncoop + USEION na READ ena WRITE ina + RANGE gbar, gna, ina, p, KJ + RANGE vsna : voltage shift parameter + GLOBAL hinf, minf, htau, mtau, hinf2, minf2, htau2, mtau2 +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + v (mV) + celsius (degC) : 22 (degC) model is defined at room temp in Baltimore + dt (ms) + ena (mV) + gbar = 0.07958 (mho/cm2) <0,1e9> + q10 = 3.0 : q10 for rates + p = 0.0 (): fraction of cooperative channels (0-1) + KJ = 0 (mV) : coupling strength between cooperative channels (0-1000mV is usable range) + : setting either KJ = 0 or p = 0 will remove cooperativity. + vsna = 0 (mV) +} + +STATE { + m h m2 h2 +} + +ASSIGNED { + ina (mA/cm2) + gna (mho/cm2) + vNa (mV) : shifted V for cooperative behavior + minf hinf minf2 hinf2 + mtau (ms) htau (ms) mtau2 (ms) htau2 (ms) + + } + +LOCAL mexp, hexp, mexp2, hexp2 + +BREAKPOINT { + SOLVE states METHOD cnexp + + gna = gbar*(p*(m2^3*h2) + (1.-p)*(m^3)*h) + ina = gna*(v - ena) +} + +UNITSOFF + +INITIAL { + rates(v) + m = minf + h = hinf + m2 = minf2 + h2 = hinf2 + vNa = v + vsna + KJ*m^3*h +} + +DERIVATIVE states { :Computes state variables m, h, and n + rates(v) : at the current v and dt. + m' = (minf - m)/mtau + h' = (hinf - h)/htau + m2' = (minf2 - m2)/mtau2 + h2' = (hinf2 - h2)/htau2 + vNa = v + vsna + KJ*m^3*h : note addition of vsna shift here so that we do not add it in rates +} + +LOCAL qt + +PROCEDURE rates(v) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + + qt = q10^((celsius - 22)/10) : if you don't like room temp, it can be changed! + +: average sodium channel + minf = 1 / (1+exp(-(v + 38 + vsna) / 7)) + hinf = 1 / (1+exp((v + 65 + vsna) / 6)) + mtau = (10 / (5*exp((v + 60 + vsna) / 18) + 36*exp(-(v + 60+vsna) / 25))) + 0.04 + mtau = mtau/qt + htau = (100 / (7*exp((v + 60 + vsna) / 11) + 10*exp(-(v + 60 + vsna) / 25))) + 0.6 + htau = htau/qt + +: cooperative group of channels + minf2 = 1 / (1+exp(-(vNa + 38) / 7)) + hinf2 = 1 / (1+exp((vNa + 65) / 6)) + mtau2 = (10 / (5*exp((vNa+60) / 18) + 36*exp(-(vNa+60) / 25))) + 0.04 + mtau2 = mtau2/qt + htau2 = (100 / (7*exp((vNa+60) / 11) + 10*exp(-(vNa+60) / 25))) + 0.6 + htau2 = htau2/qt + +} + +UNITSON diff --git a/cnmodel/mechanisms/nap.mod b/cnmodel/mechanisms/nap.mod new file mode 100755 index 0000000..cf6470d --- /dev/null +++ b/cnmodel/mechanisms/nap.mod @@ -0,0 +1,130 @@ +TITLE nap.mod Persistent sodium conductance + +COMMENT + + +Persistent sodium current from deSchutter and Bower, J. Neurophys. +71:375, 1994. + + +2/10/02, 10/10/2014. P. Manis. + +ENDCOMMENT + + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) +} + + +NEURON { + THREADSAFE + SUFFIX nap + USEION na READ ena WRITE ina + + RANGE nap_inf, nap_tau, napi_inf, napi_tau + RANGE gbar, gnap + RANGE nap_A, nap_B, nap_C, nap_D, nap_E, nap_F, nap_G, nap_H + +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + v (mV) + celsius (degC) + dt (ms) + ena (mV) : = 50.0 (mV) + gbar = 0.00001 (mho/cm2) <0,1e9> + q10tau = 3.0 + q10g = 2.0 + + nap_shift = 0 (mV) + + nap_A = 200 (/ms): parameters from Bowers et al. + nap_B = 1 + nap_C = -18 (mV) + nap_D = -16 (mV) + nap_E = 25 (/ms) + nap_F = 1 + nap_G = 58 (mV) + nap_H = 8 (mV) + } + +STATE { + nap napi + } + +ASSIGNED { + gnap (mho/cm2) + ina (mA/cm2) + nap_inf + nap_tau (ms) + nap_tau1 (/ms) + nap_tau2 (/ms) + napi_inf + napi_tau (ms) + napi_tau1 (/ms) + napi_tau2 (/ms) + qg () : computed q10 for gnabar based on q10g + q10 () +} + +BREAKPOINT { + SOLVE states METHOD cnexp + gnap = gbar*nap*nap*nap*napi + ina = gnap*(v-ena) +} + + +INITIAL { + qg = q10g^((celsius-22)/10 (degC)) + q10 = q10tau^((celsius - 22)/10 (degC)) : if you don't like room temp, it can be changed! + rates(v) + nap = nap_inf + napi = napi_inf +} + + +DERIVATIVE states { + rates(v) + nap' = (nap_inf - nap) / nap_tau + napi' = (napi_inf - napi) / napi_tau +} + + +PROCEDURE rates(v (mV)) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + LOCAL x + : "nap" persistent sodium system + nap_inf = na_p(v + nap_shift) + nap_tau1 = nap_A/(nap_B + exp((v + nap_shift + nap_C)/nap_D)) + nap_tau2 = nap_E/(nap_F + exp((v + nap_shift + nap_G)/nap_H)) + nap_tau = 1./(nap_tau1 + nap_tau2) + + :nap_tau = na_ptau(v + nap_shift) + + : "nap" persistent sodium system - inactivation... + napi_inf = na_pi(v + nap_shift) + napi_tau1 = (1 (/ms)) /(0.06435/(1+exp((v + nap_shift + 73.26415)/3.71928 (mV)))) + napi_tau2 = (0.13496 (/ms))/(1 +exp((v + nap_shift + 10.27853)/(-9.09334 (mV)))) + napi_tau = 1 /(napi_tau1 + napi_tau2) +} + +LOCAL p + +FUNCTION na_p(v (mV)) { : persistent sodium activation +: Bowers + p = nap_A/(nap_B + exp((v + nap_shift + nap_C)/nap_D)) + na_p = p/(p+nap_E/(nap_F + exp((v + nap_shift + nap_G)/nap_H))) +} + + +FUNCTION na_pi(x (mV)) { : persistent sodium inactivation +: Bowers + na_pi = 0.06435/(1+exp((x+73.26415)/3.71928 (mV))) + na_pi = na_pi/(na_pi + (0.13496/(1+exp((v+10.27853)/(-9.09334 (mV)))))) +} + + diff --git a/cnmodel/mechanisms/napyr.mod b/cnmodel/mechanisms/napyr.mod new file mode 100644 index 0000000..a6200a1 --- /dev/null +++ b/cnmodel/mechanisms/napyr.mod @@ -0,0 +1,137 @@ +TITLE pyrna.mod DCN pyramidal cell model sodium channel + +COMMENT + +Revised version of DCN Pyramidal cell model sodium channel + +This model implements part of a Dorsal Cochlear Nucleus Pyramidal point cell +based on kinetic data from Kanold and Manis (1999) and Kanold's dissertation (1999) + +-- 15 Jan 1999 P. Manis + +This mechanism is the fast sodium channel portion of the model. + + +Orignal: 2/10/02. P. Manis. + +Extraced from Pyr.mod, 7/24/2014. + +ENDCOMMENT + + +UNITS { + (mA) = (milliamp) + (mV) = (millivolt) +} + + +NEURON { + THREADSAFE + SUFFIX napyr + USEION na READ ena WRITE ina + RANGE gna, minf, hinf, ninf, gbar : sodium channels and delayed rectifier + RANGE mtau, htau, ntau : time constants for sodium channels and delayed rectifier +} + +INDEPENDENT {t FROM 0 TO 1 WITH 1 (ms)} + +PARAMETER { + v (mV) + celsius (degC) + dt (ms) + ek (mV) : = -81.5 (mV) + ena (mV) : = 50.0 (mV) + gbar = 0.02857 (mho/cm2) <0,1e9> + mtau0 = 0.05 (ms) <0.01,100> + htau0 = 0.5 (ms) <0.1,100> + ntau = 0.5 (ms) <0.1,100> + } + +STATE { + m h + } + +ASSIGNED { + gna (mho/cm2) + ina (mA/cm2) + minf hinf mtau htau +} + +LOCAL mexp, hexp + +BREAKPOINT { + SOLVE states METHOD cnexp + gna = gbar*m*m*h + ina = gna*(v - ena) +} + +UNITSOFF + +INITIAL { + rates(v) + m = minf + h = hinf +} + +DERIVATIVE states { + rates(v) + m' = (minf - m) / mtau + h' = (hinf - h) / htau +} + +LOCAL q10 + + +PROCEDURE rates(v(mV)) { :Computes rate and other constants at current v. + :Call once from HOC to initialize inf at resting v. + LOCAL alpha, beta, sum + TABLE minf, mtau, hinf, htau DEPEND celsius FROM -200 TO 100 WITH 400 + +UNITSOFF + q10 = 3^((celsius - 22)/10) + + : "m" sodium activation system + minf = na_m(v) + mtau = na_mt(v) + + : "h" sodium inactivation system + hinf = na_h(v) + htau = na_ht(v) + +} + +: Make these as functions so we can view them from hoc, although this +: may slow things down a bit + +FUNCTION na_m(x) { : sodium activation + na_m = 1/(1+exp(-(x+38)/3.0)) : POK version +: na_m = alphbet(x,35,0,5,-10) :de Schutter (doesn't work well in our version) +: na_m = na_m/(na_m + alphbet(x,7,0,65,20)) +} + +FUNCTION na_mt(x) { : sodium activation with taus + na_mt = mtau0 : flat time constants +: na_mt = alphbet(x,35,0,5,-10) +: na_mt = 1/(na_mt + alphbet(x,7,0,65,20)) +} + +FUNCTION na_h(x) { : sodium inactivation + na_h = 1/(1+exp((x+43)/3.0)) : flat time constants (POK version) +: na_h = alphbet(x,0.225,1,80,10) +: na_h = na_h/(na_h + alphbet(x,7.5,0,-3,-18)) +} + +FUNCTION na_ht(x) { : sodium inactivation tau + na_ht = htau0 : POK: flat time constants +: na_ht = alphbet(x,0.225,1,80,10) : de Schutter version (doesn't work well with other stuff) +: na_ht = 1/(na_ht + alphbet(x,7.5,0,-3,-18)) +} + + +FUNCTION alphbet(x,A,B,C,D) { : alpha/beta general functions for + : transcrbing GENESIS models +alphbet = A/(B+exp((x+C)/D)) +} + +UNITSON + diff --git a/cnmodel/mechanisms/pkjlk.mod b/cnmodel/mechanisms/pkjlk.mod new file mode 100644 index 0000000..ae47848 --- /dev/null +++ b/cnmodel/mechanisms/pkjlk.mod @@ -0,0 +1,17 @@ +TITLE Purkinje Leak Current + +: A passive purkinje cell leak current +NEURON { + SUFFIX lkpkj + NONSPECIFIC_CURRENT i + RANGE i, e, gbar +} +PARAMETER { + gbar = 5e-5 (siemens/cm2) < 0, 1e9 > + e = -60.5 (millivolt) +} +ASSIGNED { + i (milliamp/cm2) + v (millivolt) +} +BREAKPOINT { i = gbar*(v - e) } diff --git a/cnmodel/mechanisms/rsg.mod b/cnmodel/mechanisms/rsg.mod new file mode 100644 index 0000000..3a3291d --- /dev/null +++ b/cnmodel/mechanisms/rsg.mod @@ -0,0 +1,196 @@ +TITLE Rsg sodium channel +: Resurgent sodium channel (with blocking particle) +: with updated kinetic parameters from Raman and Bean + +NEURON { + SUFFIX naRsg + USEION na READ ena WRITE ina + RANGE gna, gbar +} + +UNITS { + (mV) = (millivolt) + (S) = (siemens) +} + +PARAMETER { + gbar = .015 (S/cm2) + + : kinetic parameters + Con = 0.005 (/ms) : closed -> inactivated transitions + Coff = 0.5 (/ms) : inactivated -> closed transitions + Oon = .75 (/ms) : open -> Ineg transition + Ooff = 0.005 (/ms) : Ineg -> open transition + alpha = 150 (/ms) : activation + beta = 3 (/ms) : deactivation + gamma = 150 (/ms) : opening + delta = 40 (/ms) : closing, greater than BEAN/KUO = 0.2 + epsilon = 1.75 (/ms) : open -> Iplus for tau = 0.3 ms at +30 with x5 + zeta = 0.03 (/ms) : Iplus -> open for tau = 25 ms at -30 with x6 + + : Vdep + x1 = 20 (mV) : Vdep of activation (alpha) + x2 = -20 (mV) : Vdep of deactivation (beta) + x3 = 1e12 (mV) : Vdep of opening (gamma) + x4 = -1e12 (mV) : Vdep of closing (delta) + x5 = 1e12 (mV) : Vdep into Ipos (epsilon) + x6 = -25 (mV) : Vdep out of Ipos (zeta) +} + +ASSIGNED { + alfac : microscopic reversibility factors + btfac + + : rates + f01 (/ms) + f02 (/ms) + f03 (/ms) + f04 (/ms) + f0O (/ms) + fip (/ms) + f11 (/ms) + f12 (/ms) + f13 (/ms) + f14 (/ms) + f1n (/ms) + fi1 (/ms) + fi2 (/ms) + fi3 (/ms) + fi4 (/ms) + fi5 (/ms) + fin (/ms) + + b01 (/ms) + b02 (/ms) + b03 (/ms) + b04 (/ms) + b0O (/ms) + bip (/ms) + b11 (/ms) + b12 (/ms) + b13 (/ms) + b14 (/ms) + b1n (/ms) + bi1 (/ms) + bi2 (/ms) + bi3 (/ms) + bi4 (/ms) + bi5 (/ms) + bin (/ms) + + v (mV) + ena (mV) + ina (milliamp/cm2) + gna (S/cm2) +} + +STATE { + C1 FROM 0 TO 1 + C2 FROM 0 TO 1 + C3 FROM 0 TO 1 + C4 FROM 0 TO 1 + C5 FROM 0 TO 1 + I1 FROM 0 TO 1 + I2 FROM 0 TO 1 + I3 FROM 0 TO 1 + I4 FROM 0 TO 1 + I5 FROM 0 TO 1 + O FROM 0 TO 1 + B FROM 0 TO 1 + I6 FROM 0 TO 1 +} + +BREAKPOINT { + SOLVE activation METHOD sparse + gna = gbar * O : O is "open state" + ina = gna * (v - ena) +} + +INITIAL { + rates(v) + SOLVE seqinitial +} + +KINETIC activation +{ + rates(v) + ~ C1 <-> C2 (f01,b01) + ~ C2 <-> C3 (f02,b02) + ~ C3 <-> C4 (f03,b03) + ~ C4 <-> C5 (f04,b04) + ~ C5 <-> O (f0O,b0O) + ~ O <-> B (fip,bip) + ~ O <-> I6 (fin,bin) + ~ I1 <-> I2 (f11,b11) + ~ I2 <-> I3 (f12,b12) + ~ I3 <-> I4 (f13,b13) + ~ I4 <-> I5 (f14,b14) + ~ I5 <-> I6 (f1n,b1n) + ~ C1 <-> I1 (fi1,bi1) + ~ C2 <-> I2 (fi2,bi2) + ~ C3 <-> I3 (fi3,bi3) + ~ C4 <-> I4 (fi4,bi4) + ~ C5 <-> I5 (fi5,bi5) + +CONSERVE C1 + C2 + C3 + C4 + C5 + O + B + I1 + I2 + I3 + I4 + I5 + I6 = 1 +} + +LINEAR seqinitial { : sets initial equilibrium + ~ I1*bi1 + C2*b01 - C1*( fi1+f01) = 0 + ~ C1*f01 + I2*bi2 + C3*b02 - C2*(b01+fi2+f02) = 0 + ~ C2*f02 + I3*bi3 + C4*b03 - C3*(b02+fi3+f03) = 0 + ~ C3*f03 + I4*bi4 + C5*b04 - C4*(b03+fi4+f04) = 0 + ~ C4*f04 + I5*bi5 + O*b0O - C5*(b04+fi5+f0O) = 0 + ~ C5*f0O + B*bip + I6*bin - O*(b0O+fip+fin) = 0 + ~ O*fip + B*bip = 0 + + ~ C1*fi1 + I2*b11 - I1*( bi1+f11) = 0 + ~ I1*f11 + C2*fi2 + I3*b12 - I2*(b11+bi2+f12) = 0 + ~ I2*f12 + C3*fi3 + I4*bi3 - I3*(b12+bi3+f13) = 0 + ~ I3*f13 + C4*fi4 + I5*b14 - I4*(b13+bi4+f14) = 0 + ~ I4*f14 + C5*fi5 + I6*b1n - I5*(b14+bi5+f1n) = 0 + + ~ C1 + C2 + C3 + C4 + C5 + O + B + I1 + I2 + I3 + I4 + I5 + I6 = 1 +} + +PROCEDURE rates(v(mV) ) +{ + alfac = (Oon/Con)^(1/4) + btfac = (Ooff/Coff)^(1/4) + f01 = 4 * alpha * exp(v/x1) + f02 = 3 * alpha * exp(v/x1) + f03 = 2 * alpha * exp(v/x1) + f04 = 1 * alpha * exp(v/x1) + f0O = gamma * exp(v/x3) + fip = epsilon * exp(v/x5) + f11 = 4 * alpha * alfac * exp(v/x1) + f12 = 3 * alpha * alfac * exp(v/x1) + f13 = 2 * alpha * alfac * exp(v/x1) + f14 = 1 * alpha * alfac * exp(v/x1) + f1n = gamma * exp(v/x3) + fi1 = Con + fi2 = Con * alfac + fi3 = Con * alfac^2 + fi4 = Con * alfac^3 + fi5 = Con * alfac^4 + fin = Oon + + b01 = 1 * beta * exp(v/x2) + b02 = 2 * beta * exp(v/x2) + b03 = 3 * beta * exp(v/x2) + b04 = 4 * beta * exp(v/x2) + b0O = delta * exp(v/x4) + bip = zeta * exp(v/x6) + b11 = 1 * beta * btfac * exp(v/x2) + b12 = 2 * beta * btfac * exp(v/x2) + b13 = 3 * beta * btfac * exp(v/x2) + b14 = 4 * beta * btfac * exp(v/x2) + b1n = delta * exp(v/x4) + bi1 = Coff + bi2 = Coff * btfac + bi3 = Coff * btfac^2 + bi4 = Coff * btfac^3 + bi5 = Coff * btfac^4 + bin = Ooff +} + diff --git a/cnmodel/mechanisms/tests/test_mechanisms.py b/cnmodel/mechanisms/tests/test_mechanisms.py new file mode 100644 index 0000000..1a128c4 --- /dev/null +++ b/cnmodel/mechanisms/tests/test_mechanisms.py @@ -0,0 +1,40 @@ +import numpy as np +from neuron import h +from cnmodel.util import reset + + +def test_max_open_probability(): + reset( + raiseError=False + ) # reset() fails as unable to remove all neuron objects, unless we ignore the error + sec = h.Section() + + # Create AMPA and NMDA mechanisms + # AMPA uses mode=0; no rectification + apsd = h.AMPATRUSSELL(0.5, sec=sec) + # For NMDA we will hold the cell at +40 mV + npsd = h.NMDA_Kampa(0.5, sec=sec) + + # And a presynaptic terminal to provide XMTR input + term = h.MultiSiteSynapse(0.5, sec=sec) + term.nZones = 1 + h.setpointer(term._ref_XMTR[0], "XMTR", apsd) + h.setpointer(term._ref_XMTR[0], "XMTR", npsd) + + h.celsius = 34.0 + h.finitialize() + op = [[], []] + for i in range(100): + # force very high transmitter concentration for every timestep + term.XMTR[0] = 10000 + sec.v = 40.0 + h.fadvance() + op[0].append(apsd.Open) + op[1].append(npsd.Open) + + assert np.allclose(max(op[0]), apsd.MaxOpen) + assert np.allclose(max(op[1]), npsd.MaxOpen) + + +if __name__ == "__main__": + test_max_open_probability() diff --git a/cnmodel/mechanisms/vecevent.mod b/cnmodel/mechanisms/vecevent.mod new file mode 100644 index 0000000..5aadf4f --- /dev/null +++ b/cnmodel/mechanisms/vecevent.mod @@ -0,0 +1,72 @@ +: Vector stream of events +: From NEURON source: nrn/examples/nrniv/netcon/vecevent.mod + +NEURON { + ARTIFICIAL_CELL VecStim +} + +ASSIGNED { + index + etime (ms) + space +} + +INITIAL { + index = 0 + element() + if (index > 0) { + net_send(etime - t, 1) + } +} + +NET_RECEIVE (w) { + if (flag == 1) { + net_event(t) + element() + if (index > 0) { + net_send(etime - t, 1) + } + } +} + +VERBATIM +extern double* vector_vec(); +extern int vector_capacity(); +extern void* vector_arg(); +ENDVERBATIM + +PROCEDURE element() { +VERBATIM + { void* vv; int i, size; double* px; + i = (int)index; + if (i >= 0) { + vv = *((void**)(&space)); + if (vv) { + size = vector_capacity(vv); + px = vector_vec(vv); + if (i < size) { + etime = px[i]; + index += 1.; + }else{ + index = -1.; + } + }else{ + index = -1.; + } + } + } +ENDVERBATIM +} + +PROCEDURE play() { +VERBATIM + void** vv; + vv = (void**)(&space); + *vv = (void*)0; + if (ifarg(1)) { + *vv = vector_arg(1); + } +ENDVERBATIM +} + + diff --git a/cnmodel/morphology/__init__.py b/cnmodel/morphology/__init__.py new file mode 100755 index 0000000..4299d96 --- /dev/null +++ b/cnmodel/morphology/__init__.py @@ -0,0 +1,12 @@ +#!/usr/bin/python +# +# Morphology definitions for models. +# +# This file includes readers for +# +# Paul B. Manis, Ph.D. 2009 (August - November 2009) +# +from neuron import h + +from .morphology import Morphology +from .hoc_reader import HocReader diff --git a/cnmodel/morphology/bushy_stick.hoc b/cnmodel/morphology/bushy_stick.hoc new file mode 100644 index 0000000..e0db2f1 --- /dev/null +++ b/cnmodel/morphology/bushy_stick.hoc @@ -0,0 +1,90 @@ +objref soma +soma = new SectionList() +objref primarydendrite +primarydendrite = new SectionList() +objref secondarydendrite +secondarydendrite = new SectionList() +objref hillock +hillock = new SectionList() +objref unmyelinatedaxon +unmyelinatedaxon = new SectionList() +objref myelinatedaxon +myelinatedaxon = new SectionList() + +create sections[9] +access sections[0] +soma.append() +sections[0] { + pt3dadd(0., 0., 0., 25.) + pt3dadd(0., 25., 0., 25.) +} + +// axon hillock, 15 microns long, tapered +access sections[1] +hillock.append() +connect sections[1](0), sections[0](0) +sections[1] { + pt3dadd(0., 0., 0., 2.5) + pt3dadd(0., -15., 0., 1.0) +} + +// initial segment, unmyelinated, 10 microns long, not tapering +access sections[2] +unmyelinatedaxon.append() +connect sections[2](0), sections[1](1) +sections[2] { + pt3dadd(0., -15., 0., 1.0) + pt3dadd(0., -25., 0., 1.0) + +} + +// beginning of myelinated axon, 20 micron, enlarging with distance +access sections[3] +myelinatedaxon.append() +connect sections[3](0), sections[2](1) +sections[3] { + pt3dadd(0., -25., 0., 1.0) + pt3dadd(0., -45., 0., 2.0) + +} + +access sections[4] +primarydendrite.append() +connect sections[4](0), sections[0](1) +sections[4] { + pt3dadd(0., 25., 0., 3.0) + pt3dadd(0., 45., 0., 2.0) +} + +access sections[5] +secondarydendrite.append() +connect sections[5](0), sections[4](1) +sections [5] { + pt3dadd(0., 45., 0., 2.0) + pt3dadd(0., 55., -50., 1.5) +} + +access sections[6] +secondarydendrite.append() +connect sections[6](0), sections[4](1) +sections [6] { + pt3dadd(0., 45., 0., 2.0) + pt3dadd(0., 55., 50., 1.5) +} + +access sections[7] +secondarydendrite.append() +connect sections[7](0), sections[4](1) +sections [7] { + pt3dadd(0., 45., 0., 2.0) + pt3dadd(-50., 55., 0., 1.5) +} + +access sections[8] +secondarydendrite.append() +connect sections[8](0), sections[4](1) +sections [8] { + pt3dadd(0., 45., 0., 2.0) + pt3dadd(50., 55., 0, 1.5) +} + diff --git a/cnmodel/morphology/hoc_reader.py b/cnmodel/morphology/hoc_reader.py new file mode 100644 index 0000000..41aac62 --- /dev/null +++ b/cnmodel/morphology/hoc_reader.py @@ -0,0 +1,622 @@ +from __future__ import print_function +from neuron import h +import neuron +import collections +import numpy as np +import pyqtgraph as pg +import os +import re +import os.path + +try: + basestring +except NameError: + basestring = str + + +class HocReader(object): + def __init__(self, hoc): + """ + Provides useful methods for reading hoc structures. + + Parameters + ---------- + hoc : :obj: `hoc` or str + Either a hoc object that hs been already created, or a string that defines a hoc file name. + """ + + self.file_loaded = False + if isinstance(hoc, basestring): + fullfile = os.path.join(os.getcwd(), hoc) + if not os.path.isfile(fullfile): + raise Exception("File not found: %s" % (fullfile)) + neuron.h.hoc_stdout( + "/dev/null" + ) # prevent junk from printing while reading the file + success = neuron.h.load_file(str(fullfile)) + neuron.h.hoc_stdout() + if success == 0: # indicates failure to read the file + raise NameError("Found file, but NEURON load failed: %s" % (fullfile)) + self.file_loaded = True + self.h = h # save a copy of the hoc object itself. + else: + self.h = hoc # just use the passed argument + self.file_loaded = True + + # geometry containers + self.edges = None + self.vertexes = None + + # all sections in the hoc {sec_name: hoc Section} + self.sections = collections.OrderedDict() + # {sec_name: index} indicates index into self.sections.values() where + # Section can be found. + self.sec_index = {} + # {sec_name: [mechanism, ...]} + self.mechanisms = collections.OrderedDict() + # {sec_group_name: set(sec_name, ...)} + self.sec_groups = {} + + # topology {section: (parent, [children,...])} + self.topology = {} + + # populate self.sections, self.sec_index, and self.mechanisms + self.read_section_info() + + # auto-generate section groups based on either hoc section lists, or + # on section name prefixes. + sec_lists = self.get_section_lists() + sec_prefixes = self.get_section_prefixes() + + # Add groupings by section list if possible: + if len(sec_lists) > 1: + self.add_groups_by_section_list(sec_lists) + + # Otherwise, try section prefixes + elif len(sec_prefixes) > 1: + for group, sections in sec_prefixes.items(): + self.add_section_group(group, sections) + + # generate topology + self._generate_topology() + + def get_section(self, sec_name): + """ + Get the section associated with the section name + + Parameters + ---------- + sec_name : str + The name of the section object. + + Returns + ------- + The hoc Section object with the given name. + + """ + try: + return self.sections[sec_name] + except KeyError: + raise KeyError("No section named '%s'" % sec_name) + + def get_section_prefixes(self): + """ + Go through all the sections and generate a dictionary mapping their + name prefixes to the list of sections with that prefix. + + For example, with sections names axon[0], axon[1], ais[0], and soma[0], + we would generate the following structure: + + {'axon': ['axon[0]', 'axon[1]'], + 'ais': ['ais[0]'], + 'soma': ['soma[0]']} + """ + prefixes = {} + regex = re.compile("(?P\w+)\[(\d*)\]") + for sec_name in self.sections: + g = regex.match(sec_name) + if g is None: + continue + prefix = g.group("prefix") + prefixes.setdefault(prefix, []).append(sec_name) + return prefixes + + def get_mechanisms(self, section): + """ + Get a set of all of the mechanisms inserted into a given section + + Parameters + ---------- + section : :obj: `NEURON section` + The NEURON section object. + + Returns + ------- + A list of mechanism names + + """ + return self.mechanisms[section] + + def get_density(self, section, mechanism): + """ + Get density mechanism that may be found the section. + mechanism is a list ['name', 'gbarname']. This is needed because + some mechanisms do not adhere to any convention and may have a different + kind of 'gbarname' than 'gbar_mechname' + returns the average of the conductance density, as that may range across different + values in a section (e.g., can vary by segments) + + Parameters + ---------- + section : :obj: `NEURON section` + The NEURON section object. + mechanism : list + mechanism is a list ['name', 'gbarname']. It is used to + retrieve the mechanism density from HOC as + `segment.name.gbarname`. + + Returns + ------- + Mean conductance of the selected mechanism in the section, averaged across all segments of the section. + """ + + gmech = [] + for seg in section: + try: + x = getattr(seg, mechanism[0]) + mecbar = "%s_%s" % (mechanism[1], mechanism[0]) + if mecbar in dir(x): + gmech.append(getattr(x, mechanism[1])) + else: + print( + "hoc_reader:get_density did not find the mechanism in dir x", + dir(x), + ) + except NameError: + return 0.0 + except: + print("hoc_reader:get_density failed to evaluate the mechanisms... ") + raise + + # print gmech + if len(gmech) == 0: + gmech = 0.0 + return np.mean(gmech) + + def get_sec_info(self, section, html=False): + """ + Get the info of the given section + modified from: neuronvisio + + Parameters + ---------- + section : :obj: `NEURON section` + The NEURON section object. + + Returns + ------- + str + containing the information, with html formatting. + """ + if html: + br = " " + bre = "" + lbrk = "
" + li = "
  • " + lie = "
  • " + else: + br = " " + bre = "" + li = "" + lie = "" + lbrk = "\n" + info = f"{br:s}Section Name:{bre:s} {section.name():s}{lbrk:s}" + info += f"{br:s}Length [um]:{bre:s} {section.L:f}{lbrk:s}" + info += f"{br:s}Diameter [um]:{bre:s} {section.diam:f}{lbrk:s}" + info += f"{br:s}Membrane Capacitance:{bre:s} {section.cm:f}{lbrk:s}" + info += f"{br:s}Axial Resistance :{bre:s} {section.Ra:f}{lbrk:s}" + info += f"{br:s}Number of Segments:{bre:s} {section.nseg:f}{lbrk:s}" + mechs = [] + for seg in section: + for mech in seg: + mechs.append(mech.name()) + mechs = set(mechs) # Excluding the repeating ones + + mech_info = f"{br:s}Mechanisms in the section{bre:s}{lbrk:s}" + for mech_name in mechs: + s = f"{li:s} {mech_name:s} {lie:s}" + mech_info += s + info += mech_info + return info + + def read_section_info(self): + """ + Read all the information about the sections in the current hoc file + Stores the result in the mechanisms class variable. + """ + # Collect list of all sections and their mechanism names. + self.sections = collections.OrderedDict() + self.mechanisms = collections.OrderedDict() + for i, sec in enumerate(self.h.allsec()): + self.sections[sec.name()] = sec + self.sec_index[sec.name()] = i + mechs = set() + for seg in sec: + for mech in seg: + mechs.add(mech.name()) + self.mechanisms[sec.name()] = mechs + + def hoc_namespace(self): + """ + Get a dict of the HOC namespace {'variable_name': hoc_object}. + NOTE: this method requires NEURON >= 7.3 + """ + names = {} + for hvar in dir(self.h): # look through the whole list, no other way + try: + # some variables can't be pointed to... + if hvar in [ + "nseg", + "diam_changed", + "nrn_shape_changed_", + "secondorder", + "stoprun", + ]: + continue + u = getattr(self.h, hvar) + names[hvar] = u + except: + continue + return names + + def find_hoc_hname(self, regex): + """ + Find hoc names matching a pattern + + Parameters + ---------- + regex : str + Regular expression (Python Re module) to search for. + + Returns + ------- + list + The names of HOC objects whose *hname* matches regex. + """ + objs = [] + ns = self.hoc_namespace() + for n, v in ns.items(): + try: + hname = v.hname() + if re.match(regex, hname): + objs.append(n) + except: + continue + return objs + + def add_section_group(self, name, sections, overwrite=False): + """ + Declare a grouping of sections (or section names). Sections may be + grouped by any arbitrary criteria (cell, anatomical type, etc). + + Parameters + ---------- + name : str + name of the section group + sections: list + section names or hoc Section objects. + + """ + if name in self.sec_groups and not overwrite: + raise Exception( + "Group name %s is already used (use overwrite=True)." % name + ) + + group = set() + for sec in sections: + if not isinstance(sec, basestring): + sec = sec.name() + group.add(sec) + self.sec_groups[name] = group + + def get_section_group(self, name): + """ + Get a section group by name + Parameters + ---------- + name : str + name of the group (dendrite, for example) + + Returns + ------- + The set of section names in the group *name*. + + """ + return self.sec_groups[name] + + def get_section_lists(self): + """ + Search through all of the hoc variables to find those that are "SectionLists" + """ + return self.find_hoc_hname(regex=r"SectionList\[") + # ns = self.hoc_namespace() + # return [name for name in ns if ns[name].hname().startswith('SectionList[')] + + def add_groups_by_section_list(self, names): + """ + Add a new section groups from the hoc variables indicated in *names*. + + Parameters + ----------- + names : list + List containing variable names as strings. Each name must refer to a list of + Sections in hoc. If a dict is supplied instead, then it + maps {hoc_list_name: section_group_name}. + + Side effects (modifies) + ----------------------- + calls add_section_group + + """ + # if a list is supplied, then the names of groups to create are + # exactly the same as the names of hoc lists. + if not isinstance(names, dict): + names = {name: name for name in names} + for hoc_name, group_name in names.items(): + var = getattr(self.h, hoc_name) + self.add_section_group(group_name, list(var)) + + def get_geometry(self): + """ + modified from:neuronvisio + Generate structures that describe the geometry of the sections and their segments (all segments are returned) + + Returns + ------- + vertexes : record array containing {pos: (x,y,z), dia, sec_id} + for each segment. + edges : array of pairs indicating the indexes of connected + vertexes. + Side effects + ------------ + Modifies vertexes and edges. + + """ + + # return cached geometry if this method has already run. + if self.vertexes is not None: + return self.vertexes, self.edges + + self.h.define_shape() + + # map segments (lines) to the section that contains them + self.segment_to_section = {} + + vertexes = [] + connections = [] + + for secid, sec in enumerate(self.sections.values()): + x_sec, y_sec, z_sec, d_sec = self.retrieve_coordinate(sec) + + for i, xi in enumerate(x_sec): + vertexes.append(((x_sec[i], y_sec[i], z_sec[i]), d_sec[i], secid)) + indx_geom_seg = len(vertexes) - 1 + if len(vertexes) > 1 and i > 0: + connections.append([indx_geom_seg, indx_geom_seg - 1]) + + self.edges = np.array(connections) + self.vertexes = np.empty( + len(vertexes), dtype=[("pos", float, 3), ("dia", float), ("sec_index", int)] + ) + self.vertexes[:] = vertexes + return self.vertexes, self.edges + + def retrieve_coordinate(self, section): + """Retrieve the coordinates of a section avoiding duplicates + + Parameters + ---------- + section : :obj: `NEURON section` + The NEURON section object. + + Returns + ------- + array + arrays of x, y, z, d for all the segments of the specified section. + + """ + + section.push() + x, y, z, d = [], [], [], [] + + tot_points = 0 + connect_next = False + for i in range(int(self.h.n3d())): + present = False + x_i = self.h.x3d(i) + y_i = self.h.y3d(i) + z_i = self.h.z3d(i) + d_i = self.h.diam3d(i) + # Avoiding duplicates in the sec + if x_i in x: + ind = len(x) - 1 - x[::-1].index(x_i) # Getting the index of last value + if y_i == y[ind]: + if z_i == z[ind]: + present = True + + if not present: + k = (x_i, y_i, z_i) + x.append(x_i) + y.append(y_i) + z.append(z_i) + d.append(d_i) + self.h.pop_section() + return (np.array(x), np.array(y), np.array(z), np.array(d)) + + def _generate_topology(self): + for name, sec in self.sections.items(): + sref = self.h.SectionRef(sec=sec) + parent = sref.parent().sec.name() if sref.has_parent() else None + if name not in self.topology: + self.topology[name] = [None, []] + self.topology[name][0] = parent + if parent is not None: + if parent not in self.topology: + self.topology[parent] = [None, []] + self.topology[parent][1].append(name) + + def get_branch(self, root): + """ + Return all sections in a branch, starting with root. + + Parameters + ---------- + root : :obj: `NEURON section` + The NEURON section object. + + """ + branch = [root] + childs = [root] + while len(childs) > 0: + new_childs = [] + for ch in childs: + new_childs.extend(self.topology[ch][1]) + childs = new_childs + branch.extend(childs) + return branch + + def translate_branch(self, root, dx): + """ + Move the branch beginning at *root* by *dx*. + + Parameters + ---------- + root : :obj: `NEURON section` + The NEURON section object. + dx : array + Which must be an array of length 3 defining the translation. + + """ + self.get_geometry() + dx[np.newaxis, :] + for name in self.get_branch(root): + sid = self.sec_index[name] + mask = self.vertexes["sec_index"] == sid + self.vertexes["pos"][mask] += dx + + def make_volume_data(self, resolution=1.0, max_size=500e6): + """ + Using the current state of vertexes, edges, generates a scalar field + useful for building isosurface or volumetric renderings. + + Parameters + ---------- + resolution: float, default=1.0 microns + width (um) of a single voxel in the scalar field. + max_size: int + maximum allowed scalar field size (bytes). + Returns + ------- + * 3D scalar field indicating distance from nearest membrane, + * 3D field indicating section IDs of nearest membrane, + * QTransform that maps from 3D array indexes to original vertex + coordinates. + """ + vertexes, lines = self.get_geometry() + + maxdia = vertexes["dia"].max() # maximum diameter (defines shape of kernel) + kernel_size = int(maxdia / resolution) + 3 # width of kernel + + # read vertex data + pos = vertexes["pos"] + d = vertexes["dia"] + sec_id = vertexes["sec_index"] + + # decide on dimensions of scalar field + mx = pos.max(axis=0) + mn = pos.min(axis=0) + diff = mx - mn + shape = tuple((diff / resolution + kernel_size).astype(int)) + + # prepare blank scalar field for drawing + size = np.dtype(np.float32).itemsize * shape[0] * shape[1] * shape[2] + if size > max_size: + raise Exception( + "Scalar field would be larger than max_size (%dMB > %dMB), resolution is%f" + % (size / 1e6, max_size / 1e6, resolution) + ) + scfield = np.zeros(shape, dtype=np.float32) + scfield[:] = -1000 + + # array for holding IDs of sections that contribute to each area + idfield = np.empty(shape, dtype=int) + idfield[:] = -1 + + # map vertex locations to voxels + vox_pos = pos.copy() + vox_pos -= mn.reshape((1, 3)) + vox_pos *= 1.0 / resolution + + # Define kernel used to draw scalar field along dendrites + def cone(i, j, k): + # value decreases linearly with distance from center of kernel. + w = kernel_size / 2 + return w - ((i - w) ** 2 + (j - w) ** 2 + (k - w) ** 2) ** 0.5 + + kernel = resolution * np.fromfunction(cone, (kernel_size,) * 3) + kernel -= kernel.max() + + def array_intersection(arr1, arr2, pos): + """ + Return slices used to access the overlapping area between two + arrays that are offset such that the origin of *arr2* is a *pos* + relative to *arr1*. + """ + s1 = [0] * 3 + s2 = [0] * 3 + t1 = [0] * 3 + t2 = [0] * 3 + pos = map(int, pos) + for axis in range(3): + s1[axis] = max(0, -pos[axis]) + s2[axis] = min(arr2.shape[axis], arr1.shape[axis] - pos[axis]) + t1[axis] = max(0, pos[axis]) + t2[axis] = min(arr1.shape[axis], pos[axis] + arr2.shape[axis]) + slice1 = (slice(t1[0], t2[0]), slice(t1[1], t2[1]), slice(t1[2], t2[2])) + slice2 = (slice(s1[0], s2[0]), slice(s1[1], s2[1]), slice(s1[2], s2[2])) + return slice1, slice2 + + # Draw lines into volume using *kernel* as the brush + vox_pos[:, 0] = np.clip(vox_pos[:, 0], 0, scfield.shape[0] - 1) + vox_pos[:, 1] = np.clip(vox_pos[:, 1], 0, scfield.shape[1] - 1) + vox_pos[:, 2] = np.clip(vox_pos[:, 2], 0, scfield.shape[2] - 1) + for c in range(lines.shape[0]): + i = lines[c, 0] + j = lines[c, 1] + p1 = vox_pos[i].copy() + p2 = vox_pos[j].copy() + diff = p2 - p1 + axis = np.argmax(np.abs(diff)) + dia = d[i] + nvoxels = abs(int(diff[axis])) + 1 + for k in range(nvoxels): + kern = kernel + (dia / 2.0) + sl1, sl2 = array_intersection( + scfield, kern, p1 + ) # find the overlapping area between the field and the kernel + idfield[sl1] = np.where( + scfield[sl1] > kern[sl2], idfield[sl1], sec_id[i] + ) + scfield[sl1] = np.where( + scfield[sl1] > kern[sl2], scfield[sl1], kern[sl2] + ) + dia += (d[j] - d[i]) / nvoxels + p1 += diff / nvoxels + + # return transform relating volume data to original vertex data + transform = pg.Transform3D() + w = resolution * kernel_size / 2 # offset introduced due to kernel + transform.translate(*(mn - w)) + transform.scale(resolution, resolution, resolution) + transform.translate(1, 1, 1) + return scfield, idfield, transform diff --git a/cnmodel/morphology/morphology.py b/cnmodel/morphology/morphology.py new file mode 100644 index 0000000..2d1e1e7 --- /dev/null +++ b/cnmodel/morphology/morphology.py @@ -0,0 +1,31 @@ +class Morphology(object): + """ + Base class for morphological structure + Provides the ability to read .hoc files for NEURON simulations. + + """ + + def init(): + pass + + def hocReader(self, filename=None): + """ + Access the hoc reader + + Parameters + ---------- + filename : str (default: None) + The hoc file to read and save as the morphology object + """ + self.morphology = hoc_reader(hoc=filename) + + def swcReader(self, filename=None): + """ + Access the swc reader (***NOT IMPLEMENTED***) + + Parameters + ---------- + filename : str (default: None) + The swc file to read and save as the morphology object + """ + raise ValueError("swcReader not implmented.") diff --git a/cnmodel/morphology/octopus_spencer_stick.hoc b/cnmodel/morphology/octopus_spencer_stick.hoc new file mode 100644 index 0000000..9712bdf --- /dev/null +++ b/cnmodel/morphology/octopus_spencer_stick.hoc @@ -0,0 +1,76 @@ +// Octopus cell, stick representation +// From Spencer et al., Front. Comput. Neurosci., 22 October 2012 | https://doi.org/10.3389/fncom.2012.00083 +// Figure 1. + +objref soma +soma = new SectionList() +objref primarydendrite +primarydendrite = new SectionList() +objref hillock +hillock = new SectionList() +objref unmyelinatedaxon +unmyelinatedaxon = new SectionList() + +create sections[7] + +access sections[0] +soma.append() +sections[0] { + pt3dadd(0., 0., 0., 25.) + pt3dadd(0., 25., 0., 25.) +} + +// axon hillock, 30 microns long, untapered +access sections[1] +hillock.append() +connect sections[1](0), sections[0](0) +sections[1] { + pt3dadd(0., 0., 0., 3) + pt3dadd(0., -30., 0., 3) +} + +// initial segment, unmyelinated, 10 microns long, not tapering +access sections[2] +unmyelinatedaxon.append() +connect sections[2](0), sections[1](1) +sections[2] { + pt3dadd(0., -30., 0., 3.0) + pt3dadd(0., -32., 0., 3.0) +} + +// angle dendrites out a bit from original model for visibility, so +// length for 20 u end deviation is 279.285 um, end pos 304.285 + +access sections[3] +primarydendrite.append() +connect sections[3](0), sections[0](1) +sections[3] { + pt3dadd(0., 25., 0., 3) + pt3dadd(20., 304.285, 0., 3) +} + +access sections[4] +primarydendrite.append() +connect sections[4](0), sections[0](1) +sections [4] { + pt3dadd(0., 25., 0., 3) + pt3dadd(0., 304.285, 20., 3) +} + +access sections[5] +primarydendrite.append() +connect sections[5](0), sections[0](1) +sections [5] { + pt3dadd(0., 25., 0., 3) + pt3dadd(-20., 304.285, 0., 3) +} + +access sections[6] +primarydendrite.append() +connect sections[6](0), sections[0](1) +sections [6] { + pt3dadd(0., 25., 0., 3) + pt3dadd(0., 304.285, -20., 3) +} + + diff --git a/cnmodel/morphology/tstellate_stick.hoc b/cnmodel/morphology/tstellate_stick.hoc new file mode 100644 index 0000000..f4ff679 --- /dev/null +++ b/cnmodel/morphology/tstellate_stick.hoc @@ -0,0 +1,82 @@ +objref soma +soma = new SectionList() +objref primarydendrite +primarydendrite = new SectionList() +objref secondarydendrite +secondarydendrite = new SectionList() +objref hillock +hillock = new SectionList() +objref unmyelinatedaxon +unmyelinatedaxon = new SectionList() +objref myelinatedaxon +myelinatedaxon = new SectionList() + +create sections[8] +access sections[0] +soma.append() +sections[0] { + pt3dadd(0., 0., 0., 25.) + pt3dadd(0., 25., 0., 25.) +} + +// axon hillock, 15 microns long, tapered +access sections[1] +hillock.append() +connect sections[1](0), sections[0](0) +sections[1] { + pt3dadd(0., 0., 0., 2.5) + pt3dadd(0., -15., 0., 1.0) +} + +// initial segment, unmyelinated, 10 microns long, not tapering +access sections[2] +unmyelinatedaxon.append() +connect sections[2](0), sections[1](1) +sections[2] { + pt3dadd(0., -15., 0., 1.0) + pt3dadd(0., -25., 0., 1.0) + +} + +// beginning of myelinated axon, 20 micron, enlarging with distance +access sections[3] +myelinatedaxon.append() +connect sections[3](0), sections[2](1) +sections[3] { + pt3dadd(0., -25., 0., 1.0) + pt3dadd(0., -45., 0., 2.0) + +} + +access sections[4] +primarydendrite.append() +connect sections[4](0), sections[0](1) +sections[4] { + pt3dadd(0., 25., 0., 2) + pt3dadd(125., 25., 25., 1.5) +} + +access sections[5] +primarydendrite.append() +connect sections[5](0), sections[0](1) +sections [5] { + pt3dadd(0., 25., 0., 2.0) + pt3dadd(-125., 25., 25., 1.5) +} + +access sections[6] +primarydendrite.append() +connect sections[6](0), sections[0](1) +sections [6] { + pt3dadd(0., 25., 0., 2.0) + pt3dadd(125, 25., -25., 1.5) +} + +access sections[7] +primarydendrite.append() +connect sections[7](0), sections[0](1) +sections [7] { + pt3dadd(0., 25., 0., 2.0) + pt3dadd(-125., 25., -25., 1.5) +} + diff --git a/cnmodel/morphology/tv_stick.hoc b/cnmodel/morphology/tv_stick.hoc new file mode 100644 index 0000000..deb10e4 --- /dev/null +++ b/cnmodel/morphology/tv_stick.hoc @@ -0,0 +1,32 @@ +objref soma +soma = new SectionList() +objref axon +axon = new SectionList() +objref dendrite +dendrite = new SectionList() + +create sections[3] +access sections[0] +soma.append() +sections[0] { + pt3dadd(0., 0., 0., 25.) + pt3dadd(0., 25., 0., 25.) +} + +access sections[1] +dendrite.append() +connect sections[1](0), sections[0](1) +sections[1] { + pt3dadd(0., 25., 0., 1.5) + pt3dadd(0., 220., 50., 1.5) +} + +access sections[2] +dendrite.append() +connect sections[2](0), sections[0](1) +sections[2] { + pt3dadd(0., 25., 0., 1.5) + pt3dadd(0., 220., -50., 1.5) +} + + diff --git a/cnmodel/populations/__init__.py b/cnmodel/populations/__init__.py new file mode 100644 index 0000000..5a22417 --- /dev/null +++ b/cnmodel/populations/__init__.py @@ -0,0 +1,13 @@ +""" +Definitions of cell populations for each cell type. + + +""" + +from .population import Population +from .bushy import Bushy +from .tstellate import TStellate +from .dstellate import DStellate +from .pyramidal import Pyramidal +from .tuberculoventral import Tuberculoventral +from .sgc import SGC diff --git a/cnmodel/populations/bushy.py b/cnmodel/populations/bushy.py new file mode 100644 index 0000000..99ebadc --- /dev/null +++ b/cnmodel/populations/bushy.py @@ -0,0 +1,58 @@ +import scipy.stats +import numpy as np + +from .population import Population +from .. import cells + + +class Bushy(Population): + """Population of bushy cells. + + Cells are distributed uniformly from 2kHz to 64kHz. + + Note that `cf` is the mean value used when selecting SGCs to connect; + it is NOT the measured CF of the cell (although it should be close). + """ + + type = "bushy" + + def __init__(self, species="mouse", **kwds): + freqs = self._get_cf_array(species) + fields = [ + ("cf", float), + ("input_sr", list), # distribution probability of SGC SR groups + ("sr", int), + ] + super(Bushy, self).__init__(species, len(freqs), fields=fields, **kwds) + self._cells["cf"] = freqs + self._cells["input_sr"] = [np.tile([1.0, 1.0, 1.0], len(freqs))] + + def create_cell(self, cell_rec): + """ Return a single new cell to be used in this population. The + *cell_rec* argument is the row from self.cells that describes the cell + to be created. + """ + return cells.Bushy.create(species=self.species, **self._cell_args) + + def connection_stats(self, pop, cell_rec): + """ The population *pop* is being connected to the cell described in + *cell_rec*. Return the number of presynaptic cells that should be + connected and a dictionary of distributions used to select cells + from *pop*. + """ + size, dist = Population.connection_stats(self, pop, cell_rec) + + from .. import populations + + if isinstance(pop, populations.SGC): + # only select SGC inputs from a single SR group + # (this relationship is hypothesized based on reconstructions of + # endbulbs) + sr_vals = pop.cells["sr"] + u = np.random.choice(sr_vals) # assign input sr for this cell + # print('u: ', u) + # pick from one sr group for all inputs, with prob same as distribution in nerve + dist["sr"] = (sr_vals == u).astype(float) + self._cells["sr"] = u + + return size, dist diff --git a/cnmodel/populations/dstellate.py b/cnmodel/populations/dstellate.py new file mode 100644 index 0000000..246e8ea --- /dev/null +++ b/cnmodel/populations/dstellate.py @@ -0,0 +1,42 @@ +import scipy.stats +import numpy as np + +from .population import Population +from .. import cells + + +class DStellate(Population): + type = "dstellate" + + def __init__(self, species="mouse", **kwds): + # Note that `cf` is the mean value used when selecting SGCs to connect; + # it is NOT the measured CF of the cell (although it should be close). + freqs = self._get_cf_array(species) + fields = [ + ("cf", float), + ("input_sr", list), # distribution probability of SGC SR groups + ] + super(DStellate, self).__init__(species, len(freqs), fields=fields, **kwds) + self._cells["cf"] = freqs + self._cells["input_sr"] = [np.tile([1.0, 1.0, 1.0], len(freqs))] + + def create_cell(self, cell_rec): + """ Return a single new cell to be used in this population. The + *cell_rec* argument is the row from self.cells that describes the cell + to be created. + """ + return cells.DStellate.create(species=self.species, **self._cell_args) + + def connection_stats(self, pop, cell_rec): + """ The population *pop* is being connected to the cell described in + *cell_rec*. Return the number of presynaptic cells that should be + connected and a dictionary of distributions used to select cells + from *pop*. + """ + size, dist = Population.connection_stats(self, pop, cell_rec) + + from .. import populations + + if isinstance(pop, populations.SGC): + dist["sr"] = (pop.cells["sr"] < 2).astype(float) + return size, dist diff --git a/cnmodel/populations/population.py b/cnmodel/populations/population.py new file mode 100644 index 0000000..5e2c6b7 --- /dev/null +++ b/cnmodel/populations/population.py @@ -0,0 +1,443 @@ +import logging +import scipy.stats +import numpy as np + +from .. import data + + +class Population(object): + """ + A Population represents a group of cell all having the same type. + + Populations provide methods for: + + * Adding cells to the population with characteristic distributions. + * Connecting the cells in one population to the cells in another. + * Automatically adding cells to satisfy connectivity requirements when + connecting populations together. + + Populations have a concept of a "natural" underlying distribution of + neurons, and behave as if all neurons in this distribution already exist + in the model. However, initially all neurons are virtual, and are only + instantiated to become a part of the running model if the neuron provides + synaptic input to another non-virtual neuron, or if the user explicitly + requests a recording of the neuron. + + Subclasses represent populations for a specific cell type, and at least + need to reimplement the `create_cell` and `connection_stats` methods. + """ + + def __init__(self, species, size, fields, synapsetype="multisite", **kwds): + self._species = species + self._post_connections = [] # populations this one connects to + self._pre_connections = [] # populations connecting to this one + self._synapsetype = synapsetype + # numpy record array with information about each cell in the + # population + fields = [ + ("id", int), + ("cell", object), + ("input_resolved", bool), + ("connections", object), # {pop: [cells], ...} + ] + fields + self._cells = np.zeros(size, dtype=fields) + self._cells["id"] = np.arange(size) + self._cell_indexes = {} # maps cell:index + self._cell_args = kwds + + @property + def cells(self): + """ The array of cells in this population. + + For all populations, this array has a 'cell' field that is either 0 + (for virtual cells) or a Cell instance (for real cells). + + Extra fields may be added by each Population subclass. + """ + return self._cells.copy() + + @property + def species(self): + return self._species + + def unresolved_cells(self): + """ Return indexes of all real cells whose inputs have not been + resolved. + """ + real = self._cells["cell"] != 0 + unresolved = self._cells["input_resolved"] == False + return np.argwhere(real & unresolved)[:, 0] + + def real_cells(self): + """ Return indexes of all real cells in this population. + + Initially, all cells in the population are virtual--they are accounted + for, but not actually instantiated as part of the NEURON simulation. + Virtual cells can be made real by calling `get_cell()`. This method + returns the indexes of all cells for which `get_cell()` has already + been invoked. + """ + return np.argwhere(self._cells["cell"] != 0)[:, 0] + + def connect(self, *pops): + """ Connect this population to any number of other populations. + + A connection is unidirectional; calling ``pop1.connect(pop2)`` can only + result in projections from pop1 to pop2. + + Note that the connection is purely symbolic at first; no cells are + actually connected by synapses at this time. + """ + self._post_connections.extend(pops) + for pop in pops: + pop._pre_connections.append(self) + + @property + def pre_connections(self): + """ The list of populations connected to this one. + """ + return self._pre_connections[:] + + def cell_connections(self, index): + """ Return a dictionary containing, for each population, a list of + cells connected to the cell in this population at *index*. + """ + return self._cells[index]["connections"] + + def resolve_inputs(self, depth=1, showlog=False): + """ For each _real_ cell in the population, select a set of + presynaptic partners from each connected population and generate a + synapse from each. + + Although it is allowed to call ``resolve_inputs`` multiple times for + a single population, each individual cell will only resolve its inputs + once. Therefore, it is recommended to create and connect all + populations before making any calls to ``resolve_inputs``. + """ + for i in self.unresolved_cells(): + # loop over all cells whose presynaptic inputs have not been resolved + cell = self._cells[i]["cell"] + if showlog: + logging.info("Resolving inputs for %s %d", self, i) + self._cells[i]["connections"] = {} + + # select cells from each population to connect to this cell + for pop in self._pre_connections: + pre_cells = self.connect_pop_to_cell(pop, i) + if showlog: + logging.info(" connected %d cells from %s", len(pre_cells), pop) + assert pre_cells is not None + self._cells[i]["connections"][pop] = pre_cells + self._cells[i]["input_resolved"] = True + + # recursively resolve inputs in connected populations + if depth > 1: + for pop in self.pre_connections: + pop.resolve_inputs(depth - 1, showlog=showlog) + + def connect_pop_to_cell(self, pop, cell_index): + """ Connect cells in a presynaptic population to the cell in this + population at *cell_index*, and return the presynaptic indexes of cells + that were connected. + + This method is responsible for choosing pairs of cells to be connected + by synapses, and may be overridden in subclasses. + + The default implementation calls `self.connection_stats()` to determine + the number and selection criteria of presynaptic cells. + """ + cell_rec = self._cells[cell_index] + cell = cell_rec["cell"] + size, dist = self.connection_stats(pop, cell_rec) + # Select SGCs from distribution, create, and connect to this cell + # todo: select sgcs with similar spont. rate? + pre_cells = pop.select(size=size, create=False, **dist) + for j in pre_cells: + pre_cell = pop.get_cell(j) + # use default settings for connecting these. + pre_cell.connect(cell, type=self._synapsetype) + return pre_cells + + def connection_stats(self, pop, cell_rec): + """ The population *pop* is being connected to the cell described in + *cell_rec*. + + This method is responsible for deciding the distributions of presynaptic + cell properties for any given postsynaptic cell (for example, a cell + with cf=10kHz might receive SGC input from 10 cells selected from a + normal distribution centered at 10kHz). + + The default implementation of this method uses the 'convergence' and + 'convergence_range' values from the data tables to specify a lognormal + distribution of presynaptic cells around the postsynaptic cell's CF. + + This method must return a tuple (size, dist) with the following values: + + * size: integer giving the number of cells that should be selected from + the presynaptic population and connected to the postsynaptic cell. + * dist: dictionary of {property_name: distribution} pairs that describe + how cells should be selected from the presynaptic population. See + keyword arguments to `select()` for more information on the content + of this dictionary. + """ + cf = cell_rec["cf"] + + # Convergence distributions (how many presynaptic + # cells to connect) + try: + n_connections = data.get( + "convergence", + species=self.species, + pre_type=pop.type, + post_type=self.type, + ) + except KeyError: + raise TypeError( + "Cannot connect population %s to %s; no convergence specified in data table." + % (pop, self) + ) + + if isinstance(n_connections, tuple): + size_dist = scipy.stats.norm(loc=n_connections[0], scale=n_connections[1]) + size = max(0, size_dist.rvs()) + else: + size = n_connections + size = int(size) # must be an integer at this point + + # Convergence ranges -- over what range of CFs should we + # select presynaptic cells. + try: + input_range = data.get( + "convergence_range", + species=self.species, + pre_type=pop.type, + post_type=self.type, + ) + except KeyError: + raise TypeError( + "Cannot connect population %s to %s; no convergence range specified in data table." + % (pop, self) + ) + + dist = {"cf": scipy.stats.lognorm(input_range, scale=cf)} + # print(cf, input_range, dist) + return size, dist + + def get_sgcsr_array(self, freqs, species="mouse"): + """ + Create an array of length (freqs) (number of SGCs) + Each entry is a value indicating the SR group, according to some proportion + 2 = high, 1 = medium, 0 = low + + Parameters + ---------- + freqs : nunpy array + + species : str (default: 'mouse') + name of the species for the map. + + Returns: + numpy array + An array matched to freqs, with SR's indicated numerically + """ + assert species == "mouse" # only mice so far. + nhs = np.random.random_sample( + freqs.shape[0] + ) # uniform random distribution across frequency + sr_array = np.zeros_like(freqs) # build array - initially all low sponts + sr_array[ + np.argwhere(nhs < 0.53) + ] = 2 # high spont (53% estimated from Taberner and Liberman, 2005) + sr_array[ + np.argwhere((nhs >= 0.53) & (nhs < 0.77)) + ] = 1 # medium spont, about 24% (1-20 sp/sec) + # the rest have SR value of 0, corresponding to the low-spont group + return sr_array + + def select_sgcsr_inputs(self, sr_array, weights): + """ + Subsample the arrays above to create a distribution for cells that might only get + a subset of inputs (for example, only msr and lsr fibers) + + Parameters + ---------- + sr_array : numpy array + the SR array to draw the samples from + + weights : 3 element list + Weights for [lsr, msr, hsr] ANFs. Proportions will be computed + from these weights (e.g., [1,1,1] is uniform for all fibers) + weights of [1,1,0] means all hsr fibers will be masked + + Returns: + numpy array of "dist" + Values of 0 are sgcs masked from input, 1 are ok + """ + assert len(weights) == 3 + + dist = np.zeros_like(sr_array) # boolean array, all values + norm_wt = 3.0 * np.array( + weights / np.sum(weights) + ) # fraction from within each group + for i in range(len(weights)): + dx = np.where(sr_array == i)[0] + ind = np.random.choice(len(dx), int(norm_wt[i] * len(dx))) + dist[dx[ind]] = 1 + return dist + + def _get_cf_array(self, species): + """Return the array of CF values that should be used when instantiating + this population. + + Commonly used by subclasses durin initialization. + """ + size = data.get( + "populations", species=species, cell_type=self.type, field="n_cells" + ) + fmin = data.get( + "populations", species=species, cell_type=self.type, field="cf_min" + ) + fmax = data.get( + "populations", species=species, cell_type=self.type, field="cf_max" + ) + s = (fmax / fmin) ** (1.0 / size) + freqs = fmin * s ** np.arange(size) + # print('frqs #: ', len(freqs)) + # Cut off at 40kHz because the auditory nerve model only goes that far :( + freqs = freqs[freqs <= 40e3] + + return freqs + + def select(self, size, create=False, **kwds): + """ Return a list of indexes for cells matching the selection criteria. + + The *size* argument specifies the number of cells to return. + + If *create* is True, then any selected cells that are virtual will be + instantiated. + + Each keyword argument must be the name of a field in self.cells. Values + may be: + + * A distribution (see scipy.stats), in which case the distribution + influences the selection of cells + * An array giving the probability to assign to each cell in the + population + * A number, in which case the cell(s) with the closest match + are returned. If this is used, it overrides all other criteria except + where they evaluate to 0. + + If multiple distributions are provided, then the product of the survival + functions of all distributions determines the probability of selecting + each cell. + """ + if len(kwds) == 0: + raise TypeError("Must specify at least one selection criteria") + + full_dist = np.ones(len(self._cells)) + nearest = None + nearest_field = None + for field, dist in kwds.items(): + if np.isscalar(dist): + if nearest is not None: + raise Exception( + "May not specify multiple single-valued selection criteria." + ) + nearest = dist + nearest_field = field + elif isinstance(dist, scipy.stats.distributions.rv_frozen): + vals = self._cells[field] + dens = np.diff(vals) + dens = np.concatenate([dens[:1], dens]) + pdf = dist.pdf(vals) * dens + full_dist *= pdf / pdf.sum() + elif isinstance(dist, np.ndarray): + full_dist *= dist + else: + raise TypeError("Distributed criteria must be array or rv_frozen.") + + # Select cells nearest to the requested value, but only pick from + # cells with nonzero probability. + if nearest is not None: + cells = [] + mask = full_dist == 0 + err = np.abs(self._cells[nearest_field] - nearest).astype(float) + for i in range(size): + err[mask] = np.inf + cell = np.argmin(err) + mask[cell] = True + cells.append(cell) + + # Select cells randomly from the specified combined probability + # distribution + else: + cells = [] + full_dist /= full_dist.sum() + vals = np.random.uniform(size=size) + vals.sort() + cumulative = np.cumsum(full_dist) + for val in vals: + u = np.argwhere(cumulative >= val) + if len(u) > 0: + cell = u[0, 0] + cells.append(cell) + if create: + self.create_cells(cells) + + return cells + + def get_cell(self, i, create=True): + """ Return the cell at index i. If the cell is virtual, then it will + be instantiated first unless *create* is False. + """ + if create and self._cells[i]["cell"] == 0: + self.create_cells([i]) + return self._cells[i]["cell"] + + def get_cell_index(self, cell): + """Return the index of *cell*. + """ + return self._cell_indexes[cell] + + def create_cells(self, cell_inds): + """ Instantiate each cell in *cell_inds*, which is a list of indexes into + self.cells. + """ + for i in cell_inds: + if self._cells[i]["cell"] != 0: + continue + cell = self.create_cell(self._cells[i]) + self._cells[i]["cell"] = cell + self._cell_indexes[cell] = i + + def create_cell(self, cell_rec): + """ Return a single new cell to be used in this population. The + *cell_rec* argument is the row from self.cells that describes the cell + to be created. + + Subclasses must reimplement this method. + """ + raise NotImplementedError() + + def __str__(self): + return "" % ( + type(self).__name__, + (self._cells["cell"] != 0).sum(), + len(self._cells), + ) + + def __getstate__(self): + """Return a picklable copy of self.__dict__. + + Note that we remove references to the actual cells in order to allow pickling. + """ + state = self.__dict__.copy() + state["_cells"] = state["_cells"].copy() + + for cell in state["_cells"]: + if cell["cell"] != 0: + cell["cell"] = cell[ + "cell" + ].type # replace neuron object with just the cell type + cell = str(cell) # make a string + return state diff --git a/cnmodel/populations/pyramidal.py b/cnmodel/populations/pyramidal.py new file mode 100644 index 0000000..a8306cc --- /dev/null +++ b/cnmodel/populations/pyramidal.py @@ -0,0 +1,26 @@ +import scipy.stats +import numpy as np + +from .population import Population +from .. import cells + + +class Pyramidal(Population): + type = "pyramidal" + + def __init__( + self, species="mouse", **kwds + ): # ***** NOTE Species - no direct data for mouse (uses RAT data) + # Note that `cf` is the mean value used when selecting SGCs to connect; + # it is NOT the measured CF of the cell (although it should be close). + freqs = self._get_cf_array(species) + fields = [("cf", float)] + super(Pyramidal, self).__init__(species, len(freqs), fields=fields, **kwds) + self._cells["cf"] = freqs + + def create_cell(self, cell_rec): + """ Return a single new cell to be used in this population. The + *cell_rec* argument is the row from self.cells that describes the cell + to be created. + """ + return cells.Pyramidal.create(species=self.species, **self._cell_args) diff --git a/cnmodel/populations/sgc.py b/cnmodel/populations/sgc.py new file mode 100644 index 0000000..f526acd --- /dev/null +++ b/cnmodel/populations/sgc.py @@ -0,0 +1,87 @@ +import logging +import numpy as np +import pyqtgraph.multiprocess as mp + +from .population import Population +from .. import cells + + +class SGC(Population): + """A population of spiral ganglion cells. + + The cell distribution is uniform from 2kHz to 64kHz, evenly divided between + spontaneous rate groups. + """ + + type = "sgc" + + def __init__(self, species="mouse", model="dummy", **kwds): + # Completely fabricated cell distribution: uniform from 2kHz to 40kHz, + # evenly divided between SR groups. We only go up to 40kHz because the + # auditory periphery model does not support >40kHz. + freqs = self._get_cf_array(species) + fields = [("cf", float), ("sr", int)] # 0=low sr, 1=mid sr, 2=high sr + super(SGC, self).__init__( + species, len(freqs), fields=fields, model=model, **kwds + ) + self._cells["cf"] = freqs + # old version: + # evenly distribute SR groups + # self._cells['sr'] = np.arange(len(freqs)) % 3 + # new version: + # draw from distributions matching approximate SR distribution + sr_vals = self.get_sgcsr_array(freqs, species="mouse") + self._cells["sr"] = sr_vals + + def set_seed(self, seed): + self.next_seed = seed + + def create_cell(self, cell_rec): + """ Return a single new cell to be used in this population. The + *cell_rec* argument is the row from self.cells that describes the cell + to be created. + """ + return cells.SGC.create( + species=self.species, + cf=cell_rec["cf"], + sr=cell_rec["sr"], + **self._cell_args + ) + + def connect_pop_to_cell(self, pop, index): + # SGC does not support any inputs + assert len(self.connections) == 0 + + def set_sound_stim(self, stim, parallel=False): + """Set a sound stimulus to generate spike trains for all (real) cells + in this population. + """ + real = self.real_cells() + logging.info("Assigning spike trains to %d SGC cells..", len(real)) + if not parallel: + for i, ind in enumerate(real): + # logging.info("Assigning spike train to SGC %d (%d/%d)", ind, i, len(real)) + cell = self.get_cell(ind) + cell.set_sound_stim(stim, self.next_seed) + self.next_seed += 1 + + else: + seeds = range(self.next_seed, self.next_seed + len(real)) + self.next_seed = seeds[-1] + 1 + tasks = zip(seeds, real) + trains = [None] * len(tasks) + # generate spike trains in parallel + with mp.Parallelize( + enumerate(tasks), + trains=trains, + progressDialog="Generating SGC spike trains..", + ) as tasker: + for i, x in tasker: + seed, ind = x + cell = self.get_cell(ind) + train = cell.generate_spiketrain(stim, seed) + tasker.trains[i] = train + # collected all trains; now assign to cells + for i, ind in enumerate(real): + cell = self.get_cell(ind) + cell.set_spiketrain(trains[i]) diff --git a/cnmodel/populations/tstellate.py b/cnmodel/populations/tstellate.py new file mode 100644 index 0000000..a6ffcfc --- /dev/null +++ b/cnmodel/populations/tstellate.py @@ -0,0 +1,43 @@ +import scipy.stats +import numpy as np + +from .population import Population +from .. import cells + + +class TStellate(Population): + type = "tstellate" + + def __init__(self, species="mouse", **kwds): + # Note that `cf` is the mean value used when selecting SGCs to connect; + # it is NOT the measured CF of the cell (although it should be close). + freqs = self._get_cf_array(species) + fields = [("cf", float), ("input_sr", list)] + super(TStellate, self).__init__(species, len(freqs), fields=fields, **kwds) + self._cells["cf"] = freqs + self._cells["input_sr"] = [np.tile([1.0, 1.0, 1.0], len(freqs))] + + def create_cell(self, cell_rec): + """ Return a single new cell to be used in this population. The + *cell_rec* argument is the row from self.cells that describes the cell + to be created. + """ + return cells.TStellate.create(species=self.species, **self._cell_args) + + def connection_stats(self, pop, cell_rec): + """ The population *pop* is being connected to the cell described in + *cell_rec*. Return the number of presynaptic cells that should be + connected and a dictionary of distributions used to select cells + from *pop*. + """ + size, dist = Population.connection_stats(self, pop, cell_rec) + + from .. import populations + + if isinstance(pop, populations.SGC): + # Select SGC inputs from a all SR groups + sr_vals = pop.cells["sr"] + # print('SRs for TS: ', np.bincount(sr_vals)/sr_vals.shape[0], np.unique(sr_vals)) + dist["sr"] = (sr_vals < 3).astype(float) + + return size, dist diff --git a/cnmodel/populations/tuberculoventral.py b/cnmodel/populations/tuberculoventral.py new file mode 100644 index 0000000..c9cc753 --- /dev/null +++ b/cnmodel/populations/tuberculoventral.py @@ -0,0 +1,46 @@ +import scipy.stats +import numpy as np + +from .population import Population +from .. import cells + + +class Tuberculoventral(Population): + type = "tuberculoventral" + + def __init__(self, species="mouse", **kwds): + # Note that `cf` is the mean value used when selecting SGCs to connect; + # it is NOT the measured CF of the cell (although it should be close). + freqs = self._get_cf_array(species) + fields = [("cf", float), ("input_sr", list)] + super(Tuberculoventral, self).__init__( + species, len(freqs), fields=fields, **kwds + ) + self._cells["cf"] = freqs + self._cells["input_sr"] = [np.tile([1.0, 1.0, 1.0], len(freqs))] + + def create_cell(self, cell_rec): + """ Return a single new cell to be used in this population. The + *cell_rec* argument is the row from self.cells that describes the cell + to be created. + """ + return cells.Tuberculoventral.create(species=self.species, **self._cell_args) + + def connection_stats(self, pop, cell_rec): + """ The population *pop* is being connected to the cell described in + *cell_rec*. Return the number of presynaptic cells that should be + connected and a dictionary of distributions used to select cells + from *pop*. + """ + size, dist = Population.connection_stats(self, pop, cell_rec) + + from .. import populations + + if isinstance(pop, populations.SGC): + # only select SGC inputs from low- and medium SR. See: + # Spectral Integration by Type II Interneurons in Dorsal Cochlear Nucleus + # George A. Spirou, Kevin A. Davis, Israel Nelken, Eric D. Young + # Journal of Neurophysiology Aug 1999, 82 (2) 648-663; + dist["sr"] = (pop.cells["sr"] < 2).astype(float) + + return size, dist diff --git a/cnmodel/protocols/__init__.py b/cnmodel/protocols/__init__.py new file mode 100644 index 0000000..695ce44 --- /dev/null +++ b/cnmodel/protocols/__init__.py @@ -0,0 +1,7 @@ +from .iv_curve import IVCurve +from .vc_curve import VCCurve +from .cc import CurrentClamp +from .synapse_test import SynapseTest +from .simple_synapse_test import SimpleSynapseTest +from .protocol import Protocol +from .population_test import PopulationTest diff --git a/cnmodel/protocols/cc.py b/cnmodel/protocols/cc.py new file mode 100644 index 0000000..84f9463 --- /dev/null +++ b/cnmodel/protocols/cc.py @@ -0,0 +1,91 @@ +from neuron import h +import numpy as np +import scipy +import scipy.integrate +import scipy.stats + +try: + import pyqtgraph as pg + + HAVE_PG = True +except ImportError: + HAVE_PG = False + +from ..util.stim import make_pulse +from .protocol import Protocol + + +class CurrentClamp(Protocol): + def __init__(self): + super(CurrentClamp, self).__init__() + + def run(self, cell, cmd, temp=22, dt=0.025): + """ + Run a single current-clamp recording on *section*. + + Parameters + ---------- + cell : Cell + The Cell instance to test. IClamp will be attached to + cell.soma(0.5). + cmd : array + Array of current command values + temp : + temperature of simulation (22) + dt : + timestep of simulation (0.025) + """ + self.reset() + self.cell = cell + self.current_cmd = cmd + self.dt = dt + self.temp = temp + + tend = len(cmd) * dt + + # Configure IClamp + istim = h.iStim(0.5, sec=cell.soma) + istim.delay = 0 + istim.dur = 1e9 # these actually do not matter... + istim.iMax = 0.0 + i_stim = h.Vector(cmd) + i_stim.play(istim._ref_i, h.dt, 0) + + # Connect recording vectors + self["vm"] = cell.soma(0.5)._ref_v + self["i_inj"] = istim._ref_i + self["time"] = h._ref_t + + # GO + h.dt = dt + h.celsius = temp + h.tstop = tend + cell.initialize() + h.frecord_init() + while h.t < h.tstop: + h.fadvance() + + def show(self): + """ + Plot results from run() + """ + if not HAVE_PG: + raise Exception("Requires pyqtgraph") + + # + # Generate figure with subplots + # + app = pg.mkQApp() + win = pg.GraphicsWindow() + win.resize(1000, 800) + Vplot = win.addPlot(labels={"left": "Vm (mV)", "bottom": "Time (ms)"}) + win.nextRow() + Iplot = win.addPlot(labels={"left": "Iinj (nA)", "bottom": "Time (ms)"}) + + win.ci.layout.setRowStretchFactor(0, 10) + win.ci.layout.setRowStretchFactor(1, 5) + + Vplot.plot(self["time"], self["vm"]) + Iplot.plot(self["time"], self["i_inj"]) + + self.win = win diff --git a/cnmodel/protocols/democlamp.py b/cnmodel/protocols/democlamp.py new file mode 100644 index 0000000..44ee512 --- /dev/null +++ b/cnmodel/protocols/democlamp.py @@ -0,0 +1,185 @@ +import os +import os.path +from neuron import h +import pylibrary.Utility as U +from ..util import PlotHelpers as PH +import numpy as np +import scipy +import scipy.integrate +import scipy.stats + +try: + import pyqtgraph as pg + + HAVE_PG = True +except ImportError: + HAVE_PG = False + +from ..util.stim import make_pulse + +# import matplotlib as MP # must call first... before pylag/pyplot or backends +# MP.use('Qt4Agg') + +# import matplotlib.gridspec as GS +# import mpl_toolkits.axes_grid1.inset_locator as INSETS +# import mpl_toolkits.axes_grid1.anchored_artists as ANCHOR + +# stdFont = 'Arial' +# import matplotlib.pyplot as pylab +# pylab.rcParams['interactive'] = False +# pylab.rcParams['mathtext.default'] = 'sf' +## next setting allows pdf font to be readable in Adobe Illustrator +# pylab.rcParams['pdf.fonttype'] = 42 +# pylab.rcParams['figure.facecolor'] = 'white' + + +def run_democlamp(cell, dend, vsteps=[-60, -70, -60], tsteps=[10, 50, 100]): + """ + Does some stuff. + + """ + f1 = pylab.figure(1) + gs = GS.GridSpec(2, 2, width_ratios=[1, 1], height_ratios=[1, 1]) + + # note numbering for insets goes from 1 (upper right) to 4 (lower right) + # counterclockwise + pA = f1.add_subplot(gs[0]) + pAi = INSETS.inset_axes(pA, width="66%", height="40%", loc=2) + pB = f1.add_subplot(gs[1]) + pBi = INSETS.inset_axes(pB, width="66%", height="40%", loc=4) + pC = f1.add_subplot(gs[2]) + pCi = INSETS.inset_axes(pC, width="66%", height="40%", loc=2) + pD = f1.add_subplot(gs[3]) + pDi = INSETS.inset_axes(pD, width="66%", height="40%", loc=1) + # h.topology() + + Ld = 0.5 + Ld2 = 1.0 + + VClamp = h.SEClamp(0.5, cell) + VClamp.dur1 = tsteps[0] + VClamp.amp1 = vsteps[0] + VClamp.dur2 = tsteps[1] + VClamp.amp2 = vsteps[1] + VClamp.dur3 = tsteps[2] + VClamp.amp3 = vsteps[2] + Rs0 = 10.0 + VClamp.rs = Rs0 + compensation = [0.0, 70.0, 95.0] + cms = [cell.cm * (100.0 - c) / 100.0 for c in compensation] + + vrec = h.iStim(Ld, sec=dend[0]) + vrec.delay = 0 + vrec.dur = 1e9 # these actually do not matter... + vrec.iMax = 0.0 + vrec2 = h.iStim(Ld2, sec=dend[0]) + vrec2.delay = 0 + vrec2.dur = 1e9 # these actually do not matter... + vrec2.iMax = 0.0 + + stim = {} + stim["NP"] = 1 + stim["Sfreq"] = 20 # stimulus frequency + stim["delay"] = tsteps[0] + stim["dur"] = tsteps[1] + stim["amp"] = vsteps[1] + stim["PT"] = 0.0 + stim["hold"] = vsteps[0] + # (secmd, maxt, tstims) = make_pulse(stim) + tend = 79.5 + linetype = ["-", "-", "-"] + linethick = [0.5, 0.75, 1.25] + linecolor = [[0.66, 0.66, 0.66], [0.4, 0.4, 0.3], "k"] + n = 0 + vcmds = [-70, -20] + vplots = [(pA, pAi, pC, pCi), (pB, pBi, pD, pDi)] + for m, VX in enumerate(vcmds): + stim["amp"] = VX + pl = vplots[m] + print(m, VX) + (secmd, maxt, tstims) = make_pulse(stim) + for n, rsc in enumerate(compensation): + vec = {} + for var in ["VCmd", "i_inj", "time", "Vsoma", "Vdend", "Vdend2", "VCmdR"]: + vec[var] = h.Vector() + VClamp.rs = Rs0 * (100.0 - rsc) / 100.0 + cell.cm = cms[n] + # print VClamp.rs, cell.cm, VClamp.rs*cell.cm + vec["VCmd"] = h.Vector(secmd) + vec["Vsoma"].record(cell(0.5)._ref_v, sec=cell) + vec["Vdend"].record(dend[0](Ld)._ref_v, sec=dend[0]) + vec["time"].record(h._ref_t) + vec["i_inj"].record(VClamp._ref_i, sec=cell) + + vec["VCmdR"].record(VClamp._ref_vc, sec=cell) + VClamp.amp2 = VX + # vec['VCmd'].play(VClamp.amp2, h.dt, 0, sec=cell) + + h.tstop = tend + h.init() + h.finitialize(-60) + h.run() + vc = np.asarray(vec["Vsoma"]) + tc = np.asarray(vec["time"]) + + # now plot the data, raw and as insets + for k in [0, 1]: + pl[k].plot( + vec["time"], + vec["i_inj"], + color=linecolor[n], + linestyle=linetype[n], + linewidth=linethick[n], + ) + yl = pl[k].get_ylim() + if k == 0: + pass + # pl[k].set_ylim([1.5*yl[0], -1.5*yl[1]]) + else: + pass + + for k in [2, 3]: + pl[k].plot( + vec["time"], + vec["Vsoma"], + color=linecolor[n], + linestyle=linetype[n], + linewidth=linethick[n], + ) + pl[k].plot( + vec["time"], + vec["VCmdR"], + color=linecolor[n], + linestyle="--", + linewidth=1, + dashes=(1, 1), + ) + pl[k].plot( + vec["time"], + vec["Vdend"], + color=linecolor[n], + linestyle=linetype[n], + linewidth=linethick[n], + dashes=(3, 3), + ) + if VX < vsteps[0]: + pl[k].set_ylim([-72, -40]) + else: + pl[k].set_ylim([-62, VX + 30]) + + ptx = 10.8 + pBi.set_xlim([9.8, ptx]) + pAi.set_xlim([9.8, ptx]) + PH.setX(pAi, pCi) + PH.setX(pBi, pDi) + pD.set_ylim([-65, 10]) + # PH.setY(pC, pCi) # match Y limits + PH.cleanAxes([pA, pAi, pB, pBi, pC, pCi, pD, pDi]) + PH.formatTicks([pA, pB, pC, pD], axis="x", fmt="%d") + PH.formatTicks([pC, pD], axis="y", fmt="%d") + PH.calbar(pAi, [ptx - 1, 0, 0.2, 2.0]) + PH.calbar(pCi, [ptx - 1, -50.0, 0.2, 10]) + PH.calbar(pBi, [ptx - 1, 0, 0.2, 10]) + PH.calbar(pDi, [ptx - 1, -50.0, 0.2, 20]) + pylab.draw() + pylab.show() diff --git a/cnmodel/protocols/iv_curve.py b/cnmodel/protocols/iv_curve.py new file mode 100644 index 0000000..c13fc14 --- /dev/null +++ b/cnmodel/protocols/iv_curve.py @@ -0,0 +1,612 @@ +from __future__ import print_function +from neuron import h +import numpy as np +import scipy +import scipy.integrate +import scipy.stats +import scipy.optimize + +try: + import pyqtgraph as pg + + HAVE_PG = True +except ImportError: + HAVE_PG = False + +from ..util.stim import make_pulse +from ..util import fitting +from ..util import custom_init +from .protocol import Protocol + + +class IVCurve(Protocol): + def __init__(self): + super(IVCurve, self).__init__() + + def reset(self): + super(IVCurve, self).reset() + self.voltage_traces = [] + self.durs = None # durations of current steps + self.current_cmd = None # Current command levels + self.current_traces = [] + self.time_values = None + self.dt = None + self.initdelay = 0.0 + + def run( + self, + ivrange, + cell, + durs=None, + sites=None, + reppulse=None, + temp=22, + dt=0.025, + initdelay=0.0, + ): + """ + Run a current-clamp I/V curve on *cell*. + + Parameters + ---------- + ivrange : dict of list of tuples + Each item in the list is (min, max, step) describing a range of + levels to test. Range values are inclusive, so the max value may + appear in the test values. Using multiple ranges allows finer + measurements in some ranges. + For example:: + + {'pulse': [(-1., 0., 1.), (-0.1, 0., 0.02)], 'prepulse': [(-0.5, 0, 0.1)]} + + Optional keys include 'pulsedur' : the duration of the pulse, in ms + 'prepulsecur: the duration of the prepulse, in ms + The prepulse or the pulse can have a single value if the other is ranged. + cell : Cell + The Cell instance to test. + durs : tuple + durations of (pre, pulse, post) regions of the command + sites : list + Sections to add recording electrodes + reppulse : + stimulate with pulse train + temp : + temperature of simulation (32) + dt : + timestep of simulation (0.025) + + """ + self.reset() + self.cell = cell + self.initdelay = initdelay + self.dt = dt + self.temp = temp + # Calculate current pulse levels + icur = [] + precur = [0.0] + self.pre_current_cmd = [] + npresteps = 0 + if isinstance(ivrange["pulse"], tuple): + icmd = [ivrange["pulse"]] # convert to a list with tuple(s) embedded + else: + icmd = ivrange["pulse"] # was already a list with multiple tuples + for c in icmd: # unpack current levels for the main pulse + try: + (imin, imax, istep) = c # unpack a tuple... or list + except: + raise TypeError( + "run_iv arguments must be a dict with tuples {'pulse': (imin, imax, istep), 'prepulse': ...}" + ) + nstep = np.floor((imax - imin) / istep) + 1 + icur.extend(imin + istep * np.arange(nstep)) # build the list + self.current_cmd = np.array(sorted(icur)) + nsteps = self.current_cmd.shape[0] + # Configure IClamp + if durs is None: + durs = [10.0, 100.0, 50.0] # set default durs + + if "prepulse" in ivrange.keys(): + if isinstance(ivrange["prepulse"], tuple): + icmd = [ivrange["prepulse"]] # convert to a list with tuple(s) embedded + else: + icmd = ivrange["prepulse"] # was already a list with multiple tuples + precur = [] + for c in icmd: + try: + (imin, imax, istep) = c # unpack a tuple... or list + except: + raise TypeError( + "run_iv arguments must be a dict with tuples {'pulse': (imin, imax, istep), 'prepulse': ...}" + ) + nstep = np.floor((imax - imin) / istep) + 1 + precur.extend(imin + istep * np.arange(nstep)) # build the list + self.pre_current_cmd = np.array(sorted(precur)) + npresteps = self.pre_current_cmd.shape[0] + durs.insert(1, 50.0) + + self.durs = durs + # set up stimulation with a pulse train + if reppulse is not None: + stim = { + "NP": 10, + "Sfreq": 50.0, + "delay": 10.0, + "dur": 2, + "amp": 1.0, + "PT": 0.0, + "dt": self.dt, + } + elif "prepulse" in ivrange.keys(): + stim = { + "NP": 2, + "delay": durs[0], + "predur": durs[1], + "dur": durs[2], + "amp": 1.0, + "preamp": 0.0, + "dt": self.dt, + } + self.p_start = durs[0] + durs[1] + self.p_end = self.p_start + durs[2] + self.p_dur = durs[2] + else: + stim = { + "NP": 1, + "delay": durs[0], + "dur": durs[1], + "amp": 1.0, + "dt": self.dt, + } + self.p_start = durs[0] + self.p_end = self.p_start + durs[1] + self.p_dur = durs[1] + # print stim + # print('p_: ', self.p_start, self.p_end, self.p_dur) + istim = h.iStim(0.5, sec=cell.soma) + istim.delay = 5.0 + istim.dur = 1e9 # these actually do not matter... + istim.iMax = 0.0 + self.tend = np.sum(durs) # maxt + len(iextend)*stim['dt'] + + self.cell = cell + for i in range(nsteps): + # Generate current command for this level + stim["amp"] = self.current_cmd[i] + if npresteps > 0: + for j in range(npresteps): + stim["preamp"] = self.pre_current_cmd[j] + self.run_one(istim, stim, initflag=(i == 0 and j == 0)) + else: + self.run_one(istim, stim, initflag=(i == 0)) + + def run_one(self, istim, stim, initflag=True): + """ + Perform one run in current-clamp for the selected cell + and add the data to the traces + + Parameters + ---------- + istim : Stimulus electrode instance + stim : waveform information + initflag : boolean (default: True) + If true, force initialziation of the cell and computation of + point Rin, tau and Vm + """ + (secmd, maxt, tstims) = make_pulse(stim) + # print('maxt, dt*lencmd: ', maxt, len(secmd)*self.dt)# secmd = np.append(secmd, [0.]) + # print('stim: ', stim, self.tend) + + # connect current command vector + playvector = h.Vector(secmd) + playvector.play(istim._ref_i, h.dt, 0, sec=self.cell.soma) + + # Connect recording vectors + self["v_soma"] = self.cell.soma(0.5)._ref_v + # self['q10'] = self.cell.soma(0.5).ihpyr_adj._ref_q10 + # self['ih_ntau'] = self.cell.soma(0.5).ihpyr_adj._ref_kh_n_tau + self["i_inj"] = istim._ref_i + self["time"] = h._ref_t + + # h('secondorder=0') # direct call fails; let hoc do the work + h.celsius = self.cell.status["temperature"] + self.cell.cell_initialize() + h.dt = self.dt + custom_init(v_init=self.cell.vm0) + + h.t = 0.0 + h.tstop = self.tend + while h.t < h.tstop: + h.fadvance() + + self.voltage_traces.append(self["v_soma"]) + self.current_traces.append(self["i_inj"]) + self.time_values = np.array(self["time"] - self.initdelay) + # self.mon_q10 = np.array(self['q10']) + # self.mon_ih_ntau = np.array(self['ih_ntau']) + + def peak_vm(self, window=0.5): + """ + Parameters + ---------- + window : float (default: 0.5) + fraction of trace to look at to find peak value + + Returns + ------- + peak membrane voltage for each trace. + + """ + Vm = self.voltage_traces + Icmd = self.current_cmd + steps = len(Icmd) + peakStart = int(self.p_start / self.dt) + peakStop = int( + peakStart + (self.p_dur * window) / self.dt + ) # peak can be in first half + Vpeak = [] + for i in range(steps): + if Icmd[i] > 0: + Vpeak.append(Vm[i][peakStart:peakStop].max()) + else: + Vpeak.append(Vm[i][peakStart:peakStop].min()) + return np.array(Vpeak) + + def steady_vm(self, window=0.1): + """ + Parameters + ---------- + window: (float) default: 0.1 + fraction of window to use for steady-state measurement, taken + immediately before the end of the step + + Returns + ------- + steady-state membrane voltage for each trace. + + """ + Vm = self.voltage_traces + steps = len(Vm) + steadyStop = int((self.p_end) / self.dt) + steadyStart = int( + steadyStop - (self.p_end * window) / self.dt + ) # measure last 10% of trace + Vsteady = [Vm[i][steadyStart:steadyStop].mean() for i in range(steps)] + return np.array(Vsteady) + + def spike_times(self, threshold=None): + """ + Return an array of spike times for each trace. + + Parameters + ---------- + threshold: float (default: None) + Optional threshold at which to detect spikes. By + default, this queries cell.spike_threshold. + + Returns + ------- + list of spike times. + + """ + if threshold is None: + threshold = self.cell.spike_threshold + + Vm = self.voltage_traces + steps = len(Vm) + spikes = [] + for i in range(steps): + # dvdt = np.diff(Vm[i]) / self.dt + # mask = (dvdt > 40).astype(int) + mask = (Vm[i] > threshold).astype(int) + indexes = np.argwhere(np.diff(mask) == 1)[:, 0] + 1 + times = indexes.astype(float) * self.dt + spikes.append(times) + return spikes + + def spike_filter(self, spikes, window=(0.0, np.inf)): + """Filter the spikes to only those occurring in a defined window. + + Required to compute input resistance in traces with no spikes during + the stimulus, because some traces will have anodal break spikes. + + Parameters + ---------- + spikes : list + the list of spike trains returned from the spike_times method + window : (start, stop) + the window over which to look for spikes (in msec: default is + the entire trace). + + Returns + ------- + the spikes in a list + + """ + filteredspikes = [] + for i in range(len(spikes)): + winspikes = [] # spikes is arranged by current; so this is for one level + for j in range(len(spikes[i])): + if spikes[i][j] >= window[0] and spikes[i][j] <= window[1]: + winspikes.append(spikes[i][j]) + filteredspikes.append(winspikes) # now build filtered spike list + return filteredspikes + + def rest_vm(self): + """ + Parameters + ---------- + None + + Returns + ------- + The mean resting membrane potential. + """ + d = int(self.durs[0] / self.dt) + rvm = np.array( + [ + np.array(self.voltage_traces[i][d // 2 : d]).mean() + for i in range(len(self.voltage_traces)) + ] + ).mean() + return rvm + + def input_resistance_tau(self, vmin=-10.0, imax=0, return_fits=False): + """ + Estimate resting input resistance and time constant. + + Parameters + ---------- + vmin : float + minimum voltage to use in computation relative to resting + imax : float + maximum current to use in computation. + return_eval : bool + If True, return lmfit.ModelFit instances for the subthreshold trace + fits as well. + + Returns + ------- + dict : + Dict containing: + + * 'slope' and 'intercept' keys giving linear + regression for subthreshold traces near rest + * 'tau' giving the average first-exponential fit time constant + * 'fits' giving a record array of exponential fit data to subthreshold + traces. + + Analyzes only traces hyperpolarizing pulse traces near rest, with no + spikes. + + """ + Vss = self.steady_vm() + vmin += self.rest_vm() + Icmd = self.current_cmd + rawspikes = self.spike_times() + spikes = self.spike_filter(rawspikes, window=[self.p_start, self.p_end]) + steps = len(Icmd) + + nSpikes = np.array([len(s) for s in spikes]) + # find traces with Icmd < 0, Vm > -70, and no spikes. + vmask = Vss >= vmin + imask = Icmd <= imax + smask = nSpikes > 0 + mask = vmask & imask & ~smask + if mask.sum() < 2: + print( + "WARNING: Not enough traces to do linear regression in " + "IVCurve.input_resistance_tau()." + ) + print( + "{0:<15s}: {1:s}".format( + "vss", ", ".join(["{:.2f}".format(v) for v in Vss]) + ) + ) + print( + "{0:<15s}: {1:s}".format( + "Icmd", ", ".join(["{:.2f}".format(i) for i in Icmd]) + ) + ) + print("{0:<15s}: {1:s}".format("vmask", repr(vmask.astype(int)))) + print("{0:<15s}: {1:s} ".format("imask", repr(imask.astype(int)))) + print("{0:<15s}: {1:s}".format("spikemask", repr(smask.astype(int)))) + raise Exception( + "Not enough traces to do linear regression (see info above)." + ) + + # Use these to measure input resistance by linear regression. + reg = scipy.stats.linregress(Icmd[mask], Vss[mask]) + (slope, intercept, r, p, stderr) = reg + + # also measure the tau in the same traces: + pulse_start = int(self.p_start / self.dt) + pulse_stop = int((self.p_end) / self.dt) + + fits = [] + fit_inds = [] + tx = self.time_values[pulse_start:pulse_stop].copy() + for i, m in enumerate(mask): + if not m or (self.rest_vm() - Vss[i]) <= 1: + continue + trace = self.voltage_traces[i][pulse_start:pulse_stop] + + # find first minimum in the trace + min_ind = np.argmin(trace) + min_val = trace[min_ind] + min_diff = trace[0] - min_val + tau_est = min_ind * self.dt * (1.0 - 1.0 / np.e) + # print ('minind: ', min_ind, tau_est) + fit = fitting.Exp1().fit( + trace[:min_ind], + method="nelder", + x=tx[:min_ind], + xoffset=(tx[0], "fixed"), + yoffset=(min_val, -120.0, -10.0), + amp=(min_diff, 0.0, 50.0), + tau=(tau_est, 0.5, 50.0), + ) + + # find first maximum in the trace (following with first minimum) + max_ind = np.argmax(trace[min_ind:]) + min_ind + max_val = trace[max_ind] + max_diff = min_val - max_val + tau2_est = max_ind * self.dt * (1.0 - 1.0 / np.e) + amp1_est = fit.params["amp"].value + tau1_est = fit.params["tau"].value + amp2_est = fit.params["yoffset"] - max_val + # print('tau1, tau2est: ', tau1_est, tau2_est) + # fit up to first maximum with double exponential, using prior + # fit as seed. + fit = fitting.Exp2().fit( + trace[:max_ind], + method="nelder", + x=tx[:max_ind], + xoffset=(tx[0], "fixed"), + yoffset=(max_val, -120.0, -10.0), + amp1=(amp1_est, 0.0, 200.0), + tau1=(tau1_est, 0.5, 50.0), + amp2=(amp2_est, -200.0, -0.5), + tau_ratio=(tau2_est / tau1_est, 2.0, 50.0), + tau2="tau_ratio * tau1", + ) + + fits.append(fit) + fit_inds.append(i) + # convert fits to record array + # print len(fits) # fits[0].params + if len(fits) > 0: + key_order = sorted( + fits[0].params + ) # to ensure that unit tests remain stable + dtype = [(k, float) for k in key_order] + [("index", int)] + fit_data = np.empty(len(fits), dtype=dtype) + for i, fit in enumerate(fits): + for k, v in fit.params.items(): + fit_data[i][k] = v.value + fit_data[i]["index"] = fit_inds[i] + + if "tau" in fit_data.dtype.fields: + tau = fit_data["tau"].mean() + else: + tau = fit_data["tau1"].mean() + else: + slope = 0.0 + intercept = 0.0 + tau = 0.0 + fit_data = [] + ret = {"slope": slope, "intercept": intercept, "tau": tau, "fits": fit_data} + + if return_fits: + return ret, fits + else: + return ret + + def show(self, cell=None, rmponly=False): + """ + Plot results from run_iv() + + Parameters + ---------- + cell : cell object (default: None) + + """ + if not HAVE_PG: + raise Exception("Requires pyqtgraph") + + # + # Generate figure with subplots + # + app = pg.mkQApp() + win = pg.GraphicsWindow( + "%s %s (%s)" + % (cell.status["name"], cell.status["modelType"], cell.status["species"]) + ) + self.win = win + win.resize(1000, 800) + Vplot = win.addPlot(labels={"left": "Vm (mV)", "bottom": "Time (ms)"}) + rightGrid = win.addLayout(rowspan=2) + win.nextRow() + Iplot = win.addPlot(labels={"left": "Iinj (nA)", "bottom": "Time (ms)"}) + + IVplot = rightGrid.addPlot(labels={"left": "Vm (mV)", "bottom": "Icmd (nA)"}) + IVplot.showGrid(x=True, y=True) + rightGrid.nextRow() + spikePlot = rightGrid.addPlot( + labels={"left": "Iinj (nA)", "bottom": "Spike times (ms)"} + ) + rightGrid.nextRow() + FIplot = rightGrid.addPlot( + labels={"left": "Spike count", "bottom": "Iinj (nA)"} + ) + + win.ci.layout.setRowStretchFactor(0, 10) + win.ci.layout.setRowStretchFactor(1, 5) + + # + # Plot simulation and analysis results + # + Vm = self.voltage_traces + Iinj = self.current_traces + Icmd = self.current_cmd + t = self.time_values + steps = len(Icmd) + + # plot I, V traces + colors = [(i, steps * 3.0 / 2.0) for i in range(steps)] + for i in range(steps): + Vplot.plot(t, Vm[i], pen=colors[i]) + Iplot.plot(t, Iinj[i], pen=colors[i]) + + if rmponly: + return + # I/V relationships + IVplot.plot( + Icmd, + self.peak_vm(), + symbol="o", + symbolBrush=(50, 150, 50, 255), + symbolSize=4.0, + ) + IVplot.plot(Icmd, self.steady_vm(), symbol="s", symbolSize=4.0) + + # F/I relationship and raster plot + spikes = self.spike_times() + for i, times in enumerate(spikes): + spikePlot.plot( + x=times, + y=[Icmd[i]] * len(times), + pen=None, + symbol="d", + symbolBrush=colors[i], + symbolSize=4.0, + ) + FIplot.plot(x=Icmd, y=[len(s) for s in spikes], symbol="o", symbolSize=4.0) + + # Print Rm, Vrest + rmtau, fits = self.input_resistance_tau(return_fits=True) + s = rmtau["slope"] + i = rmtau["intercept"] + # tau1 = rmtau['fits']['tau1'].mean() + # tau2 = rmtau['fits']['tau2'].mean() + # print ("\nMembrane resistance (chord): {0:0.1f} MOhm Taum1: {1:0.2f} Taum2: {2:0.2f}".format(s, tau1, tau2)) + + # Plot linear subthreshold I/V relationship + ivals = np.array([Icmd.min(), Icmd.max()]) + vvals = s * ivals + i + line = pg.QtGui.QGraphicsLineItem(ivals[0], vvals[0], ivals[1], vvals[1]) + line.setPen(pg.mkPen(255, 0, 0, 70)) + line.setZValue(-10) + IVplot.addItem(line, ignoreBounds=True) + + # plot exponential fits + for fit in fits: + t = np.linspace(self.p_start, self.p_end, 1000) + y = fit.eval(x=t) + Vplot.plot( + t, y, pen={"color": (100, 100, 0), "style": pg.QtCore.Qt.DashLine} + ) + + # plot initial guess + # y = fit.eval(x=t, **fit.init_params.valuesdict()) + # Vplot.plot(t, y, pen={'color': 'b', 'style': pg.QtCore.Qt.DashLine}) + + print("Resting membrane potential: %0.1f mV\n" % self.rest_vm()) diff --git a/cnmodel/protocols/population_test.py b/cnmodel/protocols/population_test.py new file mode 100644 index 0000000..4d3dd59 --- /dev/null +++ b/cnmodel/protocols/population_test.py @@ -0,0 +1,150 @@ +from __future__ import print_function +import numpy as np +import pyqtgraph as pg + +from neuron import h + +import cnmodel.util as util +from .protocol import Protocol +from ..util import custom_init +from cnmodel.util import sound + + +class PopulationTest(Protocol): + def reset(self): + super(PopulationTest, self).reset() + + def run( + self, pops, cf=16e3, temp=34.0, dt=0.025, stim="sound", simulator="cochlea" + ): + """ + 1. Connect pop1 => pop2 + 2. Instantiate a single cell in pop2 + 3. Automatically generate presynaptic cells and synapses from pop1 + 4. Stimulate presynaptic cells and record postsynaptically + """ + + pre_pop, post_pop = pops + pre_pop.connect(post_pop) + self.pre_pop = pre_pop + self.post_pop = post_pop + + # start with one cell, selected from the user-selected population, that has + # a cf close to the center CF + post_cell_ind = post_pop.select(1, cf=cf, create=True)[0] + post_cell = post_pop.get_cell(post_cell_ind) + post_pop.resolve_inputs(depth=1) + post_sec = post_cell.soma + self.post_cell_ind = post_cell_ind + self.post_cell = post_cell + + pre_cell_inds = post_pop.cell_connections(post_cell_ind)[pre_pop] + pre_cells = [pre_pop.get_cell(i) for i in pre_cell_inds] + pre_secs = [cell.soma for cell in pre_cells] + self.pre_cells = pre_cells + self.pre_cell_inds = pre_cell_inds + self.stim = sound.TonePip( + rate=100e3, + duration=0.1, + f0=cf, + dbspl=60, + ramp_duration=2.5e-3, + pip_duration=0.05, + pip_start=[0.02], + ) + + ## + ## voltage clamp the target cell + ## + # clampV = 40.0 + # vccontrol = h.VClamp(0.5, sec=post_cell.soma) + # vccontrol.dur[0] = 10.0 + # vccontrol.amp[0] = clampV + # vccontrol.dur[1] = 100.0 + # vccontrol.amp[1] = clampV + # vccontrol.dur[2] = 20.0 + # vccontrol.amp[2] = clampV + + # + # set up stimulation of the presynaptic cells + # + self.stim_params = [] + self.istim = [] + for i, pre_cell in enumerate(pre_cells): + if stim == "sound": + pre_cell.set_sound_stim(self.stim, seed=i, simulator=simulator) + amp = 0.0 + else: + amp = 3.0 + istim = h.iStim(0.5, sec=pre_cell.soma) + stim = {} + stim["NP"] = 10 + stim["Sfreq"] = 100.0 # stimulus frequency + stim["delay"] = 10.0 + stim["dur"] = 0.5 + stim["amp"] = amp + stim["PT"] = 0.0 + stim["dt"] = dt + (secmd, maxt, tstims) = util.make_pulse(stim) + self.stim_params.append(stim) + + # istim current pulse train + i_stim_vec = h.Vector(secmd) + i_stim_vec.play(istim._ref_i, dt, 0, pre_cell.soma(0.5)) + self.istim.append((istim, i_stim_vec)) + self["istim"] = istim._ref_i + + # record presynaptic Vm + self["v_pre%d" % i] = pre_cell.soma(0.5)._ref_v + + self["t"] = h._ref_t + self["v_post"] = post_cell.soma(0.5)._ref_v + + # + # Run simulation + # + h.dt = dt + self.dt = dt + h.celsius = post_cell.status["temperature"] + self.temp = h.celsius + post_cell.cell_initialize() # proper initialization. + h.dt = self.dt + custom_init(v_init=post_cell.vm0) + h.t = 0.0 + h.tstop = 200.0 + while h.t < h.tstop: + h.fadvance() + + def show(self): + print( + "Connected %d presynaptic cells to 1 postsynaptic cell." + % len(self.pre_cell_inds) + ) + print("Postsynaptic CF = %0.2f" % self.post_pop.cells[self.post_cell_ind]["cf"]) + print("Presynaptic CF = %s" % self.pre_pop.cells[self.pre_cell_inds]["cf"]) + + self.win = pg.GraphicsWindow() + self.win.resize(1000, 1000) + + cmd_plot = self.win.addPlot(title="Stim") + try: + cmd_plot.plot(self["t"], self["istim"]) + except: + pass + + self.win.nextRow() + pre_plot = self.win.addPlot(title=self.pre_cells[0].type + " Vm") + for i in range(len(self.pre_cells)): + pre_plot.plot( + self["t"], + self["v_pre%d" % i], + pen=pg.mkPen( + pg.intColor(i, len(self.pre_cells)), + hues=len(self.pre_cells), + width=1.0, + ), + ) + + self.win.nextRow() + post_plot = self.win.addPlot(title="Post Cell: %s" % self.post_cell.type) + post_plot.plot(self["t"], self["v_post"]) diff --git a/cnmodel/protocols/protocol.py b/cnmodel/protocols/protocol.py new file mode 100644 index 0000000..cc138df --- /dev/null +++ b/cnmodel/protocols/protocol.py @@ -0,0 +1,43 @@ +from neuron import h +import numpy as np +from ..util import random_seed, custom_init + + +class Protocol(object): + """ + Base class providing common tools for running, analyzing, and displaying + simulations. + """ + + def __init__(self): + self.reset() + + def reset(self): + self._vectors = {} + + def run(self, seed=None): + """ + Run this protocol. + + Subclasses should extend this method. + """ + if seed is not None: + random_seed.set_seed(seed) + self.reset() + + def __setitem__(self, name, variable): + """ + Record *variable* during the next run. + """ + vec = h.Vector() + self._vectors[name] = vec + vec.record(variable) + + def __getitem__(self, name): + """ + Return a np array for previously recorded data given *name*. + """ + return np.array(self._vectors[name]) + + def custom_init(self, vinit=-60.0): + return custom_init(vinit) diff --git a/cnmodel/protocols/simple_synapse_test.py b/cnmodel/protocols/simple_synapse_test.py new file mode 100644 index 0000000..ee2469b --- /dev/null +++ b/cnmodel/protocols/simple_synapse_test.py @@ -0,0 +1,111 @@ +# -*- encoding: utf-8 -*- +from neuron import h +import pyqtgraph as pg + +import cnmodel.util as util +from .protocol import Protocol +from .. import cells + + +class SimpleSynapseTest(Protocol): + def reset(self): + super(SimpleSynapseTest, self).reset() + + def run( + self, + pre_sec, + post_sec, + temp=34.0, + dt=0.025, + vclamp=-65.0, + iterations=1, + tstop=200.0, + stim_params=None, + **kwds + ): + """ + """ + Protocol.run(self, **kwds) + + pre_cell = cells.cell_from_section(pre_sec) + post_cell = cells.cell_from_section(post_sec) + synapse = pre_cell.connect(post_cell, type="simple") + + self.synapse = synapse + self.pre_sec = synapse.terminal.section + self.post_sec = synapse.psd.section + self.pre_cell = pre_cell + self.post_cell = post_cell + + # + # voltage clamp the target cell + # + vccontrol = h.VClamp(0.5, sec=post_cell.soma) + vccontrol.dur[0] = tstop + vccontrol.amp[0] = vclamp + # vccontrol.dur[1] = 100.0 + # vccontrol.amp[1] = clampV + # vccontrol.dur[2] = 20.0 + # vccontrol.amp[2] = clampV + + # + # set up stimulation of the presynaptic axon/terminal + # + + istim = h.iStim(0.5, sec=pre_cell.soma) + stim = { + "NP": 10, + "Sfreq": 100.0, + "delay": 10.0, + "dur": 0.5, + "amp": 10.0, + "PT": 0.0, + "dt": dt, + } + if stim_params is not None: + stim.update(stim_params) + (secmd, maxt, tstims) = util.make_pulse(stim) + self.stim = stim + + if tstop is None: + tstop = len(secmd) * dt + + istim.delay = 0 + istim.dur = 1e9 # these actually do not matter... + istim.iMax = 0.0 + + # istim current pulse train + i_stim_vec = h.Vector(secmd) + i_stim_vec.play(istim._ref_i, dt, 0) + + # + # Run simulation + # + h.tstop = tstop # duration of a run + h.celsius = temp + h.dt = dt + self.temp = temp + self.dt = dt + for nrep in list(range(iterations)): # could do multiple runs.... + self.reset() + self["v_pre"] = pre_cell.soma(0.5)._ref_v + self["t"] = h._ref_t + self["v_soma"] = post_cell.soma(0.5)._ref_v + self["i_soma"] = vccontrol._ref_i + util.custom_init() + h.run() + + def show(self): + self.win = pg.GraphicsWindow() + self.win.resize(800, 800) + t = self["t"] + + p1 = self.win.addPlot(title=self.pre_cell.status["name"]) + p1.setLabels(left="V pre (mV)", bottom="Time (ms)") + p1.plot(t, self["v_pre"]) + + self.win.nextRow() + p2 = self.win.addPlot(title=self.post_cell.status["name"]) + p2.plot(t[1:], self["i_soma"][1:], pen=pg.mkPen("w", width=2)) + p2.setLabels(left="I post (nA)", bottom="Time (ms)") + p2.setXLink(p1) diff --git a/cnmodel/protocols/synapse_test.py b/cnmodel/protocols/synapse_test.py new file mode 100644 index 0000000..8897991 --- /dev/null +++ b/cnmodel/protocols/synapse_test.py @@ -0,0 +1,779 @@ +from __future__ import print_function +from collections import OrderedDict +from scipy import interpolate +import numpy as np +import pyqtgraph as pg +from neuron import h +import cnmodel.util as util +from .protocol import Protocol +from .. import cells +from ..synapses import GluPSD, GlyPSD, Exp2PSD +from ..util.find_point import find_crossing +import timeit + + +class SynapseTest(Protocol): + def reset(self): + super(SynapseTest, self).reset() + + def run( + self, + pre_sec, + post_sec, + n_synapses, + temp=34.0, + dt=0.025, + vclamp=40.0, + iterations=1, + tstop=240.0, + stim_params=None, + synapsetype="multisite", + **kwds + ): + """ + Basic synapse test. Connects sections of two cells with *n_synapses*. + The cells are allowed to negotiate the details of the connecting + synapse. The presynaptic soma is then driven with a pulse train + followed by a recovery pulse of varying delay. + + *stim_params* is an optional dictionary with keys 'NP', 'Sfreq', 'delay', + 'dur', 'amp'. + + Analyses: + + * Distribution of PSG amplitude, kinetics, and latency + * Synaptic depression / facilitation and recovery timecourses + """ + Protocol.run(self, **kwds) + + pre_cell = cells.cell_from_section(pre_sec) + post_cell = cells.cell_from_section(post_sec) + synapses = [] + for i in range(n_synapses): + synapses.append(pre_cell.connect(post_cell, type=synapsetype)) + if len(synapses) == 0: + raise ValueError("No synapses created for this cell combination!") + self.synapses = synapses + self.pre_sec = synapses[0].terminal.section + self.post_sec = synapses[0].psd.section + self.pre_cell = pre_cell + self.post_cell = post_cell + self.plots = {} # store plot information here + # + # voltage clamp the target cell + # + clampV = vclamp + vccontrol = h.VClamp(0.5, sec=post_cell.soma) + vccontrol.dur[0] = 10.0 + vccontrol.amp[0] = clampV + vccontrol.dur[1] = 100.0 + vccontrol.amp[1] = clampV + vccontrol.dur[2] = 20.0 + vccontrol.amp[2] = clampV + + # + # set up stimulation of the presynaptic axon/terminal + # + + istim = h.iStim(0.5, sec=pre_cell.soma) + stim = { + "NP": 10, + "Sfreq": 100.0, + "delay": 10.0, + "dur": 0.5, + "amp": 10.0, + "PT": 0.0, + "dt": dt, + } + if stim_params is not None: + stim.update(stim_params) + (secmd, maxt, tstims) = util.make_pulse(stim) + self.stim = stim + + if tstop is None: + tstop = len(secmd) * dt + + istim.delay = 0 + istim.dur = 1e9 # these actually do not matter... + istim.iMax = 0.0 + + # istim current pulse train + i_stim_vec = h.Vector(secmd) + i_stim_vec.play(istim._ref_i, dt, 0) + + # create hoc vectors for each parameter we wish to monitor and display + synapse = synapses[0] + self.all_psd = [] + if isinstance(synapses[0].psd, GlyPSD) or isinstance(synapses[0].psd, GluPSD): + for syn in synapses: + self.all_psd.extend(syn.psd.all_psd) + elif isinstance(synapses[0].psd, Exp2PSD): + for syn in synapses: + self.all_psd.append(syn) + + # for i, cleft in enumerate(synapse.psd.clefts): + # self['cleft_xmtr%d' % i] = cleft._ref_CXmtr + # self['cleft_pre%d' % i] = cleft._ref_pre + # self['cleft_xv%d' % i] = cleft._ref_XV + # self['cleft_xc%d' % i] = cleft._ref_XC + # self['cleft_xu%d' % i] = cleft._ref_XU + + # + # Run simulation + # + h.tstop = tstop # duration of a run + h.celsius = temp + h.dt = dt + self.temp = temp + self.dt = dt + self.isoma = [] + self.currents = {"ampa": [], "nmda": []} + self.all_releases = [] + self.all_release_events = [] + start_time = timeit.default_timer() + for nrep in list(range(iterations)): # could do multiple runs.... + self.reset() + self["v_pre"] = pre_cell.soma(0.5)._ref_v + self["t"] = h._ref_t + self["v_soma"] = pre_cell.soma(0.5)._ref_v + if not isinstance(synapse.psd, Exp2PSD): + self["relsite_xmtr"] = synapse.terminal.relsite._ref_XMTR[0] + + if isinstance(synapse.psd, GluPSD): + # make a synapse monitor for each release zone + self.all_nmda = [] + self.all_ampa = [] + for syn in synapses: + # collect all PSDs across all synapses + self.all_ampa.extend(syn.psd.ampa_psd) + self.all_nmda.extend(syn.psd.nmda_psd) + + # Record current through all PSDs individually + syn.psd.record("i", "g", "Open") + + # for k,p in enumerate(self.all_nmda): + # self['iNMDA%03d' % k] = p._ref_i + # self['opNMDA%03d' % k] = p._ref_Open + # for k,p in enumerate(self.all_ampa): + # self['iAMPA%03d' % k] = p._ref_i + # self['opAMPA%03d' % k] = p._ref_Open + + elif isinstance(synapse.psd, GlyPSD): + # Record current through all PSDs individually + for k, p in enumerate(self.all_psd): + self["iGLY%03d" % k] = p._ref_i + self["opGLY%03d" % k] = p._ref_Open + + psd = self.all_psd + if synapse.psd.psdType == "glyslow": + nstate = 7 + self["C0"] = psd[0]._ref_C0 + self["C1"] = psd[0]._ref_C1 + self["C2"] = psd[0]._ref_C2 + self["O1"] = psd[0]._ref_O1 + self["O2"] = psd[0]._ref_O2 + self["D1"] = psd[0]._ref_D1 + # self['D3'] = psd[0]._ref_D3 + # self['O1'] = psd[0]._ref_O1 + elif synapse.psd.psdType == "glyfast": + nstate = 7 + self["C0"] = psd[0]._ref_C0 + self["C1"] = psd[0]._ref_C1 + self["C2"] = psd[0]._ref_C2 + self["C3"] = psd[0]._ref_C3 + self["O1"] = psd[0]._ref_O1 + self["O2"] = psd[0]._ref_O2 + elif isinstance(synapse.psd, Exp2PSD): + self["iPSD"] = self.all_psd[0].psd.syn._ref_i + + if not isinstance(synapse.psd, Exp2PSD): + for i, s in enumerate(synapses): + s.terminal.relsite.rseed = util.random_seed.current_seed() + nrep + util.custom_init() + h.run() + + # add up psd current across all runs + if isinstance(synapse.psd, GluPSD): + iampa = np.zeros_like(synapse.psd.get_vector("ampa", "i")) + inmda = iampa.copy() + for syn in self.synapses: + for i in range(syn.psd.n_psd): + iampa += syn.psd.get_vector("ampa", "i", i) + inmda += syn.psd.get_vector("nmda", "i", i) + isoma = iampa + inmda + self.currents["ampa"].append(iampa) + self.currents["nmda"].append(inmda) + elif isinstance(synapse.psd, GlyPSD): + isoma = np.zeros_like(self["iGLY000"]) + for k in range(len(self.all_psd)): + isoma += self["iGLY%03d" % k] + elif isinstance(synapse.psd, Exp2PSD): + isoma = self["iPSD"] + self.isoma.append(isoma) + self.all_releases.append(self.release_timings()) + self.all_release_events.append(self.release_events()) + + elapsed = timeit.default_timer() - start_time + print("Elapsed time for %d Repetions: %f" % (iterations, elapsed)) + + def release_events(self, syn_no=0): + """ + Analyze results and return a dict of values related to terminal release + probability: + + n_zones: Array containing the number of release zones for each + synapse. + + n_requests: Array containing number of release requests for each + synapse. Note for multi-zone synapses, a single + presynaptic spike results in one release request _per_ + zone. + + n_releases: Array containing actual number of releases for each + synapse. + + tot_requests: The total number of release requests across all + release zones. + + tot_releases: The total number of releases. + + release_p: Release probability computed as + tot_releases / tot_requests + + + """ + synapse = self.synapses[syn_no] + + ret = { + "n_zones": [0], + "n_spikes": [0], + "n_requests": [0], + "n_releases": [0], + "tot_requests": 0, + "tot_releases": 0, + "release_p": 0.0, + } + # + # Count spikes and releases for each terminal + # + if not isinstance(self.synapses[0].psd, Exp2PSD): + ret["n_zones"] = np.array([syn.terminal.n_rzones for syn in self.synapses]) + ret["n_spikes"] = np.array( + [syn.terminal.relsite.nRequests for syn in self.synapses] + ) + ret["n_requests"] = ret["n_spikes"] * ret["n_zones"] + ret["n_releases"] = np.array( + [syn.terminal.relsite.nReleases for syn in self.synapses] + ) + + # + # Compute release probability + # + # total number of release requests + ret["tot_requests"] = ret["n_requests"].sum() + # total number of actual release events + ret["tot_releases"] = ret["n_releases"].sum() + + if ret["tot_requests"] > 0: + ret["release_p"] = float(ret["tot_releases"]) / ret["tot_requests"] + else: + ret["release_p"] = np.nan + + return ret + + def release_timings(self): + """ + Return a list of arrays (one array per synapse) describing the timing + and latency of release events. + """ + data = [] + if isinstance(self.synapses[0].psd, Exp2PSD): + return data + + for j in range(0, len(self.synapses)): + relsite = self.synapses[j].terminal.relsite + nev = int(relsite.ev_index) + ev = np.empty(nev, dtype=[("time", float), ("latency", float)]) + ev["latency"] = np.array(relsite.EventLatencies)[:nev] + ev["time"] = np.array(relsite.EventTime)[:nev] + data.append(ev) + return data + + def open_probability(self): + """ + Analyze results and return a dict of values related to psd open + probability: + + nmda: (imax, opmax) + ampa: (imax, opmax) + gly: (imax, opmax) + """ + synapse = self.synapses[0] + if isinstance(synapse.psd, GluPSD) and len(synapse.psd.nmda_psd) > 0: + # find a psd with ampa and nmda currents + nmImax = [] + amImax = [] + nmOmax = [] + amOmax = [] + # self.win.nextRow() + for syn in self.synapses: + for i in range(syn.psd.n_psd): + nm = np.abs(syn.psd.get_vector("nmda", "i", i)).max() + am = np.abs(syn.psd.get_vector("ampa", "i", i)).max() + opnm = np.abs(syn.psd.get_vector("nmda", "Open", i)).max() + opam = np.abs(syn.psd.get_vector("ampa", "Open", i)).max() + if nm > 1e-6 or am > 1e-6: # only count releases, not failures + nmImax.append(nm) + amImax.append(am) + nmOmax.append(opnm) + amOmax.append(opam) + break + if nmImax != 0: + break + + return { + "nmda": OrderedDict( + [ + ("Imax", np.mean(nmImax)), + ("Omax", np.mean(nmOmax)), + # ('OmaxMax', np.max(nmOmax)), # was used for testing... + # ('OmaxMin', np.min(nmOmax)) + ] + ), + "ampa": OrderedDict( + [ + ("Imax", np.mean(amImax)), + ("Omax", np.mean(amOmax)), + # ('OmaxMax', np.max(amOmax)), + # ('OmaxMin', np.min(amOmax)) + ] + ), + } + + elif isinstance(synapse.psd, GlyPSD) and len(synapse.psd.all_psd) > 0: + # find a psd with ampa and nmda currents + glyImax = 0 + glyOmax = 0 + for i in range(len(self.all_psd)): + imax = np.abs(self["iGLY%03d" % i]).max() + omax = np.abs(self["opGLY%03d" % i]).max() + + return {"gly": (glyImax, glyOmax)} + + elif isinstance(synapse.psd, Exp2PSD): + return {"Exp2PSD": (0.0, 0.0)} + + def analyze_events(self): + events = [] + for run in range(len(self.isoma)): + events.append(self.analyze_events_in_run(runno=run)) + return events + + def analyze_events_in_run(self, runno=0): + """ + Analyze postsynaptic events for peak, latency, and shape. + + Todo: + - This currently analyzes cumulative currents; might be better to + analyze individual PSD currents + - Measure decay time constant, rate of facilitation/depression, + recovery. + + """ + stim = self.stim + ipi = 1000.0 / stim["Sfreq"] # convert from Hz (seconds) to msec. + t_extend = 0.25 # allow response detection into the next frame + extend_pts = int(t_extend / self.dt) + + pscpts = ( + int(ipi / self.dt) + extend_pts + ) # number of samples to analyze for each psc + ipsc = np.zeros((stim["NP"], pscpts)) # storage for psc currents + tpsc = np.arange( + 0, ipi + t_extend, self.dt + ) # time values corresponding to *ipsc* + + # mpl.figure(num=220, facecolor='w') + # gpsc = mpl.subplot2grid((5, 2), (0, 0), rowspan=2, colspan=2) + psc_20_lat = np.zeros((stim["NP"], 1)) # latency to 20% of rising amplitude + psc_80_lat = np.zeros((stim["NP"], 1)) # latency to 80% of rising amplitude + psc_hw = np.zeros((stim["NP"], 1)) # width at half-height + psc_rt = np.zeros((stim["NP"], 1)) # 20-80 rise time + tp = np.zeros((stim["NP"], 1)) # pulse time relative to first pulse + events = np.zeros( + stim["NP"], + dtype=[ + ("20% latency", float), + ("80% latency", float), + ("half width", float), + ("half left", float), + ("half right", float), + ("rise time", float), + ("pulse time", float), + ("peak", float), + ("peak index", int), + ], + ) + events[:] = np.nan + + minLat = 0.0 # minimum latency for an event, in ms + minStart = int( + minLat / self.dt + ) # first index relative to pulse to search for psc peak + + for i in range(stim["NP"]): + tstart = stim["delay"] + i * ipi # pulse start time + events["pulse time"][i] = tstart + istart = int(tstart / self.dt) # pulse start index + tp[i] = tstart - stim["delay"] + iend = istart + pscpts + # print 'istart: %d iend: %d, len(isoma): %d\n' % (istart, iend, len(self.isoma[runno])) + ipsc[i, :] = np.abs(self.isoma[runno][istart:iend]) + psc_pk = minStart + np.argmax( + ipsc[i, minStart : -(extend_pts + 1)] + ) # position of the peak + + # print 'i, pscpk, ipsc[i,pscpk]: ', i, psc_pk, ipsc[i, psc_pk] + # print 'minLat: %f ipi+t_extend: %f, hdt: %f' % ((minLat, ipi+t_extend, self.dt)) + if psc_pk == minStart: + continue + pkval = ipsc[i, psc_pk] + events["peak"][i] = pkval + events["peak index"][i] = psc_pk + + # Find 20% and 80% crossing points to the left of the PSC peak + pscmin = ipsc[i, :psc_pk].min() + + lat20 = ( + find_crossing( + ipsc[i], + start=psc_pk, + direction=-1, + threshold=(pscmin + (pkval - pscmin) * 0.2), + ) + * self.dt + ) + lat80 = ( + find_crossing( + ipsc[i], + start=psc_pk, + direction=-1, + threshold=(pscmin + (pkval - pscmin) * 0.8), + ) + * self.dt + ) + events["20% latency"][i] = lat20 + events["80% latency"][i] = lat80 + + # Find 50% crossing points on either side of the PSC peak + psc_50l = ( + find_crossing( + ipsc[i], + start=psc_pk, + direction=-1, + threshold=(pscmin + (pkval - pscmin) * 0.5), + ) + * self.dt + ) + psc_50r = ( + find_crossing( + ipsc[i], + start=psc_pk, + direction=1, + threshold=(pscmin + (pkval - pscmin) * 0.5), + ) + * self.dt + ) + + events["half left"] = psc_50l + events["half right"] = psc_50r + + if not np.isnan(lat20) and not np.isnan(lat80): + events["rise time"][i] = lat80 - lat20 + else: + events["rise time"][i] = np.nan + if not np.isnan(psc_50r) and not np.isnan(psc_50l): + events["half width"][i] = float(psc_50r) - float(psc_50l) + # gpsc.plot(psc_50l, pkval * 0.5, 'k+') + # gpsc.plot(psc_50r, pkval * 0.5, 'k+') + # gpsc.plot(tpsc, ipsc[i, :].T) + else: + events["half width"][i] = np.nan + + return events + + def hide(self): + if hasattr(self, "win"): + self.win.hide() + + def show_result( + self, releasePlot=True, probabilityPlot=True, glyPlot=False, plotFocus="EPSC" + ): + synapse = self.synapses[0] + + # + # Print parameters related to release probability + # + events = self.release_events() + ns = len(self.synapses) + for i in range(ns): + if i < len(events["n_spikes"]) and events["n_spikes"][i] > 0: + v = ( + i, + events["n_spikes"][i], + events["n_zones"][i], + events["n_releases"][i], + ) + print("Synapse %d: spikes: %d zones: %d releases: %d" % v) + print("") + print("Total release requests: %d" % events["tot_requests"]) + print("Total release events: %d" % events["tot_releases"]) + print("Release probability: %8.3f" % events["release_p"]) + if not isinstance(synapse.psd, Exp2PSD): + prel_final = synapse.terminal.relsite.Dn * synapse.terminal.relsite.Fn + print("Final release probability (Dn * Fn): %8.3f" % prel_final) + + # + # Compute NMDA / AMPA open probability + # + print("") + oprob = self.open_probability() + if "gly" in oprob: + glyImax, glyOPmax = oprob["gly"] + print("Max GLYR Open Prob: %f" % (glyOPmax,)) + print("Max GLYR I: %f" % (glyImax,)) + elif "ampa" in oprob or "nmda" in oprob: + nmImax, nmOPmax = oprob["nmda"].values() + amImax, amOPmax = oprob["ampa"].values() + print("Max NMDAR Open Prob: %f AMPA Open Prob: %f" % (nmOPmax, amOPmax)) + print("Max NMDAR I: %f AMPA I: %f" % (nmImax, amImax)) + if nmImax + amImax != 0.0: + print(" N/(N+A): %f\n" % (nmImax / (nmImax + amImax))) + else: + print(" (no NMDA/AMPA current; release might have failed)") + + self.win = pg.GraphicsWindow() + self.win.resize(1000, 1000) + self.win.show() + + # + # Plot pre/postsynaptic currents + # + t = self["t"] + + p1 = self.win.addPlot(title=self.pre_cell.status["name"]) + p1.setLabels(left="V pre (mV)", bottom="Time (ms)") + p1.plot(t, self["v_pre"]) + self.plots["VPre"] = p1 + + if plotFocus == "EPSC": + self.win.nextRow() + p2 = self.win.addPlot(title=self.post_cell.status["name"]) + for i, isoma in enumerate(self.isoma): + p2.plot(t, isoma, pen=(i, len(self.isoma))) + p2.plot(t, np.mean(self.isoma, axis=0), pen=pg.mkPen("w", width=2)) + p2.setLabels(left="Total PSD current (nA)", bottom="Time (ms)") + p2.setXLink(p1) + self.plots["EPSC"] = p2 + else: + # todo: resurrect this? + g2 = mpl.subplot2grid((6, 1), (1, 0), rowspan=1) + g2.plot(t, self.isoma, color="cyan") + g3 = mpl.subplot2grid((6, 1), (2, 0)) + g3.plot(t, self["v_pre"], color="blue") + g3.plot(t, self["v_soma"], color="red") + g4 = mpl.subplot2grid((6, 1), (3, 0)) + p4 = g4.plot(t, self["relsite_xmtr"]) # glutamate + g4.axes.set_ylabel("relsite_xmtr") + g5 = mpl.subplot2grid((6, 1), (4, 0)) + for k, p in enumerate(synapse.psd.all_psd): + if p.hname().find("NMDA", 0, 6) >= 0: + g5.plot(t, self["isyn%03d" % k]) # current through nmdar + g5.axes.set_ylabel("inmda") + g6 = mpl.subplot2grid((6, 1), (5, 0)) + for k, p in enumerate(synapse.psd.all_psd): + if p.hname().find("NMDA", 0, 6) < 0: + g6.plot(t, self["isyn%03d" % k]) # glutamate + g6.axes.set_ylabel("iAMPA") + + # + # Analyze the individual events. + # EPSCs get rise time, latency, half-width, and decay tau estimates. + # + events = self.analyze_events() + + eventno = 0 + self.win.nextRow() + p3 = self.win.addPlot( + labels={"left": "20%-80% Latency (ms)", "bottom": "Pulse Time (ms)"} + ) + p3.plot( + events[eventno]["pulse time"], + events[eventno]["20% latency"], + pen=None, + symbol="o", + ) + p3.plot( + events[eventno]["pulse time"], + events[eventno]["80% latency"], + pen=None, + symbol="t", + ) + p3.setXLink(p1) + self.plots["latency2080"] = p3 + + self.win.nextRow() + p4 = self.win.addPlot( + labels={"left": "Half Width (ms)", "bottom": "Pulse Time (ms)"} + ) + p4.plot( + events[eventno]["pulse time"], + events[eventno]["half width"], + pen=None, + symbol="o", + ) + p4.setXLink(p1) + self.plots["halfwidth"] = p4 + + self.win.nextRow() + p5 = self.win.addPlot( + labels={"left": "Rise Time (ms)", "bottom": "Pulse Time (ms)"} + ) + p5.plot( + events[eventno]["pulse time"], + events[eventno]["rise time"], + pen=None, + symbol="o", + ) + p5.setXLink(p1) + self.plots["RT"] = p5 + + # + # Print average values from events + # + nst = range(self.stim["NP"]) + analysisWindow = [nst[0:2], nst[-5:]] + + RT_mean2080_early = np.nanmean(events[eventno]["rise time"][analysisWindow[0]]) + RT_mean2080_late = np.nanmean(events[eventno]["rise time"][analysisWindow[1]]) + Lat_mean20_early = np.nanmean(events[eventno]["20% latency"][analysisWindow[0]]) + Lat_mean20_late = np.nanmean(events[eventno]["20% latency"][analysisWindow[1]]) + HW_mean_early = np.nanmean(events[eventno]["half width"][analysisWindow[0]]) + HW_mean_late = np.nanmean(events[eventno]["half width"][analysisWindow[1]]) + print("\n--------------") + print("Means:") + print("--------------") + # print RT_mean2080_early + # print Lat_mean20_early + # print HW_mean_early + print( + "Early: RT {0:7.3f} ms Lat {1:7.3f} ms HW {2:7.3f} ms".format( + RT_mean2080_early, Lat_mean20_early, HW_mean_early + ) + ) + print( + "Late : RT {0:7.3f} ms Lat {1:7.3f} ms HW {2:7.3f} ms".format( + RT_mean2080_late, Lat_mean20_late, HW_mean_late + ) + ) + RT_std2080_early = np.nanstd(events[eventno]["rise time"][analysisWindow[0]]) + RT_std2080_late = np.nanstd(events[eventno]["rise time"][analysisWindow[1]]) + Lat_std20_early = np.nanstd(events[eventno]["20% latency"][analysisWindow[0]]) + Lat_std20_late = np.nanstd(events[eventno]["20% latency"][analysisWindow[1]]) + HW_std_early = np.nanstd(events[eventno]["half width"][analysisWindow[0]]) + HW_std_late = np.nanstd(events[eventno]["half width"][analysisWindow[1]]) + print("\n--------------") + print("Standard Deviations:") + print("--------------") + print( + "Early: RT {0:7.3f} ms Lat {1:7.3f} ms HW {2:7.3f} ms".format( + RT_std2080_early, Lat_std20_early, HW_std_early + ) + ) + print( + "Late : RT {0:7.3f} ms Lat {1:7.3f} ms HW {2:7.3f} ms".format( + RT_std2080_late, Lat_std20_late, HW_std_late + ) + ) + print("-----------------") + + # + # Plot release event distributions over time + # + if releasePlot: + self.win.nextRow() + p6 = self.win.addPlot( + labels={"left": "Release latency", "bottom": "Time (ms)"} + ) + p6.setXLink(p1) + self.plots["latency"] = p6 + p7 = self.win.addPlot( + labels={"left": "Release latency", "bottom": "Num. Releases"} + ) + p7.setYLink(p6) + self.plots["latency_distribution"] = p7 + self.win.ci.layout.setColumnFixedWidth(1, 200) + if not isinstance(self.synapses[0].psd, Exp2PSD): + + rel_events = self.all_releases + all_latencies = [] + for i, trial in enumerate(rel_events): + for syn in trial: + p6.plot( + syn["time"], + syn["latency"], + pen=None, + symbolBrush=(i, len(rel_events)), + symbolPen=(i, len(rel_events)), + symbolSize=4, + symbol="o", + ) + all_latencies.append(syn["latency"]) + all_latencies = np.concatenate(all_latencies) + (hist, binedges) = np.histogram(all_latencies) + curve = p7.plot( + binedges, + hist, + stepMode=True, + fillBrush=(100, 100, 255, 150), + fillLevel=0, + ) + curve.rotate(-90) + curve.scale(-1, 1) + + # if probabilityPlot: + # self.win.nextRow() + # p8 = self.win.addPlot(labels={'left': 'Release Prob', 'bottom': 'Time (ms)'}) + # p8.setXLink(p1) + # times = self.release_timings() + # for isyn, syn in enumerate(self.synapses): + # syn_events = self.release_events(syn_no=isyn) + # Pr = syn_events['n_releases']/syn_events['n_requests'] # Pr for each stimulus + # # print Pr + # + # i = 0 # ultimately would like to plot this for each synapse + # p8.plot(events[0]['pulse time'], Pr, pen=None, symbolBrush=(i, len(self.all_releases)), + # symbolPen=(i, len(events)), symbolSize=4, symbol='o') + + # + # Plot GlyR state variables + # + # if glyPlot: + + # i = 0 + # if synapse.psd.psdType == 'glyslow': + # mpl.figure(2) + # for var in ['C0', 'C1', 'C2', 'O1', 'O1', 'D1', 'Open']: + # mpl.subplot(nstate, 1, i + 1) + # mpl.plot(t, self[var]) + # mpl.ylabel(var) + # i = i + 1 + # if synapse.psd.psdType == 'glyfast': + # mpl.figure(2) + # for var in ['C0', 'C1', 'C2', 'C3', 'O1', 'O2', 'Open']: + # mpl.subplot(7, 1, i + 1) + # mpl.plot(t, self[var]) + # mpl.ylabel(var) + # i = i + 1 + # mpl.draw() + # mpl.show() diff --git a/cnmodel/protocols/vc_curve.py b/cnmodel/protocols/vc_curve.py new file mode 100644 index 0000000..b33e4cc --- /dev/null +++ b/cnmodel/protocols/vc_curve.py @@ -0,0 +1,206 @@ +import os +import os.path +from neuron import h +import numpy as np +import scipy +import scipy.integrate +import scipy.stats + +from .protocol import Protocol + + +try: + import pyqtgraph as pg + + HAVE_PG = True +except ImportError: + HAVE_PG = False +from ..util import custom_init +from ..util.stim import make_pulse + +# import matplotlib as MP # must call first... before pylag/pyplot or backends +# MP.use('Qt4Agg') + +# import matplotlib.gridspec as GS +# import mpl_toolkits.axes_grid1.inset_locator as INSETS +# import mpl_toolkits.axes_grid1.anchored_artists as ANCHOR + +# stdFont = 'Arial' +# import matplotlib.pyplot as pylab +# pylab.rcParams['interactive'] = False +# pylab.rcParams['mathtext.default'] = 'sf' +## next setting allows pdf font to be readable in Adobe Illustrator +# pylab.rcParams['pdf.fonttype'] = 42 +# pylab.rcParams['figure.facecolor'] = 'white' + + +class VCCurve(Protocol): + def __init__(self): + super(VCCurve, self).__init__() + + def reset(self): + super(VCCurve, self).reset() + self.voltage_traces = [] + self.current_traces = [] + self.durs = None # durations of current steps + self.voltage_cmd = None # Current command levels + self.time_values = None + self.dt = None + + def run(self, vcrange, cell, dt=0.025): + """ + Run voltage-clamp I/V curve. + + Parameters + ---------- + vmin : float + Minimum voltage step value + vmax : + Maximum voltage step value + vstep : + Voltage difference between steps + cell : + The Cell instance to test. + """ + self.reset() + self.cell = cell + try: + (vmin, vmax, vstep) = vcrange # unpack the tuple... + except: + raise TypeError("run_iv argument 1 must be a tuple (imin, imax, istep)") + + vstim = h.SEClamp(0.5, cell.soma) # set up a single-electrode clamp + vstim.dur1 = 50.0 + vstim.amp1 = -60 + vstim.dur2 = 500.0 + vstim.amp2 = -60.0 + vstim.dur3 = 400 + vstim.amp3 = -60.0 + vstim.rs = 0.01 + cell.soma.cm = 0.001 # reduce capacitative transients (cap compensation) + self.durs = [vstim.dur1, vstim.dur2, vstim.dur3] + self.amps = [vstim.amp1, vstim.amp2, vstim.amp3] + self.voltage_cmd = [] + tend = 900.0 + iv_nstepv = int(np.ceil((vmax - vmin) / vstep)) + iv_minv = vmin + iv_maxv = vmax + vstep = (iv_maxv - iv_minv) / iv_nstepv + for i in range(iv_nstepv): + self.voltage_cmd.append(float(i * vstep) + iv_minv) + nreps = iv_nstepv + h.dt = dt + self.dt = h.dt + for i in range(nreps): + # Connect recording vectors + self["v_soma"] = cell.soma(0.5)._ref_v + self["i_inj"] = vstim._ref_i + self["time"] = h._ref_t + vstim.amp2 = self.voltage_cmd[i] + custom_init(v_init=-60.0) + h.tstop = tend + self.cell.check_all_mechs() + while h.t < h.tstop: + h.fadvance() + self.voltage_traces.append(self["v_soma"]) + self.current_traces.append(self["i_inj"]) + self.time_values = np.array(self["time"]) + + def steady_im(self, window=0.1): + """ + Parameters + ---------- + window : float (default: 0.1) + fraction of window to use for steady-state measurement, taken + immediately before the end of the step + Returns + ------- + steady-state membrane current for each trace. + """ + Im = self.current_traces + steps = len(Im) + steadyStop = int((self.durs[0] + self.durs[1]) / self.dt) + steadyStart = int(steadyStop - (self.durs[1] * window) / self.dt) + Isteady = [Im[i][steadyStart:steadyStop].mean() for i in range(steps)] + return np.array(Isteady) + + def peak_im(self, window=0.4): + """ + Parameters + ---------- + window: float (default=0.4) + fraction of window to use for peak measurement, taken + immediately following the beginning of the step + Returns + ------ + steady-state membrane current for each trace. + """ + Im = self.current_traces + steps = len(Im) + peakStop = int((self.durs[0] + window * self.durs[1]) / self.dt) + peakStart = int(self.durs[0] / self.dt) + Vhold = self.amps[ + 0 + ] # np.mean([self.voltage_traces[i][:peakStart].mean() for i in range(steps)]) + Ipeak = [] + for i in range(steps): + if self.voltage_cmd[i] > Vhold: + Ipeak.append(Im[i][peakStart:peakStop].max()) + else: + Ipeak.append(Im[i][peakStart:peakStop].min()) + return np.array(Ipeak) + + def show(self, cell=None): + """ + Plot results from run_iv() + """ + if not HAVE_PG: + raise Exception("Requires pyqtgraph") + + # + # Generate figure with subplots + # + app = pg.mkQApp() + if cell is not None: + win = pg.GraphicsWindow( + "%s %s (%s)" + % ( + cell.status["name"], + cell.status["modelType"], + cell.status["species"], + ) + ) + else: + win = pg.GraphisWindow("Voltage Clamp") + self.win = win + win.resize(1000, 800) + Iplot = win.addPlot(labels={"left": "Im (nA)", "bottom": "Time (ms)"}) + rightGrid = win.addLayout(rowspan=2) + win.nextRow() + Vplot = win.addPlot(labels={"left": "V (mV)", "bottom": "Time (ms)"}) + + IVplot = rightGrid.addPlot(labels={"left": "Vm (mV)", "bottom": "Icmd (nA)"}) + IVplot.showGrid(x=True, y=True) + rightGrid.nextRow() + + win.ci.layout.setRowStretchFactor(0, 10) + win.ci.layout.setRowStretchFactor(1, 5) + + # + # Plot simulation and analysis results + # + Vm = self.voltage_traces + Iinj = self.current_traces + Vcmd = self.voltage_cmd + t = self.time_values + steps = len(Vcmd) + + # plot I, V traces + colors = [(i, steps * 3.0 / 2.0) for i in range(steps)] + for i in range(steps): + Vplot.plot(t, Vm[i], pen=colors[i]) + Iplot.plot(t, Iinj[i], pen=colors[i]) + + # I/V relationships + IVplot.plot(Vcmd, self.peak_im(), symbol="o", symbolBrush=(50, 150, 50, 255)) + IVplot.plot(Vcmd, self.steady_im(), symbol="s") diff --git a/cnmodel/synapses/__init__.py b/cnmodel/synapses/__init__.py new file mode 100644 index 0000000..eb36ab7 --- /dev/null +++ b/cnmodel/synapses/__init__.py @@ -0,0 +1,22 @@ +#!/usr/bin/python +# +# Synapse definitions for models. +# +# This file includes a number of different synapse definitions and default conductances +# for point models. Most are models from the lab for neurons of the cochlear nucleus. +# the synaptic receptor models are gleaned from the literature and sometimes fitted to the +# cochlear nucleus data. +# +# Paul B. Manis, Ph.D. 2009 (August - November 2009) +# +from neuron import h +import numpy as np + +from .synapse import Synapse +from .terminal import Terminal +from .psd import PSD +from .glu_psd import GluPSD +from .gly_psd import GlyPSD +from .stochastic_terminal import StochasticTerminal +from .simple_terminal import SimpleTerminal +from .exp2_psd import Exp2PSD diff --git a/cnmodel/synapses/exp2_psd.py b/cnmodel/synapses/exp2_psd.py new file mode 100644 index 0000000..5fbbc0e --- /dev/null +++ b/cnmodel/synapses/exp2_psd.py @@ -0,0 +1,75 @@ +import numpy as np +from neuron import h + +from .psd import PSD + + +class Exp2PSD(PSD): + """ + Simple double-exponential PSD from Neuron (fast). + """ + + def __init__( + self, section, terminal, weight=0.01, loc=0.5, tau1=0.1, tau2=0.3, erev=0 + ): + """ + Parameters + ---------- + section : Section + The postsynaptic section in which to insert the receptor mechanism. + terminal : Terminal + The presynaptic Terminal instance + weight : + loc : float, default=0.5 + Position on the postsynaptic section to insert the mechanism, from [0..1]. + + """ + PSD.__init__(self, section, terminal) + self.syn = h.Exp2Syn(loc, sec=section) + self.syn.tau1 = tau1 + self.syn.tau2 = tau2 + self.syn.e = erev + + terminal.connect(self.syn, weight=weight) + + @property + def n_psd(self): + """The number of postsynaptic densities represented by this object. + """ + return 1 + + def record(self, *args): + """Create a new set of vectors to record parameters for each release + site. + + + Parameters + ---------- + \*args : + Allowed parameters are 'i' (current), 'g' (conductnace), and 'Open' (open probability). + + """ + self.vectors = {"ampa": [], "nmda": []} + for receptor in self.vectors: + for mech in getattr(self, receptor + "_psd"): + vec = {} + for var in args: + vec[var] = h.Vector() + vec[var].record(getattr(mech, "_ref_" + var)) + self.vectors[receptor].append(vec) + + def get_vector(self, var): + """Return an array from a previously recorded vector. + + Parameters + ---------- + receptor : str + May be 'ampa' or 'nmda' + var : str + Allowed parameters are 'i' (current), 'g' (conductance), and 'Open' (open probability). + i : int, default=0 + The integer index of the psd (if this is a multi-site synapse) + + """ + v = self.vectors[receptor][i][var] + return np.array(v) diff --git a/cnmodel/synapses/glu_psd.py b/cnmodel/synapses/glu_psd.py new file mode 100644 index 0000000..4d3ae6e --- /dev/null +++ b/cnmodel/synapses/glu_psd.py @@ -0,0 +1,146 @@ +import numpy as np +from neuron import h + +from .psd import PSD + + +class GluPSD(PSD): + """ + Glutamatergic PSD with ionotropic AMPA / NMDA receptors + + This creates a set of postsynaptoc NMDA and AMPA receptors, one pair + per terminal release site. Receptors are connected to the XMTR range + variable of the terminal release mechanisms. + + Parameters + ---------- + section : Section instance + The postsynaptic section into which the receptor mechanisms should be + attached + terminal : Terminal instance + The presynaptic terminal that provides input to the receptor XMTR + variables. + ampa_gmax : float + Maximum conductance of AMPARs + nmda_gmax : float + Maximum conductance of NMDARs + gvar : float + Coefficient of variation for randomly adjusting ampa_gmax and nmda_gmax. + Note that ampa and nmda maximum conductances will be scaled together, + but the scale values will be selected randomly for each pair of + receptor mechanisms. + eRev : float + Reversal potential to use for both receptor types. + ampa_params : dict + Dictionary containing kinetic parameters for AMPA mechanism. Suggested + keys are Ro1, Ro2, Rc1, Rc2, and PA. + + Notes + ----- + + *ampa_gmax* and *nmda_gmax* should be provided as the maximum *measured* + conductances; these will be automatically corrected for the maximum open + probability of the receptor mechanisms. + + GluPSD does not include a cleft mechanism because AMPATRUSSELL implements + its own cleft and NMDA_Kampa is slow enough that a cleft would have + insignificant effect. + + """ + + def __init__( + self, + section, + terminal, + ampa_gmax, + nmda_gmax, + gvar=0, + eRev=0, + nmda_vshift=0, + ampa_params=None, + loc=0.5, + ): + PSD.__init__(self, section, terminal) + # print('\033[0;33;40m ^^^^^ GVAR = %.4f ^^^^^\033[0;37;40m ' % gvar) + ampa_params = {} if ampa_params is None else ampa_params + + # and then make a set of postsynaptic receptor mechanisms + ampa_psd = [] + nmda_psd = [] + relsite = terminal.relsite + self.section.push() + for i in range(0, terminal.n_rzones): + # create mechanisms + ampa = h.AMPATRUSSELL( + loc, self.section + ) # raman/trussell AMPA with rectification + nmda = h.NMDA_Kampa(loc, self.section) # Kampa state model NMDA receptors + + # Connect terminal to psd + h.setpointer(relsite._ref_XMTR[i], "XMTR", ampa) + h.setpointer(relsite._ref_XMTR[i], "XMTR", nmda) + + # Set any extra ampa parameters provided by the caller + # (Ro1, Ro2, Rc1, Rc2, PA, ...) + for k, v in ampa_params.items(): + setattr(ampa, k, v) + + # add a little variability - gvar is CV of amplitudes + v = 1.0 + gvar * np.random.standard_normal() + + # set gmax and eRev for each postsynaptic receptor mechanism + ampa.gmax = ampa_gmax * v + ampa.Erev = eRev + nmda.gmax = nmda_gmax * v + nmda.Erev = eRev + nmda.vshift = nmda_vshift + + ampa_psd.append(ampa) + nmda_psd.append(nmda) + + h.pop_section() + + self.ampa_psd = ampa_psd + self.nmda_psd = nmda_psd + self.all_psd = nmda_psd + ampa_psd + + @property + def n_psd(self): + """The number of postsynaptic densities represented by this object. + """ + return len(self.ampa_psd) + + def record(self, *args): + """Create a new set of vectors to record parameters for each release + site. + + Parameters + ---------- + \*args : + Allowed parameters are 'i' (current), 'g' (conductance), and 'Open' (open probability). + + """ + self.vectors = {"ampa": [], "nmda": []} + for receptor in self.vectors: + for mech in getattr(self, receptor + "_psd"): + vec = {} + for var in args: + vec[var] = h.Vector() + vec[var].record(getattr(mech, "_ref_" + var)) + self.vectors[receptor].append(vec) + + def get_vector(self, receptor, var, i=0): + """Return an array from a previously recorded vector. + + Parameters + ---------- + receptor : str + May be 'ampa' or 'nmda' + var : str + Allowed parameters are 'i' (current), 'g' (conductance), and 'Open' (open probability). + i : int, default=0 + The integer index of the psd (if this is a multi-site synapse) + + """ + v = self.vectors[receptor][i][var] + return np.array(v) diff --git a/cnmodel/synapses/gly_psd.py b/cnmodel/synapses/gly_psd.py new file mode 100644 index 0000000..84fd429 --- /dev/null +++ b/cnmodel/synapses/gly_psd.py @@ -0,0 +1,398 @@ +from __future__ import print_function +import numpy as np +from neuron import h + +from .psd import PSD + + +class GlyPSD(PSD): + """Glycinergic PSD + + This creates postsynaptoc glycinergic receptors. Receptors are connected to the XMTR range + variable of the terminal release mechanisms. + + Parameters + ---------- + section : Section + The postsynaptic section in which to insert the receptor mechanism. + terminal : Terminal + The presynaptic Terminal instance + params : dict, default=None + Dictionary of kinetic parameters to override {'KV', 'KU', 'XMax'} + gmax : float, default=1000. + maximal conductance unless overridden by values used in psdType + psdType : str, default='glyfast' + Kinetic model of receptors: possiblities are: + glyfast, glyslow, glyGC, glya5, or glyexp, as defined in the mechanisms. + message : str, default: None + placeholder for a message to be printed out when testing. + debug: bool, default=False + enable printing of internal debugging messages. + gvar : float, default=0 + coefficient of variation of the amplitudes for each of the release zones. + eRev : float, default=-70 + "Reversal" potential, or Nernst potential for ions through the receptor channel. + loc : float, default=0.5 + Position on the postsynaptic section to insert the mechanism, from [0..1]. + + """ + + def __init__( + self, + section, + terminal, + params=None, + gmax=1000.0, + psdType="glyfast", + message=None, + debug=False, + gvar=0, + eRev=-70, + loc=0.5, + ): + + PSD.__init__(self, section, terminal) + pre_sec = terminal.section + post_sec = section + + from .. import cells + + params = {} if params is None else params + + self.pre_cell = cells.cell_from_section(pre_sec) + self.post_cell = cells.cell_from_section(post_sec) + + self.psdType = psdType + self.gmax = gmax + glyslowPoMax = ( + 0.162297 + ) # thse were measured from the kinetic models in Synapses.py, as peak open P for the glycine receptors + glyfastPoMax = 0.038475 # also later verified, same numbers... + if self.psdType == "glyfast": + gmax /= ( + glyfastPoMax + ) # normalized to maximum open probability for this receptor + if self.psdType == "glyslow": + gmax /= glyslowPoMax # normalized to max open prob for the slow receptor. + + # print "Stochastic syn: j = %d of n_fibers = %d n_rzones = %d\n" % (j, n_fibers, n_rzones) + relzone = terminal.relsite + n_rzones = terminal.n_rzones + + # + # Create cleft mechanisms + # + clefts = [] + for k in range(0, n_rzones): + cl = h.cleftXmtr(loc, sec=post_sec) + clefts.append(cl) + + # and then make a set of postsynaptic receptor mechanisms + if self.psdType == "glyslow": + (psd, par) = self.template_Gly_PSD_State_Gly6S( + nReceptors=n_rzones, psdtype=self.psdType + ) + elif self.psdType == "glyfast": + (psd, par) = self.template_Gly_PSD_State_PL( + nReceptors=n_rzones, psdtype=self.psdType + ) + elif self.psdType == "glyGC": + (psd, par) = self.template_Gly_PSD_State_GC( + nReceptors=n_rzones, psdtype=self.psdType + ) + elif self.psdType == "glya5": + (psd, par) = self.template_Gly_PSD_State_Glya5( + nReceptors=n_rzones, psdtype=self.psdType + ) + elif self.psdType == "glyexp": + (psd, par) = self.template_Gly_PSD_exp( + nReceptors=n_rzones, psdtype=self.psdType + ) + else: + print("**PSDTYPE IS NOT RECOGNIZED: [%s]\n" % (self.psdType)) + exit() + if debug: + print("pre_sec: ", pre_sec) + + # Connect terminal to psd (or cleft) + self._cleft_netcons = [] + for k in range(0, n_rzones): + pre_sec.push() + netcon = h.NetCon(relzone._ref_XMTR[k], clefts[k], 0.1, 0.0, 1.0) + self._cleft_netcons.append(netcon) + h.pop_section() + + # set cleft transmitter kinetic parameters + for pname, pval in params.items(): + setattr(clefts[k], pname, pval) + + h.setpointer( + clefts[k]._ref_CXmtr, "XMTR", psd[k] + ) # connect transmitter release to the PSD + + v = 1.0 + gvar * np.random.standard_normal() + psd[k].gmax = ( + gmax * v + ) # add a little variability - gvar is CV of amplitudes + # print 'GLY psd %s %d gmax=%f' % (self.psdType, k, gmax) + psd[k].Erev = eRev # set the reversal potential + + par = list(par) + + if message is not None: + print(message) + + self.all_psd = psd + self.clefts = clefts + self.par = par + + # the following templates are a bit more complicated. + # The parameter names as defined in the model are returned + # but also those that are involved in the forward binding reactions are + # listed separately - this is to allow us to run curve fits that adjust + # only a subset of the parameters a time - e.g., the rising phase, then + # the falling phase with the rising phase fixed. + # the dictionary selection is made by selectpars in glycine_fit.py. + # + + def template_Gly_PSD_exp( + self, debug=False, nReceptors=2, cellname=None, message=None, loc=0.5 + ): + """ + Template to build simple glycinergic exp-style PSD + + Parameters + ---------- + nReceptors : int, default=2 + number of sites to implement + loc : float, default=0.5 + Position on the postsynaptic section to insert the mechanism, from [0..1]. + + Unused parameters: + cellname, debug, message. + + """ + + sec = self.section + psd = [] + sec.push() + for k in range(0, nReceptors): + psd.append(h.GLY2(loc, sec)) + h.pop_section() + par = ["alpha", "beta"] + p = [] + for n in par: + p.append(eval("psd[0]." + n)) # get default values from the mod file + return (psd, par, p) + + def template_Gly_PSD_State_Glya5( + self, debug=False, nReceptors=2, psdtype=None, message=None, loc=0.5 + ): + """ + Template to build PSD using state model of glycine receptors, model glya5.mod + + Parameters + ---------- + nReceptors : int, default=2 + number of sites to implement + loc : float, default=0.5 + Position on the postsynaptic section to insert the mechanism, from [0..1]. + + Unused parameters: + cellname, debug, message, psdtype. + + """ + sec = self.section + psd = [] + sec.push() + for k in range(0, nReceptors): + psd.append(h.GLYa5(loc, sec)) + h.pop_section() + par = { + "kf1": ("r", psd[0].kf1), # retreive values in the MOD file + "kf2": ("r", psd[0].kf2), + "kb1": ("r", psd[0].kb1), + "kb2": ("r", psd[0].kb2), + "a1": ("f", psd[0].a1), + "b1": ("f", psd[0].b1), + "a2": ("f", psd[0].a2), + "b2": ("f", psd[0].b2), + } + return (psd, par) + + def template_Gly_PSD_State_Gly6S( + self, debug=False, nReceptors=2, psdtype=None, message=None, loc=0.5 + ): + """ + Template to build PSD using state model of glycine receptors, model gly6s.mod + + Parameters + ---------- + nReceptors : int, default=2 + number of sites to implement + loc : float, default=0.5 + Position on the postsynaptic section to insert the mechanism, from [0..1]. + psdtype : str, default=None + resets the psd type to have slow kinetics if 'glyslow'. Any other string + defaults to kinetics in the mod file. + + Unused parameters: + cellname, debug, message. + + """ + sec = self.section + psd = [] + sec.push() + for k in range(0, nReceptors): + psd.append( + h.Gly6S(loc, sec) + ) # simple using Trussell model 6 states with desens + if debug: + print("Gly6S psdtype: ", psdtype) + if ( + psdtype == "glyslow" + ): # fit on 8 March 2010, error = 0.164, max open: 0.155 + psd[-1].Rd = 1.177999 + psd[-1].Rr = 0.000005 + psd[-1].Rb = 0.009403 + psd[-1].Ru2 = 0.000086 + psd[-1].Ro1 = 0.187858 + psd[-1].Ro2 = 1.064426 + psd[-1].Ru1 = 0.028696 + psd[-1].Rc1 = 0.103625 + psd[-1].Rc2 = 1.730578 + h.pop_section() + par = { + "Rb": ("n", psd[0].Rb), # retrive values in the MOD file + "Ru1": ("r", psd[0].Ru1), + "Ru2": ("r", psd[0].Ru2), + "Rd": ("f", psd[0].Rd), + "Rr": ("f", psd[0].Rr), + "Ro1": ("f", psd[0].Ro1), + "Ro2": ("r", psd[0].Ro2), + "Rc1": ("f", psd[0].Rc1), + "Rc2": ("r", psd[0].Rc2), + } + return (psd, par) + + def template_Gly_PSD_State_PL( + self, + debug=False, + nReceptors=2, + cellname=None, + psdtype=None, + message=None, + loc=0.5, + ): + """ + Template to build PSD using state model of glycine receptors, model glypl.mod + + Parameters + ---------- + nReceptors : int, default=2 + number of sites to implement + loc : float, default=0.5 + Position on the postsynaptic section to insert the mechanism, from [0..1]. + psdtype : str, default=None + resets the psd type to have slow kinetics if 'glyslow'. + 'glyfast' forces fast kinetics. + Any other string defaults to the default kinetics in the mod file. + + Unused parameters: + cellname, debug, message,. + + """ + sec = self.section + psd = [] + sec.push() + for k in range(0, nReceptors): + psd.append(h.GLYaPL(loc, sec)) # simple dextesche glycine receptors + if debug: + print("PL psdtype: ", psdtype) + if psdtype == "glyslow": + psd[-1].a1 = 0.000451 + psd[-1].a2 = 0.220 + psd[-1].b1 = 13.27 + psd[-1].b2 = 6.845 + psd[-1].kon = 0.00555 + psd[-1].koff = 2.256 + psd[-1].r = 1.060 + psd[-1].d = 55.03 + if ( + psdtype == "glyfast" + ): # fit from 3/5/2010. error = 0.174 maxopen = 0.0385 + psd[-1].a1 = 1.000476 + psd[-1].a2 = 0.137903 + psd[-1].b1 = 1.700306 + psd[-1].koff = 13.143132 + psd[-1].kon = 0.038634 + psd[-1].r = 0.842504 + psd[-1].b2 = 8.051435 + psd[-1].d = 12.821820 + h.pop_section() + par = { + "kon": ("r", psd[0].kon), # retrive values in the MOD file + "koff": ("r", psd[0].koff), + "a1": ("r", psd[0].a1), + "b1": ("r", psd[0].b1), + "a2": ("f", psd[0].a2), + "b2": ("f", psd[0].b2), + "r": ("f", psd[0].r), + "d": ("f", psd[0].d), + } + return (psd, par) + + def template_Gly_PSD_State_GC( + self, debug=False, nReceptors=2, psdtype=None, message=None, loc=0.5 + ): + """ + Template to build PSD using state model of glycine receptors, model glyaGC.mod + + Parameters + ---------- + nReceptors : int, default=2 + number of sites to implement + loc : float, default=0.5 + Position on the postsynaptic section to insert the mechanism, from [0..1]. + psdtype : str, default=None + resets the psd type to have slow kinetics if 'glyslow'. Any other string + defaults to predefined kinetics in the mod file. + + Unused parameters: + cellname, debug, message, psdtype. + + """ + sec = self.section + psd = [] + sec.push() + for k in range(0, nReceptors): + psd.append(h.GLYaGC(loc, sec)) # simple Dextesche glycine receptors + if psdtype == "glyslow": + psd[-1].k1 = 12.81 # (/uM /ms) : binding + psd[-1].km1 = 0.0087 # (/ms) : unbinding + psd[-1].a1 = 0.0195 # (/ms) : opening + psd[-1].b1 = 1.138 # (/ms) : closing + psd[-1].r1 = 6.13 # (/ms) : desense 1 + psd[-1].d1 = 0.000462 # (/ms) : return from d1 + psd[-1].r2 = 0.731 # (/ms) : return from deep state + psd[-1].d2 = 1.65 # (/ms) : going to deep state + psd[-1].r3 = 3.83 # (/ms) : return from deep state + psd[-1].d3 = 1.806 # (/ms) : going to deep state + psd[-1].rd = 1.04 # (/ms) + psd[-1].dd = 1.004 # (/ms) + h.pop_section() + par = { + "k1": ("r", psd[0].k1), # retrive values in the MOD file + "km1": ("r", psd[0].km1), + "a1": ("r", psd[0].a1), + "b1": ("r", psd[0].b1), + "r1": ("f", psd[0].r1), + "d1": ("f", psd[0].d1), + "r2": ("f", psd[0].r2), + "d2": ("f", psd[0].d2), + "r3": ("f", psd[0].r3), + "d3": ("f", psd[0].d3), + "rd": ("f", psd[0].rd), + "dd": ("f", psd[0].dd), + } + return (psd, par) diff --git a/cnmodel/synapses/psd.py b/cnmodel/synapses/psd.py new file mode 100644 index 0000000..c675b2e --- /dev/null +++ b/cnmodel/synapses/psd.py @@ -0,0 +1,41 @@ +class PSD(object): + """ + Base class for postsynaptic density mechanisms, possibly including cleft. + May accept either NetCon or pointer inputs from a Terminal, and directly + modifies the membrane potential and/or ion concentrations of the + postsynaptic cell. + """ + + def __init__(self, section, terminal): + """ + Parameters + ---------- + section : :obj:`NEURON section` + Set the section in the postsynaptic cell that the terminal is attached to. + + terminal : :obj:`Synapse` + + + """ + self._section = section + self._terminal = terminal + + @property + def section(self): + """ The cell section this PSD is attached to. + """ + return self._section + + @property + def cell(self): + """ The cell this PSD is attached to. + """ + from ..cells import Cell + + return Cell.from_section(self.section) + + @property + def terminal(self): + """ The presynaptic terminal connected to this PSD. + """ + return self._terminal diff --git a/cnmodel/synapses/simple_terminal.py b/cnmodel/synapses/simple_terminal.py new file mode 100644 index 0000000..8b6b1fb --- /dev/null +++ b/cnmodel/synapses/simple_terminal.py @@ -0,0 +1,52 @@ +from neuron import h + +from .terminal import Terminal + + +class SimpleTerminal(Terminal): + """ + Simple terminal using netcon. + """ + + def __init__(self, pre_sec, target_cell, spike_source=None, loc=0.5): + """ + Parameters + ---------- + pre_sec : :obj: `NEURON Section` + The presynaptic section that is monitored for spikes. The voltage + in this section is monitored to trigger the postsynaptic conductance + as the spike source + spike_source : :obj: `NEURON Section` + Overrides the pre_sec as the spike source for this terminal. + terminal : :obj: `Synapse Terminal` + The presynaptic Terminal instance + loc : float, default=0.5 + Position on the postsynaptic section to insert the mechanism, from [0..1]. + """ + + Terminal.__init__(self, pre_sec) + if spike_source is None: + spike_source = pre_sec(loc)._ref_v + self.spike_source = spike_source + self.pre_sec = pre_sec + + def connect(self, post, weight): + """ + Connect this terminal to a postsynaptic cell section + The synaptic delay is 0.5 msec, and the presynaptic + action potential threshold is -20 mV. + + Parameters + ---------- + post : :obj: `NEURON Section` + + weight : float + Strength of the connection + + """ + thresh = -20 + delay = 0.5 + self.netcon = h.NetCon( + self.spike_source, post, thresh, delay, weight, sec=self.pre_sec + ) + self.netcon.weight[0] = weight diff --git a/cnmodel/synapses/stochastic_terminal.py b/cnmodel/synapses/stochastic_terminal.py new file mode 100644 index 0000000..b49be40 --- /dev/null +++ b/cnmodel/synapses/stochastic_terminal.py @@ -0,0 +1,393 @@ +from __future__ import print_function +from neuron import h + +from .terminal import Terminal +from ..util import random_seed + +# utility class to create parameter lists... +# create like: p = Params(abc=2.0, defg = 3.0, lunch='sandwich') +# reference like p.abc, p.defg, etc. +class Params(object): + def __init__(self, **kwds): + self.__dict__.update(kwds) + + +class StochasticTerminal(Terminal): + """ + Axon terminal with multi-site sctochastic release mechanism. + """ + + def __init__( + self, + pre_sec, + target_cell, + nzones=1, + multisite=True, + message=None, + type="lognormal", + identifier=0, + stochastic_pars=None, + calcium_pars=None, + delay=0, + debug=False, + select=None, + spike_source=None, + dep_flag=1, + ): + """ + This routine creates a (potentially) multisite synapse using a NEURON mod file with: + - A MultiSiteSynapse release mechanism that includes stochastic release, with a lognormal + release latency distribution. The Facilitation and Depression of release are governed + by parameters obtaine from fitting the Dittman-Kreitzer-Regher (DKR) model (J Neurosci. 2000 Feb 15;20(4):1374-85.) + to experimental data at various + frequencies. + - A "cleft" mechanism (models diffusion of transmitter). Note that the cleft is inserted as part of the + presynaptic section, but is not connected to the postsynaptic side yet. + + Each release site is stochastically independent, but all sites within a terminal are drive by the + same presynaptic action potentials. + + Turning off the depression and facilitation in the kinetic portion of the model substantially decreases + the time the terminal mechanism takes to run. + + Parameters + ---------- + pre_sec : :obj:`section` + The NEURON section where the synaptic mechanisms should be inserted. + target_cell : :obj:`Cell` + The target cell object that the synapse will innervate. + nzones : int + The number of activate zones to insert into the section. + multisite : bool, default: True + A flag that determines whether the terminal actually creates multiple + release zones (True) or just creates a single release zone that + varies its amplitude based on the depression/facilitation state. + message : str + A message to when instantiating (mostly for verification of code flow). + type: str (default: 'lognormal') + 'lognormal' sets the release event latency distribution to use a lognormal function. Currently, + no other function is supported. + identifier : int (default: 0) + An identifier to associate with these release sites so we can find them later. + stochastic_pars : dict (default: None) + A dictionary of parameters (Param class) used to specifiy the stochastic behavior of this site, + including release latency, stdev, and lognormal distribution paramaters + calcium_pars : dict (default: None) + A dictionary of parameters (Param class) to determine the calcium channels in this section. + If None, then no calcium channels are inserted; otherwise, a P-type calcium conductance and a dynamic + mechanism are inserted, and their conductance is set. + delay : float (default: 0) + Delay time in msec from action potential until transmitter release for this terminal. + debug : bool (default: False) + Flag to print stuff out while debugging. + spike_source : :obj:`section` (default: None) + The input spike source to use in net con - default is to use pre_sec when set to None. + dep_flag : int (default: 1) + Set to 1 for depression mechanism (slows computation), 0 to turn off the depression calculations + + Returns + ------- + list + the list contains the terminal, the relsites, and the list of cleft mechanisms: + + - terminal: this is the pointer to the terminal section that was inserted (same as pre_sec if it was + specified) + - relsite: a list of the nzones release sites that were created + - cleft: a list of the nzones cleft mechanisms that were created. + + """ + Terminal.__init__(self, pre_sec) + + # set parameter control for the stochastic release of vesicles... + # this structure is passed to stochastic synapses, and replaces several variables + # that were previously defined in the call to that function. + + thresh = -30 # mV - AP detection on the presynaptic side. + + ANTerminals_Latency = 0.5 # latency + vPars = Params( + LN_Flag=1, + LN_t0=10.0, + LN_A0=0.05, + LN_tau=35, + LN_std=0.05, + Lat_Flag=1, + Lat_t0=10.0, + Lat_A0=0.140, + Lat_tau=21.5, + latency=ANTerminals_Latency, + ) + # NOTE: stochastic_pars must define parameters used by multisite, including: + # .delay is the netcon delay between the presynaptic AP and the start of release events + # .Latency is the latency to the mean release event... this could be confusing. + + if stochastic_pars is None: + stochastic_pars = vPars + + message = ( + " >> creating terminal with %d release zones using lognormal release latencies (coh4)" + % nzones + ) + if debug: + print(message) + terminal = pre_sec + # terminal.push() + if calcium_pars is not None: + terminal.insert("cap") # insert calcium channel density + terminal().cap.pcabar = calcium_pars.Ca_gbar + terminal.insert("cad") + + # Create point process to simulate multiple independent release zones. + relsite = h.MultiSiteSynapse(0.5, sec=terminal) + relsite.nZones = nzones + if multisite: + relsite.multisite = 1 + relsite.rseed = random_seed.current_seed() # use global random seed + relsite.latency = stochastic_pars.latency + relsite.latstd = stochastic_pars.LN_std + self.n_rzones = nzones + else: + relsite.multisite = 0 + self.release_rng = h.Random(random_seed.current_seed()) + self.release_rng.uniform(0, 1) + relsite.setUniformRNG(self.release_rng) + self.n_rzones = 1 + + relsite.Dep_Flag = dep_flag # control synaptic dynamics + if debug is True: + relsite.debug = 1 + relsite.Identifier = identifier + # if type == 'gamma': + # gd = gamma.rvs(2, size=10000)/2.0 # get a sample of 10000 events with a gamma dist of 2, set to mean of 1.0 + # if relsite.latstd > 0.0: + # gds = relsite.latency+std*(gd-1.0)/gd.std() # scale standard deviation + # else: + # gds = relsite.latency*np.ones((10000,1)) + # if type == 'lognormal': + # if std > 0.0: + # gds = lognormal(mean=0, sigma=relsite.latstd, size=10000) + # else: + # gds = np.zeros((10000, 1)) + # use the variable latency mode of COH4. And, it is lognormal no matter what. + # the parameters are defined in COH4.mod as follows + # Time course of latency shift in release during repetitive stimulation + # Lat_Flag = 0 (1) : 0 means fixed latency, 1 means lognormal distribution + # Lat_t0 = 0.0 (ms) : minimum time since simulation start before changes in latency are calculated + # Lat_A0 = 0.0 (ms) : size of latency shift from t0 to infinity + # Lat_tau = 100.0 (ms) : rate of change of latency shift (from fit of a+b(1-exp(-t/tau))) + # : Statistical control of log-normal release shape over time during repetive stimulation + # LN_Flag = 0 (1) : 0 means fixed values for all time + # LN_t0 = 0.0 (ms) : : minimum time since simulation start before changes in distribution are calculated + # LN_A0 = 0.0 (ms) : size of change in sigma from t0 to infinity + # LN_tau = 100.0 (ms) : rate of change of sigma over time (from fit of a+b*(1-exp(-t/tau))) + + relsite.LN_Flag = ( + stochastic_pars.LN_Flag + ) # enable use of lognormal release latency + relsite.LN_t0 = stochastic_pars.LN_t0 + relsite.LN_A0 = stochastic_pars.LN_A0 + relsite.LN_tau = stochastic_pars.LN_tau + relsite.Lat_Flag = stochastic_pars.Lat_Flag + relsite.Lat_t0 = stochastic_pars.Lat_t0 + relsite.Lat_A0 = stochastic_pars.Lat_A0 + relsite.Lat_tau = stochastic_pars.Lat_tau + # mpl.figure(2) + + h.pop_section() + self.relsite = relsite + + if spike_source is None: + spike_source = pre_sec(0.5)._ref_v + + self.netcon = h.NetCon(spike_source, relsite, thresh, delay, 1.0, sec=pre_sec) + self.netcon.weight[0] = 1 + self.netcon.threshold = -30.0 + + self.setPsdType(target_cell, select) + + def setPsdType(self, target_cell, select=None): + """ + Assign a postsynpatic density type - selection of receptors to be + associated with the presynaptic terminal. + + Parameters + ---------- + target_cell : :obj:`NEURON section` + Define the target cell so that the correct PSD is inserted + + select : str + Not used in current implementation. + + """ + # TODO: must resurrect this for inhibitory synapses. + # (and move constants out to their respective synapse locations) + # elif psdtype.startswith('gly'): + # self.setDF(target_cell, 'ipsc', select) # set the parameters for release + self.setDF(target_cell, "epsc") # set the parameters for release + + ################################################################################ + # The following routines set the synapse dynamics, based on measurements and fit + # to the DKR model. + ################################################################################ + + def setDF(self, target_cell, synapsetype, select=None): + """ + Set the facilitation/depression parameters for the multisite release model. + The parameters used here were obtained from an optimized fit of the DKR + model to stimulus and recovery data for the auditory nerve synapses onto bushy + and T-stellate cells at 100, 200 and 300 Hz (simultaneous fitting), for times out to about + 0.5 - 1.0 second. Data were collected by Dr. Ruili Xie and Dr. Yong Wang. + Fitting by Paul Manis. + + Parameters + ---------- + target_cell : :obj:`NEURON section` + Define the target cell so that the correct release kinetics are used + + synapsetype : str + String defining the type of synapse: 'ipsc' or 'epsc' + + select : str (default: None) + Select kinetcs from a particular example cell. + + """ + from .. import cells + + if isinstance(target_cell, cells.Bushy): + if synapsetype == "ipsc": + if select is None: + self.bushy_ipsc_average() + else: + self.bushy_ipsc_single(select=select) + elif isinstance(target_cell, cells.TStellate): + if synapsetype == "ipsc": + self.stellate_ipsc() + + def set_params(self, **params): + """Set arbitrary parameters on the release mechanism. + + Parameters + ---------- + \**params : dict + dictionary of parameters to set on the release mechanism. + + """ + for k, v in params.items(): + setattr(self.relsite, k, v) + + def stellate_ipsc(self): + """ Facilitation/Depression parameters for DKR model for IPSCs onto stellate cells. + IPSCs were derived from stimulation of the dorsal cochlear nucleus, and so represent + the glycinergic synapses from tuberculoventral neurons. + Data is average of 3 cells studied with recovery curves and individually fit, at 100 Hz. + """ + self.relsite.F = 0.23047 + self.relsite.k0 = 1.23636 + self.relsite.kmax = 45.34474 + self.relsite.taud = 98.09 + self.relsite.kd = 0.01183 + self.relsite.taus = 17614.50 + self.relsite.ks = 17.88618 + self.relsite.kf = 19.11424 + self.relsite.tauf = 32.28 + self.relsite.dD = 2.52072 + self.relsite.dF = 2.33317 + self.relsite.glu = 3.06948 + + def bushy_ipsc_average(self): + """ Facilitation/Depression parameters for DKR model for IPSCs onto bushy cells. + IPSCs were derived from stimulation of the dorsal cochlear nucleus, and so represent + the glycinergic synapses from tuberculoventral neurons. + Data for the kinetcs are the average of 16 bushy cells. + The individual fits were compiled, and an average computed for just the 100 Hz data + across the individual fits. This average was then fit to the DKR model + (also see Matthew Xu-Friedman's papers). + The individual cells show a great deal of variability, from straight depression, to + mixed depression/facilitaiton, to facilation alone. This set of parameters generates + a weak facilitation followed by depression back to baseline. + + There are other data sets in the source that are commented out. + """ + # print( "USING average kinetics for Bushy IPSCs") + + # average of 16cells for 100 Hz (to model); no recovery. + self.relsite.F = 0.18521 + self.relsite.k0 = 2.29700 + self.relsite.kmax = 27.6667 + self.relsite.taud = 0.12366 + self.relsite.kd = 0.12272 + self.relsite.taus = 9.59624 + self.relsite.ks = 8.854469 + self.relsite.kf = 5.70771 + self.relsite.tauf = 0.37752 + self.relsite.dD = 4.00335 + self.relsite.dF = 0.72605 + self.relsite.glu = 5.61985 + + def bushy_ipsc_single(self, select=None): + """ + Facilitation/Depression parameters for DKR model for IPSCs onto 3 individual bushy cells. + IPSCs were derived from stimulation of the dorsal cochlear nucleus, and so represent + the glycinergic synapses from tuberculoventral neurons. + + Parameters + ---------- + select : int, default=None + select which cell's measured kinetics will be used: + + 0: Use average + 1: use data from 30aug08f + 2: select = 2, use data from 30aug08h + 3: select = 3, use data from 31aug08b (single cell, clean dataset) + + """ + # print ("Using bushy ipsc") + + if select is None or select > 4 or select <= 0: + self.bushy_ipsc_average() + return + + if select is 1: # 30aug08f + # print ("using 30aug08f ipsc") + self.relsite.F = 0.221818 + self.relsite.k0 = 0.003636364 + self.relsite.kmax = 0.077562107 + self.relsite.taud = 0.300000 + self.relsite.kd = 1.112554 + self.relsite.taus = 3.500000 + self.relsite.ks = 0.600000 + self.relsite.kf = 3.730452 + self.relsite.tauf = 0.592129 + self.relsite.dD = 0.755537 + self.relsite.dF = 2.931578 + self.relsite.glu = 1.000000 + + if select is 2: # 30aug08h + # print ("using 30aug08H ipsc") + self.relsite.F = 0.239404 + self.relsite.k0 = 3.636364 / 1000.0 + self.relsite.kmax = 16.725479 / 1000.0 + self.relsite.taud = 0.137832 + self.relsite.kd = 0.000900 + self.relsite.taus = 3.500000 + self.relsite.ks = 0.600000 + self.relsite.kf = 4.311995 + self.relsite.tauf = 0.014630 + self.relsite.dD = 3.326148 + self.relsite.dF = 0.725512 + self.relsite.glu = 1.000000 + + if select is 3: + # print ("using IPSC#3 ") + self.relsite.F = 0.29594 + self.relsite.k0 = 0.44388 / 1000.0 + self.relsite.kmax = 15.11385 / 1000.0 + self.relsite.taud = 0.00260 + self.relsite.kd = 0.00090 + self.relsite.taus = 11.40577 + self.relsite.ks = 27.98783 + self.relsite.kf = 30.00000 + self.relsite.tauf = 0.29853 + self.relsite.dD = 3.70000 + self.relsite.dF = 2.71163 + self.relsite.glu = 4.97494 diff --git a/cnmodel/synapses/synapse.py b/cnmodel/synapses/synapse.py new file mode 100644 index 0000000..f6a31b9 --- /dev/null +++ b/cnmodel/synapses/synapse.py @@ -0,0 +1,15 @@ +from .stochastic_terminal import StochasticTerminal +from .psd import PSD + + +class Synapse(object): + """Encapsulates a synaptic connection between two cells. + + Instances of this class are created by calling `Cell.connect()`. + """ + + def __init__(self, pre_cell, pre_opts, post_cell, post_opts, type="multisite"): + pre_opts["term_type"] = type + post_opts["psd_type"] = type + self.terminal = pre_cell.make_terminal(post_cell, **pre_opts) + self.psd = post_cell.make_psd(self.terminal, **post_opts) diff --git a/cnmodel/synapses/terminal.py b/cnmodel/synapses/terminal.py new file mode 100644 index 0000000..61faea4 --- /dev/null +++ b/cnmodel/synapses/terminal.py @@ -0,0 +1,32 @@ +class Terminal(object): + """ + Base class for axon terminals. A terminal has a single postsynaptic + neuron, but may have multiple release zones. It defines a release mechanism + with a NetCon input (triggering from presynaptic voltage or calcium level) + and either NetCon or pointer output for driving a PSD. + + """ + + def __init__(self, section): + """ + Parameters + ---------- + section : :obj:`NEURON section` + Set the section in the postsynaptic cell that the terminal is attached to. + + """ + self._section = section + + @property + def section(self): + """ The cell section this terminal is attached to. + """ + return self._section + + @property + def cell(self): + """ The cell this terminal is attached to. + """ + from ..cells import Cell + + return Cell.from_section(self.section) diff --git a/cnmodel/synapses/tests/test_data/dstellate_bushy.pk b/cnmodel/synapses/tests/test_data/dstellate_bushy.pk new file mode 100644 index 0000000..46ef8e8 --- /dev/null +++ b/cnmodel/synapses/tests/test_data/dstellate_bushy.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:770319a9229c66e4796757854b0d1e341f5d376abf0284385360788c41c6d20b +size 11836 diff --git a/cnmodel/synapses/tests/test_data/dstellate_dstellate.pk b/cnmodel/synapses/tests/test_data/dstellate_dstellate.pk new file mode 100644 index 0000000..e2dcb0f --- /dev/null +++ b/cnmodel/synapses/tests/test_data/dstellate_dstellate.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:83554699cefe547a22eb959c83cf9a86d62383d858a1b8d78716eae16b382e43 +size 6110 diff --git a/cnmodel/synapses/tests/test_data/dstellate_tstellate.pk b/cnmodel/synapses/tests/test_data/dstellate_tstellate.pk new file mode 100644 index 0000000..27e3da3 --- /dev/null +++ b/cnmodel/synapses/tests/test_data/dstellate_tstellate.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c812143a8582d423c7fababd2060bbbaa064b5b767f576cd117685af207c944e +size 11421 diff --git a/cnmodel/synapses/tests/test_data/sgc_bushy.pk b/cnmodel/synapses/tests/test_data/sgc_bushy.pk new file mode 100644 index 0000000..dc01dde --- /dev/null +++ b/cnmodel/synapses/tests/test_data/sgc_bushy.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42d5eed880a498157400a9fdc442341e7e32c1ef1db8d398ac016e27fcbb6286 +size 42555 diff --git a/cnmodel/synapses/tests/test_data/sgc_dstellate.pk b/cnmodel/synapses/tests/test_data/sgc_dstellate.pk new file mode 100644 index 0000000..d9a0184 --- /dev/null +++ b/cnmodel/synapses/tests/test_data/sgc_dstellate.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6176f9cbf15f5f81d36a7cf64e0d9a72e0187a0d647642b838f72c0373a3349e +size 8867 diff --git a/cnmodel/synapses/tests/test_data/sgc_tstellate.pk b/cnmodel/synapses/tests/test_data/sgc_tstellate.pk new file mode 100644 index 0000000..bd3a9ab --- /dev/null +++ b/cnmodel/synapses/tests/test_data/sgc_tstellate.pk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e62835df05a9f859bbae3d48639bdb4456ca91a7ce62405f618e692494d5c92c +size 10586 diff --git a/cnmodel/synapses/tests/test_psd.py b/cnmodel/synapses/tests/test_psd.py new file mode 100644 index 0000000..06bedc5 --- /dev/null +++ b/cnmodel/synapses/tests/test_psd.py @@ -0,0 +1,190 @@ +# -*- encoding: utf-8 -*- +from __future__ import print_function +import sys +import numpy as np +import pyqtgraph as pg +import neuron + +import cnmodel +import cnmodel.cells as cells +from cnmodel.protocols import SynapseTest +from cnmodel.util import random_seed, reset +from cnmodel import data + +""" +Check that sgc PSDs have correct AMPA and NMDA peak conductances / CV. +""" + + +def test_sgc_bushy_psd(plot=False): + sgc_psd_test(cells.Bushy, seed=23572385, tstop=4.0, plot=plot) + + +def test_sgc_tstellate_psd(plot=False): + sgc_psd_test(cells.TStellate, seed=34754398, plot=plot) + + +def test_sgc_dstellate_psd(plot=False): + sgc_psd_test(cells.DStellate, seed=54743998, plot=plot, n_syn=50) + + +def test_sgc_octopus_psd(plot=False): + sgc_psd_test(cells.Octopus, seed=54743998, plot=plot, n_syn=50) + + +def sgc_psd_test(cell_class, seed, plot=False, tstop=5.0, n_syn=20): + """ + Tests a multisite synapse from the SGC to a target cell. + The values returned from an actual set of runs of the synapse are compared + to the expected values in the synapses.py table. This is needed because + the maximal open probability of the receptor models is not 1, so the maximal + conductance per receptor needs to be adjusted empirically. If the measured current + does not match the expected current, then we print a message with the expected value, + and fail with an assert statment in the test. + The measurement itself is made in measure_gmax(). + + Parameters + ---------- + cell_class : an instance of the cell class + seed : int + random number seed for the call + plot : boolean (default False) + plot request, passed to measure_gmax + tstop : float (default 5.0 ms) + duration of run for measurement of gmax. Needs to be long enough to find the + maximum of the EPSC/IPSC. + n_syn : int (default 20) + number of synapses to instantiate for testing (to get an average value) + + """ + celltyp = cell_class.__name__.lower() + + random_seed.set_seed(seed) + reset( + raiseError=False + ) # avoid failure because we cannot release NEURON objects completely. + tsc = cell_class.create(ttx=True) + (ampa_gmax, nmda_gmax, epsc_cv) = measure_gmax( + tsc, n_syn=n_syn, tstop=tstop, plot=plot + ) + exp_ampa_gmax = data.get( + "sgc_synapse", species="mouse", post_type=celltyp, field="AMPA_gmax" + )[0] + exp_nmda_gmax = data.get( + "sgc_synapse", species="mouse", post_type=celltyp, field="NMDA_gmax" + )[0] + exp_epsc_cv = data.get( + "sgc_synapse", species="mouse", post_type=celltyp, field="EPSC_cv" + ) + ampa_correct = np.allclose(exp_ampa_gmax, ampa_gmax) + if not ampa_correct: + AMPAR_gmax = data.get( + "sgc_synapse", species="mouse", post_type=celltyp, field="AMPAR_gmax" + ) + ratio = exp_ampa_gmax / ampa_gmax + print( + "AMPA Receptor conductance in model should be %.16f (table is %.16f)" + % (AMPAR_gmax * ratio, AMPAR_gmax) + ) + nmda_correct = np.allclose(exp_nmda_gmax, nmda_gmax) + if not nmda_correct: + NMDAR_gmax = data.get( + "sgc_synapse", species="mouse", post_type=celltyp, field="NMDAR_gmax" + ) + ratio = exp_nmda_gmax / nmda_gmax + print("ratio: ", ratio, exp_nmda_gmax, nmda_gmax) + print( + "NMDA Receptor conductance in model should be %.16f (table is %.16f)" + % (NMDAR_gmax * ratio, NMDAR_gmax) + ) + cv_correct = abs(exp_epsc_cv / epsc_cv - 1.0) < 0.1 + print("cv_correct: ", cv_correct) + if not cv_correct: + ratio = exp_epsc_cv / epsc_cv + print( + "CV Receptor in synapses.py model should be %.6f (measured = %.6f; table = %.6f)" + % (epsc_cv * ratio, epsc_cv, exp_epsc_cv) + ) + print((abs(exp_epsc_cv / (epsc_cv * ratio) - 1.0) < 0.1)) + assert cv_correct + assert ampa_correct and nmda_correct + + +def measure_gmax(cell, n_syn=20, tstop=5.0, plot=False): + sgc = cells.SGC.create() + prot = SynapseTest() + + # Connect 20 synapses and stimulate once each + # Temp is 33 C and vm=+40 to match Cao & Oertel 2010 + prot.run( + sgc.soma, + cell.soma, + n_synapses=n_syn, + temp=33.0, + dt=0.025, + vclamp=40.0, + tstop=tstop, + stim_params={"NP": 1, "delay": 0.1}, + ) + + # For each synapse: + # * Add up ampa and nmda conductances across all sites + # (although SGC-TS synapses currently have only 1 site) + # * Keep track of the maximum ampa and nmda conductance + if plot: + global plt + plt = pg.plot() + ampa_gmax = [] + nmda_gmax = [] + epsc_gmax = [] + for syn in prot.synapses: + ampa = np.zeros_like(syn.psd.get_vector("ampa", "g")) + nmda = ampa.copy() + ampa_po = ampa.copy() + for i in range(syn.psd.n_psd): + + ampa += ( + syn.psd.get_vector("ampa", "g", i) * 1e-3 + ) # convert pS from mechanism to nS + nmda += syn.psd.get_vector("nmda", "g", i) * 1e-3 + if nmda[-1] - nmda[-2] > 0.001: + raise Exception("Did not reach nmda gmax; need longer run.") + amax = ampa.max() + ampa_gmax.append(amax) + nmda_gmax.append(nmda.max()) + epsc_gmax.append((ampa + nmda).max()) + tb = np.linspace(0.0, len(ampa) * prot.dt, len(ampa)) + if plot: + plt.plot(tb, ampa, pen="g") + plt.plot(tb, nmda, pen="y") + return ( + np.mean(ampa_gmax), + np.mean(nmda_gmax), + np.std(epsc_gmax) / np.mean(epsc_gmax), + ) + + +if __name__ == "__main__": + if len(sys.argv[0]) > 1: + testcell = sys.argv[1] + if testcell not in ["bushy", "tstellate", "dstellate", "octopus", "all"]: + print("PSD test for cell type %s is not yet supported." % testcell) + exit(1) + else: + if testcell in ["bushy"]: + test_sgc_bushy_psd(plot=True) + if testcell in ["tstellate"]: + test_sgc_tstellate_psd(plot=True) + if testcell in ["dstellate"]: + test_sgc_dstellate_psd(plot=True) + if testcell in ["octopus"]: + test_sgc_octopus_psd(plot=True) + if testcell in ["all"]: + test_sgc_bushy_psd(plot=True) + test_sgc_tstellate_psd(plot=True) + test_sgc_dstellate_psd(plot=True) + test_sgc_octopus(plot=True) + + # pg.show() + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() diff --git a/cnmodel/synapses/tests/test_synapses.py b/cnmodel/synapses/tests/test_synapses.py new file mode 100644 index 0000000..dd8ab8e --- /dev/null +++ b/cnmodel/synapses/tests/test_synapses.py @@ -0,0 +1,119 @@ +""" +Create presynaptic and postsynaptic neurons, automatically connect them with +a synapse, stimulate the presynaptic cell, and analyze the resulting PSCs +in the postsynaptic cell. +""" +import faulthandler + +faulthandler.enable() +import os, pickle, pprint +import numpy as np +import neuron + +import cnmodel +import cnmodel.cells as cells +from cnmodel.util import UserTester +from cnmodel.protocols import SynapseTest +from cnmodel.util import reset + +# +# Synapse tests +# +def test_sgc_bushy(): + SynapseTester("sgc", "bushy") + + +def test_sgc_tstellate(): + SynapseTester("sgc", "tstellate") + + +def test_sgc_tstellate2(): # again to test RNG stability + SynapseTester("sgc", "tstellate") + + +def test_sgc_dstellate(): + SynapseTester("sgc", "dstellate") + + +def test_dstellate_bushy(): + SynapseTester("dstellate", "bushy") + + +def test_dstellate_tstellate(): + SynapseTester("dstellate", "tstellate") + + +def test_dstellate_dstellate(): + SynapseTester("dstellate", "dstellate") + + +# +# Supporting functions +# +convergence = { + "sgc": {"bushy": 3, "tstellate": 6, "dstellate": 10, "dstellate_eager": 10}, + "dstellate": {"bushy": 10, "tstellate": 15, "dstellate": 5}, +} + + +def make_cell(typ): + if typ == "sgc": + cell = cells.SGC.create() + elif typ == "tstellate": + cell = cells.TStellate.create(debug=True, ttx=False) + elif ( + typ == "dstellate" + ): # Type I-II Rothman model, similiar excitability (Xie/Manis, unpublished) + cell = cells.DStellate.create(model="RM03", debug=True, ttx=False) + elif typ == "dstellate_eager": # From Eager et al. + cell = cells.DStellate.create(model="Eager", debug=True, ttx=False) + elif typ == "bushy": + cell = cells.Bushy.create(debug=True, ttx=False) + else: + raise ValueError("Unknown cell type '%s'" % typ) + return cell + + +class SynapseTester(UserTester): + def __init__(self, pre, post): + self.st = None + UserTester.__init__(self, "%s_%s" % (pre, post), pre, post) + + def run_test(self, pre, post): + # Make sure no objects are left over from previous tests + reset(raiseError=False) + + # seed random generator using the name of this test + seed = "%s_%s" % (pre, post) + + pre_cell = make_cell(pre) + post_cell = make_cell(post) + + n_term = convergence.get(pre, {}).get(post, None) + if n_term is None: + n_term = 1 + st = SynapseTest() + st.run(pre_cell.soma, post_cell.soma, n_term, seed=seed) + if self.audit: + st.show_result() + + info = dict( + rel_events=st.release_events(), + rel_timings=st.release_timings(), + open_prob=st.open_probability(), + event_analysis=st.analyze_events(), + ) + self.st = st + + # import weakref + # global last_syn + # last_syn = weakref.ref(st.synapses[0].terminal.relsi) + + return info + + def assert_test_info(self, *args, **kwds): + try: + super(SynapseTester, self).assert_test_info(*args, **kwds) + finally: + if self.st is not None: + self.st.hide() diff --git a/cnmodel/util/Params.py b/cnmodel/util/Params.py new file mode 100755 index 0000000..7e4a6e2 --- /dev/null +++ b/cnmodel/util/Params.py @@ -0,0 +1,69 @@ +# -*- encoding: utf-8 -*- + +import sys +import os +import unittest + + +class Params(object): + def __init__(self, **kwds): + """ + Utility class to create parameter lists + create using: + p = Params(abc=2.0, defg = 3.0, lunch='sandwich') + reference using: + p.abc, p.defg, etc. + Supports getting the keys, finding whether a key exists, returning the strucure as a simple dictionary, + and printing (show) the parameter structure. + """ + self.__dict__.update(kwds) + + def additem(self, key, value): + self.__dict__[key] = value + + def getkeys(self): + """ + Get the keys in the current dictionary + """ + return self.__dict__.keys() + + def haskey(self, key): + """ + Find out if the param list has a specific key in it + """ + if key in self.__dict__.keys(): + return True + else: + return False + + def todict(self): + """ + convert param list to standard dictionary + Useful when writing the data + """ + r = {} + for dictelement in self.__dict__: + if isinstance(self.__dict__[dictelement], Params): + # print 'nested: ', dictelement + r[dictelement] = self.__dict__[dictelement].todict() + else: + r[dictelement] = self.__dict__[dictelement] + return r + + def show(self, printFlag=True): + """ + print the parameter block created in Parameter Init + """ + print("-------- Parameter Block ----------") + for key in self.__dict__.keys(): + print("%15s = " % (key), eval("self.%s" % key)) + print("-------- ---------------------- ----------") + + +class ParamTests(unittest.TestCase): + def setUp(self): + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/cnmodel/util/PlotHelpers.py b/cnmodel/util/PlotHelpers.py new file mode 100755 index 0000000..a4fcc89 --- /dev/null +++ b/cnmodel/util/PlotHelpers.py @@ -0,0 +1,1415 @@ +#!/usr/bin/env python +# encoding: utf-8 +""" +PlotHelpers.py + +Routines to help use matplotlib and make cleaner plots +as well as get plots ready for publication. + +Modified to allow us to use a list of axes, and operate on all of those, +or to use just one axis if that's all that is passed. +Therefore, the first argument to these calls can either be an axes object, +or a list of axes objects. 2/10/2012 pbm. + +Plotter class: a simple class for managing figures with multiple plots. +Uses gridspec to build sets of axes. + +Created by Paul Manis on 2010-03-09. +Copyright 2010-2016 Paul Manis +Distributed under MIT/X11 license. See license.txt for more infofmation. + +""" + +import sys +import os +import string +from collections import OrderedDict + +stdFont = "Arial" +from matplotlib.ticker import FormatStrFormatter +from matplotlib.font_manager import FontProperties +from matplotlib.offsetbox import AnchoredOffsetbox, TextArea, DrawingArea, HPacker +from scipy.stats import gaussian_kde +import numpy as np +import matplotlib.pyplot as mpl +import matplotlib.gridspec as gridspec +from matplotlib.patches import Circle +from matplotlib.patches import Rectangle +from matplotlib.patches import Ellipse +from matplotlib.collections import PatchCollection +import matplotlib + +rcParams = matplotlib.rcParams +rcParams["svg.fonttype"] = "none" # No text as paths. Assume font installed. +rcParams["pdf.fonttype"] = 42 +rcParams["ps.fonttype"] = 42 +# rcParams['font.serif'] = ['Times New Roman'] +from matplotlib import rc + +rc("font", **{"family": "sans-serif", "sans-serif": ["Arial"]}) +# rcParams['font.sans-serif'] = ['Arial'] +# rcParams['font.family'] = 'sans-serif' +# check for LaTeX install - +from distutils.spawn import find_executable + +latex_avail = False +if find_executable("latex"): + latex_avail = True +rc("text", usetex=latex_avail) +rcParams["text.latex.unicode"] = latex_avail + + +def _ax_tolist(ax): + if isinstance(ax, list): + return ax + elif isinstance(ax, dict): + axlist = list(axl.keys()) + return [ax for ax in axl[axlist]] + else: + return [ax] + + +def nice_plot( + axl, spines=["left", "bottom"], position=10, direction="inward", axesoff=False +): + """ Adjust a plot so that it looks nicer than the default matplotlib plot. + Also allow quickaccess to things we like to do for publication plots, including: + using a calbar instead of an axes: calbar = [x0, y0, xs, ys] + inserting a reference line (grey, 3pt dashed, 0.5pt, at refline = y position) + + Parameters + ---------- + axl : list of axes objects + If a single axis object is present, it will be converted to a list here. + + spines : list of strings (default : ['left', 'bottom']) + Sets whether spines will occur on particular axes. Choices are 'left', 'right', + 'bottom', and 'top'. Chosen spines will be displayed, others are not + + position : float (default : 10) + Determines position of spines in points, typically outward by x points. The + spines are the main axes lines, not the tick marks + if the position is dict, then interpret as such. + + direction : string (default : 'inward') + Sets the direction of spines. Choices are 'inward' and 'outward' + + axesoff : boolean (default : False) + If true, forces the axes to be turned completely off. + + Returns + ------- + Nothing. + """ + # print 'NICEPLOT' + if type(axl) is not list: + axl = [axl] + for ax in axl: + if ax is None: + continue + # print 'ax: ', ax + for loc, spine in ax.spines.items(): + if loc in spines: + spine.set_color("k") + # print 'spine color : k' + if type(position) in [int, float]: + spine.set_position(("axes", position)) + elif type(position) is dict: + spine.set_position(("axes", position[loc])) + else: + raise ValueError( + "position must be int, float or dict [ex: ]{'left': -0.05, 'bottom': -0.05}]" + ) + else: + spine.set_color("none") + # print 'spine color : none' + if axesoff is True: + noaxes(ax) + + # turn off ticks where there is no spine, if there are axes + if "left" in spines and not axesoff: + ax.yaxis.set_ticks_position("left") + ax.yaxis.set_tick_params(color="k") + else: + ax.yaxis.set_ticks([]) # no yaxis ticks + + if "bottom" in spines and not axesoff: + ax.xaxis.set_ticks_position("bottom") + ax.xaxis.set_tick_params(color="k") + else: + ax.xaxis.set_ticks([]) # no xaxis ticks + + if direction == "inward": + ax.tick_params(axis="y", direction="in") + ax.tick_params(axis="x", direction="in") + else: + ax.tick_params(axis="y", direction="out") + ax.tick_params(axis="x", direction="out") + + +def noaxes(axl, whichaxes="xy"): + """ take away all the axis ticks and the lines + + Parameters + ---------- + + axl : list of axes objects + If a single axis object is present, it will be converted to a list here. + + whichaxes : string (default : 'xy') + Sets which axes are turned off. The presence of an 'x' in + the string turns off x, the presence of 'y' turns off y. + + Returns + ------- + Nothing + """ + if type(axl) is not list: + axl = [axl] + for ax in axl: + if ax is None: + continue + if "x" in whichaxes: + ax.xaxis.set_ticks([]) + if "y" in whichaxes: + ax.yaxis.set_ticks([]) + if "xy" == whichaxes: + ax.set_axis_off() + + +def setY(ax1, ax2): + """ + Set the Y limits for an axes from a source axes to + the target axes. + + Parameters + ---------- + + ax1 : axis object + The source axis object + ax2 : list of axes objects + If a single axis object is present, it will be converted to a list here. + These are the target axes objects that will take on the limits of the source. + + Returns + ------- + Nothing + + """ + if type(ax1) is list: + print("PlotHelpers: cannot use list as source to set Y axis") + return + ax2 = _ax_tolist(ax2) + # if type(ax2) is not list: + # ax2 = [ax2] + refy = ax1.get_ylim() + for ax in ax2: + ax.set_ylim(refy) + + +def setX(ax1, ax2): + """ + Set the X limits for an axes from a source axes to + the target axes. + + Parameters + ---------- + + ax1 : axis object + The source axis object + ax2 : list of axes objects + If a single axis object is present, it will be converted to a list here. + These are the target axes objects that will take on the limits of the source. + + Returns + ------- + Nothing + + """ + if type(ax1) is list: + print("PlotHelpers: cannot use list as source to set Y axis") + return + ax2 = _ax_tolist(ax2) + # if type(ax2) is not list: + # ax2 = [ax2] + refx = ax1.get_xlim() + for ax in ax2: + ax.set_xlim(refx) + + +def labelPanels( + axl, + axlist=None, + font="Arial", + fontsize=18, + weight="normal", + xy=(-0.05, 1.05), + horizontalalignment="right", + verticalalignment="bottom", + rotation=0.0, +): + """ + Provide labeling of panels in a figure with multiple subplots (axes) + + Parameters + ---------- + axl : list of axes objects + If a single axis object is present, it will be converted to a list here. + + axlist : list of string labels (default : None) + Contains a list of the string labels. If the default value is provided, + the axes will be lettered in alphabetical sequence. + + font : string (default : 'Arial') + Name of a valid font to use for the panel labels + + fontsize : float (default : 18, in points) + Font size to use for axis labeling + + weight : string (default : 'normal') + Font weight to use for labels. 'Bold', 'Italic', and 'Normal' are options + + xy : tuple (default : (-0.05, 1.05)) + A tuple (x,y) indicating where the label should go relative to the axis frame. + Values are normalized as a fraction of the frame size. + + Returns + ------- + list of the annotations + + """ + if isinstance(axl, dict): + axlist = list(axl.keys()) + axl = _ax_tolist(axl) + # if isinstance(axl, dict): + # axt = [axl[x] for x in axl] + # axlist = axl.keys() + # axl = axt + # if not isinstance(axl, list): + # axl = [axl] + if axlist is None: + axlist = string.ascii_uppercase[0 : len(axl)] + # assume we wish to go in sequence + if len(axlist) > len(axl): + raise ValueError( + "axl must have more entries than axlist: got axl=%d and axlist=%d for axlist:" + % (len(axl), len(axlist)), + axlist, + ) + font = FontProperties() + font.set_family("sans-serif") + font.set_weight = weight + font.set_size = fontsize + font.set_style("normal") + labels = [] + for i, ax in enumerate(axl): + if i >= len(axlist): + continue + if ax is None: + continue + if isinstance(ax, list): + ax = ax[0] + ann = ax.annotate( + axlist[i], + xy=xy, + xycoords="axes fraction", + annotation_clip=False, + color="k", + verticalalignment=verticalalignment, + weight=weight, + horizontalalignment=horizontalalignment, + fontsize=fontsize, + family="sans-serif", + rotation=rotation, + ) + labels.append(ann) + return labels + + +def listAxes(axd): + """ + make a list of the axes from the dictionary + """ + if type(axd) is not dict: + if type(axd) is list: + return axd + else: + print("listAxes expects dictionary or list; type not known (fix the code)") + raise + axl = [axd[x] for x in axd] + return axl + + +def cleanAxes(axl): + axl = _ax_tolist(axl) + for ax in axl: + if ax is None: + continue + for loc, spine in ax.spines.items(): + if loc in ["left", "bottom"]: + spine.set_visible(True) + elif loc in ["right", "top"]: + spine.set_visible(False) + # spine.set_color('none') + # do not draw the spine + else: + raise ValueError("Unknown spine location: %s" % loc) + # turn off ticks when there is no spine + ax.xaxis.set_ticks_position("bottom") + # pdb.set_trace() + ax.yaxis.set_ticks_position("left") # stopped working in matplotlib 1.10 + update_font(ax) + + +def setTicks(axl, axis="x", ticks=np.arange(0, 1.1, 1.0)): + axl = _ax_tolist(axl) + # if type(axl) is dict: + # axl = [axl[x] for x in axl.keys()] + # if type(axl) is not list: + # axl = [axl] + for ax in axl: + if ax is None: + continue + if axis == "x": + ax.set_xticks(ticks) + if axis == "y": + ax.set_yticks(ticks) + + +def formatTicks(axl, axis="xy", fmt="%d", font="Arial"): + """ + Convert tick labels to integers + To do just one axis, set axis = 'x' or 'y' + Control the format with the formatting string + """ + axl = _ax_tolist(axl) + # if type(axl) is not list: + # axl = [axl] + majorFormatter = FormatStrFormatter(fmt) + for ax in axl: + if ax is None: + continue + if "x" in axis: + ax.xaxis.set_major_formatter(majorFormatter) + if "y" in axis: + ax.yaxis.set_major_formatter(majorFormatter) + + +def autoFormatTicks(axl, axis="xy", font="Arial"): + axl = _ax_tolist(axl) + # if type(axl) is not list: + # axl = [axl] + for ax in axl: + if ax is None: + continue + if "x" in axis: + # print ax.get_xlim() + x0, x1 = ax.get_xlim() + setFormatter(ax, x0, x1, axis="x") + if "y" in axis: + y0, y1 = ax.get_xlim + setFormatter(ax, y0, y1, axis="y") + + +def setFormatter(axl, x0, x1, axis="x"): + axl = _ax_tolist(axl) + datarange = np.abs(x0 - x1) + mdata = np.ceil(np.log10(datarange)) + if mdata > 0 and mdata <= 4: + majorFormatter = FormatStrFormatter("%d") + elif mdata > 4: + majorFormatter = FormatStrFormatter("%e") + elif mdata <= 0 and mdata > -1: + majorFormatter = FormatStrFormatter("%5.1f") + elif mdata < -1 and mdata > -3: + majorFormatatter = FormatStrFormatter("%6.3f") + else: + majorFormatter = FormatStrFormatter("%e") + for ax in axl: + if axis == "x": + ax.xaxis.set_major_formatter(majorFormatter) + elif axis == "y": + ax.yaxis.set_major_formatter(majorFormatter) + + +def update_font(axl, size=9, font=stdFont): + axl = _ax_tolist(axl) + # if type(axl) is not list: + # axl = [axl] + fontProperties = { + "family": "sans-serif", #'sans-serif': font, + "weight": "normal", + "size": size, + } + for ax in axl: + if ax is None: + continue + for tick in ax.xaxis.get_major_ticks(): + # tick.label1.set_family('sans-serif') + # tick.label1.set_fontname(stdFont) + tick.label1.set_size(size) + + for tick in ax.yaxis.get_major_ticks(): + # tick.label1.set_family('sans-serif') + # tick.label1.set_fontname(stdFont) + tick.label1.set_size(size) + ax.set_xticklabels(ax.get_xticks(), fontProperties) + ax.set_yticklabels(ax.get_yticks(), fontProperties) + ax.xaxis.set_smart_bounds(True) + ax.yaxis.set_smart_bounds(True) + ax.tick_params(axis="both", labelsize=size) + + +def lockPlot(axl, lims, ticks=None): + """ + This routine forces the plot of invisible data to force the axes to take certain + limits and to force the tick marks to appear. + call with the axis and lims (limits) = [x0, x1, y0, y1] + """ + axl = _ax_tolist(axl) + # if type(axl) is not list: + # axl = [axl] + plist = [] + for ax in axl: + if ax is None: + continue + lpl = ax.plot( + [lims[0], lims[0], lims[1], lims[1]], + [lims[2], lims[3], lims[2], lims[3]], + color="none", + marker="", + linestyle="None", + ) + plist.extend(lpl) + ax.axis(lims) + return plist # just in case you want to modify these plots later. + + +def adjust_spines( + axl, spines=["left", "bottom"], direction="outward", distance=5, smart=True +): + axl = _ax_tolist(axl) + # if type(axl) is not list: + # axl = [axl] + for ax in axl: + if ax is None: + continue + # turn off ticks where there is no spine + if "left" in spines: + ax.yaxis.set_ticks_position("left") + else: + # no yaxis ticks + ax.yaxis.set_ticks([]) + + if "bottom" in spines: + ax.xaxis.set_ticks_position("bottom") + else: + # no xaxis ticks + ax.xaxis.set_ticks([]) + for loc, spine in ax.spines.items(): + if loc in spines: + spine.set_position((direction, distance)) # outward by 10 points + if smart is True: + spine.set_smart_bounds(True) + else: + spine.set_smart_bounds(False) + else: + spine.set_color("none") # don't draw spine + + +def getLayoutDimensions(n, pref="height"): + """ + Return a tuple of optimized layout dimensions for n axes + + Parameters + ---------- + n : int (no default): + Number of plots needed + pref : string (default : 'height') + prefered way to organized the plots (height, or width) + + Returns + ------- + (h, w) : tuple + height (rows) and width (columns) + + """ + nopt = np.sqrt(n) + inoptw = int(nopt) + inopth = int(nopt) + while inoptw * inopth < n: + if pref == "width": + inoptw += 1 + if inoptw * inopth > (n - inopth): + inoptw -= 1 + inopth += 1 + else: + inopth += 1 + if inoptw * inopth > (n - inoptw): + inopth -= 1 + inoptw += 1 + + return (inopth, inoptw) + + +def calbar( + axl, + calbar=None, + axesoff=True, + orient="left", + unitNames=None, + fontsize=11, + weight="normal", + font="Arial", +): + """ + draw a calibration bar and label it. The calibration bar is defined as: + [x0, y0, xlen, ylen] + """ + axl = _ax_tolist(axl) + # if type(axl) is not list: + # axl = [axl] + for ax in axl: + if ax is None: + continue + if axesoff is True: + noaxes(ax) + Hfmt = r"{:.0f}" + if calbar[2] < 1.0: + Hfmt = r"{:.1f}" + Vfmt = r" {:.0f}" + if calbar[3] < 1.0: + Vfmt = r" {:.1f}" + if unitNames is not None: + Vfmt = Vfmt + r" " + r"{:s}".format(unitNames["y"]) + Hfmt = Hfmt + r" " + r"{:s}".format(unitNames["x"]) + # print(Vfmt, unitNames['y']) + # print(Vfmt.format(calbar[3])) + font = FontProperties() + font.set_family("sans-serif") + font.set_weight = weight + font.set_size = fontsize + font.set_style("normal") + if calbar is not None: + if orient == "left": # vertical part is on the left + ax.plot( + [calbar[0], calbar[0], calbar[0] + calbar[2]], + [calbar[1] + calbar[3], calbar[1], calbar[1]], + color="k", + linestyle="-", + linewidth=1.5, + ) + ax.text( + calbar[0] + 0.05 * calbar[2], + calbar[1] + 0.5 * calbar[3], + Vfmt.format(calbar[3]), + horizontalalignment="left", + verticalalignment="center", + fontsize=fontsize, + weight=weight, + family="sans-serif", + ) + elif orient == "right": # vertical part goes on the right + ax.plot( + [calbar[0] + calbar[2], calbar[0] + calbar[2], calbar[0]], + [calbar[1] + calbar[3], calbar[1], calbar[1]], + color="k", + linestyle="-", + linewidth=1.5, + ) + ax.text( + calbar[0] + calbar[2] - 0.05 * calbar[2], + calbar[1] + 0.5 * calbar[3], + Vfmt.format(calbar[3]), + horizontalalignment="right", + verticalalignment="center", + fontsize=fontsize, + weight=weight, + family="sans-serif", + ) + else: + print("PlotHelpers.py: I did not understand orientation: %s" % (orient)) + print("plotting as if set to left... ") + ax.plot( + [calbar[0], calbar[0], calbar[0] + calbar[2]], + [calbar[1] + calbar[3], calbar[1], calbar[1]], + color="k", + linestyle="-", + linewidth=1.5, + ) + ax.text( + calbar[0] + 0.05 * calbar[2], + calbar[1] + 0.5 * calbar[3], + Vfmt.format(calbar[3]), + horizontalalignment="left", + verticalalignment="center", + fontsize=fontsize, + weight=weight, + family="sans-serif", + ) + ax.text( + calbar[0] + calbar[2] * 0.5, + calbar[1] - 0.1 * calbar[3], + Hfmt.format(calbar[2]), + horizontalalignment="center", + verticalalignment="top", + fontsize=fontsize, + weight=weight, + family="sans-serif", + ) + + +def referenceline( + axl, + reference=None, + limits=None, + color="0.33", + linestyle="--", + linewidth=0.5, + dashes=None, +): + """ + draw a reference line at a particular level of the data on the y axis + returns the line object. + """ + axl = _ax_tolist(axl) + # if type(axl) is not list: + # axl = [axl] + if reference is None: + refeference = 0.0 + for ax in axl: + if ax is None: + continue + if limits is None or type(limits) is not list or len(limits) != 2: + xlims = ax.get_xlim() + else: + xlims = limits + rl, = ax.plot( + [xlims[0], xlims[1]], + [reference, reference], + color=color, + linestyle=linestyle, + linewidth=linewidth, + ) + if dashes is not None: + rl.set_dashes(dashes) + return rl + + +def crossAxes(axl, xyzero=[0.0, 0.0], limits=[None, None, None, None]): + """ + Make plot(s) with crossed axes at the data points set by xyzero, and optionally + set axes limits + """ + axl = _ax_tolist(axl) + # if type(axl) is not list: + # axl = [axl] + for ax in axl: + if ax is None: + continue + # ax.set_title('spines at data (1,2)') + # ax.plot(x,y) + ax.spines["left"].set_position(("data", xyzero[0])) + ax.spines["right"].set_color("none") + ax.spines["bottom"].set_position(("data", xyzero[1])) + ax.spines["top"].set_color("none") + ax.spines["left"].set_smart_bounds(True) + ax.spines["bottom"].set_smart_bounds(True) + ax.xaxis.set_ticks_position("bottom") + ax.yaxis.set_ticks_position("left") + if limits[0] is not None: + ax.set_xlim(left=limits[0], right=limits[2]) + ax.set_ylim(bottom=limits[1], top=limits[3]) + + +def violin_plot(ax, data, pos, bp=False, median=False): + """ + create violin plots on an axis + """ + dist = max(pos) - min(pos) + w = min(0.15 * max(dist, 1.0), 0.5) + for d, p in zip(data, pos): + k = gaussian_kde(d) # calculates the kernel density + m = k.dataset.min() # lower bound of violin + M = k.dataset.max() # upper bound of violin + x = np.arange(m, M, (M - m) / 100.0) # support for violin + v = k.evaluate(x) # violin profile (density curve) + v = v / v.max() * w # scaling the violin to the available space + ax.fill_betweenx(x, p, v + p, facecolor="y", alpha=0.3) + ax.fill_betweenx(x, p, -v + p, facecolor="y", alpha=0.3) + if median: + ax.plot([p - 0.5, p + 0.5], [np.median(d), np.median(d)], "-") + if bp: + bpf = ax.boxplot(data, notch=0, positions=pos, vert=1) + mpl.setp(bpf["boxes"], color="black") + mpl.setp(bpf["whiskers"], color="black", linestyle="-") + + +# # from somewhere on the web: + + +class NiceScale: + def __init__(self, minv, maxv): + self.maxTicks = 6 + self.tickSpacing = 0 + self.lst = 10 + self.niceMin = 0 + self.niceMax = 0 + self.minPoint = minv + self.maxPoint = maxv + self.calculate() + + def calculate(self): + self.lst = self.niceNum(self.maxPoint - self.minPoint, False) + self.tickSpacing = self.niceNum(self.lst / (self.maxTicks - 1), True) + self.niceMin = np.floor(self.minPoint / self.tickSpacing) * self.tickSpacing + self.niceMax = np.ceil(self.maxPoint / self.tickSpacing) * self.tickSpacing + + def niceNum(self, lst, rround): + self.lst = lst + exponent = 0 # exponent of range */ + fraction = 0 # fractional part of range */ + niceFraction = 0 # nice, rounded fraction */ + + exponent = np.floor(np.log10(self.lst)) + fraction = self.lst / np.power(10, exponent) + + if self.lst: + if fraction < 1.5: + niceFraction = 1 + elif fraction < 3: + niceFraction = 2 + elif fraction < 7: + niceFraction = 5 + else: + niceFraction = 10 + else: + if fraction <= 1: + niceFraction = 1 + elif fraction <= 2: + niceFraction = 2 + elif fraction <= 5: + niceFraction = 5 + else: + niceFraction = 10 + + return niceFraction * np.power(10, exponent) + + def setMinMaxPoints(self, minPoint, maxPoint): + self.minPoint = minPoint + self.maxPoint = maxPoint + self.calculate() + + def setMaxTicks(self, maxTicks): + self.maxTicks = maxTicks + self.calculate() + + +def circles(x, y, s, c="b", ax=None, vmin=None, vmax=None, **kwargs): + """ + Make a scatter of circles plot of x vs y, where x and y are sequence + like objects of the same lengths. The size of circles are in data scale. + + Parameters + ---------- + x,y : scalar or array_like, shape (n, ) + Input data + s : scalar or array_like, shape (n, ) + Radius of circle in data scale (ie. in data unit) + c : color or sequence of color, optional, default : 'b' + `c` can be a single color format string, or a sequence of color + specifications of length `N`, or a sequence of `N` numbers to be + mapped to colors using the `cmap` and `norm` specified via kwargs. + Note that `c` should not be a single numeric RGB or + RGBA sequence because that is indistinguishable from an array of + values to be colormapped. `c` can be a 2-D array in which the + rows are RGB or RGBA, however. + ax : Axes object, optional, default: None + Parent axes of the plot. It uses gca() if not specified. + vmin, vmax : scalar, optional, default: None + `vmin` and `vmax` are used in conjunction with `norm` to normalize + luminance data. If either are `None`, the min and max of the + color array is used. (Note if you pass a `norm` instance, your + settings for `vmin` and `vmax` will be ignored.) + + Returns + ------- + paths : `~matplotlib.collections.PathCollection` + + Other parameters + ---------------- + kwargs : `~matplotlib.collections.Collection` properties + eg. alpha, edgecolors, facecolors, linewidths, linestyles, norm, cmap + + Examples + -------- + a = np.arange(11) + circles(a, a, a*0.2, c=a, alpha=0.5, edgecolor='none') + + License + -------- + This code is under [The BSD 3-Clause License] + (http://opensource.org/licenses/BSD-3-Clause) + """ + + # import matplotlib.colors as colors + + if ax is None: + ax = mpl.gca() + + if isinstance(c, str): + color = c # ie. use colors.colorConverter.to_rgba_array(c) + else: + color = None # use cmap, norm after collection is created + kwargs.update(color=color) + + if np.isscalar(x): + patches = [Circle((x, y), s)] + elif np.isscalar(s): + patches = [Circle((x_, y_), s) for x_, y_ in zip(x, y)] + else: + patches = [Circle((x_, y_), s_) for x_, y_, s_ in zip(x, y, s)] + collection = PatchCollection(patches, **kwargs) + + if color is None: + collection.set_array(np.asarray(c)) + if vmin is not None or vmax is not None: + collection.set_clim(vmin, vmax) + + ax.add_collection(collection) + ax.autoscale_view() + return collection + + +def rectangles(x, y, sw, sh=None, c="b", ax=None, vmin=None, vmax=None, **kwargs): + """ + Make a scatter of squares plot of x vs y, where x and y are sequence + like objects of the same lengths. The size of sqares are in data scale. + + Parameters + ---------- + x,y : scalar or array_like, shape (n, ) + Input data + s : scalar or array_like, shape (n, ) + side of square in data scale (ie. in data unit) + c : color or sequence of color, optional, default : 'b' + `c` can be a single color format string, or a sequence of color + specifications of length `N`, or a sequence of `N` numbers to be + mapped to colors using the `cmap` and `norm` specified via kwargs. + Note that `c` should not be a single numeric RGB or + RGBA sequence because that is indistinguishable from an array of + values to be colormapped. `c` can be a 2-D array in which the + rows are RGB or RGBA, however. + ax : Axes object, optional, default: None + Parent axes of the plot. It uses gca() if not specified. + vmin, vmax : scalar, optional, default: None + `vmin` and `vmax` are used in conjunction with `norm` to normalize + luminance data. If either are `None`, the min and max of the + color array is used. (Note if you pass a `norm` instance, your + settings for `vmin` and `vmax` will be ignored.) + + Returns + ------- + paths : `~matplotlib.collections.PathCollection` + + Other parameters + ---------------- + kwargs : `~matplotlib.collections.Collection` properties + eg. alpha, edgecolors, facecolors, linewidths, linestyles, norm, cmap + + Examples + -------- + a = np.arange(11) + squaress(a, a, a*0.2, c=a, alpha=0.5, edgecolor='none') + + License + -------- + This code is under [The BSD 3-Clause License] + (http://opensource.org/licenses/BSD-3-Clause) + """ + # import matplotlib.colors as colors + + if ax is None: + ax = mpl.gca() + + if isinstance(c, str): + color = c # ie. use colors.colorConverter.to_rgba_array(c) + else: + color = None # use cmap, norm after collection is created + kwargs.update(color=color) + if sh is None: + sh = sw + x = x - sw / 2.0 # offset as position specified is "lower left corner" + y = y - sh / 2.0 + if np.isscalar(x): + patches = [Rectangle((x, y), sw, sh)] + elif np.isscalar(sw): + patches = [Rectangle((x_, y_), sw, sh) for x_, y_ in zip(x, y)] + else: + patches = [ + Rectangle((x_, y_), sw_, sh_) for x_, y_, sw_, sh_ in zip(x, y, sw, sh) + ] + collection = PatchCollection(patches, **kwargs) + + if color is None: + collection.set_array(np.asarray(c)) + if vmin is not None or vmax is not None: + collection.set_clim(vmin, vmax) + + ax.add_collection(collection) + ax.autoscale_view() + return collection + + +def show_figure_grid(fig, figx=10.0, figy=10.0): + """ + Create a background grid with major and minor lines like graph paper + if using default figx and figy, the grid will be in units of the + overall figure on a [0,1,0,1] grid + if figx and figy are in units of inches or cm, then the grid + will be on that scale. + + Figure grid is useful when building figures and placing labels + at absolute locations on the figure. + + Parameters + ---------- + + fig : Matplotlib figure handle (no default): + The figure to which the grid will be applied + + figx : float (default: 10.) + # of major lines along the X dimension + + figy : float (default: 10.) + # of major lines along the Y dimension + + """ + backGrid = fig.add_axes([0, 0, 1, 1], frameon=False) + backGrid.set_ylim(0.0, figy) + backGrid.set_xlim(0.0, figx) + backGrid.grid(True) + + backGrid.set_yticks(np.arange(0.0, figy + 0.01, 1.0)) + backGrid.set_yticks(np.arange(0.0, figy + 0.01, 0.1), minor=True) + backGrid.set_xticks(np.arange(0.0, figx + 0.01, 1.0)) + backGrid.set_xticks(np.arange(0.0, figx + 0.01, 0.1), minor=True) + # backGrid.get_xaxis().set_minor_locator(matplotlib.ticker.AutoMinorLocator()) + # backGrid.get_yaxis().set_minor_locator(matplotlib.ticker.AutoMinorLocator()) + backGrid.grid(b=True, which="major", color="g", alpha=0.6, linewidth=0.8) + backGrid.grid(b=True, which="minor", color="g", alpha=0.4, linewidth=0.2) + return backGrid + + +def hide_figure_grid(fig, grid): + grid.grid(False) + + +def delete_figure_grid(fig, grid): + mpl.delete(grid) + + +class Plotter: + """ + The Plotter class provides a simple convenience for plotting data in + an row x column array. + """ + + def __init__( + self, + rcshape=None, + axmap=None, + arrangement=None, + title=None, + label=False, + roworder=True, + refline=None, + figsize=(11, 8.5), + fontsize=10, + position=0, + labeloffset=[0.0, 0.0], + labelsize=12, + ): + """ + Create an instance of the plotter. Generates a new matplotlib figure, + and sets up an array of subplots as defined, initializes the counters + + Examples + -------- + Ex. 1: + One way to generate plots on a standard grid, uses gridspec to specify an axis map: + labels = ['A', 'B1', 'B2', 'C1', 'C2', 'D', 'E', 'F'] + gr = [(0, 4, 0, 1), (0, 3, 1, 2), (3, 4, 1, 2), (0, 3, 2, 3), (3, 4, 2, 3), (5, 8, 0, 1), (5, 8, 1, 2), (5, 8, 2, 3)] + axmap = OrderedDict(zip(labels, gr)) + P = PH.Plotter((8, 1), axmap=axmap, label=True, figsize=(8., 6.)) + PH.show_figure_grid(P.figure_handle) + + Ex. 2: + Place plots on defined locations on the page - no messing with gridspec or subplots. + For this version, we just generate N subplots with labels (used to tag each plot) + The "sizer" array then maps the tags to specific panel locations + # define positions for each panel in Figure coordinages (0, 1, 0, 1) + # you don't have to use an ordered dict for this, I just prefer it when debugging + sizer = OrderedDict([('A', [0.08, 0.22, 0.55, 0.4]), ('B1', [0.40, 0.25, 0.65, 0.3]), ('B2', [0.40, 0.25, 0.5, 0.1]), + ('C1', [0.72, 0.25, 0.65, 0.3]), ('C2', [0.72, 0.25, 0.5, 0.1]), + ('D', [0.08, 0.25, 0.1, 0.3]), ('E', [0.40, 0.25, 0.1, 0.3]), ('F', [0.72, 0.25, 0.1, 0.3]), + ]) # dict elements are [left, width, bottom, height] for the axes in the plot. + gr = [(a, a+1, 0, 1) for a in range(0, 8)] # just generate subplots - shape does not matter + axmap = OrderedDict(zip(sizer.keys(), gr)) + P = PH.Plotter((8, 1), axmap=axmap, label=True, figsize=(8., 6.)) + PH.show_figure_grid(P.figure_handle) + P.resize(sizer) # perform positioning magic + P.axdict['B1'] access the plot associated with panel B1 + + Parameters + ---------- + rcshape : a list or tuple: 2x1 (no default) + rcshape is an array [row, col] telling us how many rows and columns to build. + default defines a rectangular array r x c of plots + a dict : + None: expect axmap to provide the input... + + axmap : + list of gridspec slices (default : None) + define slices for the axes of a gridspec, allowing for non-rectangular arrangements + The list is defined as: + [(r1t, r1b, c1l, c1r), slice(r2, c2)] + where r1t is the top for row 1 in the grid, r1b is the bottom, etc... + When using this mode, the axarr returned is a 1-D list, as if r is all plots indexed, + and the number of columns is 1. The results match in order the list entered in axmap + + + + arrangement: Ordered Dict (default: None) + Arrangement allows the data to be plotted according to a logical arrangement + The dict keys are the names ("groups") for each column, and the elements are + string names for the entities in the groups + + title : string (default: None) + Provide a title for the entire plot + + label : Boolean (default: False) + If True, sets labels on panels + + roworder : Boolean (default: True) + Define whether labels run in row order first or column order first + + refline : float (default: None) + Define the position of a reference line to be used in all panels + + figsize : tuple (default : (11, 8.5)) + Figure size in inches. Default is for a landscape figure + + fontsize : points (default : 10) + Defines the size of the font to use for panel labels + + position : position of spines (0 means close, 0.05 means break out) + x, y spines.. + Returns + ------- + Nothing + """ + self.arrangement = arrangement + self.fontsize = fontsize + self.referenceLines = {} + self.figure_handle = mpl.figure(figsize=figsize) # create the figure + self.figure_handle.set_size_inches(figsize[0], figsize[1], forward=True) + self.axlabels = [] + self.axdict = ( + OrderedDict() + ) # make axis label dictionary for indirect access (better!) + if isinstance(fontsize, int): + fontsize = {"tick": fontsize, "label": fontsize, "panel": fontsize} + gridbuilt = False + # compute label offsets + p = [0.0, 0.0] + if label: + if type(labeloffset) is int: + p = [labeloffset, labeloffset] + elif type(labeloffset) is dict: + p = [position["left"], position["bottom"]] + elif type(labeloffset) in [list, tuple]: + p = labeloffset + else: + p = [0.0, 0.0] + + # build axes arrays + # 1. nxm grid + if isinstance(rcshape, list) or isinstance(rcshape, tuple): + rc = rcshape + gs = gridspec.GridSpec(rc[0], rc[1]) # define a grid using gridspec + # assign to axarr + self.axarr = np.empty( + shape=(rc[0], rc[1]), dtype=object + ) # use a numpy object array, indexing features + ix = 0 + for r in range(rc[0]): + for c in range(rc[1]): + self.axarr[r, c] = mpl.subplot(gs[ix]) + ix += 1 + gridbuilt = True + # 2. specified values - starts with Nx1 subplots, then reorganizes according to shape boxes + elif isinstance(rcshape, dict): # true for OrderedDict also + nplots = len(list(rcshape.keys())) + gs = gridspec.GridSpec(nplots, 1) + rc = (nplots, 1) + self.axarr = np.empty( + shape=(rc[0], rc[1]), dtype=object + ) # use a numpy object array, indexing features + ix = 0 + for r in range(rc[0]): + for c in range(rc[1]): + self.axarr[r, c] = mpl.subplot(gs[ix]) + ix += 1 + gridbuilt = True + for k, pk in enumerate(rcshape.keys()): + self.axdict[pk] = self.axarr[k, 0] + plo = labeloffset + self.axlabels = labelPanels( + self.axarr.tolist(), + axlist=list(rcshape.keys()), + xy=(-0.095 + plo[0], 0.95 + plo[1]), + fontsize=fontsize["panel"], + ) + self.resize(rcshape) + else: + raise ValueError("Input rcshape must be list/tuple or dict") + + # create sublots + if axmap is not None: + if isinstance(axmap, list) and not gridbuilt: + self.axarr = np.empty(shape=(len(axmap), 1), dtype=object) + for k, g in enumerate(axmap): + self.axarr[k,] = mpl.subplot(gs[g[0] : g[1], g[2] : g[3]]) + elif isinstance(axmap, dict) or isinstance( + axmap, OrderedDict + ): # keys are panel labels + if not gridbuilt: + self.axarr = np.empty( + shape=(len(list(axmap.keys())), 1), dtype=object + ) + na = np.prod(self.axarr.shape) # number of axes + for k, pk in enumerate(axmap.keys()): + g = axmap[pk] # get the gridspec info + if not gridbuilt: + self.axarr[k,] = mpl.subplot(gs[g[0] : g[1], g[2] : g[3]]) + self.axdict[pk] = self.axarr.ravel()[k] + else: + raise TypeError("Plotter in PlotHelpers: axmap must be a list or dict") + + if len(self.axdict) == 0: + for i, a in enumerate(self.axarr.flatten()): + label = string.ascii_uppercase[i] + self.axdict[label] = a + + if title is not None: + self.figure_handle.canvas.set_window_title(title) + self.figure_handle.suptitle(title) + self.nrows = self.axarr.shape[0] + if len(self.axarr.shape) > 1: + self.ncolumns = self.axarr.shape[1] + else: + self.ncolumns = 1 + self.row_counter = 0 + self.column_counter = 0 + for i in range(self.nrows): + for j in range(self.ncolumns): + self.axarr[i, j].spines["top"].set_visible(False) + self.axarr[i, j].get_xaxis().set_tick_params( + direction="out", width=0.8, length=4.0 + ) + self.axarr[i, j].get_yaxis().set_tick_params( + direction="out", width=0.8, length=4.0 + ) + self.axarr[i, j].tick_params( + axis="both", which="major", labelsize=fontsize["tick"] + ) + # if i < self.nrows-1: + # self.axarr[i, j].xaxis.set_major_formatter(mpl.NullFormatter()) + nice_plot(self.axarr[i, j], position=position) + if refline is not None: + self.referenceLines[self.axarr[i, j]] = referenceline( + self.axarr[i, j], reference=refline + ) + + if label: + if isinstance(axmap, dict) or isinstance( + axmap, OrderedDict + ): # in case predefined... + self.axlabels = labelPanels( + self.axarr.ravel().tolist(), + axlist=list(axmap.keys()), + xy=(-0.095 + p[0], 0.95 + p[1]), + fontsize=fontsize["panel"], + ) + return + self.axlist = [] + if roworder == True: + for i in range(self.nrows): + for j in range(self.ncolumns): + self.axlist.append(self.axarr[i, j]) + else: + for i in range(self.ncolumns): + for j in range(self.nrows): + self.axlist.append(self.axarr[j, i]) + + if self.nrows * self.ncolumns > 26: # handle large plot using "A1..." + ctxt = string.ascii_uppercase[0 : self.ncolumns] # columns are lettered + rtxt = [ + str(x + 1) for x in range(self.nrows) + ] # rows are numbered, starting at 1 + axl = [] + for i in range(self.nrows): + for j in range(self.ncolumns): + axl.append(ctxt[j] + rtxt[i]) + self.axlabels = labelPanels( + self.axlist, axlist=axl, xy=(-0.35 + p[0], 0.75) + ) + else: + self.axlabels = labelPanels( + self.axlist, xy=(-0.095 + p[0], 0.95 + p[1]) + ) + + def _next(self): + """ + Private function + _next gets the axis pointer to the next row, column index that is available + Only sets internal variables + """ + self.column_counter += 1 + if self.column_counter >= self.ncolumns: + self.row_counter += 1 + self.column_counter = 0 + if self.row_counter >= self.nrows: + raise ValueError( + "Call to get next row exceeds the number of rows requested initially: %d" + % self.nrows + ) + + def getaxis(self, group=None): + """ + getaxis gets the current row, column counter, and calls _next to increment the counter + (so that the next getaxis returns the next available axis pointer) + + Parameters + ---------- + group : string (default: None) + forces the current axis to be selected from text name of a "group" + + Returns + ------- + the current axis or the axis associated with a group + """ + + if group is None: + currentaxis = self.axarr[self.row_counter, self.column_counter] + self._next() # prepare for next call + else: + currentaxis = self.getRC(group) + + return currentaxis + + def getRC(self, group): + """ + Get the axis associated with a group + + Parameters + ---------- + group : string (default: None) + returns the matplotlib axis associated with a text name of a "group" + + Returns + ------- + The matplotlib axis associated with the group name, or None if no group by + that name exists in the arrangement + """ + + if self.arrangement is None: + raise ValueError("specifying a group requires an arrangment dictionary") + # look for the group label in the arrangement dicts + for c, colname in enumerate(self.arrangement.keys()): + if group in self.arrangement[colname]: + # print ('column name, column: ', colname, self.arrangement[colname]) + # print ('group: ', group) + r = self.arrangement[colname].index( + group + ) # get the row position this way + return self.axarr[r, c] + print(("Group {:s} not in the arrangement".format(group))) + return None + + sizer = { + "A": {"pos": [0.08, 0.22, 0.50, 0.4]}, + "B1": {"pos": [0.40, 0.25, 0.60, 0.3]}, + "B2": {"pos": [0.40, 0.25, 0.5, 0.1]}, + "C1": {"pos": [0.72, 0.25, 0.60, 0.3]}, + "C2": {"pos": [0.72, 0.25, 0.5, 0.1]}, + "D": {"pos": [0.08, 0.25, 0.1, 0.3]}, + "E": {"pos": [0.40, 0.25, 0.1, 0.3]}, + "F": {"pos": [0.72, 0.25, 0.1, 0.3]}, + } + + def resize(self, sizer): + """ + Resize the graphs in the array. + + Parameters + ---------- + sizer : dict (no default) + A dictionary with keys corresponding to the plot labels. + The values for each key are a list (or tuple) of [left, width, bottom, height] + for each panel in units of the graph [0, 1, 0, 1]. + + sizer = {'A': {'pos': [0.08, 0.22, 0.50, 0.4], 'labelpos': (x,y), 'noaxes': True}, 'B1': {'pos': [0.40, 0.25, 0.60, 0.3], 'labelpos': (x,y)}, + 'B2': {'pos': [0.40, 0.25, 0.5, 0.1],, 'labelpos': (x,y), 'noaxes': False}, + 'C1': {'pos': [0.72, 0.25, 0.60, 0.3], 'labelpos': (x,y)}, 'C2': {'pos': [0.72, 0.25, 0.5, 0.1], 'labelpos': (x,y)}, + 'D': {'pos': [0.08, 0.25, 0.1, 0.3], 'labelpos': (x,y)}, + 'E': {'pos': [0.40, 0.25, 0.1, 0.3], 'labelpos': (x,y)}, 'F': {'pos': [0.72, 0.25, 0.1, 0.3],, 'labelpos': (x,y)} + } + Returns + ------- + Nothing + """ + + for i, s in enumerate(sizer.keys()): + ax = self.axdict[s] + bbox = ax.get_position() + bbox.x0 = sizer[s]["pos"][0] + bbox.x1 = sizer[s]["pos"][1] + sizer[s]["pos"][0] + bbox.y0 = sizer[s]["pos"][2] + bbox.y1 = ( + sizer[s]["pos"][3] + sizer[s]["pos"][2] + ) # offsets are in figure fractions + ax.set_position(bbox) + if "labelpos" in list(sizer[s].keys()) and len(sizer[s]["labelpos"]) == 2: + x, y = sizer[s]["labelpos"] + self.axlabels[i].set_x(x) + self.axlabels[i].set_y(y) + if "noaxes" in sizer[s] and sizer[s]["noaxes"] == True: + noaxes(ax) + + +if __name__ == "__main__": + # P = Plotter((3,3), axmap=[(0, 1, 0, 3), (1, 2, 0, 2), (2, 1, 2, 3), (2, 3, 0, 1), (2, 3, 1, 2)]) + labels = ["A", "B", "C", "D", "E", "F", "G", "H", "I"] + l = [(a, a + 2, 0, 1) for a in range(0, 6, 2)] + r = [(a, a + 1, 1, 2) for a in range(0, 6)] + axmap = OrderedDict(list(zip(labels, l + r))) + P = Plotter((6, 2), axmap=axmap, figsize=(6.0, 6.0), label=True) + # P = Plotter((2,3), label=True) # create a figure with plots + # for a in P.axarr.flatten(): + # a.plot(np.random.random(10), np.random.random(10)) + + # hfig, ax = mpl.subplots(2, 3) + axd = OrderedDict() + for i, a in enumerate(P.axarr.flatten()): + label = string.ascii_uppercase[i] + axd[label] = a + for a in list(axd.keys()): + axd[a].plot(np.random.random(10), np.random.random(10)) + nice_plot([axd[a] for a in axd], position=-0.1) + cleanAxes([axd["B"], axd["C"]]) + calbar([axd["B"], axd["C"]], calbar=[0.5, 0.5, 0.2, 0.2]) + # labelPanels([axd[a] for a in axd], axd.keys()) + # mpl.tight_layout(pad=2, w_pad=0.5, h_pad=2.0) + mpl.show() diff --git a/cnmodel/util/__init__.py b/cnmodel/util/__init__.py new file mode 100644 index 0000000..ebcbd71 --- /dev/null +++ b/cnmodel/util/__init__.py @@ -0,0 +1,9 @@ +from .stim import * +from .find_point import * +from .pynrnutilities import * +from .nrnutils import * +from .expfitting import * +from .user_tester import UserTester +from .get_anspikes import * +from .Params import * +from .talbotetalTicks import Extended diff --git a/cnmodel/util/ccstim.py b/cnmodel/util/ccstim.py new file mode 100644 index 0000000..ccc96f2 --- /dev/null +++ b/cnmodel/util/ccstim.py @@ -0,0 +1,125 @@ +__author__ = "pbmanis" +""" +ccstim +Generate current-clamp (or voltage-clamp) stimulus waveforms from a dictionary +used for vectory play modes in current clamp +(prior version was called 'makestim') + +Can generate several types of pulses + +""" + +import numpy as np + + +def ccstim(stim, dt, pulsetype="square"): + """ + Create stimulus pulse waveforms of different types. + + Parameters + ---------- + stim : dict + a dictionary with keys [required] + delay (delay to start of pulse train, msec [all] + duration: duration of pulses in train, msec [all] + Sfreq: stimulus train frequency (Hz) [timedSpikes] + PT: post-train test delay [all] + NP: number of pulses in the train [timedSpikes, exp] + amp: amplitude of the pulses in the train [all] + hypamp: amplitude of prehyperpolarizing pulse [hyp] + hypdur: duration of prehyperpolarizing pulse [hyp] + spikeTimes" times of spikes [timedSpikes] + + dt : time (microseconds) [required] + step time, in microseconds. Required parameter + + pulsetype : string (default: 'square') + Type of pulse to generate: one of square, hyp, timedspikes or exp + square produces a train of "square" (retangular) pulses levels 0 and ampitude + hyp is like square, but precedes the pulse train with a single prepulse + of hypamp and hypdur + timedspikes is like square, excpet the pulses are generated at times specified + in the spikeTimes key in the stim dictionary + exp: pulses with an exponential decay. + + TO DO: + add pulsetypes, including sine wave, rectified sine wave, etc. + + Returns + ------- + list containing [waveform (numpy array), + maxtime(float), + timebase (numpy array)] + """ + + assert dt is not None + assert "delay" in stim.keys() + delay = int(np.floor(stim["delay"] / dt)) + if pulsetype in ["square", "hyp", "exp"]: + ipi = int(np.floor((1000.0 / stim["Sfreq"]) / dt)) + pdur = int(np.floor(stim["duration"] / dt)) + posttest = int(np.floor(stim["PT"] / dt)) + if pulsetype not in ["timedSpikes"]: + NP = int(stim["NP"]) + else: + NP = len(stim["spikeTimes"]) + tstims = [0] * NP + if pulsetype == "hyp": + assert "hypamp" in stim.keys() + assert "hypdur" in stim.keys() + hypdur = int(np.floor(stim["hypdur"] / dt)) + delay0 = delay # save original delay + + if pulsetype in ["square", "hyp"]: + maxt = dt * (stim["delay"] + (ipi * (NP + 2)) + posttest + pdur * 2) + if pulsetype == "hyp": + maxt = maxt + dt * stim["hypdur"] + delay = delay + hypdur + w = np.zeros(int(np.floor(maxt / dt))) + for j in range(0, NP): + t = (delay + j * ipi) * dt + w[delay + ipi * j : delay + (ipi * j) + pdur] = stim["amp"] + tstims[j] = delay + ipi * j + if stim["PT"] > 0.0: + send = delay + ipi * j + for i in range(send + posttest, send + posttest + pdur): + w[i] = stim["amp"] + if pulsetype == "hyp": # fill in the prepulse now + for i in range(delay0, delay0 + hypdur): + w[i] = stim["hypamp"] + + if pulsetype == "timedSpikes": + maxt = np.max(stim["spikeTimes"]) + stim["PT"] + stim["duration"] * 2 + w = np.zeros(int(np.floor(maxt / dt))) + for j in range(len(stim["spikeTimes"])): + st = delay + int(np.floor(stim["spikeTimes"][j] / dt)) + t = st * dt + w[st : st + pdur] = stim["amp"] + tstims[j] = st + + if stim["PT"] > 0.0: + for i in range(st + posttest, st + posttest + pdur): + w[i] = stim["amp"] + + if pulsetype == "exp": + maxt = dt * (stim["delay"] + (ipi * (NP + 2)) + posttest + pdur * 2) + w = np.zeros(int(np.floor(maxt / dt))) + + for j in range(0, NP): + for i in range(0, len(w)): + if delay + ipi * j + i < len(w): + w[delay + ipi * j + i] = w[delay + ipi * j + i] + stim["amp"] * ( + (1.0 - np.exp(-i / (pdur / 3.0))) + * np.exp(-(i - (pdur / 3.0)) / pdur) + ) + tstims[j] = delay + ipi * j + if stim["PT"] > 0.0: + send = delay + ipi * j + for i in range(send + posttest, len(w)): + w[i] += ( + stim["amp"] + * (1.0 - np.exp(-i / (pdur / 3.0))) + * np.exp(-(i - (pdur / 3.0)) / pdur) + ) + + return (w, maxt, tstims) diff --git a/cnmodel/util/compare_simple_multisynapses.py b/cnmodel/util/compare_simple_multisynapses.py new file mode 100644 index 0000000..6f0f3a1 --- /dev/null +++ b/cnmodel/util/compare_simple_multisynapses.py @@ -0,0 +1,658 @@ +""" +Test synaptic connections between two different cell types. + +Usage: python compare_simple_multisynapses.py + +This script: + +1. Creates single pre- and postsynaptic cells +2. Creates a single synaptic terminal between the two cells, using the multisite synapse method. +3. Stimulates the presynaptic cell by current injection. +4. Records and analyzes the resulting post-synaptic events. +5. Repeats 3, 4 100 times to get an average postsynaptic event. +6. stores the resulting waveform in a pandas database + +This is used mainly to check that the strength, kinetics, and dynamics of +each synapse type is working as expected. + +Requires Python 3.6 +""" +import sys +import argparse +from pathlib import Path +import numpy as np + +# import pyqtgraph as pg +import matplotlib.pyplot as mpl +import neuron as h +import cnmodel.util.PlotHelpers as PH +from cnmodel.protocols import SynapseTest +from cnmodel import cells +from cnmodel.synapses import Synapse +import pickle +import lmfit + + +convergence = { + "sgc": { + "bushy": 1, + "tstellate": 1, + "dstellate": 1, + "octopus": 1, + "pyramidal": 1, + "tuberculoventral": 1, + }, + "dstellate": { + "bushy": 1, + "tstellate": 1, + "dstellate": 1, + "pyramidal": 1, + "tuberculoventral": 1, + }, + "tuberculoventral": { + "bushy": 1, + "tstellate": 1, + "pyramidal": 1, + "tuberculoventral": 1, + }, +} + + +class Exp2SynFitting: + """ + Fit waveform against Exp2SYN function (used by Neuron) + THe function is (from the documentation): + i = G * (v - e) i(nanoamps), g(micromhos); + G = weight * factor * (exp(-t/tau2) - exp(-t/tau1)) + WHere factor is evaluated when initializing(in neuron; see exp2syn.mod source) as: + tp = (tau1*tau2)/(tau2 - tau1) * log(tau2/tau1) (log10) + factor = -exp(-tp/tau1) + exp(-tp/tau2) + factor = 1/factor + + Parameters + ---------- + initpars : dict + dict of initial parameters. For example: {'tau1': 0.1, + 'tau2': 0.3, 'weight': 0.1, 'delay' : 0.0, 'erev': -80.} (erev in mV) + bounds : dict + dictionary of bounds for each parameter, with a list of lower and upper values. + + """ + + def __init__(self, initpars=None, bounds=None, functype="exp2syn"): + self.fitpars = lmfit.Parameters() + if functype == "exp2syn": # future handle other functions like alpha + # (Name, Value, Vary, Min, Max, Expr) + self.fitpars.add_many( + ("tau1", initpars["tau1"], True, 0.05, 25.0, None), + # ('tau2', initpars['tau2'], True, 0.1, 50., None), + ("tauratio", initpars["tauratio"], True, 1.0001, 100.0, None), + ("weight", initpars["weight"], True, 1e-6, 1, None), + ("erev", initpars["erev"], False), # do not adjust! + ("v", initpars["v"], False), + ("delay", initpars["delay"], True, 0.0, 5.0, None), + ) + self.func = self.exp2syn_err + else: + raise ValueError + + def fit(self, x, y, p, verbose=False): + """ + Perform the curve fit against the specified function + + Parameters + ---------- + x : time base for waveform (np array or list) + y : waveform (1-d np array or list) + p : parameters in lmfit Parameters structure + verbose : boolean (default: False) + If true, print the parameters in a nice format + """ + + kws = {"maxfev": 5000} + # print('p: ', p) + self.mim = lmfit.minimize( + self.func, p, method="least_squares", args=(x, y) + ) # , kws=kws) + if verbose: + lmfit.printfuncs.report_fit(self.mim.params) + fitpars = self.mim.params + return fitpars + + # @staticmethod + def exp2syn(self, x, tau1, tauratio, weight, erev, v, delay): + """ + Compute the exp2syn waveform current as it is done in Neuron + + Note on units: + The units are assumed to be "self consistent" + Thus, if the time base is in msec, tau1, tau2 and the delay are + in msec. erev and v should be in matching units (e.g., mV) + Note thtat the weight is not equal to the conducdtance G, because + of the scaling of the waveform + + Parameters + ---------- + x : time base + tau1 : rising tau for waveform + tau2 : falling tau for waveform + weight : amplitude of the waveform (conductance) + erev : reversal potential for ionic species (used to compute i) + v : holding voltage at which waveform is computed + delay : delay to start of function + + Returns + ------- + i, the calucated current trace for these parameters. + """ + # we handle the requirement that tau2 > tau1 by setting the + # expression in lmfit, and using tauratio rather than a direct + # tau2. + # if tau1/tau2 > 1.0: # make sure tau1 is less than tau2 + # tau1 = 0.999*tau2 + tau2 = tauratio * tau1 + tp = (tau1 * tau2) / (tau2 - tau1) * np.log(tau2 / tau1) + factor = -np.exp(-tp / tau1) + np.exp(-tp / tau2) + factor = 1.0 / factor + G = ( + weight + * factor + * (np.exp(-(x - delay) / tau2) - np.exp(-(x - delay) / tau1)) + ) + G[x - delay < 0] = 0.0 + i = G * (v - erev) # i(nanoamps), g(micromhos); + + return i + + def exp2syn_err(self, p, x, y): + return np.fabs( + y - self.exp2syn(x, **dict([(k, p.value) for k, p in p.items()])) + ) + + def factor(self, tau1, tauratio, weight): + """ + calculate tau-scaled weight + """ + tau2 = tau1 * tauratio + tp = (tau1 * tau2) / (tau2 - tau1) * np.log(tau2 / tau1) + factor = -np.exp(-tp / tau1) + np.exp(-tp / tau2) + factor = 1.0 / factor + G = weight * factor + return G + + +def testexp(): + """ + Test the exp2syn fitting function + """ + pars = { + "tau1": 0.1, + "tauratio": 2.0, + "weight": 0.1, + "erev": -70.0, + "v": -65.0, + "delay": 1, + } + F = Exp2SynFitting( + initpars={ + "tau1": 0.2, + "tauratio": 2.0, + "weight": 0.1, + "erev": -70.0, + "v": -65.0, + "delay": 0, + } + ) + t = np.arange(0, 10.0, 0.01) + p = F.fitpars + target = F.exp2syn( + t, + pars["tau1"], + pars["tauratio"], + pars["weight"], + pars["erev"], + pars["v"], + pars["delay"], + ) + # print(F.fitpars) + pars_fit = F.fit(t, target, F.fitpars) + print("\nTest fit result: ") + lmfit.printfuncs.report_fit(F.mim.params) + print("( tau2 = ", pars_fit["tau1"].value * pars_fit["tauratio"].value, ")") + print("target parameters: ", pars) + print("\n") + + +def compute_psc(synapsetype="multisite", celltypes=["sgc", "tstellate"]): + """ + Compute the PSC between the specified two cell tpes + The type of PSC is set by synspase type and must be 'multisite' or 'simple' + """ + assert synapsetype in ["multisite", "simple"] + + c = [] + for cellType in celltypes: + if cellType == "sgc": + cell = cells.SGC.create() + elif cellType == "tstellate": + cell = cells.TStellate.create(debug=True, ttx=False) + elif ( + cellType == "dstellate" + ): # Type I-II Rothman model, similiar excitability (Xie/Manis, unpublished) + cell = cells.DStellate.create(model="RM03", debug=True, ttx=False) + # elif cellType == 'dstellate_eager': # From Eager et al. + # cell = cells.DStellate.create(model='Eager', debug=True, ttx=False) + elif cellType == "bushy": + cell = cells.Bushy.create(debug=True, ttx=True) + elif cellType == "octopus": + cell = cells.Octopus.create(debug=True, ttx=True) + elif cellType == "tuberculoventral": + cell = cells.Tuberculoventral.create(debug=True, ttx=True) + elif cellType == "pyramidal": + cell = cells.Pyramidal.create(debug=True, ttx=True) + elif cellType == "cartwheel": + cell = cells.Cartwheel.create(debug=True, ttx=True) + else: + raise ValueError("Unknown cell type '%s'" % cellType) + c.append(cell) + + preCell, postCell = c + + print(f"Computing psc for connection {celltypes[0]:s} -> {celltypes[1]:s}") + nTerminals = convergence.get(celltypes[0], {}).get(celltypes[1], None) + if nTerminals is None: + nTerminals = 1 + print( + f"Warning: Unknown convergence for {celltypes[0]:s} -> {celltypes[1]:s}, ASSUMING {nTerminals:d} terminals" + ) + + if celltypes == ["sgc", "bushy"]: + niter = 50 + else: + niter = 200 + assert synapsetype in ["simple", "multisite"] + if synapsetype == "simple": + niter = 1 + st = SynapseTest() + dt = 0.010 + stim = { + "NP": 1, + "Sfreq": 100.0, + "delay": 0.0, + "dur": 0.5, + "amp": 10.0, + "PT": 0.0, + "dt": dt, + } + st.run( + preCell.soma, + postCell.soma, + nTerminals, + dt=dt, + vclamp=-65.0, + iterations=niter, + synapsetype=synapsetype, + tstop=50.0, + stim_params=stim, + ) + # st.show_result() # pyqtgraph plotting - + # st.plots['VPre'].setYRange(-70., 10.) + # st.plots['EPSC'].setYRange(-2.0, 0.5) + # st.plots['latency2080'].setYRange(0., 1.0) + # st.plots['halfwidth'].setYRange(0., 1.0) + # st.plots['RT'].setYRange(0., 0.2) + # st.plots['latency'].setYRange(0., 1.0) + # st.plots['latency_distribution'].setYRange(0., 1.0) + return st # need to keep st alive in memory + + +def fit_one(st, stk): + """ + Fit one trace to the exp2syn function + + Parameters + ---------- + + st : dict (no default) + A dictionary containing (at least) the following keys: + 't' : the time base for the trace to be fit + 'i' : a list of arrays or a 2d numpy array of the data to be fit + + Returns + ------- + pars : The fitting parameters + The fitted parameters are returned as an lmfit Parameters object, so access + individual parameters a pars['parname'].value + + fitted : The fitted waveform, of the same length as the source data waveform + """ + + if stk[0] in ["sgc", "tstellate", "granule"]: + erev = ( + 0.0 + ) # set erev according to the source cell (excitatory: 0, inhibitory: -80) + else: + erev = -70.0 # value used in gly_psd + print("\nstk, erev: ", stk, erev) + F = Exp2SynFitting( + initpars={ + "tau1": 1.0, + "tauratio": 5.0, + "weight": 0.0001, + "erev": erev, + "v": -65.0, + "delay": 0, + } + ) + t = st["t"] + p = F.fitpars + target = np.mean(np.array(st["i"]), axis=0) + # print(F.fitpars) + pars = F.fit(t, target, F.fitpars) + gw = F.factor(pars["tau1"].value, pars["tauratio"].value, pars["weight"].value) + pars.add("GWeight", value=gw, vary=False) + fitted = F.exp2syn( + st["t"], + pars["tau1"], + pars["tauratio"], + pars["weight"], + pars["erev"], + pars["v"], + pars["delay"], + ) + lmfit.printfuncs.report_fit(F.mim.params) + return (pars, fitted) + + +def fit_all(): + """ + Fit exp2syn against the traces in stm + This fits all pre-post cell pairs, and returns the fit + + """ + stm = read_pickle("multisite.pkl") + fits = {} + fitted = {} + # print('stm keys: ', stm.keys()) + # exit() + for i, stk in enumerate(stm.keys()): # for each pre-post cell pair + fitp, fit = fit_one(stm[stk], stk) + fits[stk] = fitp + + fitted[stk] = {"t": stm[stk]["t"], "i": [fit], "pars": fitp} + with (open("simple.pkl", "wb")) as fh: + pickle.dump(fitted, fh) + return fits + + +def plot_all(stm, sts=None): + P = PH.Plotter((3, 5), figsize=(11, 6)) + ax = P.axarr.ravel() + keypairorder = [] + for i, stk in enumerate(stm.keys()): + keypairorder.append(stk) + data = stm[stk] + idat = np.array(data["i"]) + ax[i].plot(np.array(data["t"]), np.mean(idat, axis=0), "c-", linewidth=1.5) + sd = np.std(idat, axis=0) + ax[i].plot( + np.array(data["t"]), np.mean(idat, axis=0) + sd, "c--", linewidth=0.5 + ) # for j in range(idat.shape[0]): + ax[i].plot( + np.array(data["t"]), np.mean(idat, axis=0) - sd, "c--", linewidth=0.5 + ) # for j in range(idat.shape[0]): + rel = 0 + for j in range(idat.shape[0]): + if np.min(idat[j, :]) < -1e-2 or np.max(idat[j, :]) > 1e-2: + rel += 1 + print(f"{str(stk):s} {rel:d} of {idat.shape[0]:d} {str(idat.shape):s}") + + # ax[i].plot(data['t'], idat[j], 'k-', linewidth=0.5, alpha=0.25) + ax[i].set_title("%s : %s" % (stk[0], stk[1]), fontsize=7) + + if sts is not None: # plot the matching exp2syn on this + for i, stks in enumerate(keypairorder): + datas = sts[stks] + isdat = np.array(datas["i"]) + ax[i].plot(datas["t"], np.mean(isdat, axis=0), "m-", linewidth=3, alpha=0.5) + mpl.show() + + +def print_exp2syn_fits(st): + stkeys = list(st.keys()) + postcells = [ + "bushy", + "tstellate", + "dstellate", + "octopus", + "pyramidal", + "tuberculoventral", + "cartwheel", + ] + fmts = { + "weight": "{0:<18.6f}", + "GWeight": "{0:<18.6f}", + "tau1": "{0:<18.3f}", + "tau2": "{0:<18.3f}", + "delay": "{0:<18.3f}", + "erev": "{0:<18.1f}", + } + pars = list(fmts.keys()) + for pre in ["sgc", "dstellate", "tuberculoventral"]: + firstline = False + vrow = dict.fromkeys(pars, False) + for v in pars: + for post in postcells: + if (pre, post) not in stkeys: + print("{0:<18s}".format("0"), end="") + continue + if not firstline: + print("\n%s" % pre.upper()) + print("{0:<18s}".format(" "), end="") + for i in range(len(postcells)): + print("{0:<18s}".format(postcells[i]), end="") + print() + firstline = True + if firstline: + if not vrow[v]: + if v == "tauratio": + print("{0:<18s}".format("tau2"), end="") + else: + print("{0:<18s}".format(v), end="") + vrow[v] = True + # print(fits[(pre, post)].keys()) + fits = st[(pre, post)]["pars"] + # print(v, fits) + if v in ["tauratio", "tau2"]: + print( + fmts[v].format(fits["tau1"].value * fits["tauratio"].value), + end="", + ) + else: + print(fmts[v].format(fits[v].value), end="") + print() + + +def read_pickle(mode): + """ + Read the pickled file generated by runall + + Parameters + ---------- + mode : str + either 'simple' or 'multisite' + + Returns: + the resulting data, which is a dictionary + """ + with (open(Path(mode).with_suffix(".pkl"), "rb")) as fh: + st = pickle.load(fh) + return st + + +def run_all(): + """ + Run all of the multisite synapse calculations for each cell pair + Save the results in the multisite.pkl file + """ + st = {} + pkst = {} + for pre in convergence.keys(): + for post in convergence[pre]: + # if pre == 'sgc' and post in ['bushy', 'tstellate']: + sti = compute_psc(synapsetype="multisite", celltypes=[pre, post]) + st[(pre, post)] = sti + # remove neuron objects before pickling + pkst[(pre, post)] = { + "t": sti["t"], + "i": sti.isoma, + "v": sti["v_soma"], + "pre": sti["v_pre"], + } + + with (open(Path("multisite").with_suffix(".pkl"), "wb")) as fh: + pickle.dump(pkst, fh) + plot_all(pkst) + + +def run_one(pre, post): + """ + Run all of the multisite synapse calculations for each cell pair + Save the results in the multisite.pkl file + """ + assert pre in ["sgc", "tstellate", "dstellate", "tuberculoventral"] + assert post in ["bushy", "tstellate", "dstellate", "tuberculoventral", "pyramidal"] + st = {} + pkst = read_pickle("multisite") + # if pre == 'sgc' and post in ['bushy', 'tstellate']: + sti = compute_psc(synapsetype="multisite", celltypes=[pre, post]) + st[(pre, post)] = sti + # remove neuron objects before pickling + pkst[(pre, post)] = { + "t": sti["t"], + "i": sti.isoma, + "v": sti["v_soma"], + "pre": sti["v_pre"], + } + + with (open(Path("multisite").with_suffix(".pkl"), "wb")) as fh: + pickle.dump(pkst, fh) + plot_all(pkst) + + +def main(): + parser = argparse.ArgumentParser( + description="Compare simple and multisite synapses" + ) + parser.add_argument( + "-m", + "--mode", + type=str, + dest="mode", + default="None", + choices=["simple", "multisite", "both"], + help="Select mode [simple, multisite, compare]", + ) + parser.add_argument( + "-r", + "--run", + action="store_true", + dest="run", + help="Run multisite models between all cell types", + ) + parser.add_argument( + "-o", + "--runone", + action="store_true", + dest="runone", + help="Run multisite models between specified cell types", + ) + parser.add_argument( + "--pre", + type=str, + dest="pre", + default="None", + help="Select presynaptic cell for runone", + ) + parser.add_argument( + "--post", + type=str, + dest="post", + default="None", + help="Select postsynaptic cell for runone", + ) + + parser.add_argument( + "-f", + "--fit", + action="store_true", + dest="fit", + help="Fit exp2syn waveforms to multisite data", + ) + parser.add_argument( + "-t", + "--test", + action="store_true", + dest="test", + help="Run the test on exp2syn fitting", + ) + parser.add_argument( + "-p", + "--plot", + action="store_true", + dest="plot", + help="Plot the current comparison between simple and multisite", + ) + parser.add_argument( + "-l", + "--list", + action="store_true", + dest="list", + help="List the simple fit parameters", + ) + + args = parser.parse_args() + + if args.test: + testexp() + exit() + + if args.run: + run_all() + exit() + + if args.runone: + run_one(args.pre, args.post) + exit() + + if args.fit: + fit_all() # self contained - always fits exp2syn against the current multistie data + ds = read_pickle("simple") + dm = read_pickle("multisite") + plot_all(dm, ds) + exit() + + if args.plot: + if args.mode in ["simple", "multisite"]: + d = read_pickle(args.mode) + plot_all(d) + exit() + elif args.mode in ["both"]: + ds = read_pickle("simple") + dm = read_pickle("multisite") + plot_all(dm, ds) + exit() + else: + print(f"Mode {args.mode:s} is not valid") + exit() + + if args.list: + ds = read_pickle("simple") + print_exp2syn_fits(ds) + + # if sys.flags.interactive == 0: + # pg.QtGui.QApplication.exec_() + + +if __name__ == "__main__": + main() diff --git a/cnmodel/util/difftreewidget/DataTreeWidget.py b/cnmodel/util/difftreewidget/DataTreeWidget.py new file mode 100644 index 0000000..11bcad0 --- /dev/null +++ b/cnmodel/util/difftreewidget/DataTreeWidget.py @@ -0,0 +1,131 @@ +# -*- coding: utf-8 -*- +from pyqtgraph.Qt import QtGui, QtCore +from pyqtgraph.pgcollections import OrderedDict +from .TableWidget import TableWidget +from pyqtgraph.python2_3 import asUnicode +import types, traceback +import numpy as np + +try: + import metaarray + + HAVE_METAARRAY = True +except: + HAVE_METAARRAY = False + +__all__ = ["DataTreeWidget"] + + +class DataTreeWidget(QtGui.QTreeWidget): + """ + Widget for displaying hierarchical python data structures + (eg, nested dicts, lists, and arrays) + """ + + def __init__(self, parent=None, data=None): + QtGui.QTreeWidget.__init__(self, parent) + self.setVerticalScrollMode(self.ScrollPerPixel) + self.setData(data) + self.setColumnCount(3) + self.setHeaderLabels(["key / index", "type", "value"]) + self.setAlternatingRowColors(True) + + def setData(self, data, hideRoot=False): + """data should be a dictionary.""" + self.clear() + self.widgets = [] + self.nodes = {} + self.buildTree(data, self.invisibleRootItem(), hideRoot=hideRoot) + self.expandToDepth(3) + self.resizeColumnToContents(0) + + def buildTree(self, data, parent, name="", hideRoot=False, path=()): + if hideRoot: + node = parent + else: + node = QtGui.QTreeWidgetItem([name, "", ""]) + parent.addChild(node) + + # record the path to the node so it can be retrieved later + # (this is used by DiffTreeWidget) + self.nodes[path] = node + + typeStr, desc, childs, widget = self.parse(data) + node.setText(1, typeStr) + node.setText(2, desc) + + # Truncate description and add text box if needed + if len(desc) > 100: + desc = desc[:97] + "..." + if widget is None: + widget = QtGui.QPlainTextEdit(asUnicode(data)) + widget.setMaximumHeight(200) + widget.setReadOnly(True) + + # Add widget to new subnode + if widget is not None: + self.widgets.append(widget) + subnode = QtGui.QTreeWidgetItem(["", "", ""]) + node.addChild(subnode) + self.setItemWidget(subnode, 0, widget) + self.setFirstItemColumnSpanned(subnode, True) + + # recurse to children + for key, data in childs.items(): + self.buildTree(data, node, asUnicode(key), path=path + (key,)) + + def parse(self, data): + """ + Given any python object, return: + * type + * a short string representation + * a dict of sub-objects to be parsed + * optional widget to display as sub-node + """ + # defaults for all objects + typeStr = type(data).__name__ + if typeStr == "instance": + typeStr += ": " + data.__class__.__name__ + widget = None + desc = "" + childs = {} + + # type-specific changes + if isinstance(data, dict): + desc = "length=%d" % len(data) + if isinstance(data, OrderedDict): + childs = data + else: + childs = OrderedDict(sorted(data.items())) + elif isinstance(data, (list, tuple)): + desc = "length=%d" % len(data) + childs = OrderedDict(enumerate(data)) + elif HAVE_METAARRAY and ( + hasattr(data, "implements") and data.implements("MetaArray") + ): + childs = OrderedDict( + [("data", data.view(np.ndarray)), ("meta", data.infoCopy())] + ) + elif isinstance(data, np.ndarray): + desc = "shape=%s dtype=%s" % (data.shape, data.dtype) + table = TableWidget() + table.setData(data) + table.setMaximumHeight(200) + widget = table + elif isinstance( + data, types.TracebackType + ): ## convert traceback to a list of strings + frames = list( + map(str.strip, traceback.format_list(traceback.extract_tb(data))) + ) + # childs = OrderedDict([ + # (i, {'file': child[0], 'line': child[1], 'function': child[2], 'code': child[3]}) + # for i, child in enumerate(frames)]) + # childs = OrderedDict([(i, ch) for i,ch in enumerate(frames)]) + widget = QtGui.QPlainTextEdit(asUnicode("\n".join(frames))) + widget.setMaximumHeight(200) + widget.setReadOnly(True) + else: + desc = asUnicode(data) + + return typeStr, desc, childs, widget diff --git a/cnmodel/util/difftreewidget/DiffTreeWidget.py b/cnmodel/util/difftreewidget/DiffTreeWidget.py new file mode 100644 index 0000000..03a7ff1 --- /dev/null +++ b/cnmodel/util/difftreewidget/DiffTreeWidget.py @@ -0,0 +1,170 @@ +# -*- coding: utf-8 -*- +from pyqtgraph.Qt import QtGui, QtCore +from pyqtgraph.pgcollections import OrderedDict +from .DataTreeWidget import DataTreeWidget +import pyqtgraph.functions as fn +import types, traceback +import numpy as np + +__all__ = ["DiffTreeWidget"] + + +class DiffTreeWidget(QtGui.QWidget): + """ + Widget for displaying differences between hierarchical python data structures + (eg, nested dicts, lists, and arrays) + """ + + def __init__(self, parent=None, a=None, b=None): + QtGui.QWidget.__init__(self, parent) + self.layout = QtGui.QHBoxLayout() + self.setLayout(self.layout) + self.trees = [DataTreeWidget(self), DataTreeWidget(self)] + for t in self.trees: + self.layout.addWidget(t) + if a is not None: + self.setData(a, b) + + def setData(self, a, b): + """ + Set the data to be compared in this widget. + """ + self.data = (a, b) + self.trees[0].setData(a) + self.trees[1].setData(b) + + return self.compare(a, b) + + def compare(self, a, b, path=()): + """ + Compare data structure *a* to structure *b*. + + Return True if the objects match completely. + Otherwise, return a structure that describes the differences: + + { 'type': bool + 'len': bool, + 'str': bool, + 'shape': bool, + 'dtype': bool, + 'mask': array, + } + + + """ + bad = (255, 200, 200) + diff = [] + # generate typestr, desc, childs for each object + typeA, descA, childsA, _ = self.trees[0].parse(a) + typeB, descB, childsB, _ = self.trees[1].parse(b) + + if typeA != typeB: + self.setColor(path, 1, bad) + if descA != descB: + self.setColor(path, 2, bad) + + if isinstance(a, dict) and isinstance(b, dict): + keysA = set(a.keys()) + keysB = set(b.keys()) + for key in keysA - keysB: + self.setColor(path + (key,), 0, bad, tree=0) + for key in keysB - keysA: + self.setColor(path + (key,), 0, bad, tree=1) + for key in keysA & keysB: + self.compare(a[key], b[key], path + (key,)) + + elif isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)): + for i in range(max(len(a), len(b))): + if len(a) <= i: + self.setColor(path + (i,), 0, bad, tree=1) + elif len(b) <= i: + self.setColor(path + (i,), 0, bad, tree=0) + else: + self.compare(a[i], b[i], path + (i,)) + + elif ( + isinstance(a, np.ndarray) + and isinstance(b, np.ndarray) + and a.shape == b.shape + ): + tableNodes = [tree.nodes[path].child(0) for tree in self.trees] + if a.dtype.fields is None and b.dtype.fields is None: + eq = self.compareArrays(a, b) + if not np.all(eq): + for n in tableNodes: + n.setBackground(0, fn.mkBrush(bad)) + # for i in np.argwhere(~eq): + + else: + if a.dtype == b.dtype: + for i, k in enumerate(a.dtype.fields.keys()): + eq = self.compareArrays(a[k], b[k]) + if not np.all(eq): + for n in tableNodes: + n.setBackground(0, fn.mkBrush(bad)) + # for j in np.argwhere(~eq): + + # dict: compare keys, then values where keys match + # list: + # array: compare elementwise for same shape + + def compareArrays(self, a, b): + intnan = -9223372036854775808 # happens when np.nan is cast to int + anans = np.isnan(a) | (a == intnan) + bnans = np.isnan(b) | (b == intnan) + eq = anans == bnans + mask = ~anans + eq[mask] = np.allclose(a[mask], b[mask]) + return eq + + def setColor(self, path, column, color, tree=None): + brush = fn.mkBrush(color) + + # Color only one tree if specified. + if tree is None: + trees = self.trees + else: + trees = [self.trees[tree]] + + for tree in trees: + item = tree.nodes[path] + item.setBackground(column, brush) + + def _compare(self, a, b): + """ + Compare data structure *a* to structure *b*. + """ + # Check test structures are the same + assert type(info) is type(expect) + if hasattr(info, "__len__"): + assert len(info) == len(expect) + + if isinstance(info, dict): + for k in info: + assert k in expect + for k in expect: + assert k in info + self.compare_results(info[k], expect[k]) + elif isinstance(info, list): + for i in range(len(info)): + self.compare_results(info[i], expect[i]) + elif isinstance(info, np.ndarray): + assert info.shape == expect.shape + assert info.dtype == expect.dtype + if info.dtype.fields is None: + intnan = -9223372036854775808 # happens when np.nan is cast to int + inans = np.isnan(info) | (info == intnan) + enans = np.isnan(expect) | (expect == intnan) + assert np.all(inans == enans) + mask = ~inans + assert np.allclose(info[mask], expect[mask]) + else: + for k in info.dtype.fields.keys(): + self.compare_results(info[k], expect[k]) + else: + try: + assert info == expect + except Exception: + raise NotImplementedError( + "Cannot compare objects of type %s" % type(info) + ) diff --git a/cnmodel/util/difftreewidget/README b/cnmodel/util/difftreewidget/README new file mode 100644 index 0000000..116dcbc --- /dev/null +++ b/cnmodel/util/difftreewidget/README @@ -0,0 +1,2 @@ +Copied from github.com/campagnola/pyqtgraph datatree-arrays branch; this gives us DiffTreeWidget. +This file can be removed if DiffTreeWidget has been merged into pyqtgraph. diff --git a/cnmodel/util/difftreewidget/TableWidget.py b/cnmodel/util/difftreewidget/TableWidget.py new file mode 100644 index 0000000..baff6d2 --- /dev/null +++ b/cnmodel/util/difftreewidget/TableWidget.py @@ -0,0 +1,515 @@ +# -*- coding: utf-8 -*- +import numpy as np +from pyqtgraph.Qt import QtGui, QtCore +from pyqtgraph.python2_3 import asUnicode, basestring +import pyqtgraph.metaarray as metaarray + + +__all__ = ["TableWidget"] + + +def _defersort(fn): + def defersort(self, *args, **kwds): + # may be called recursively; only the first call needs to block sorting + setSorting = False + if self._sorting is None: + self._sorting = self.isSortingEnabled() + setSorting = True + self.setSortingEnabled(False) + try: + return fn(self, *args, **kwds) + finally: + if setSorting: + self.setSortingEnabled(self._sorting) + self._sorting = None + + return defersort + + +class TableWidget(QtGui.QTableWidget): + """Extends QTableWidget with some useful functions for automatic data handling + and copy / export context menu. Can automatically format and display a variety + of data types (see :func:`setData() ` for more + information. + """ + + def __init__(self, *args, **kwds): + """ + All positional arguments are passed to QTableWidget.__init__(). + + ===================== ================================================= + **Keyword Arguments** + editable (bool) If True, cells in the table can be edited + by the user. Default is False. + sortable (bool) If True, the table may be soted by + clicking on column headers. Note that this also + causes rows to appear initially shuffled until + a sort column is selected. Default is True. + *(added in version 0.9.9)* + ===================== ================================================= + """ + + QtGui.QTableWidget.__init__(self, *args) + + self.itemClass = TableWidgetItem + + self.setVerticalScrollMode(self.ScrollPerPixel) + self.setSelectionMode(QtGui.QAbstractItemView.ContiguousSelection) + self.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) + self.clear() + + kwds.setdefault("sortable", True) + kwds.setdefault("editable", False) + self.setEditable(kwds.pop("editable")) + self.setSortingEnabled(kwds.pop("sortable")) + + if len(kwds) > 0: + raise TypeError("Invalid keyword arguments '%s'" % kwds.keys()) + + self._sorting = None # used when temporarily disabling sorting + + self._formats = { + None: None + } # stores per-column formats and entire table format + self.sortModes = {} # stores per-column sort mode + + self.itemChanged.connect(self.handleItemChanged) + + self.contextMenu = QtGui.QMenu() + self.contextMenu.addAction("Copy Selection").triggered.connect(self.copySel) + self.contextMenu.addAction("Copy All").triggered.connect(self.copyAll) + self.contextMenu.addAction("Save Selection").triggered.connect(self.saveSel) + self.contextMenu.addAction("Save All").triggered.connect(self.saveAll) + + def clear(self): + """Clear all contents from the table.""" + QtGui.QTableWidget.clear(self) + self.verticalHeadersSet = False + self.horizontalHeadersSet = False + self.items = [] + self.setRowCount(0) + self.setColumnCount(0) + self.sortModes = {} + + def setData(self, data): + """Set the data displayed in the table. + Allowed formats are: + + * numpy arrays + * numpy record arrays + * metaarrays + * list-of-lists [[1,2,3], [4,5,6]] + * dict-of-lists {'x': [1,2,3], 'y': [4,5,6]} + * list-of-dicts [{'x': 1, 'y': 4}, {'x': 2, 'y': 5}, ...] + """ + self.clear() + self.appendData(data) + self.resizeColumnsToContents() + + @_defersort + def appendData(self, data): + """ + Add new rows to the table. + + See :func:`setData() ` for accepted + data types. + """ + startRow = self.rowCount() + + fn0, header0 = self.iteratorFn(data) + if fn0 is None: + self.clear() + return + it0 = fn0(data) + try: + first = next(it0) + except StopIteration: + return + fn1, header1 = self.iteratorFn(first) + if fn1 is None: + self.clear() + return + + firstVals = [x for x in fn1(first)] + self.setColumnCount(len(firstVals)) + + if not self.verticalHeadersSet and header0 is not None: + labels = [self.verticalHeaderItem(i).text() for i in range(self.rowCount())] + self.setRowCount(startRow + len(header0)) + self.setVerticalHeaderLabels(labels + header0) + self.verticalHeadersSet = True + if not self.horizontalHeadersSet and header1 is not None: + self.setHorizontalHeaderLabels(header1) + self.horizontalHeadersSet = True + + i = startRow + self.setRow(i, firstVals) + for row in it0: + i += 1 + self.setRow(i, [x for x in fn1(row)]) + + if ( + self._sorting + and self.horizontalHeadersSet + and self.horizontalHeader().sortIndicatorSection() >= self.columnCount() + ): + self.sortByColumn(0, QtCore.Qt.AscendingOrder) + + def setEditable(self, editable=True): + self.editable = editable + for item in self.items: + item.setEditable(editable) + + def setFormat(self, format, column=None): + """ + Specify the default text formatting for the entire table, or for a + single column if *column* is specified. + + If a string is specified, it is used as a format string for converting + float values (and all other types are converted using str). If a + function is specified, it will be called with the item as its only + argument and must return a string. Setting format = None causes the + default formatter to be used instead. + + Added in version 0.9.9. + + """ + if ( + format is not None + and not isinstance(format, basestring) + and not callable(format) + ): + raise ValueError( + "Format argument must string, callable, or None. (got %s)" % format + ) + + self._formats[column] = format + + if column is None: + # update format of all items that do not have a column format + # specified + for c in range(self.columnCount()): + if self._formats.get(c, None) is None: + for r in range(self.rowCount()): + item = self.item(r, c) + if item is None: + continue + item.setFormat(format) + else: + # set all items in the column to use this format, or the default + # table format if None was specified. + if format is None: + format = self._formats[None] + for r in range(self.rowCount()): + item = self.item(r, column) + if item is None: + continue + item.setFormat(format) + + def iteratorFn(self, data): + ## Return 1) a function that will provide an iterator for data and 2) a list of header strings + if isinstance(data, list) or isinstance(data, tuple): + return lambda d: d.__iter__(), None + elif isinstance(data, dict): + return lambda d: iter(d.values()), list(map(asUnicode, data.keys())) + elif hasattr(data, "implements") and data.implements("MetaArray"): + if data.axisHasColumns(0): + header = [ + asUnicode(data.columnName(0, i)) for i in range(data.shape[0]) + ] + elif data.axisHasValues(0): + header = list(map(asUnicode, data.xvals(0))) + else: + header = None + return self.iterFirstAxis, header + elif isinstance(data, np.ndarray): + return self.iterFirstAxis, None + elif isinstance(data, np.void): + return self.iterate, list(map(asUnicode, data.dtype.names)) + elif data is None: + return (None, None) + elif np.isscalar(data): + return self.iterateScalar, None + else: + msg = "Don't know how to iterate over data type: {!s}".format(type(data)) + raise TypeError(msg) + + def iterFirstAxis(self, data): + for i in range(data.shape[0]): + yield data[i] + + def iterate(self, data): + # for numpy.void, which can be iterated but mysteriously + # has no __iter__ (??) + for x in data: + yield x + + def iterateScalar(self, data): + yield data + + def appendRow(self, data): + self.appendData([data]) + + @_defersort + def addRow(self, vals): + row = self.rowCount() + self.setRowCount(row + 1) + self.setRow(row, vals) + + @_defersort + def setRow(self, row, vals): + if row > self.rowCount() - 1: + self.setRowCount(row + 1) + for col in range(len(vals)): + val = vals[col] + item = self.itemClass(val, row) + item.setEditable(self.editable) + sortMode = self.sortModes.get(col, None) + if sortMode is not None: + item.setSortMode(sortMode) + format = self._formats.get(col, self._formats[None]) + item.setFormat(format) + self.items.append(item) + self.setItem(row, col, item) + item.setValue(val) # Required--the text-change callback is invoked + # when we call setItem. + + def setSortMode(self, column, mode): + """ + Set the mode used to sort *column*. + + ============== ======================================================== + **Sort Modes** + value Compares item.value if available; falls back to text + comparison. + text Compares item.text() + index Compares by the order in which items were inserted. + ============== ======================================================== + + Added in version 0.9.9 + """ + for r in range(self.rowCount()): + item = self.item(r, column) + if hasattr(item, "setSortMode"): + item.setSortMode(mode) + self.sortModes[column] = mode + + def sizeHint(self): + # based on http://stackoverflow.com/a/7195443/54056 + width = sum(self.columnWidth(i) for i in range(self.columnCount())) + width += self.verticalHeader().sizeHint().width() + width += self.verticalScrollBar().sizeHint().width() + width += self.frameWidth() * 2 + height = sum(self.rowHeight(i) for i in range(self.rowCount())) + height += self.verticalHeader().sizeHint().height() + height += self.horizontalScrollBar().sizeHint().height() + return QtCore.QSize(width, height) + + def serialize(self, useSelection=False): + """Convert entire table (or just selected area) into tab-separated text values""" + if useSelection: + selection = self.selectedRanges()[0] + rows = list(range(selection.topRow(), selection.bottomRow() + 1)) + columns = list(range(selection.leftColumn(), selection.rightColumn() + 1)) + else: + rows = list(range(self.rowCount())) + columns = list(range(self.columnCount())) + + data = [] + if self.horizontalHeadersSet: + row = [] + if self.verticalHeadersSet: + row.append(asUnicode("")) + + for c in columns: + row.append(asUnicode(self.horizontalHeaderItem(c).text())) + data.append(row) + + for r in rows: + row = [] + if self.verticalHeadersSet: + row.append(asUnicode(self.verticalHeaderItem(r).text())) + for c in columns: + item = self.item(r, c) + if item is not None: + row.append(asUnicode(item.value)) + else: + row.append(asUnicode("")) + data.append(row) + + s = "" + for row in data: + s += "\t".join(row) + "\n" + return s + + def copySel(self): + """Copy selected data to clipboard.""" + QtGui.QApplication.clipboard().setText(self.serialize(useSelection=True)) + + def copyAll(self): + """Copy all data to clipboard.""" + QtGui.QApplication.clipboard().setText(self.serialize(useSelection=False)) + + def saveSel(self): + """Save selected data to file.""" + self.save(self.serialize(useSelection=True)) + + def saveAll(self): + """Save all data to file.""" + self.save(self.serialize(useSelection=False)) + + def save(self, data): + fileName = QtGui.QFileDialog.getSaveFileName( + self, "Save As..", "", "Tab-separated values (*.tsv)" + ) + if fileName == "": + return + open(fileName, "w").write(data) + + def contextMenuEvent(self, ev): + self.contextMenu.popup(ev.globalPos()) + + def keyPressEvent(self, ev): + if ev.key() == QtCore.Qt.Key_C and ev.modifiers() == QtCore.Qt.ControlModifier: + ev.accept() + self.copySel() + else: + QtGui.QTableWidget.keyPressEvent(self, ev) + + def handleItemChanged(self, item): + item.itemChanged() + + +class TableWidgetItem(QtGui.QTableWidgetItem): + def __init__(self, val, index, format=None): + QtGui.QTableWidgetItem.__init__(self, "") + self._blockValueChange = False + self._format = None + self._defaultFormat = "%0.3g" + self.sortMode = "value" + self.index = index + flags = QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled + self.setFlags(flags) + self.setValue(val) + self.setFormat(format) + + def setEditable(self, editable): + """ + Set whether this item is user-editable. + """ + if editable: + self.setFlags(self.flags() | QtCore.Qt.ItemIsEditable) + else: + self.setFlags(self.flags() & ~QtCore.Qt.ItemIsEditable) + + def setSortMode(self, mode): + """ + Set the mode used to sort this item against others in its column. + + ============== ======================================================== + **Sort Modes** + value Compares item.value if available; falls back to text + comparison. + text Compares item.text() + index Compares by the order in which items were inserted. + ============== ======================================================== + """ + modes = ("value", "text", "index", None) + if mode not in modes: + raise ValueError("Sort mode must be one of %s" % str(modes)) + self.sortMode = mode + + def setFormat(self, fmt): + """Define the conversion from item value to displayed text. + + If a string is specified, it is used as a format string for converting + float values (and all other types are converted using str). If a + function is specified, it will be called with the item as its only + argument and must return a string. + + Added in version 0.9.9. + """ + if fmt is not None and not isinstance(fmt, basestring) and not callable(fmt): + raise ValueError( + "Format argument must string, callable, or None. (got %s)" % fmt + ) + self._format = fmt + self._updateText() + + def _updateText(self): + self._blockValueChange = True + try: + self._text = self.format() + self.setText(self._text) + finally: + self._blockValueChange = False + + def setValue(self, value): + self.value = value + self._updateText() + + def itemChanged(self): + """Called when the data of this item has changed.""" + if self.text() != self._text: + self.textChanged() + + def textChanged(self): + """Called when this item's text has changed for any reason.""" + self._text = self.text() + + if self._blockValueChange: + # text change was result of value or format change; do not + # propagate. + return + + try: + + self.value = type(self.value)(self.text()) + except ValueError: + self.value = str(self.text()) + + def format(self): + if callable(self._format): + return self._format(self) + if isinstance(self.value, (float, np.floating)): + if self._format is None: + return self._defaultFormat % self.value + else: + return self._format % self.value + else: + return asUnicode(self.value) + + def __lt__(self, other): + if self.sortMode == "index" and hasattr(other, "index"): + return self.index < other.index + if self.sortMode == "value" and hasattr(other, "value"): + return self.value < other.value + else: + return self.text() < other.text() + + +if __name__ == "__main__": + app = QtGui.QApplication([]) + win = QtGui.QMainWindow() + t = TableWidget() + win.setCentralWidget(t) + win.resize(800, 600) + win.show() + + ll = [[1, 2, 3, 4, 5]] * 20 + ld = [{"x": 1, "y": 2, "z": 3}] * 20 + dl = {"x": list(range(20)), "y": list(range(20)), "z": list(range(20))} + + a = np.ones((20, 5)) + ra = np.ones((20,), dtype=[("x", int), ("y", int), ("z", int)]) + + t.setData(ll) + + ma = metaarray.MetaArray( + np.ones((20, 3)), + info=[ + {"values": np.linspace(1, 5, 20)}, + {"cols": [{"name": "x"}, {"name": "y"}, {"name": "z"}]}, + ], + ) + t.setData(ma) diff --git a/cnmodel/util/difftreewidget/__init__.py b/cnmodel/util/difftreewidget/__init__.py new file mode 100644 index 0000000..9b261da --- /dev/null +++ b/cnmodel/util/difftreewidget/__init__.py @@ -0,0 +1 @@ +from .DiffTreeWidget import DiffTreeWidget diff --git a/cnmodel/util/expfitting.py b/cnmodel/util/expfitting.py new file mode 100755 index 0000000..efbc1a4 --- /dev/null +++ b/cnmodel/util/expfitting.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python +# encoding: utf-8 +""" +expfitting.py +Provide single or double exponential fits to data. +""" + +import lmfit +import numpy as np +import scipy.optimize + + +class ExpFitting: + """ + Parameters + ---------- + nexp : int + 1 or 2 for single or double exponential fit + initpars : dict + dict of initial parameters. For example: {'dc': 0., + 'a1': 1., 't1': 3, 'a2' : 0.5, 'delta': 3.}, where + delta determines the ratio between the time constants. + bounds : dict + dictionary of bounds for each parameter, with a list of lower and upper values. + + """ + + def __init__(self, nexp=1, initpars=None, bounds=None): + self.fitpars = lmfit.Parameters() + if nexp == 1: + # (Name, Value, Vary, Min, Max, Expr) + self.fitpars.add_many( + ("dc", 0, True, -100.0, 0.0, None), + ("a1", 1.0, True, -25.0, 25.0, None), + ("t1", 10.0, True, 0.1, 50, None), + ) + self.efunc = self.exp1_err + elif nexp == 2: + self.fitpars.add_many( + ("dc", 0, True, -100.0, 0.0, None), + ("a1", 1.0, True, 0.0, 25.0, None), + ("t1", 10.0, True, 0.1, 50, None), + ("a2", 1.0, True, 0.0, 25.0, None), + ("delta", 3.0, True, 3.0, 100.0, None), + ) + if initpars is not None: + assert len(initpars) == 5 + for k, v in initpars.iteritems(): + self.fitpars[k].value = v + if bounds is not None: + assert len(bounds) == 5 + for k, v in bounds.iteritems(): + self.fitpars[k].min = v[0] + self.fitpars[k].max = v[1] + + self.efunc = self.exp2_err + else: + raise ValueError + + def fit(self, x, y, p, verbose=False): + + kws = {"maxfev": 5000} + mim = lmfit.minimize( + self.efunc, p, method="least_squares", args=(x, y) + ) # , kws=kws) + if verbose: + lmfit.printfuncs.report_fit(mim.params) + fitpars = mim.params + return fitpars + + @staticmethod + def exp1(x, dc, t1, a1): + return dc + a1 * np.exp(-x / t1) + + def exp1_err(self, p, x, y): + return np.fabs(y - self.exp1(x, **dict([(k, p.value) for k, p in p.items()]))) + + @staticmethod + def exp2(x, dc, t1, a1, a2, delta): + return dc + a1 * np.exp(-x / t1) + a2 * np.exp(-x / (t1 * delta)) + + def exp2_err(self, p, x, y): + return np.fabs(y - self.exp2(x, **dict([(k, p.value) for k, p in p.items()]))) diff --git a/cnmodel/util/filelock.py b/cnmodel/util/filelock.py new file mode 100644 index 0000000..50d8f3b --- /dev/null +++ b/cnmodel/util/filelock.py @@ -0,0 +1,133 @@ +# Copyright (c) 2009, Evan Fosmark +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# The views and conclusions contained in the software and documentation are those +# of the authors and should not be interpreted as representing official policies, +# either expressed or implied, of the FreeBSD Project. + +import os +import time +import errno + + +class FileLockException(Exception): + pass + + +class FileLock(object): + """ A file locking mechanism that has context-manager support so + you can use it in a with statement. This should be relatively cross + compatible as it doesn't rely on msvcrt or fcntl for the locking. + """ + + lock_count = {} # lock count for each locked file + lock_handles = {} # file handle for each locked file + + def __init__(self, file_name, timeout=10, delay=0.05): + """ Prepare the file locker. Specify the file to lock and optionally + the maximum timeout and the delay between each attempt to lock. + """ + self.fd = None + self.is_locked = False + self.lockfile = os.path.join(os.getcwd(), "%s.lock" % file_name) + self.file_name = file_name + self.timeout = timeout + self.delay = delay + + def acquire(self): + """ Acquire the lock, if possible. If the lock is in use, it check again + every `wait` seconds. It does this until it either gets the lock or + exceeds `timeout` number of seconds, in which case it throws + an exception. + """ + # Don't try to lock the same file more than once + if FileLock.lock_count.setdefault(self.lockfile, 0) > 0: + self.is_locked = True + self.fd = FileLock.lock_handles[self.lockfile] + FileLock.lock_count[self.lockfile] += 1 + return + + start_time = time.time() + while True: + try: + # create the cache directory if it does not exist (new installations will not have a cache directory) + stimdir = os.path.dirname(self.lockfile) + cachedir = os.path.dirname(stimdir) + if not os.path.isdir(cachedir): # make sure the cache exists + os.mkdir(cachedir) + if not os.path.isdir(stimdir): # and the specific stimulus dir + os.mkdir(stimdir) + self.fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR) + open(self.lockfile, "w").write(str(os.getpid())) + break + except OSError as e: + if e.errno != errno.EEXIST: + raise + if (time.time() - start_time) >= self.timeout: + try: + pid = open(self.lockfile).read() + except Exception: + pid = "[error reading lockfile: %s]" % sys.exc_info()[0] + raise FileLockException( + "Timeout occured. (%s is locked by pid %s)" + % (self.lockfile, pid) + ) + time.sleep(self.delay) + + self.is_locked = True + FileLock.lock_count[self.lockfile] += 1 + FileLock.lock_handles[self.lockfile] = self.fd + + def release(self): + """ Get rid of the lock by deleting the lockfile. + When working in a `with` statement, this gets automatically + called at the end. + """ + if self.is_locked: + self.is_locked = False + FileLock.lock_count[self.lockfile] -= 1 + if FileLock.lock_count[self.lockfile] == 0: + os.close(self.fd) + os.unlink(self.lockfile) + del FileLock.lock_handles[self.lockfile] + + def __enter__(self): + """ Activated when used in the with statement. + Should automatically acquire a lock to be used in the with block. + """ + if not self.is_locked: + self.acquire() + return self + + def __exit__(self, type, value, traceback): + """ Activated at the end of the with statement. + It automatically releases the lock if it isn't locked. + """ + if self.is_locked: + self.release() + + def __del__(self): + """ Make sure that the FileLock instance doesn't leave a lockfile + lying around. + """ + self.release() diff --git a/cnmodel/util/find_point.py b/cnmodel/util/find_point.py new file mode 100644 index 0000000..30228f7 --- /dev/null +++ b/cnmodel/util/find_point.py @@ -0,0 +1,95 @@ +from __future__ import print_function +from scipy import interpolate +import numpy as np + + +def find_point(x, y, peakindex, val, direction="left", limits=None): + """ + Given a waveform defined by *x* and *y* arrays, return the first time + at which the waveform crosses (y[peakindex] * val). The search begins at + *peakindex* and proceeds in *direction*. + + Optionally, *limits* may specify a smaller search region in the form of + (t0, t1, dt). + """ + # F = interpolate.UnivariateSpline(x, y, s=0) # declare function + # To find x at y then do: + istart = 0 + iend = len(y) + if limits is not None: + istart = int(limits[0] / limits[2]) + iend = int(limits[1] / limits[2]) + yToFind = y[peakindex] * val + if direction == "left": + yreduced = np.array(y[istart:peakindex]) - yToFind + try: + Fr = interpolate.UnivariateSpline(x[istart:peakindex], yreduced, s=0) + except: + print("find_point: insufficient time points for analysis") + print("arg lengths:", len(x[istart:peakindex]), len(yreduced)) + print("istart, peakindex: ", istart, peakindex) + print("ytofine: ", yToFind) + raise + res = float("nan") + return res + res = Fr.roots() + if len(res) > 1: + res = res[-1] + else: + yreduced = np.array(y[peakindex:iend]) - yToFind + try: + Fr = interpolate.UnivariateSpline(x[peakindex:iend], yreduced, s=0) + except: + print("find_point: insufficient time points for analysis?") + print("arg lengths:", len(x[peakindex:iend]), len(yreduced)) + raise + res = float("nan") + return res + res = Fr.roots() + if len(res) > 1: + res = res[0] + # pdb.set_trace() + try: + res.pop() + except: + pass + if not res: # tricky - an empty list is False, but does not evaluate to False + res = float("nan") # replace with a NaN + else: + res = float(res) # make sure is just a simple number (no arrays) + return res + + +def find_crossing(data, start=0, direction=1, threshold=0): + """Return the index at which *data* crosses *threshold*, starting + at index *start* and proceeding in *direction* (+/-1). + + The value returned is a float indicating the interpolated index + position where the data crosses threshold, or NaN if the threshold was + never crossed. + """ + + # Note: this function is very similar in purpose to find_point, but was + # added due to issues with interpolate.UnivariateSpline + + assert direction in (1, -1) + cross_rising = data[start] < threshold + + def test(x): + if cross_rising: + return x > threshold + else: + return x < threshold + + while True: + next_ind = start + direction + if next_ind < 0 or next_ind >= len(data): + return np.nan + + if test(data[next_ind]): + # crossed; return interpolated value + s1 = data[next_ind] - threshold + s2 = threshold = data[start] + return (next_ind * s2 + start * s1) / (s2 + s1) + + start = next_ind diff --git a/cnmodel/util/fitting.py b/cnmodel/util/fitting.py new file mode 100644 index 0000000..f4890e4 --- /dev/null +++ b/cnmodel/util/fitting.py @@ -0,0 +1,219 @@ +import numpy as np +import lmfit +import pyqtgraph as pg +from pyqtgraph.Qt import QtCore, QtGui + + +class FitModel(lmfit.Model): + """ Simple extension of lmfit.Model that allows one-line fitting. + + Example uses: + + # single exponential fit:: + + fit = expfitting.Exp1.fit(data, + x=time_vals, + xoffset=(0, 'fixed'), + yoffset=(yoff_guess, -120, 0), + amp=(amp_guess, 0, 50), + tau=(tau_guess, 0.1, 50)) + + # plot the fit:: + + fit_curve = fit.eval() + plot(time_vals, fit_curve) + + + # double exponential fit with tau ratio constraint + # note that 'tau_ratio' does not appear in the exp2 model; + # we can define new parameters here.:: + + fit = expfitting.Exp2.fit(data, + x=time_vals, + xoffset=(0, 'fixed'), + yoffset=(yoff_guess, -120, 0), + amp1=(amp_guess, 0, 50), + tau1=(tau_guess, 0.1, 50), + amp2=(-0.5, -50, 0), + tau_ratio=(10, 3, 50), + tau2='tau1 * tau_ratio' + ) + + """ + + def fit(self, data, interactive=False, **params): + """ Return a fit of data to this model. + + Parameters + ---------- + data : array + dependent data to fit + interactive : bool + If True, show a GUI used for interactively exploring fit parameters + + Extra keyword arguments are passed to make_params() if they are model + parameter names, or passed directly to Model.fit() for independent + variable names. + + Returns + ------- + fit of data to model as an lmfit object + """ + + fit_params = {} + model_params = {} + for k, v in params.items(): + if k in self.independent_vars or k in [ + "weights", + "method", + "scale_covar", + "iter_cb", + ]: + fit_params[k] = v + else: + model_params[k] = v + p = self.make_params(**model_params) + # print ('params: ', p) + # print ('fitparams: ', fit_params) + # import matplotlib.pyplot as mpl + # mpl.plot(data) + # mpl.show() + + fit = lmfit.Model.fit(self, data, params=p, **fit_params) + if interactive: + self.show_interactive(fit) + return fit + + def make_params(self, **params): + """ + Make parameters used for fitting with this model. + + Keyword arguments are used to generate parameters for the fit. Each + parameter may be specified by the following formats: + + param=value : + The initial value of the parameter + param=(value, 'fixed') : + Fixed value for the parameter + param=(value, min, max) : + Initial value and min, max values, which may be float or None + param='expression' : + Expression used to compute parameter value. See: + http://lmfit.github.io/lmfit-py/constraints.html#constraints-chapter + """ + p = lmfit.Parameters() + for k in self.param_names: + p.add(k) + + for param, val in params.items(): + if param not in p: + p.add(param) + + if isinstance(val, str): + p[param].expr = val + elif np.isscalar(val): + p[param].value = val + elif isinstance(val, tuple): + if len(val) == 2: + assert val[1] == "fixed" + p[param].value = val[0] + p[param].vary = False + elif len(val) == 3: + p[param].value = val[0] + p[param].min = val[1] + p[param].max = val[2] + else: + raise TypeError( + "Tuple parameter specifications must be (val, 'fixed')" + " or (val, min, max)." + ) + else: + raise TypeError("Invalid parameter specification: %r" % val) + + # set initial values for parameters with mathematical constraints + # this is to allow fit.eval(**fit.init_params) + global_ns = np.__dict__ + for param, val in params.items(): + if isinstance(val, str): + p[param].value = eval(val, global_ns, p.valuesdict()) + return p + + def show_interactive(self, fit=None): + """ Show an interactive GUI for exploring fit parameters. + """ + if not hasattr(self, "_interactive_win"): + self._interactive_win = FitExplorer(model=self, fit=fit) + self._interactive_win.show() + + +def exp1(x, xoffset, yoffset, tau, amp): + return yoffset + amp * np.exp(-(x - xoffset) / tau) + + +class Exp1(FitModel): + """ Single exponential fitting model. + + Parameters are xoffset, yoffset, amp, and tau. + """ + + def __init__(self): + FitModel.__init__(self, exp1, independent_vars=["x"]) + + +def exp2(x, xoffset, yoffset, tau1, amp1, tau2, amp2): + xoff = x - xoffset + return yoffset + amp1 * np.exp(-xoff / tau1) + amp2 * np.exp(-xoff / tau2) + + +class Exp2(FitModel): + """ Double exponential fitting model. + + Parameters are xoffset, yoffset, amp1, tau1, amp2, and tau2. + """ + + def __init__(self): + FitModel.__init__(self, exp2, independent_vars=["x"]) + + +class FitExplorer(QtGui.QWidget): + def __init__(self, model, fit): + QtGui.QWidget.__init__(self) + self.model = model + self.fit = fit + self.layout = QtGui.QGridLayout() + self.setLayout(self.layout) + self.splitter = QtGui.QSplitter(QtCore.Qt.Horizontal) + self.layout.addWidget(self.splitter) + self.ptree = pg.parametertree.ParameterTree() + self.splitter.addWidget(self.ptree) + self.plot = pg.PlotWidget() + self.splitter.addWidget(self.plot) + + self.params = pg.parametertree.Parameter.create( + name="param_root", + type="group", + children=[ + dict(name="fit", type="action"), + dict(name="parameters", type="group"), + ], + ) + + for k in fit.params: + p = pg.parametertree.Parameter.create( + name=k, type="float", value=fit.params[k].value + ) + self.params.param("parameters").addChild(p) + + self.ptree.setParameters(self.params) + + self.update_plots() + + self.params.param("parameters").sigTreeStateChanged.connect(self.update_plots) + + def update_plots(self): + for k in self.fit.params: + self.fit.params[k].value = self.params["parameters", k] + + self.plot.clear() + self.plot.plot(self.fit.data) + self.plot.plot(self.fit.eval(), pen="y") diff --git a/cnmodel/util/get_anspikes.py b/cnmodel/util/get_anspikes.py new file mode 100644 index 0000000..78abd2d --- /dev/null +++ b/cnmodel/util/get_anspikes.py @@ -0,0 +1,477 @@ +from __future__ import print_function + +__author__ = "pbmanis" +""" +ManageANSpikes is a class to read the output of the Zilany et al. 2009 AN model into +python, and provides services to access that data. + +Basic usage is to create an instance of the class, and specify the data directory +if necessary. + +You may then get the data in the format of a list using one of the "get" routines. +The data is pulled from the nearest CF or the specified CF. + +""" +import os +import re +import numpy as np +from collections import OrderedDict +import scipy.io +import matplotlib.pyplot as MP + + +class ManageANSpikes: + """ + ManageANSpikes is a class to read the output of the Zilany et al. 2009 AN model into + python, and provides services to access that data. + + Basic usage is to create an instance of the class, and specify the data directory + if necessary. + + You may then get the data in the format of a list using one of the "get" routines. + The data is pulled from the nearest CF or the specified CF. + + """ + + def __init__(self): + # self.datadir = environment['HOME'] + '/Desktop/Matlab/ZilanyCarney-JASAcode-2009/' + self.data_dir = os.environ["HOME"] + "/Desktop/Matlab/ANData/" + self.data_read_flag = False + self.dataType = "RI" + self.set_CF_map(4000, 38000, 25) # the default list + self.all_AN = None + + def get_data_dir(self): + return self.data_dir + + def set_data_dir(self, directory): + if os.path.isdir(directory): + self.data_dir = directory + else: + raise ValueError("ManageANSpikes.set_data_dir: Path %d is not a directory") + + def get_data_read(self): + return self.data_read_flag + + def get_CF_map(self): + return self.CF_map + + def set_CF_map(self, low, high, nfreq): + self.CF_map = np.round(np.logspace(np.log10(low), np.log10(high), nfreq)) + + def get_dataType(self): + return self.dataType + + def set_dataType(self, datatype): + if datatype in ["RI", "PL"]: # only for recognized data types + self.dataType = datatype + else: + raise ValueError( + "get_anspikes.set_dataType: unrecognized type %s " % datatype + ) + + def plot_RI_vs_F(self, freq=10000.0, spontclass="HS", display=False): + cfd = {} + if display: + MP.figure(10) + for i, fr in enumerate(self.CF_map): + self.read_AN_data(freq=freq, CF=fr, spontclass=spontclass, ignoreflag=True) + nsp = np.zeros(len(self.SPLs)) # this is the same regardless + for i, db in enumerate(self.SPLs): + spkl = self.combine_reps(self.spikelist[i]) + nsp[i] = len(spkl) # /self.SPLs[i] + if display: + MP.plot(self.SPLs, nsp) + + def plot_Rate_vs_F(self, freq=10000.0, spontclass="HS", display=False, SPL=0.0): + """ + assumes we have done a "read all" + + :param freq: + :param spontclass: + :param display: + :param SPL: + :return: + """ + cfd = {} + if display: + MP.figure(10) + for i, db in enumerate(self.SPLs): # plot will have lines at each SPL + # retrieve_from_all_AN(self, cf, SPL) # self.read_AN_data(freq=freq, CF=fr, spontclass=spontclass) + nsp = np.zeros(len(self.CF_map)) # this is the same regardless + for j, fr in enumerate(self.CF_map): + spikelist = self.retrieve_from_all_AN(fr, db) + spkl = self.combine_reps(spikelist) + nsp[j] = len(spkl) / len(spikelist) + if display: + MP.plot(self.CF_map, nsp) + + def getANatFandSPL(self, spontclass="MS", freq=10000.0, CF=None, SPL=0): + """ + Get the AN data at a particular frequency and SPL. Note that the tone freq is specified, + but the CF of the fiber might be different. If CF is None, we try to get the closest + fiber data to the tone Freq. + Other arguments are the spontaneous rate and the SPL level. + The data must exist, or we epically fail. + + :param spontclass: 'HS', 'MS', or 'LS' for high, middle or low spont groups (1,2,3 in Zilany et al model) + :param freq: The stimulus frequency, in Hz + :param CF: The 'characteristic frequency' of the desired AN fiber, in Hz + :param SPL: The sound pressure level, in dB SPL for the stimulus + :return: an array of nReps of spike times. + """ + + if CF is None: + closest = np.argmin( + np.abs(self.CF_map - freq) + ) # find closest to the stim freq + else: + closest = np.argmin( + np.abs(self.CF_map - CF) + ) # find closest to the stim freq + CF = self.CF_map[closest] + print("closest f: ", CF) + self.read_AN_data(spontclass=spontclass, freq=10000.0, CF=CF) + return self.get_AN_at_SPL(SPL) + + def get_AN_at_SPL(self, spl=None): + """ + grabs the AN data for the requested SPL for the data set currently loaded + The data must exist, or we epically fail. + + :param spl: sound pressure level, in dB SPL + :return: spike trains (times) as a list of nReps numpy arrays. + """ + + if not self.data_read_flag: + print("getANatSPL: No data read yet") + return None + try: + k = int(np.where(self.SPLs == spl)[0]) + except (ValueError, TypeError) as e: + print( + "get_anspikes::getANatSPL: spl=%6.1f not in list of spls:" % (spl), + self.SPLs, + ) + exit() # no match + # now clean up array to keep it iterable upon return + spkl = [[]] * len(self.spikelist[k]) + for i in xrange(len(self.spikelist[k])): + try: + len(self.spikelist[k][i]) + spkl[i] = self.spikelist[k][i] + except: + spkl[i] = [np.array(self.spikelist[k][i])] + return spkl # returns all the trials in the list + + def read_all_ANdata( + self, freq=10000.0, CFList=None, spontclass="HS", stim="BFTone" + ): + """ + Reads a bank of AN data, across frequency and intensity, for a given stimulus frequency + Assumptions: the bank of data is consistent in terms of nReps and SPLs + + :param freq: Tone stimulus frequency (if stim is Tone or BFTone) + :param CFList: A list of the CFs to read + :param spontclass: 'HS', 'MS', or 'LS', corresponding to spont rate groups + :param stim: Stimulus type - Tone/BFTone, or Noise + :return: Nothing. The data are stored in an array accessible directly or through a selector function + """ + + self.all_AN = OrderedDict( + [(f, None) for f in CFList] + ) # access through dictionary with keys as freq + for cf in CFList: + self.read_AN_data( + freq=freq, CF=cf, spontclass=spontclass, stim=stim, setflag=False + ) + self.all_AN[cf] = self.spikelist + self.data_read_flag = True # inform and block + + def retrieve_from_all_AN(self, cf, SPL): + """ + :param cf: + :param SPL: + :return: spike list (all nreps) at the cf and SPL requested, for the loaded stimulus set + + """ + + if not self.data_read_flag or self.all_AN is None: + print("get_anspikes::retrieve_from_all_AN: No data read yet: ") + exit() + + ispl = int(np.where(self.SPLs == float(SPL))[0]) + icf = self.all_AN.keys().index(cf) + spikelist = self.all_AN[cf][ispl] + spkl = [[]] * len(spikelist) + # print len(spikelist) + for i in xrange(len(spikelist)): # across trials + try: + len(spikelist[i]) + spkl[i] = spikelist[i] + except: + spkl[i] = [np.array(spikelist[i])] + # print 'cf: %f spl: %d nspk: %f' % (cf, SPL, len(spkl[i])) + return spikelist + + def read_AN_data( + self, + freq=10000, + CF=5300, + spontclass="HS", + display=False, + stim="BFTone", + setflag=True, + ignoreflag=True, + ): + """ + read responses of auditory nerve model of Zilany et al. (2009). + display = True plots the psth's for all ANF channels in the dataset + Request response to stimulus at Freq, for fiber with CF + and specified spont rate + This version is for rate-intensity runs March 2014. + Returns: Nothing + """ + + if not ignoreflag: + assert self.data_read_flag == False + # print 'Each instance of ManageANSPikes is allowed ONE data set to manage' + # print 'This is a design decision to avoid confusion about which data is in the instance' + # exit() + if stim in ["BFTone", "Tone"]: + fname = "%s_F%06.3f_CF%06.3f_%2s.mat" % ( + self.dataType, + freq / 1000.0, + CF / 1000.0, + spontclass, + ) + elif stim == "Noise": + fname = "%s_Noise_CF%06.3f_%2s.mat" % ( + self.dataType, + CF / 1000.0, + spontclass, + ) + + # print 'Reading: %s' % (fname) + try: + mfile = scipy.io.loadmat( + os.path.join(self.data_dir, fname), squeeze_me=True + ) + except IOError: + print("get_anspikes::read_AN_data: Failed to find data file %s" % (fname)) + print( + "Corresponding to Freq: %f CF: %f spontaneous rate class: %s" + % (freq, CF, spontclass) + ) + exit() + + n_spl = len(mfile[self.dataType]) + if display: + n = int(np.sqrt(n_spl)) + 1 + mg = np.meshgrid(range(n), range(n)) + mg = [mg[0].flatten(), mg[1].flatten()] + spkl = [[]] * n_spl + spl = np.zeros(n_spl) + for k in range(n_spl): + spkl[k] = mfile[self.dataType]["data"][k] # get data for one SPL + spl[k] = mfile[self.dataType]["SPL"][k] # get SPL for this set of runs + # print spkl[k].shape + if display: + self.display(spkl[k], k, n, mg) + + if display: + MP.show() + self.spikelist = spkl # save these so we can have a single point to parse them + self.SPLs = spl + self.n_reps = mfile[self.dataType]["nrep"] + if setflag: + self.data_read_flag = True + # return spkl, spl, mfile['RI']['nrep'] + + def getANatSPL(self, spl=None): + if not self.dataRead: + print("getANatSPL: No data read yet") + return None + try: + k = int(np.where(self.SPLs == spl)[0]) + except (ValueError, TypeError) as e: + print( + "get_anspikes::getANatSPL: spl=%6.1f not in list of spls:" % (spl), + self.SPLs, + ) + exit() # no match + # now clean up array to keep it iterable upon return + spkl = [[]] * len(self.spikelist[k]) + for i in xrange(len(self.spikelist[k])): + try: + len(self.spikelist[k][i]) + spkl[i] = self.spikelist[k][i] + except: + spkl[i] = [np.array(self.spikelist[k][i])] + return spkl # returns all the trials in the list + + def get_AN_info(self): + """ + :return: Dictionary of nReps and SPLs that are in the current data set (instance). + """ + + if not self.data_read_flag: + print("getANatSPL: No data read yet") + return None + return {"nReps": self.n_reps, "SPLs": self.SPLs} + + def read_cmrr_data(self, P, signal="S0", display=False): + """ + read responses of auditory nerve model of Zilany et al. (2009). + The required parameters are passed via the class P. + This includes: + + the SN (s2m) is the signal-to-masker ratio to select + the mode is 'CMR', 'CMD' (deviant) or 'REF' (reference, no flanking bands), + 'Tone', or 'Noise' + the Spont rate group + + signal is either 'S0' (signal present) or 'NS' (no signal) + display = True plots the psth's for all ANF channels in the dataset + Returns: + tuple of (spikelist and frequency list for modulated tones) + """ + + if P.modF == 10: + datablock = "%s_F4000.0" % (P.mode) + else: + datablock = "%s_F4000.0_M%06.1f" % ( + P.mode, + P.modF, + ) # 100 Hz modulation directory + # print P.mode + fs = os.listdir(self.datadir + datablock) + s_sn = "SN%03d" % (P.s2m) + fntemplate = "(\S+)_%s_%s_%s_%s.mat" % (s_sn, P.mode, signal, P.SR) + p = re.compile(fntemplate) + fl = [re.match(p, file) for file in fs] + fl = [f.group(0) for f in fl if f != None] # returns list of files matching... + fr = [float(f[1:7]) for f in fl] # frequency list + if display: + self.makeFig() + i = 0 + j = 0 + spkl = [[]] * len(fl) + n = int(np.sqrt(len(fl))) + mg = np.meshgrid(range(n), range(n)) + mg = [mg[0].flatten(), mg[1].flatten()] + for k, fi in enumerate(fl): + mfile = scipy.io.loadmat( + self.datadir + datablock + "/" + fi, squeeze_me=True + ) + spkl[k] = mfile["Cpsth"] + if display: + self.display(spkl[k], k, n, mg) + + if display: + MP.show() + return (spkl, fr) + + def make_fig(self): + self.fig = MP.figure(1) + + def combine_reps(self, spkl): + """ + + Just turns the spike list into one big linear sequence. + :param spkl: a spike train (nreps of numpy arrays) + :return: all the spikes in one long array. + """ + + # print spkl + allsp = np.array(self.flatten(spkl)) + # print allsp.shape + if allsp.shape == (): # nothing to show + return + # print allsp + spks = [] + for i in range(len(allsp)): + if allsp[i] == (): + continue + if isinstance(allsp[i], float): + spks.append(allsp[i]) + else: + spks.extend(np.array(allsp[i])) + return spks + + def display(self, spkl, k, n, mg): + # print spkl + spks = self.combine_reps(spkl) + if spks != []: + spks = np.sort(spks) + MP.hist(spks, 100) + return + + def flatten(self, x): + """ + flatten(sequence) -> list + + Returns a single, flat list which contains all elements retrieved + from the sequence and all recursively contained sub-sequences + (iterables). + """ + result = [] + if isinstance(x, float) or len([x]) <= 1: + return x + for el in x: + if hasattr(el, "__iter__") and not isinstance(el, basestring): + result.extend(self.flatten(el)) + else: + result.append(el) + return result + + +if __name__ == "__main__": + from cnmodel.util import Params + + modes = ["CMR", "CMD", "REF"] + sr_types = ["H", "M", "L"] + sr_type = sr_types[0] + sr_names = { + "H": "HS", + "M": "MS", + "L": "LS", + } # spontaneous rate groups (AN fiber input selection) + # define params for reading/testing. This is a subset of params... + P = Params( + mode=modes[0], + s2m=0, + n_rep=0, + start_rep=0, + sr=sr_names["L"], + modulation_freq=10, + DS_phase=0, + dataset="test", + sr_types=sr_types, + sr_names=sr_names, + fileVersion=1.5, + ) + + manager = ManageANSpikes() # create instance of the manager + print(dir(manager)) + test = "RI" + + if test == "all": + manager.read_all_ANdata( + freq=10000.0, CFList=manager.CF_map, spontclass="HS", stim="BFTone" + ) + # spkl = manager.retrieve_from_all_AN(manager.CF_map[0], 40.) + # spks = manager.combine_reps(spkl) + manager.plot_Rate_vs_F(freq=manager.CF_map[0], display=True, spontclass="HS") + MP.show() + + if test == manager.dataType: + spikes = manager.getANatFandSPL(spontclass="MS", freq=10000.0, CF=None, SPL=50) + spks = manager.combine_reps(spikes) + if spks != []: + print("spikes.") + manager.plot_RI_vs_F(freq=10000.0, display=True, spontclass="MS") + MP.figure(11) + spks = np.sort(spks) + MP.hist(spks, 100) + MP.show() diff --git a/cnmodel/util/matlab_proc.py b/cnmodel/util/matlab_proc.py new file mode 100644 index 0000000..66ab588 --- /dev/null +++ b/cnmodel/util/matlab_proc.py @@ -0,0 +1,402 @@ +from __future__ import print_function + +""" +Simple system for interfacing with a MATLAB process using stdin/stdout pipes. + +""" +from .process import Process +from io import StringIO +import scipy.io +import numpy as np +import tempfile +import os, sys, glob, signal +import weakref +import atexit + + +class MatlabProcess(object): + """ This class starts a new matlab process, allowing remote control of + the interpreter and transfer of data between python and matlab. + """ + + # Implements a MATLAB CLI that is a bit easier for us to parse + _bootstrap = r""" + while true + fprintf('\n::ready\n'); + + % Accumulate command lines until we see ::cmd_done + cmd = ''; + empty_count = 0; + while true + line = input('', 's'); + if length(line) == 0 + % If we encounter many empty lines, assume the host process + % has ended. Is there a better way to detect this? + empty_count = empty_count + 1; + if empty_count > 100 + fprintf('Shutting down!\n'); + exit; + end + end + if strcmp(line, '::cmd_done') + break + end + cmd = [cmd, line, sprintf('\n')]; + end + + % Evaluate command + try + %fprintf('EVAL: %s\n', cmd); + eval(cmd); + fprintf('\n::ok\n'); + catch err + fprintf('\n::err\n'); + fprintf(['::message:', err.message, '\n']); + fprintf(['::identifier:', err.identifier, '\n']); + for i = 1:length(err.stack) + frame = err.stack(i,1); + fprintf(['::stack:', frame.name, ' in ', frame.file, ' line ', frame.line]); + end + end + end + """ + + def __init__(self, executable=None, **kwds): + self.__closed = False + self.__refs = weakref.WeakValueDictionary() + + # Decide which executables to try + if executable is not None: + execs = [executable] + else: + execs = ["matlab"] # always pick the matlab in the path, if available + if sys.platform == "darwin": + installed = glob.glob("/Applications/MATLAB_R*") + installed.sort(reverse=True) + execs.extend([os.path.join(p, "bin", "matlab") for p in installed]) + + # try starting each in order until one works + self.__proc = None + for exe in execs: + try: + self.__proc = Process([exe, "-nodesktop", "-nosplash"], **kwds) + break + except Exception as e: + last_exception = e + pass + + # bail out if we couldn't start any + if self.__proc is None: + raise RuntimeError( + "Could not start MATLAB process.\nPaths attempted: %s " + "\nLast error: %s" % (str(execs), str(e)) + ) + + # Wait a moment for MATLAB to start up, + # read the version string + while True: + line = self.__proc.stdout.readline() + if "Copyright" in line: + # next line is version info + self.__version_str = self.__proc.stdout.readline().strip() + break + + # start input loop + self.__proc.stdin.write(self._bootstrap) + + # wait for input loop to be ready + while True: + line = self.__proc.stdout.readline() + if line == "::ready\n": + break + + atexit.register(self.close) + + def __call__(self, cmd, parse_result=True): + """ + Execute the specified statement(s) on the MATLAB interpreter and return + the output string or raise an exception if there was an error. + """ + assert not self.__closed, "MATLAB process has already closed." + if cmd[-1] != "\n": + cmd += "\n" + cmd += "::cmd_done\n" + self.__proc.stdout.read() + self.__proc.stdin.write(cmd) + + if parse_result: + return self._parse_result() + + def _parse_result(self): + assert not self.__closed, "MATLAB process has already closed." + output = [] + while True: + line = self.__proc.stdout.readline() + if line == "::ready\n": + break + output.append(line) + + for i in reversed(range(len(output))): + line = output[i] + if line == "::ok\n": + return "".join(output[:i]) + elif line == "::err\n": + raise MatlabError(output[i + 1 :], output[:i]) + + raise RuntimeError("No success/failure code found in output (printed above).") + + def _get(self, name): + """ + Transfer an object from MATLAB to Python. + """ + assert isinstance(name, str) + tmp = tempfile.mktemp(suffix=".mat") + out = self("save('%s', '%s', '-v7')" % (tmp, name)) + objs = scipy.io.loadmat(tmp) + os.remove(tmp) + return objs[name] + + def _set(self, **kwds): + """ + Transfer an object from Python to MATLAB and assign it to the given + variable name. + """ + tmp = tempfile.mktemp(suffix=".mat") + scipy.io.savemat(tmp, kwds) + self("load('%s')" % tmp) + os.remove(tmp) + + def _get_via_pipe(self, name): + """ + Transfer an object from MATLAB to Python. + + This method sends data over the pipe, but is less reliable than get(). + """ + assert isinstance(name, str) + out = self("save('stdio', '%s', '-v7')" % name) + start = stop = None + for i, line in enumerate(out): + if line.startswith("start_binary"): + start = i + elif line.startswith("::ok"): + stop = i + data = "".join(out[start + 1 : stop]) + io = StringIO(data[:-1]) + objs = scipy.io.loadmat(io) + return objs[name] + + def _set_via_pipe(self, **kwds): + """ + Transfer an object from Python to MATLAB and assign it to the given + variable name. + + This method sends data over the pipe, but is less reliable than set(). + """ + assert not self.__closed, "MATLAB process has already closed." + io = StringIO() + scipy.io.savemat(io, kwds) + io.seek(0) + strn = io.read() + self.__proc.stdout.read() + self.__proc.stdin.write("load('stdio')\n::cmd_done\n") + while True: + line = self.__proc.stdout.readline() + if line == "ack load stdio\n": + # now it is safe to send data + break + self.__proc.stdin.write(strn) + self.__proc.stdin.write("\n") + while True: + line = self.__proc.stdout.readline() + if line == "ack load finished\n": + break + self._parse_result() + + def exist(self, name): + if name == "exist": + return 5 + else: + for line in self("exist %s" % name).split("\n"): + try: + return int(line.strip()) + except ValueError: + pass + + def __getattr__(self, name): + if name not in self.__refs: + ex = self.exist(name) + if ex == 0: + raise AttributeError("No object named '%s' in matlab workspace." % name) + elif ex in (2, 3, 5): + r = MatlabFunction(self, name) + elif ex == 1: + r = self._mkref(name) + else: + typ = {4: "library file", 6: "P-file", 7: "folder", 8: "class"}[ex] + raise TypeError("Variable '%s' has unsupported type '%s'" % (name, typ)) + self.__refs[name] = r + return self.__refs[name] + + def _mkref(self, name): + assert name not in self.__refs + ref = MatlabReference(self, name) + self.__refs[name] = ref + return ref + + def __setattr__(self, name, value): + if name.startswith("_MatlabProcess__"): + object.__setattr__(self, name, value) + else: + self._set(**{name: value}) + + def close(self): + if self.__closed: + return + self("exit;\n", parse_result=False) + self.__closed = True + + +class MatlabReference(object): + """ Reference to a variable in the matlab workspace. + """ + + def __init__(self, proc, name): + self._proc = proc + self._name = name + + @property + def name(self): + return self._name + + def get(self): + return self._proc._get(self._name) + + def clear(self): + self._proc("clear %s;" % self._name) + + def __del__(self): + self.clear() + + +class MatlabFunction(object): + """ + Proxy to a MATLAB function. + + Calling this object transfers the arguments to MATLAB, invokes the function + remotely, and then transfers the return value back to Python. + """ + + def __init__(self, proc, name): + self._proc = proc + self._name = name + self._nargout = None + + @property + def nargout(self): + """ Number of output arguments for this function. + + For some functions, requesting nargout() will fail. In these cases, + the nargout property must be set manually before calling the function. + """ + if self._nargout is None: + cmd = "fprintf('%%d\\n', nargout('%s'));" % (self._name) + ret = self._proc(cmd) + self._nargout = int(ret.strip()) + return self._nargout + + @nargout.setter + def nargout(self, n): + self._nargout = n + + def __call__(self, *args, **kwds): + """ + Call this function with the given arguments. + + If _transfer is False, then the return values are left in MATLAB and + references to these values are returned instead. + """ + import pyqtgraph as pg + + _transfer = kwds.pop("_transfer", True) + assert len(kwds) == 0 + + # for generating unique variable names + rand = np.random.randint(1e12) + + # store args to temporary variables, excluding those already present + # in the workspace + argnames = [] + upload = {} + for i, arg in enumerate(args): + if isinstance(arg, MatlabReference): + argnames.append(arg.name) + elif np.isscalar(arg): + argnames.append(repr(arg)) + else: + argname = "%s_%d_%d" % (self._name, i, rand) + argnames.append(argname) + upload[argname] = arg + if len(upload) > 0: + self._proc._set(**upload) + + try: + # get number of output args + nargs = self.nargout + + # invoke function, fetch return value(s) + retvars = ["%s_rval_%d_%d" % (self._name, i, rand) for i in range(nargs)] + cmd = "[%s] = %s(%s);" % (",".join(retvars), self._name, ",".join(argnames)) + self._proc(cmd) + if _transfer: + ret = [self._proc._get(var) for var in retvars] + self._proc("clear %s;" % (" ".join(retvars))) + else: + ret = [self._proc._mkref(name) for name in retvars] + if len(ret) == 1: + ret = ret[0] + else: + ret = tuple(ret) + return ret + finally: + # clear all temp variables + clear = list(upload.keys()) + # if _transfer: + # clear += retvars + if len(clear) > 0: + cmd = "clear %s;" % (" ".join(clear)) + self._proc(cmd) + return ret + + +class MatlabError(Exception): + def __init__(self, error, output): + self.output = "".join(output) + for line in error: + self.stack = [] + if line.startswith("::message:"): + self.message = line[10:].strip() + elif line.startswith("::identifier:"): + self.identifier = line[13:].strip() + elif line.startswith("::stack:"): + self.stack.append(line[8:].strip()) + + def __repr__(self): + return "MatlabError(message=%s, identifier=%s)" % ( + repr(self.message), + repr(self.identifier), + ) + + def __str__(self): + if len(self.stack) > 0: + stack = "\nMATLAB Stack:\n%s\nMATLAB Error: " % "\n".join(self.stack) + return stack + self.message + else: + return self.message + + +if __name__ == "__main__": + p = MatlabProcess() + io = StringIO() + scipy.io.savemat(io, {"x": 1}) + io.seek(0) + strn = io.read() diff --git a/cnmodel/util/nrnutils.py b/cnmodel/util/nrnutils.py new file mode 100644 index 0000000..e342587 --- /dev/null +++ b/cnmodel/util/nrnutils.py @@ -0,0 +1,218 @@ +from __future__ import print_function + +""" +Wrapper classes to make working with NEURON easier. + +Author: Andrew P. Davison, UNIC, CNRS +""" + +__version__ = "0.3.0" + +from neuron import nrn, h, hclass + +h.load_file("stdrun.hoc") + +PROXIMAL = 0 +DISTAL = 1 + + +class Mechanism(object): + """ + Examples: + >>> leak = Mechanism('pas', {'e': -65, 'g': 0.0002}) + >>> hh = Mechanism('hh') + added set_parameters to allow post-instantiation parameter modification + """ + + def __init__(self, name, **parameters): + self.name = name + self.parameters = parameters + + def set_parameters(self, parameters): + self.parameters = parameters + + def insert_into(self, section): + section.insert(self.name) + for name, value in self.parameters.items(): + for segment in section: + mech = getattr(segment, self.name) + setattr(mech, name, value) + + +class Section(nrn.Section): + """ + Examples: + >>> soma = Section(L=30, diam=30, mechanisms=[hh, leak]) + >>> apical = Section(L=600, diam=2, nseg=5, mechanisms=[leak], + ... parent=soma, connection_point=DISTAL) + """ + + def __init__( + self, + L, + diam, + nseg=1, + Ra=100, + cm=1, + mechanisms=[], + parent=None, + connection_point=DISTAL, + ): + nrn.Section.__init__(self) + # set geometry + self.L = L + self.diam = diam + self.nseg = nseg + # set cable properties + self.Ra = Ra + self.cm = cm + # connect to parent section + if parent: + self.connect(parent, connection_point, PROXIMAL) + # add ion channels + for mechanism in mechanisms: + mechanism.insert_into(self) + + def add_synapses(self, label, type, locations=[0.5], **parameters): + if hasattr(self, label): + raise Exception("Can't overwrite synapse labels (to keep things simple)") + synapse_group = [] + for location in locations: + synapse = getattr(h, type)(location, sec=self) + for name, value in parameters.items(): + setattr(synapse, name, value) + synapse_group.append(synapse) + if len(synapse_group) == 1: + synapse_group = synapse_group[0] + setattr(self, label, synapse_group) + + add_synapse = add_synapses # for backwards compatibility + + def plot(self, variable, location=0.5, tmin=0, tmax=5, xmin=-80, xmax=40): + import neuron.gui + + self.graph = h.Graph() + h.graphList[0].append(self.graph) + self.graph.size(tmin, tmax, xmin, xmax) + self.graph.addvar("%s(%g)" % (variable, location), sec=self) + + def record_spikes(self, threshold=-30): + self.spiketimes = h.Vector() + self.spikecount = h.APCount(0.5, sec=self) + self.spikecount.thresh = threshold + self.spikecount.record(self.spiketimes) + + +def alias(attribute_path): + """ + Returns a new property, mapping an attribute nested in an object hierarchy + to a simpler name + + For example, suppose that an object of class A has an attribute b which + itself has an attribute c which itself has an attribute d. Then placing + e = alias('b.c.d') + in the class definition of A makes A.e an alias for A.b.c.d + """ + + parts = attribute_path.split(".") + attr_name = parts[-1] + attr_path = parts[:-1] + + def set(self, value): + obj = reduce(getattr, [self] + attr_path) + setattr(obj, attr_name, value) + + def get(self): + obj = reduce(getattr, [self] + attr_path) + return getattr(obj, attr_name) + + return property(fset=set, fget=get) + + +def uniform_property(section_list, attribute_path): + """ + Define a property that will have a uniform value across a list of sections. + + For example, suppose we define a neuron model as a class A, which contains + three compartments: soma, dendrite and axon. Then placing + + gnabar = uniform_property(["soma", "axon"], "hh.gnabar") + + in the class definition of A means that setting a.gnabar (where a is an + instance of A) will set the value of hh.gnabar in both the soma and axon, i.e. + + a.gnabar = 0.01 + + is equivalent to: + + for sec in [a.soma, a.axon]: + for seg in sec: + seg.hh.gnabar = 0.01 + + """ + parts = attribute_path.split(".") + attr_name = parts[-1] + attr_path = parts[:-1] + + def set(self, value): + for sec_name in section_list: + sec = getattr(self, sec_name) + for seg in sec: + obj = reduce(getattr, [seg] + attr_path) + setattr(obj, attr_name, value) + + def get(self): + sec = getattr(self, section_list[0]) + obj = reduce(getattr, [sec(0.5)] + attr_path) + return getattr(obj, attr_name) + + return property(fset=set, fget=get) + + +if __name__ == "__main__": + + class SimpleNeuron(object): + def __init__(self): + # define ion channel parameters + leak = Mechanism("pas", e=-65, g=0.0002) + hh = Mechanism("hh") + # create cable sections + self.soma = Section(L=30, diam=30, mechanisms=[hh]) + self.apical = Section( + L=600, + diam=2, + nseg=5, + mechanisms=[leak], + parent=self.soma, + connection_point=DISTAL, + ) + self.basilar = Section( + L=600, + diam=2, + nseg=5, + mechanisms=[leak], + parent=self.soma, + connection_point=0.5, + ) + self.axon = Section( + L=1000, diam=1, nseg=37, mechanisms=[hh], connection_point=0 + ) + # synaptic input + self.soma.add_synapses("syn", "AlphaSynapse", onset=0.5, gmax=0.05, e=0) + + gnabar = uniform_property(["soma", "axon"], "hh.gnabar") + gkbar = uniform_property(["soma", "axon"], "hh.gkbar") + + neuron = SimpleNeuron() + neuron.soma.plot("v") + neuron.apical.plot("v") + + print("gNa_bar: ", neuron.gnabar) + neuron.gnabar = 0.15 + assert neuron.soma(0.5).hh.gnabar == 0.15 + + h.dt = 0.025 + v_init = -65 + tstop = 5 + h.finitialize(v_init) + h.run() diff --git a/cnmodel/util/process.py b/cnmodel/util/process.py new file mode 100644 index 0000000..425a258 --- /dev/null +++ b/cnmodel/util/process.py @@ -0,0 +1,111 @@ +from __future__ import print_function + +""" +Utility class for spawning and controlling CLI processes. +See: http://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python +""" +import sys, time +from subprocess import PIPE, Popen +from threading import Thread + +try: + from Queue import Queue, Empty +except ImportError: + from queue import Queue, Empty # python 3.x + +ON_POSIX = "posix" in sys.builtin_module_names + + +class Process(object): + """ + Process encapsulates a subprocess with queued stderr/stdout pipes. + Wraps most methods from subprocess.Popen. + + For non-blocking reads, use proc.stdout.get_nowait() or + proc.stdout.get(timeout=0.1). + """ + + def __init__(self, exec_args, cwd=None): + self.proc = Popen( + exec_args, + stdout=PIPE, + stdin=PIPE, + stderr=PIPE, + bufsize=1, + close_fds=ON_POSIX, + universal_newlines=True, + cwd=cwd, + ) + self.stdin = self.proc.stdin + # self.stdin = PipePrinter(self.proc.stdin) + self.stdout = PipeQueue(self.proc.stdout) + self.stderr = PipeQueue(self.proc.stderr) + for method in ["poll", "wait", "send_signal", "kill", "terminate"]: + setattr(self, method, getattr(self.proc, method)) + + +class PipePrinter(object): + """ For debugging writes to a pipe. + """ + + def __init__(self, pipe): + self._pipe = pipe + + def __getattr__(self, attr): + return getattr(self._pipe, attr) + + def write(self, strn): + print("WRITE:" + repr(strn)) + return self._pipe.write(strn) + + +class PipeQueue(Queue): + """ + Queue that starts a second process to monitor a PIPE for new data. + This is needed to allow non-blocking pipe reads. + """ + + def __init__(self, pipe): + Queue.__init__(self) + self.thread = Thread(target=self.enqueue_output, args=(pipe, self)) + self.thread.daemon = True # thread dies with the program + self.thread.start() + + @staticmethod + def enqueue_output(out, queue): + for line in iter(out.readline, b""): + queue.put(line) + # print "READ: " + repr(line) + out.close() + + def read(self): + """ + Read all available lines from the queue, concatenated into a single string. + """ + out = "" + while True: + try: + out += self.get_nowait() + except Empty: + break + return out + + def readline(self, timeout=None): + """ Read a single line from the queue. + """ + # we break this up into multiple short reads to allow keyboard + # interrupts + start = time.time() + ret = "" + while True: + if timeout is not None: + remaining = start + timeout - time.time() + if remaining <= 0: + return "" + else: + remaining = 1 + + try: + return self.get(timeout=min(0.1, remaining)) + except Empty: + pass diff --git a/cnmodel/util/pynrnutilities.py b/cnmodel/util/pynrnutilities.py new file mode 100755 index 0000000..175abde --- /dev/null +++ b/cnmodel/util/pynrnutilities.py @@ -0,0 +1,734 @@ +from __future__ import print_function + +#!/usr/bin/python +# +# utilities for NEURON, in Python +# Module neuron for cnmodel + +import numpy as np +import numpy.ma as ma # masked array +import re, sys, gc, collections + +import neuron + + +_mechtype_cache = None + + +def all_mechanism_types(): + """Return a dictionary of all available mechanism types. + + Each dictionary key is the name of a mechanism and each value is + another dictionary containing information about the mechanism:: + + mechanism_types = { + 'mech_name1': { + 'point_process': bool, + 'artificial_cell': bool, + 'netcon_target': bool, + 'has_netevent': bool, + 'internal_type': int, + 'globals': {name:size, ...}, + 'parameters': {name:size, ...}, + 'assigned': {name:size, ...}, + 'state': {name:size, ...}, + }, + 'mech_name2': {...}, + 'mech_name3': {...}, + ... + } + + * point_process: False for distributed mechanisms, True for point + processes and artificial cells. + * artificial_cell: True for artificial cells, False otherwise + * netcon_target: True if the mechanism can receive NetCon events + * has_netevent: True if the mechanism can emit NetCon events + * internal_type: Integer specifying the NEURON internal type index of + the mechanism + * globals: dict of the name and vector size of the mechanism's global + variables + * parameters: dict of the name and vector size of the mechanism's + parameter variables + * assigned: dict of the name and vector size of the mechanism's + assigned variables + * state: dict of the name and vector size of the mechanism's state + variables + + + Note: The returned data structure is cached; do not modify it. + + For more information on global, parameter, assigned, and state + variables see: + http://www.neuron.yale.edu/neuron/static/docs/help/neuron/nmodl/nmodl.html + """ + global _mechtype_cache + if _mechtype_cache is None: + _mechtype_cache = collections.OrderedDict() + mname = neuron.h.ref("") + # Iterate over two mechanism types (distributed, point/artificial) + for i in [0, 1]: + mt = neuron.h.MechanismType(i) + nmech = int(mt.count()) + # Iterate over all mechanisms of this type + for j in range(nmech): + mt.select(j) + mt.selected(mname) + + # General mechanism properties + name = mname[0] # convert hoc string ptr to python str + + desc = { + "point_process": bool(i), + "netcon_target": bool(mt.is_netcon_target(j)), + "has_netevent": bool(mt.has_net_event(j)), + "artificial_cell": bool(mt.is_artificial(j)), + "internal_type": int(mt.internal_type()), + } + + # Collect information about 4 different types of variables + for k, ptype in [ + (-1, "globals"), + (1, "parameters"), + (2, "assigned"), + (3, "state"), + ]: + desc[ptype] = {} # collections.OrderedDict() + ms = neuron.h.MechanismStandard(name, k) + for l in range(int(ms.count())): + psize = ms.name(mname, l) + pname = mname[0] # parameter name + desc[ptype][pname] = int(psize) + + # Assemble everything in one place + _mechtype_cache[name] = desc + + return _mechtype_cache + + +def reset(raiseError=True): + """Introspect the NEURON kernel to verify that no objects are left over + from previous simulation runs. + """ + # Release objects held by an internal buffer + # See https://www.neuron.yale.edu/phpBB/viewtopic.php?f=2&t=3221 + neuron.h.Vector().size() + + # Make sure nothing is hanging around in an old exception or because of + # reference cycles + + # sys.exc_clear() + gc.collect(2) + neuron.h.Vector().size() + numsec = 0 + + remaining = [] + n = len(list(neuron.h.allsec())) + + if n > 0: + remaining.append((n, "Section")) + + n = len(neuron.h.List("NetCon")) + if n > 0: + remaining.append((n, "NetCon")) + + # No point processes or artificial cells left + for name, typ in all_mechanism_types().items(): + if typ["artificial_cell"] or typ["point_process"]: + n = len(neuron.h.List(name)) + if n > 0: + remaining.append((n, name)) + + if ( + len(remaining) > 0 and raiseError + ): # note that not raising the error leads to memory leak + msg = "Cannot reset--old objects have not been cleared: %s" % ", ".join( + ["%d %s" % rem for rem in remaining] + ) + raise RuntimeError(msg) + + +def custom_init(v_init=-60.0): + """ + Perform a custom initialization of the current model/section. + + This initialization follows the scheme outlined in the + NEURON book, 8.4.2, p 197 for initializing to steady state. + + N.B.: For a complex model with dendrites/axons and different channels, + this initialization will not find the steady-state the whole cell, + leading to initial transient currents. In that case, this initialization + should be followed with a 0.1-5 second run (depends on the rates in the + various channel mechanisms) with no current injection or active point + processes to allow the system to settle to a steady- state. Use either + h.svstate or h.batch_save to save states and restore them. Batch is + preferred + + Parameters + ---------- + v_init : float (default: -60 mV) + Voltage to start the initialization process. This should + be close to the expected resting state. + """ + inittime = -1e10 + tdt = neuron.h.dt # save current step size + dtstep = 1e9 + neuron.h.finitialize(v_init) + neuron.h.t = inittime # set time to large negative value (avoid activating + # point processes, we hope) + tmp = neuron.h.cvode.active() # check state of variable step integrator + if tmp != 0: # turn off CVode variable step integrator if it was active + neuron.h.cvode.active(0) # now just use backward Euler with large step + neuron.h.dt = dtstep + n = 0 + while neuron.h.t < -1e9: # Step forward + neuron.h.fadvance() + n += 1 + # print('advances: ', n) + if tmp != 0: + neuron.h.cvode.active(1) # restore integrator + neuron.h.t = 0 + if neuron.h.cvode.active(): + neuron.h.cvode.re_init() # update d(state)/dt and currents + else: + neuron.h.fcurrent() # recalculate currents + neuron.h.frecord_init() # save new state variables + neuron.h.dt = tdt # restore original time step + + +# routine to convert conductances from nS as given elsewhere +# to mho/cm2 as required by NEURON 1/28/99 P. Manis +# units: nano siemens, soma area in um^2 +# +def nstomho(ns, somaarea, refarea=None): + if refarea == None: + return 1e-9 * float(ns) / float(somaarea) + else: + return 1e9 * float(ns) / float(refarea) + + +def mho2ns(mho, somaarea): + return float(mho) * somaarea / 1e-9 + + +def spherearea(dia): + """ + given diameter in microns, return sphere area in cm2 + """ + r = dia * 1e-4 # convert to cm + return 4 * np.pi * r ** 2 + + +def get_sections(h): + """ + go through all the sections and find the names of the sections and all of their + parts (ids). Returns a dict, of sec: [id0, id1...] + + """ + secnames = {} + resec = re.compile("(\w+)\[(\d*)\]") + for sec in h.allsec(): + g = resec.match(sec.name()) + if g.group(1) not in secnames.keys(): + secnames[g.group(1)] = [int(g.group(2))] + else: + secnames[g.group(1)].append(int(g.group(2))) + return secnames + + +def all_objects(): + """ Return a dict of all objects known to NEURON. + + Keys are 'Section', 'Segment', 'Mechanism', 'Vector', 'PointProcess', + 'NetCon', ... + """ + objs = {} + objs["Section"] = list(h.all_sec()) + objs["Segment"] = [] + for sec in objs["Section"]: + objs["Segment"].extend(list(sec.allseg())) + objs["PointProcess"] = [] + for seg in objs["Segment"]: + objs["PointProcess"].extend(list(seg.point_processes())) + + return objs + + +def alpha(alpha=0.1, delay=1, amp=1.0, tdur=50.0, dt=0.010): + tvec = np.arange(0, tdur, dt) + aw = np.zeros(tvec.shape) + i = 0 + for t in tvec: + if t > delay: + aw[i] = ( + amp * (t - delay) * (1.0 / alpha) * np.exp(-(t - delay) / alpha) + ) # alpha waveform time course + else: + aw[i] = 0.0 + i += 1 + return (aw, tvec) + + +def syns( + alpha=0.1, + rate=10, + delay=0, + dur=50, + amp=1.0, + dt=0.020, + N=1, + mindur=120, + makewave=True, +): + """ Calculate a poisson train of alpha waves + with mean rate rate, with a delay and duration (in mseco) dt in msec. + N specifies the number of such independent waveforms to sum """ + deadtime = 0.7 + if dur + delay < mindur: + tvec = np.arange(0.0, mindur, dt) + else: + tvec = np.arange(0.0, dur + delay, dt) + npts = len(tvec) + ta = np.arange(0.0, 20.0, dt) + aw = ta * alpha * np.exp(-ta / alpha) / alpha # alpha waveform time course + spt = [[]] * N # list of spike times + wave = np.array([]) # waveform + sptime = [] + for j in range(0, N): + done = False + t = 0.0 + nsp = 0 + while not done: + a = np.random.sample(1) + if t < delay: + t = delay + continue + if t >= delay and t <= (delay + dur): + ti = -np.log(a) / ( + rate / 1000.0 + ) # convert to exponential distribution with rate + if ti < deadtime: + continue + t = t + ti # running time + if t > delay + dur: + done = True + continue + if nsp is 0: + sptime = t + nsp = nsp + 1 + else: + sptime = np.append(sptime, t) + nsp = nsp + 1 + if j is 0: + wavej = np.zeros(len(tvec)) + for i in range(0, len(sptime)): + st = int(sptime[i] / dt) + wavej[st] = wavej[st] + 1 + spt[j] = sptime + + if makewave: + w = np.convolve(wavej, aw / max(aw)) * amp + if len(w) < npts: + w = np.append(w, np.zeros(npts - len(w))) + if len(w) > npts: + w = w[0:npts] + if j is 0: + wave = w + else: + wave = wave + w + return (spt, wave, tvec, N) + + +def an_syn( + alpha=0.1, + spont=10, + driven=100, + delay=50, + dur=100, + post=20, + amp=0.1, + dt=0.020, + N=1, + makewave=True, +): + # constants for AN: + deadtime = 0.7 # min time between spikes, msec + trise = 0.2 # rise rate, ms + tfall = 0.5 # fall rate, ms + rss = driven / 1000.0 # spikes/millisecond + rr = 3 * rss # transient driven rate + rst = rss + taur = 3 # rapid decay, msec + taust = 10 + ton = delay # msec + stim_end = ton + dur + trace_end = stim_end + post + tvec = np.arange(0.0, trace_end, dt) # dt is in msec, so tvec is in milliseconds + ta = np.arange(0.0, 20.0, dt) + aw = ta * alpha * np.exp(-ta / alpha) / alpha # alpha waveform time course + spt = [[]] * N # list of spike times + wave = [[]] * N # waveform + for j in range(0, N): # for each + done = False + sptime = [] + qe = 0 + nsp = 0 + i = int(0) + if spont <= 0: + q = 1e6 + else: + q = 1000.0 / spont # q is in msec (spont in spikes/second) + t = 0.0 + while not done: + a = np.random.sample(1) + if t < ton: + if spont <= 0: + t = ton + continue + ti = -(np.log(a) / (spont / 1000.0)) # convert to msec + if ti < deadtime: # delete intervals less than deadtime + continue + t = t + ti + if t > ton: # if the interval would step us to the stimulus onset + t = ton # then set to to the stimulus onset + continue + if t >= ton and t < stim_end: + if t > ton: + rise = 1.0 - np.exp(-(t - ton) / trise) + else: + rise = 1.0 + ra = rr * np.exp(-(t - ton) / taur) + rs = rst * np.exp(-(t - ton) / taust) + q = rise * (ra + rs + rss) + ti = -np.log(a) / (q + spont / 1000) # random.negexp(1000/q) + if ti < deadtime: + continue + t = t + ti + if t > stim_end: # only include interval if it falls inside window + t = stim_end + continue + if t >= stim_end and t <= trace_end: + if spont <= 0.0: + t = trace_end + continue + if qe is 0: # have not calculated the new qe at end of stimulus + rise = 1.0 - np.exp(-(stim_end - ton) / trise) + ra = rr * np.exp(-(stim_end - ton) / taur) + rs = rst * np.exp(-(stim_end - ton) / taust) + qe = rise * (ra + rs + rss) # calculate the rate at the end + fall = np.exp(-(t - stim_end) / tfall) + q = qe * fall + ti = -np.log(a) / ( + q + spont / 1000.0 + ) # keeps rate from falling below spont rate + if ti < deadtime: + continue + t = t + ti + if t >= trace_end: + done = True + continue + # now add the spike time to the list + if nsp is 0: + sptime = t + nsp = nsp + 1 + else: + sptime = np.append(sptime, t) + nsp = nsp + 1 + # end of for loop on i + if j is 0: + wavej = np.zeros(len(tvec)) + for i in range(0, len(sptime)): + st = int(sptime[i] / dt) + wavej[st] = wavej[st] + 1 + spt[j] = sptime + npts = len(tvec) + if makewave: + w = np.convolve(wavej, aw / max(aw)) * amp + wave[j] = w[0:npts] + return (spt, wave, tvec, N) + + +def findspikes(t, v, thresh): + """ findspikes identifies the times of action potential in the trace v, with the + times in t. An action potential is simply timed at the first point that exceeds + the threshold. + """ + tm = np.array(t) + s0 = ( + np.array(v) > thresh + ) # np.where(v > thresh) # np.array(v) > thresh # find points above threshold + + # print ('v: ', v) + dsp = tm[s0] + if dsp.shape[0] == 1: + dsp = np.array(dsp) + sd = np.append(True, np.diff(dsp) > 1.0) # find first points of spikes + if len(dsp) > 0: + sp = dsp[sd] + else: + sp = [] + return sp # list of spike times. + + +def measure(mode, x, y, x0, x1): + """ return the mean and standard deviation of y in the window x0 to x1 + """ + xm = ma.masked_outside(x, x0, x1) + ym = ma.array(y, mask=ma.getmask(xm)) + if mode == "mean": + r1 = ma.mean(ym) + r2 = ma.std(ym) + if mode == "max": + r1 = ma.max(ym) + r2 = 0 + if mode == "min": + r1 = ma.min(ym) + r2 = 0 + if mode == "median": + r1 = ma.median(ym) + r2 = 0 + if mode == "p2p": # peak to peak + r1 = ma.ptp(ym) + r2 = 0 + return (r1, r2) + + +def mask(x, xm, x0, x1): + xmask = ma.masked_outside(xm, x0, x1) + xnew = ma.array(x, mask=ma.getmask(xmask)) + return xnew.compressed() + + +def vector_strength(spikes, freq): + """ + Calculate vector strength and related parameters from a spike train, for the specified frequency + :param spikes: Spike train, in msec. + :param freq: Stimulus frequency in Hz + :return: a dictionary containing: + + r: vector strength + n: number of spikes + R: Rayleigh coefficient + p: p value (is distribution not flat?) + ph: the circularized spike train over period of the stimulus freq, freq, in radians + d: the "dispersion" computed according to Ashida et al., 2010, etc. + """ + + per = 1e3 / freq # convert from Hz to period in msec + ph = 2 * np.pi * np.fmod(spikes, per) / (per) # convert to radians within a cycle + c = np.sum(np.cos(ph)) ** 2 + s = np.sum(np.sin(ph)) ** 2 + vs = (1.0 / len(ph)) * np.sqrt(c + s) # standard vector strength computation + n = len(spikes) + R = n * vs # Raleigh coefficient + Rp = np.exp(-n * vs * vs) # p value for n > 50 (see Ashida et al. 2010). + d = np.sqrt(2.0 * (1 - vs)) / (2 * np.pi * freq) + return {"r": vs, "n": n, "R": R, "p": Rp, "ph": ph, "d": d} + + +def isi_cv2(splist, binwidth=1, t0=0, t1=300, tgrace=25): + """ compute the cv and regularity according to Young et al., J. Neurophys, 60: 1, 1988. + Analysis is limited to isi's starting at or after t0 but before t1, and ending completely + before t1 + tgrace(to avoid end effects). t1 should correspond to the + the end of the stimulus + VERSION using dictionary for cvisi + """ + cvisit = np.arange(0, t1, binwidth) # build time bins + cvisi = {} # isi is dictionary, since each bin may have different length + for i in range(0, len(splist)): # for all the traces + isit = splist[i] # get the spike times for this trial [1:-1] + if len(isit) <= 1: # need 2 spikes to get an interval + continue + isib = np.floor(isit[0:-2] / binwidth) # discreetize + isii = np.diff(splist[i]) # isis. + for j in range(0, len(isib)): # loop over possible start time bins + if ( + isit[j] < t0 or isit[j] > t1 or isit[j + 1] > t1 + tgrace + ): # start time and interval in the window + continue + if isib[j] in cvisi: + print("spike in bin: %d" % (isib[j])) + cvisi[isib[j]] = np.append( + cvisi[isib[j]], isii[j] + ) # and add the isi in that bin + else: + cvisi[isib[j]] = isii[j] # create it + cvm = np.array([]) # set up numpy arrays for mean, std and time for cv analysis + cvs = np.array([]) + cvt = np.array([]) + for i in cvisi.keys(): # for each entry (possible bin) + c = [cvisi[i]] + s = c.shape + # print c + if len(s) > 1 and s[1] >= 3: # require 3 spikes in a bin for statistics + cvm = np.append(cvm, np.mean(c)) + cvs = np.append(cvs, np.std(c)) + cvt = np.append(cvt, i * binwidth) + return (cvisit, cvisi, cvt, cvm, cvs) + + +def isi_cv(splist, binwidth=1, t0=0, t1=300, tgrace=25): + """ compute the cv and regularity according to Young et al., J. Neurophys, 60: 1, 1988. + Analysis is limited to isi's starting at or after t0 but before t1, and ending completely + before t1 + tgrace(to avoid end effects). t1 should correspond to the + the end of the stimulus + Version using a list of numpy arrays for cvisi + """ + cvisit = np.arange(0, t1, binwidth) # build time bins + cvisi = [[]] * len(cvisit) + for i in range(0, len(splist)): # for all the traces + if len(splist[i]) < 2: # need at least 2 spikes + continue + isib = np.floor( + splist[i][0:-2] / binwidth + ) # begining spike times for each interval + isii = np.diff(splist[i]) # associated intervals + for j in range(0, len(isib)): # loop over spikes + if ( + splist[i][j] < t0 or splist[i][j] > t1 or splist[i][j + 1] > t1 + tgrace + ): # start time and interval in the window + continue + cvisi[int(isib[j])] = np.append( + cvisi[int(isib[j])], isii[j] + ) # and add the isi in that bin + cvm = np.array([]) # set up numpy arrays for mean, std and time for cv analysis + cvs = np.array([]) + cvt = np.array([]) + for i in range(0, len(cvisi)): # for each entry (possible bin) + c = cvisi[i] + if len(c) >= 3: # require 3 spikes in a bin for statistics + cvm = np.append(cvm, np.mean(c)) + cvs = np.append(cvs, np.std(c)) + cvt = np.append(cvt, i * binwidth) + return (cvisit, cvisi, cvt, cvm, cvs) + + +if __name__ == "__main__": + + test = "isicv" + + if test == "isicv": + """ this test is not perfect. Given an ISI, we calculate spike times + by drawing from a normal distribution whose standard deviation varies + with time, from 0 (regular) to 1 (irregular). As coded, the standard + deviation never reaches the target value because spikes fall before or + after previous spikes (thus reducing the stdev). Nonetheless, this shows + that the CV calculation works correctly. """ + nreps = 500 + # cv will be 0 for first 50 msec, 0.5 for next 50 msec, and 1 for next 50 msec + d = [[]] * nreps + isi = 5.0 # mean isi + # we create 100 msec of data where the CV goes from 0 to 1 + maxt = 100.0 + for i in range(nreps): + for j in range(int(maxt / isi) + 1): + t = float(j) * isi + sd = float(j) / isi + if sd == 0.0: + d[i] = np.append(d[i], t) + else: + d[i] = np.append(d[i], np.random.normal(t, sd, 1)) + for j in range(1, 10): # add more intervals at the end + te = t + float(j) * isi + d[i] = np.append(d[i], np.random.normal(te, sd, 1)) + d[i] = np.sort(d[i]) + # print d[i] + # print diff(d[i]) + sh = np.array([]) + for i in range(len(d)): + sh = np.append(sh, np.array(d[i])) + (hist, bins) = np.histogram(sh, bins=250, range=(0, 250), new=True) + if len(bins) > len(hist): + bins = bins[0 : len(hist)] + + pl.figure(1) + pl.subplot(2, 2, 1) + pl.plot(bins, hist) + + (cvisit, cvisi, cvt, cvm, cvs) = isi_cv( + d, binwidth=0.5, t0=0, t1=100, tgrace=25 + ) + order = np.argsort(cvt) + cvt = cvt[order] + cvs = cvs[order] + cvm = cvm[order] + pl.subplot(2, 2, 2) + pl.plot(cvt, cvm) + pl.hold(True) + pl.plot(cvt, cvs) + pl.subplot(2, 2, 4) + pl.plot(cvt, cvs / cvm) + pl.show() + + if test == "measure": + x = np.arange(0, 100, 0.1) + s = np.shape(x) + y = np.random.randn(s[0]) + for i in range(0, 4): + print("\ni is : %d" % (i)) + x0 = i * 20 + x1 = x0 + 20 + (r0, r1) = measure("mean", x, y, x0, x1) + print("mean: %f std: %f [0, 20]" % (r0, r1)) + (r0, r1) = measure("max", x, y, x0, x1) + print("max: %f std: %f [0, 20]" % (r0, r1)) + (r0, r1) = measure("min", x, y, x0, x1) + print("min: %f std: %f [0, 20]" % (r0, r1)) + (r0, r1) = measure("median", x, y, x0, x1) + print("median: %f std: %f [0, 20]" % (r0, r1)) + (r0, r1) = measure("p2p", x, y, x0, x1) + print("peak to peak: %f std: %f [0, 20]" % (r0, r1)) + + if test == "an_syn": + (s, w, t, n) = an_syn(N=50, spont=50, driven=150, post=100, makewave=True) + sh = np.array([]) + for i in range(len(s)): + sh = np.append(sh, np.array(s[i])) + (hist, bins) = np.histogram(sh, bins=250, range=(0, 250), new=True) + if len(bins) > len(hist): + bins = bins[0 : len(hist)] + + import pylab as pl + + pl.figure(1) + pl.subplot(2, 2, 1) + pl.plot(bins, hist) + + pl.subplot(2, 2, 3) + for i in range(len(w)): + pl.plot(t, w[i]) + pl.hold = True + (cvisit, cvisi, cvt, cvm, cvs) = isi_cv(s) + order = np.argsort(cvt) + cvt = cvt[order] + cvs = cvs[order] + cvm = cvm[order] + pl.subplot(2, 2, 2) + pl.plot(cvt, cvs / cvm) + pl.show() + + if test == "syns": + (s, w, t, n) = syns(rate=20, delay=0, dur=100.0, N=5, makewave=True) + sh = np.array([]) + for i in range(len(s)): + sh = np.append(sh, np.array(s[i])) + (hist, bins) = np.histogram(sh, bins=250, range=(0, 250), new=True) + if len(bins) > len(hist): + bins = bins[0 : len(hist)] + + import pylab as pl + + pl.figure(1) + pl.subplot(2, 2, 1) + pl.plot(bins, hist) + + pl.subplot(2, 2, 3) + pl.plot(t, w) + pl.hold = True + (cvisit, cvisi, cvt, cvm, cvs) = isi_cv(s) + order = np.argsort(cvt) + cvt = cvt[order] + cvs = cvs[order] + cvm = cvm[order] + pl.subplot(2, 2, 2) + pl.plot(cvt, cvs / cvm) + pl.show() diff --git a/cnmodel/util/pyqtgraphPlotHelpers.py b/cnmodel/util/pyqtgraphPlotHelpers.py new file mode 100755 index 0000000..ea61236 --- /dev/null +++ b/cnmodel/util/pyqtgraphPlotHelpers.py @@ -0,0 +1,1505 @@ +from __future__ import print_function + +# encoding: utf-8 +""" +pyqtgraphPlotHelpers.py + +Routines to help use pyqtgraph and make cleaner plots +as well as get plots read for publication. + +Intially copied from PlotHelpers.py for matplotlib. +Modified to allow us to use a list of axes, and operate on all of those, +or to use just one axis if that's all that is passed. +Therefore, the first argument to these calls can either be a pyqtgraph axis object, +or a list of axes objects. 2/10/2012 pbm. + +Created by Paul Manis on 2010-03-09. +""" + + +import string + +stdFont = "Arial" + +import scipy.stats +import numpy as np +import pyqtgraph as pg +from .talbotetalTicks import Extended # logical tick formatting... + +""" +Basic functions: +""" + + +def nice_plot( + plotlist, spines=["left", "bottom"], position=10, direction="inward", axesoff=False +): + """ Adjust a plot so that it looks nicer than the default matplotlib plot + Also allow quickaccess to things we like to do for publication plots, including: + using a calbar instead of an axes: calbar = [x0, y0, xs, ys] + inserting a reference line (grey, 3pt dashed, 0.5pt, at refline = y position) + + Paramaetrs + ---------- + plotlist : list + a plot handle or list of plot handles to which the "niceplot" will be applied + spines : list + a list of which axes should have spines. Not relevant for pyqtgraph + position : int + not relevant for pyqtgraph + direction : string + need to implement for pyqtgraph + axesoff : boolean + flag that forces plots to turn axes off + + """ + if type(plotlist) is not list: + plotlist = [plotlist] + for pl in plotlist: + if axesoff is True: + pl.hideAxis("bottom") + pl.hideAxis("left") + + +def noaxes(plotlist, whichaxes="xy"): + """ take away all the axis ticks and the lines + + Parameters + ---------- + plotlist : list + list of plot handles + whichaxes : string + string describing which axes to remove: 'x', 'y', or 'xy' for both + + """ + if type(plotlist) is not list: + plotlist = [plotlist] + for pl in plotlist: + if "x" in whichaxes: + pl.hideAxis("bottom") + if "y" in whichaxes: + pl.hideAxis("left") + + +def setY(ax1, ax2): + """ + Set the Y axis of all the plots in ax2 to be like ax1 + + Parameters + ---------- + ax1 : pyqtgraph plot instance + ax2 : list + list of target plots that will have the axes properties of ax1 + """ + if type(ax1) is list: + print("PlotHelpers: cannot use list as source to set Y axis") + return + if type(ax2) is not list: + ax2 = [ax2] + y = ax1.getAxis("left") + refy = y.range # return the current range + for ax in ax2: + ax.setRange(refy) + + +def setX(ax1, ax2): + """ + Set the X axis of all the plots in ax2 to be like ax1 + + Parameters + ---------- + ax1 : pyqtgraph plot instance + ax2 : list + list of target plots that will have the axes properties of ax1 + """ + if type(ax1) is list: + print("PlotHelpers: cannot use list as source to set X axis") + return + if type(ax2) is not list: + ax2 = [ax2] + x = ax1.getAxis("bottom") + refx = x.range + for ax in ax2: + ax.setrange(refx) + + +def labelPanels(axl, axlist=None, font="Arial", fontsize=18, weight="normal"): + """ + Label the panels like a specific panel + + Parameters + ---------- + axl : dict or list + axlist : list, optional + list of labels to use for the axes, defaults to None + font : str, optional + Font to use for the labels, defaults to Arial + fontsize : int, optional + Font size in points for the labels, defaults to 18 + weight : str, optional + Font weight to use, defaults to 'normal' + + """ + if type(axl) is dict: + axt = [axl[x] for x in axl] + axlist = axl.keys() + axl = axt + if type(axl) is not list: + axl = [axl] + if axlist is None: + axlist = string.uppercase(1, len(axl)) # assume we wish to go in sequence + + for i, ax in enumerate(axl): + labelText = pg.TextItem(axlist[i]) + y = ax.getAxis("left").range + x = ax.getAxis("bottom").range + ax.addItem(labelText) + labelText.setPos(x[0], y[1]) + + +def listAxes(axd): + """ + make a list of the axes from the dictionary of axes + + Parameters + ---------- + axd : dict + a dict of axes, whose values are returned in a list + + Returns + ------- + list : a list of the axes + + """ + if type(axd) is not dict: + if type(axd) is list: + return axd + else: + print("listAxes expects dictionary or list; type not known (fix the code)") + raise + axl = [axd[x] for x in axd] + return axl + + +def cleanAxes(axl): + """ + """ + if type(axl) is not list: + axl = [axl] + # does nothing at the moment, as axes are already "clean" + # for ax in axl: + # + # update_font(ax) + + +def formatTicks(axl, axis="xy", fmt="%d", font="Arial"): + """ + Convert tick labels to intergers + to do just one axis, set axis = 'x' or 'y' + control the format with the formatting string + """ + if type(axl) is not list: + axl = [axl] + + +def autoFormatTicks(axl, axis="xy", font="Arial"): + if type(axl) is not list: + axl = [axl] + for ax in axl: + if "x" in axis: + b = ax.getAxis("bottom") + x0 = b.range + # setFormatter(ax, x0, x1, axis = 'x') + if "y" in axis: + l = ax.getAxis("left") + y0 = l.range + + +# setFormatter(ax, y0, y1, axis = 'y') + + +def setFormatter(ax, x0, x1, axis="x"): + datarange = np.abs(x0 - x1) + mdata = np.ceil(np.log10(datarange)) + # if mdata > 0 and mdata <= 4: + # majorFormatter = FormatStrFormatter('%d') + # elif mdata > 4: + # majorFormatter = FormatStrFormatter('%e') + # elif mdata <= 0 and mdata > -1: + # majorFormatter = FormatStrFormatter('%5.1f') + # elif mdata < -1 and mdata > -3: + # majorFormatatter = FormatStrFormatter('%6.3f') + # else: + # majorFormatter = FormatStrFormatter('%e') + # if axis == 'x': + # ax.xaxis.set_major_formatter(majorFormatter) + # else: + # ax.yaxis.set_major_formatter(majorFormatter) + + +def update_font(axl, size=6, font=stdFont): + pass + # if type(axl) is not list: + # axl = [axl] + # fontProperties = {'family':'sans-serif','sans-serif':[font], + # 'weight' : 'normal', 'size' : size} + # for ax in axl: + # for tick in ax.xaxis.get_major_ticks(): + # tick.label1.set_family('sans-serif') + # tick.label1.set_fontname(stdFont) + # tick.label1.set_size(size) + # + # for tick in ax.yaxis.get_major_ticks(): + # tick.label1.set_family('sans-serif') + # tick.label1.set_fontname(stdFont) + # tick.label1.set_size(size) + # ax.set_xticklabels(ax.get_xticks(), fontProperties) + # ax.set_yticklabels(ax.get_yticks(), fontProperties) + # ax.xaxis.set_smart_bounds(True) + # ax.yaxis.set_smart_bounds(True) + # ax.tick_params(axis = 'both', labelsize = 9) + + +def lockPlot(axl, lims, ticks=None): + """ + This routine forces the plot of invisible data to force the axes to take certain + limits and to force the tick marks to appear. + call with the axis and lims = [x0, x1, y0, y1] + """ + if type(axl) is not list: + axl = [axl] + plist = [] + for ax in axl: + y = ax.getAxis("left") + x = ax.getAxis("bottom") + x.setRange(lims[0], lims[1]) + y.setRange(lims[2], lims[3]) + + +def adjust_spines( + axl, spines=("left", "bottom"), direction="outward", distance=5, smart=True +): + pass + # if type(axl) is not list: + # axl = [axl] + # for ax in axl: + # # turn off ticks where there is no spine + # if 'left' in spines: + # ax.yaxis.set_ticks_position('left') + # else: + # # no yaxis ticks + # ax.yaxis.set_ticks([]) + # + # if 'bottom' in spines: + # ax.xaxis.set_ticks_position('bottom') + # else: + # # no xaxis ticks + # ax.xaxis.set_ticks([]) + # for loc, spine in ax.spines.iteritems(): + # if loc in spines: + # spine.set_position((direction,distance)) # outward by 10 points + # if smart is True: + # spine.set_smart_bounds(True) + # else: + # spine.set_smart_bounds(False) + # else: + # spine.set_color('none') # don't draw spine + # return + # + + +def calbar(plotlist, calbar=None, axesoff=True, orient="left", unitNames=None): + """ draw a calibration bar and label it up. The calibration bar is defined as: + [x0, y0, xlen, ylen] + + Parameters + ---------- + plotlist : list + a plot item or a list of plot items for which a calbar will be applied + calbar : list, optional + a list with 4 elements, describing the calibration bar + [xposition, yposition, xlength, ylength] in units of the data inthe plot + defaults to None + axesoff : boolean, optional + Set true to turn off the standard axes, defaults to True + orient : text, optional + 'left': put vertical part of the bar on the left + 'right': put the vertical part of the bar on the right + defaults to 'left' + unitNames: str, optional + a dictionary with the names of the units to append to the calibration bar + lengths. Example: {'x': 'ms', 'y': 'nA'} + defaults to None + Returns + ------- + Nothing + """ + + if type(plotlist) is not list: + plotlist = [plotlist] + for pl in plotlist: + if axesoff is True: + noaxes(pl) + Vfmt = "%.0f" + if calbar[2] < 1.0: + Vfmt = "%.1f" + Hfmt = "%.0f" + if calbar[3] < 1.0: + Hfmt = "%.1f" + if unitNames is not None: + Vfmt = Vfmt + " " + unitNames["x"] + Hfmt = Hfmt + " " + unitNames["y"] + Vtxt = pg.TextItem(Vfmt % calbar[2], anchor=(0.5, 0.5), color=pg.mkColor("k")) + Htxt = pg.TextItem(Hfmt % calbar[3], anchor=(0.5, 0.5), color=pg.mkColor("k")) + # print pl + if calbar is not None: + if orient == "left": # vertical part is on the left + pl.plot( + [calbar[0], calbar[0], calbar[0] + calbar[2]], + [calbar[1] + calbar[3], calbar[1], calbar[1]], + pen=pg.mkPen("k"), + linestyle="-", + linewidth=1.5, + ) + ht = Htxt.setPos( + calbar[0] + 0.05 * calbar[2], calbar[1] + 0.5 * calbar[3] + ) + elif orient == "right": # vertical part goes on the right + pl.plot( + [calbar[0] + calbar[2], calbar[0] + calbar[2], calbar[0]], + [calbar[1] + calbar[3], calbar[1], calbar[1]], + pen=pg.mkPen("k"), + linestyle="-", + linewidth=1.5, + ) + ht = Htxt.setPos( + calbar[0] + calbar[2] - 0.05 * calbar[2], + calbar[1] + 0.5 * calbar[3], + ) + else: + print("PlotHelpers.py: I did not understand orientation: %s" % (orient)) + print("plotting as if set to left... ") + pl.plot( + [calbar[0], calbar[0], calbar[0] + calbar[2]], + [calbar[1] + calbar[3], calbar[1], calbar[1]], + pen=pg.mkPen("k"), + linestyle="-", + linewidth=1.5, + ) + ht = Htxt.setPos( + calbar[0] + 0.05 * calbar[2], calbar[1] + 0.5 * calbar[3] + ) + Htxt.setText(Hfmt % calbar[3]) + xc = float(calbar[0] + calbar[2] * 0.5) # always centered, below the line + yc = float(calbar[1] - 0.1 * calbar[3]) + vt = Vtxt.setPos(xc, yc) + Vtxt.setText(Vfmt % calbar[2]) + pl.addItem(Htxt) + pl.addItem(Vtxt) + + +def refline( + axl, + refline=None, + color=[64, 64, 64], + linestyle="--", + linewidth=0.5, + orient="horizontal", +): + """ + Draw a reference line at a particular level of the data on the y axis + + Parameters + ---------- + axl : list + axis handle or list of axis handles + refline : float, optional + the position of the reference line, defaults to None + color : list, optional + the RGB color list for the line, in format [r,g,b], defaults to [64, 64, 64] (faint grey line) + linestyle : str, optional + defines the linestyle to be used: -- for dash, . for doted, - for solid, -. for dash-dot, + -.. for -.., etc. + defaults to '--' (dashed) + linewidth : float, optional + width of the line, defaults to 0.5 + """ + if type(axl) is not list: + axl = [axl] + if linestyle == "--": + style = pg.QtCore.Qt.DashLine + elif linestyle == ".": + style = pg.QtCore.Qt.DotLine + elif linestyle == "-": + style = pg.QtCore.Qt.SolidLine + elif linestyle == "-.": + style = pg.QtCore.Qt.DsahDotLine + elif linestyle == "-..": + style = pg.QtCore.Qt.DashDotDotLine + else: + style = pg.QtCore.Qt.SolidLine # default is solid + if orient is "horizontal": + for ax in axl: + if refline is not None: + x = ax.getAxis("bottom") + xlims = x.range + ax.plot( + xlims, + [refline, refline], + pen=pg.mkPen(color, width=linewidth, style=style), + ) + if orient is "vertical": + for ax in axl: + if refline is not None: + y = ax.getAxis("left") + ylims = y.range + ax.plot( + [refline, refline], + [ylims[0] + 0.5, ylims[1] - 0.5], + pen=pg.mkPen(color, width=linewidth, style=style), + ) + + +def tickStrings(values, scale=1, spacing=None, tickPlacesAdd=1): + """Return the strings that should be placed next to ticks. This method is called + when redrawing the axis and is a good method to override in subclasses. + + Parameters + ---------- + values : array or list + An array or list of tick values + scale : float, optional + a scaling factor (see below), defaults to 1 + spacing : float, optional + spaceing between ticks (this is required since, in some instances, there may be only + one tick and thus no other way to determine the tick spacing). Defaults to None + tickPlacesToAdd : int, optional + the number of decimal places to add to the ticks, default is 1 + + Returns + ------- + list : a list containing the tick strings + + The scale argument is used when the axis label is displaying units which may have an SI scaling prefix. + When determining the text to display, use value*scale to correctly account for this prefix. + For example, if the axis label's units are set to 'V', then a tick value of 0.001 might + be accompanied by a scale value of 1000. This indicates that the label is displaying 'mV', and + thus the tick should display 0.001 * 1000 = 1. + Copied rom pyqtgraph; we needed it here. + """ + if spacing is None: + spacing = np.mean(np.diff(values)) + places = max(0, np.ceil(-np.log10(spacing * scale))) + tickPlacesAdd + strings = [] + for v in values: + vs = v * scale + if abs(vs) < 0.001 or abs(vs) >= 10000: + vstr = "%g" % vs + else: + vstr = ("%%0.%df" % places) % vs + strings.append(vstr) + return strings + + +def crossAxes(axl, xyzero=[0.0, 0.0], limits=[None, None, None, None], **kwds): + """ + Make the plot(s) have crossed axes at the data points set by xyzero, and optionally + set axes limits + + Parameters + ---------- + axl : pyqtgraph plot/axes instance or list + the plot to modify + xyzero : list + A 2-element list for the placement of x=0 and y=0, defaults to [0., 0.] + limits : list + A 4-element list with the min and max limits of the axes, defaults to all None + **kwds : keyword arguments to pass to make_crossedAxes + + """ + if type(axl) is not list: + axl = [axl] + for ax in axl: + make_crossedAxes(ax, xyzero, limits, **kwds) + + +def make_crossedAxes( + ax, + xyzero=[0.0, 0.0], + limits=[None, None, None, None], + ndec=3, + density=(1.0, 1.0), + tickl=0.0125, + insideMargin=0.05, + pointSize=12, + tickPlacesAdd=(0, 0), +): + """ + Parameters + ---------- + axl : pyqtgraph plot/axes instance or list + the plot to modify + xyzero : list + A 2-element list for the placement of x=0 and y=0, defaults to [0., 0.] + limits : list + A 4-element list with the min and max limits of the axes, defaults to all None + ndec : int + Number of decimals (would be passed to talbotTicks if that was being called) + density : tuple + tick density (for talbotTicks), defaults to (1.0, 1.0) + tickl : float + Tick length, defaults to 0.0125 + insideMargin : float + Inside margin space for plot, defaults to 0.05 (5%) + pointSize : int + point size for tick text, defaults to 12 + tickPlacesAdd : tuple + number of decimal places to add in tickstrings for the ticks, pair for x and y axes, defaults to (0,0) + + Returns + ------- + Nothing + + + """ + # get axis limits + aleft = ax.getAxis("left") + abottom = ax.getAxis("bottom") + aleft.setPos(pg.Point(3.0, 0.0)) + yRange = aleft.range + xRange = abottom.range + hl = pg.InfiniteLine(pos=xyzero[0], angle=90, pen=pg.mkPen("k")) + ax.addItem(hl) + vl = pg.InfiniteLine(pos=xyzero[1], angle=0, pen=pg.mkPen("k")) + ax.addItem(vl) + ax.hideAxis("bottom") + ax.hideAxis("left") + # now create substitue tick marks and labels, using Talbot et al algorithm + xr = np.diff(xRange)[0] + yr = np.diff(yRange)[0] + xmin, xmax = ( + np.min(xRange) - xr * insideMargin, + np.max(xRange) + xr * insideMargin, + ) + ymin, ymax = ( + np.min(yRange) - yr * insideMargin, + np.max(yRange) + yr * insideMargin, + ) + xtick = ticks.Extended( + density=density[0], figure=None, range=(xmin, xmax), axis="x" + ) + ytick = ticks.Extended( + density=density[1], figure=None, range=(ymin, ymax), axis="y" + ) + xt = xtick() + yt = ytick() + ytk = yr * tickl + xtk = xr * tickl + y0 = xyzero[1] + x0 = xyzero[0] + tsx = tickStrings(xt, tickPlacesAdd=tickPlacesAdd[0]) + tsy = tickStrings(yt, tickPlacesAdd=tickPlacesAdd[1]) + for i, x in enumerate(xt): + t = pg.PlotDataItem(x=x * np.ones(2), y=[y0 - ytk, y0 + ytk], pen=pg.mkPen("k")) + ax.addItem(t) # tick mark + # put text in only if it does not overlap the opposite line + if x == y0: + continue + txt = pg.TextItem( + tsx[i], anchor=(0.5, 0), color=pg.mkColor("k") + ) # , size='10pt') + txt.setFont(pg.QtGui.QFont("Arial", pointSize=pointSize)) + txt.setPos(pg.Point(x, y0 - ytk)) + ax.addItem(txt) # , pos=pg.Point(x, y0-ytk)) + for i, y in enumerate(yt): + t = pg.PlotDataItem( + x=np.array([x0 - xtk, x0 + xtk]), y=np.ones(2) * y, pen=pg.mkPen("k") + ) + ax.addItem(t) + if y == x0: + continue + txt = pg.TextItem( + tsy[i], anchor=(1, 0.5), color=pg.mkColor("k") + ) # , size='10pt') + txt.setFont(pg.QtGui.QFont("Arial", pointSize=pointSize)) + txt.setPos(pg.Point(x0 - xtk, y)) + ax.addItem(txt) # , pos=pg.Point(x, y0-ytk)) + + +class polarPlot: + """ + Create a polar plot, as a PlotItem for pyqtgraph. + + + """ + + def __init__(self, plot=None): + """ + Instantiate a plot as a polar plot + + Parmeters + --------- + plot : pyqtgraph plotItem + the plot that will be converted to a polar plot, defaults to None + if None, then a new PlotItem will be created, accessible + as polarPlot.plotItem + """ + if plot is None: + self.plotItem = pg.PlotItem() # create a plot item for the plot + else: + self.plotItem = plot + self.plotItem.setAspectLocked() + self.plotItem.hideAxis("bottom") + self.plotItem.hideAxis("left") + self.gridSet = False + self.data = None + self.rMax = None + + def setAxes(self, steps=4, rMax=None, makeGrid=True): + """ + Make the polar plot axes + + Parameters + ---------- + steps : int, optional + The number of radial steps for the grid, defaults to 4 + rMax : float, optional + The maximum radius of the plot, defaults to None (the rMax is 1) + makeGrid : boolean, optional + Whether the grid will actually be plotted or not, defaults to True + + """ + if makeGrid is False or self.gridSet: + return + if rMax is None: + if self.data is None: + rMax = 1.0 + else: + rMax = np.max(self.data["y"]) + self.rMax = rMax + # Add radial grid lines (theta markers) + gridPen = pg.mkPen(width=0.55, color="k", style=pg.QtCore.Qt.DotLine) + ringPen = pg.mkPen(width=0.75, color="k", style=pg.QtCore.Qt.SolidLine) + for th in np.linspace(0.0, np.pi * 2, 8, endpoint=False): + rx = np.cos(th) * rMax + ry = np.sin(th) * rMax + self.plotItem.plot(x=[0, rx], y=[0.0, ry], pen=gridPen) + ang = th * 360.0 / (np.pi * 2) + # anchor is odd: 0,0 is upper left corner, 1,1 is lower right corner + if ang < 90.0: + x = 0.0 + y = 0.5 + elif ang == 90.0: + x = 0.5 + y = 1 + elif ang < 180: + x = 1.0 + y = 0.5 + elif ang == 180.0: + x = 1 + y = 0.5 + elif ang < 270: + x = 1 + y = 0 + elif ang == 270.0: + x = 0.5 + y = 0 + elif ang < 360: + x = 0 + y = 0 + ti = pg.TextItem("%d" % (int(ang)), color=pg.mkColor("k"), anchor=(x, y)) + self.plotItem.addItem(ti) + ti.setPos(rx, ry) + # add polar grid lines (r) + for gr in np.linspace(rMax / steps, rMax, steps): + circle = pg.QtGui.QGraphicsEllipseItem(-gr, -gr, gr * 2, gr * 2) + if gr < rMax: + circle.setPen(gridPen) + else: + circle.setPen(ringPen) + self.plotItem.addItem(circle) + ti = pg.TextItem("%d" % (int(gr)), color=pg.mkColor("k"), anchor=(1, 1)) + ti.setPos(gr, 0.0) + self.plotItem.addItem(ti) + self.gridSet = True + + def plot( + self, + r, + theta, + vectors=False, + arrowhead=True, + normalize=False, + sort=False, + **kwds + ): + """ + plot puts the data into a polar plot. + the plot will be converted to a polar graph + + Parameters + ---------- + r : list or numpy array + a list or array of radii + theta : list or numpy array + a list or array of angles (in radians) corresponding to the values in r + vectors : boolean, optional + vectors True means that plot is composed of vectors to each point radiating from the origin, defaults to False + arrowhead : boolean, optional + arrowhead True plots arrowheads at the end of the vectors, defaults to True + normalize : boolean, optional + normalize forces the plot to be scaled to the max values in r, defaults to False + sort : boolean, optional + causes data r, theta to be sorted by theta, defaults to False + **kwds are passed to the data plot call. + + """ + + # sort r, theta by r + + rs = np.array(r) + thetas = np.array(theta) + + if sort: + indx = np.argsort(thetas) + theta = thetas + if not isinstance(indx, np.int64): + for i, j in enumerate(indx): + rs[i] = r[j] + thetas[i] = theta[j] + + # Transform to cartesian and plot + if normalize: + rs = rs / np.max(rs) + x = rs * np.cos(thetas) + y = rs * np.sin(thetas) + try: + len(x) + except: + x = [x] + y = [y] + if vectors: # plot r,theta as lines from origin + for i, xi in enumerate(x): + # print x[i], y[i] + if arrowhead: + arrowAngle = -( + thetas[i] * 360 / (2 * np.pi) + 180 + ) # convert to degrees, and correct orientation + arrow = pg.ArrowItem( + angle=arrowAngle, tailLen=0, tailWidth=1.5, **kwds + ) + arrow.setPos(x[i], y[i]) + self.plotItem.addItem(arrow) + self.plotItem.plot([0.0, x[i]], [0.0, y[i]], **kwds) + + else: + self.plotItem.plot(x, y, **kwds) + self.rMax = np.max(y) + self.data = {"x": x, "y": y} + + def hist( + self, + r, + theta, + binwidth=np.pi / 6.0, + normalize=False, + density=False, + mode="straight", + **kwds + ): + """ + plot puts the data into a polar plot as a histogram of the number of observations + within a wedge + the plot will be converted to a polar graph + + Parameters + ---------- + r : list or numpy array + a list or array of radii + theta : list or numpy array + a list or array of angles (in radians) corresponding to the values in r + binwidth : bin width, in radians optional + vectors True means that plot is composed of vectors to each point radiating from the origin, defaults to 30 degrees (np.pi/6) + normalize : boolean, optional + normalize forces the plot to be scaled to the max values in r, defaults to False + density : boolean, optional + plot a count histogram, or a density histogram weighted by r values, defaults to False + mode : str, optional + 'straight' selects straight line between bars. 'arc' makes the end of the bar an arc (truer representation), defaults to 'straight' + **kwds are passed to the data plot call. + + Returns + ------- + tuple : (list of rHist, list of bins) + The histogram that was plotted (use for statistical comparisions) + """ + + rs = np.array(r) + thetas = np.array(theta) + twopi = np.pi * 2.0 + for i, t in enumerate(thetas): # restrict to positive half plane [0....2*pi] + while t < 0.0: + t += twopi + while t > twopi: + t -= twopi + thetas[i] = t + bins = np.arange(0, np.pi * 2 + 1e-12, binwidth) + # compute histogram + (rhist, rbins) = np.histogram(thetas, bins=bins, weights=rs, density=density) + # Transform to cartesian and plot + if normalize: + rhist = rhist / np.max(rhist) + xo = rhist * np.cos(bins[:-1]) # get cartesian form + xp = rhist * np.cos(bins[:-1] + binwidth) + yo = rhist * np.sin(bins[:-1]) + yp = rhist * np.sin(bins[:-1] + binwidth) + arcinc = np.pi / 100.0 # arc increments + for i in range(len(xp)): + if mode is "arc": + self.plotItem.plot( + [xo[i], 0.0, xp[i]], [yo[i], 0.0, yp[i]], **kwds + ) # "v" segement + arcseg = np.arange(bins[i], bins[i + 1], arcinc) + x = np.array(rhist[i] * np.cos(arcseg)) + y = np.array(rhist[i] * np.sin(arcseg)) + self.plotItem.plot(x, y, **kwds) + + else: + self.plotItem.plot( + [0.0, xo[i], xp[i], 0.0], [0.0, yo[i], yp[i], 0.0], **kwds + ) + self.data = {"x": xo, "y": yo} + self.rMax = np.max(yo) + return (rhist, rbins) + + def circmean(self, alpha, axis=None): + """ + Compute the circular mean of a set of angles along the axis + + Parameters + ---------- + alpha : numpy array + the angles to compute the circular mean of + axis : int + The axis of alpha for the computatoin, defaults to None + + Returns + ------- + float : the mean angle + """ + mean_angle = np.arctan2( + np.mean(np.sin(alpha), axis), np.mean(np.cos(alpha), axis) + ) + return mean_angle + + +def talbotTicks(axl, **kwds): + """ + Adjust the tick marks using the talbot et al algorithm, on an existing plot. + """ + if type(axl) is not list: + axl = [axl] + for ax in axl: + do_talbotTicks(ax, **kwds) + + +def do_talbotTicks( + ax, + ndec=3, + density=(1.0, 1.0), + insideMargin=0.05, + pointSize=None, + tickPlacesAdd=(0, 0), +): + """ + Change the axis ticks to use the talbot algorithm for ONE axis + Paramerters control the ticks + + Parameters + ---------- + ax : pyqtgraph axis instance + the axis to change the ticks on + ndec : int + Number of decimals (would be passed to talbotTicks if that was being called) + density : tuple + tick density (for talbotTicks), defaults to (1.0, 1.0) + insideMargin : float + Inside margin space for plot, defaults to 0.05 (5%) + pointSize : int + point size for tick text, defaults to 12 + tickPlacesAdd : tuple + number of decimal places to add in tickstrings for the ticks, pair for x and y axes, defaults to (0,0) + + """ + # get axis limits + aleft = ax.getAxis("left") + abottom = ax.getAxis("bottom") + yRange = aleft.range + xRange = abottom.range + # now create substitue tick marks and labels, using Talbot et al algorithm + xr = np.diff(xRange)[0] + yr = np.diff(yRange)[0] + xmin, xmax = ( + np.min(xRange) - xr * insideMargin, + np.max(xRange) + xr * insideMargin, + ) + ymin, ymax = ( + np.min(yRange) - yr * insideMargin, + np.max(yRange) + yr * insideMargin, + ) + xtick = ticks.Extended( + density=density[0], figure=None, range=(xmin, xmax), axis="x" + ) + ytick = ticks.Extended( + density=density[1], figure=None, range=(ymin, ymax), axis="y" + ) + xt = xtick() + yt = ytick() + xts = tickStrings(xt, scale=1, spacing=None, tickPlacesAdd=tickPlacesAdd[0]) + yts = tickStrings(yt, scale=1, spacing=None, tickPlacesAdd=tickPlacesAdd[1]) + xtickl = [[(x, xts[i]) for i, x in enumerate(xt)], []] # no minor ticks here + ytickl = [[(y, yts[i]) for i, y in enumerate(yt)], []] # no minor ticks here + + # ticks format: [ (majorTickValue1, majorTickString1), (majorTickValue2, majorTickString2), ... ], + aleft.setTicks(ytickl) + abottom.setTicks(xtickl) + # now set the point size (this may affect spacing from axis, and that would have to be adjusted - see the pyqtgraph google groups) + if pointSize is not None: + b = pg.QtGui.QFont() + b.setPixelSize(pointSize) + aleft.tickFont = b + abottom.tickFont = b + + +def violinPlotScatter(ax, data, symbolColor="k", symbolSize=4, symbol="o"): + """ + Plot data as violin plot with scatter and error bar + + Parameters + ---------- + ax : pyqtgraph plot instance + is the axs to plot into + data : dict + dictionary containing {pos1: data1, pos2: data2}, where pos is the x position for the data in data. Each data + set iis plotted as a separate column + symcolor : string, optional + color of the symbols, defaults to 'k' (black) + symbolSize : int, optional + Size of the symbols in the scatter plot, points, defaults to 4 + symbol : string, optoinal + The symbol to use, defaults to 'o' (circle) + """ + + y = [] + x = [] + xb = np.arange(0, len(data.keys()), 1) + ybm = [0] * len(data.keys()) # np.zeros(len(sdat.keys())) + ybs = [0] * len(data.keys()) # np.zeros(len(sdat.keys())) + for i, k in enumerate(data.keys()): + yvals = np.array(data[k]) + xvals = pg.pseudoScatter(yvals, spacing=0.4, bidir=True) * 0.2 + ax.plot( + x=xvals + i, + y=yvals, + pen=None, + symbol=symbol, + symbolSize=symbolSize, + symbolBrush=pg.mkBrush(symbolColor), + ) + y.append(yvals) + x.append([i] * len(yvals)) + ybm[i] = np.nanmean(yvals) + ybs[i] = np.nanstd(yvals) + mbar = pg.PlotDataItem( + x=np.array([xb[i] - 0.2, xb[i] + 0.2]), + y=np.array([ybm[i], ybm[i]]), + pen={"color": "k", "width": 0.75}, + ) + ax.addItem(mbar) + bar = pg.ErrorBarItem( + x=xb, + y=np.array(ybm), + height=np.array(ybs), + beam=0.2, + pen={"color": "k", "width": 0.75}, + ) + violin_plot(ax, y, xb, bp=False) + ax.addItem(bar) + ticks = [[(v, k) for v, k in enumerate(data.keys())], []] + ax.getAxis("bottom").setTicks(ticks) + + +def violin_plot(ax, data, pos, dist=0.0, bp=False): + """ + create violin plots on an axis + """ + + if data is None or len(data) == 0: + return # skip trying to do the plot + + dist = max(pos) - min(pos) + w = min(0.15 * max(dist, 1.0), 0.5) + for i, d in enumerate(data): + if d == [] or len(d) == 0: + continue + k = scipy.stats.gaussian_kde(d) # calculates the kernel density + m = k.dataset.min() # lower bound of violin + M = k.dataset.max() # upper bound of violin + y = np.arange(m, M, (M - m) / 100.0) # support for violin + v = k.evaluate(y) # violin profile (density curve) + v = v / v.max() * w # scaling the violin to the available space + c1 = pg.PlotDataItem(y=y, x=pos[i] + v, pen=pg.mkPen("k", width=0.5)) + c2 = pg.PlotDataItem(y=y, x=pos[i] - v, pen=pg.mkPen("k", width=0.5)) + # mean = k.dataset.mean() + # vm = k.evaluate(mean) + # vm = vm * w + # ax.plot(x=np.array([pos[i]-vm[0], pos[i]+vm[0]]), y=np.array([mean, mean]), pen=pg.mkPen('k', width=1.0)) + ax.addItem(c1) + ax.addItem(c2) + # ax.addItem(hbar) + f = pg.FillBetweenItem( + curve1=c1, curve2=c2, brush=pg.mkBrush((255, 255, 0, 96)) + ) + ax.addItem(f) + + if bp: + pass + # bpf = ax.boxplot(data, notch=0, positions=pos, vert=1) + # pylab.setp(bpf['boxes'], color='black') + # pylab.setp(bpf['whiskers'], color='black', linestyle='-') + + +def labelAxes(plot, xtext, ytext, **kwargs): + """ + helper to label up the plot + + Parameters + ----------- + plot : plot item + xtext : string + text for x axis + ytext : string + text for y axis + **kwargs : keywords + additional arguments to pass to pyqtgraph setLabel + """ + + plot.setLabel("bottom", xtext, **kwargs) + plot.setLabel("left", ytext, **kwargs) + + +def labelPanels(plot, label=None, **kwargs): + """ + helper to label up the plot + Inputs: plot item + text for x axis + text for yaxis + plot title (on top) OR + plot panel label (for example, "A", "A1") + """ + + if label is not None: + setPlotLabel(plot, plotlabel="%s" % label, **kwargs) + else: + setPlotLabel(plot, plotlabel="") + + +def labelTitles(plot, title=None, **kwargs): + """ + Set the title of a plotitem. Basic HTML formatting is allowed, along + with "size", "bold", "italic", etc.. + If the title is not defined, then a blank label is used + A title is a text label that appears centered above the plot, in + QGridLayout (position 0,2) of the plotitem. + params + ------- + :param plotitem: The plot item to label + :param title: The text string to use for the label + :kwargs: keywords to pass to the pg.LabelItem + :return: None + + """ + + if title is not None: + plot.setTitle(title="%s" % title, visible=True, **kwargs) + else: # clear the plot title + plot.setTitle(title=" ") + + +def setPlotLabel(plotitem, plotlabel="", **kwargs): + """ + Set the plotlabel of a plotitem. Basic HTML formatting is allowed, along + with "size", "bold", "italic", etc.. + If plotlabel is not defined, then a blank label is used + A plotlabel is a text label that appears the upper left corner of the + QGridLayout (position 0,0) of the plotitem. + params + ------- + :param plotitem: The plot item to label + :param plotlabel: The text string to use for the label + :kwargs: keywords to pass to the pg.LabelItem + :return: None + + """ + + plotitem.LabelItem = pg.LabelItem(plotlabel, **kwargs) + plotitem.LabelItem.setMaximumHeight(30) + plotitem.layout.setRowFixedHeight(0, 30) + plotitem.layout.addItem(plotitem.LabelItem, 0, 0) + plotitem.LabelItem.setVisible(True) + + +class LayoutMaker: + def __init__( + self, + win=None, + cols=1, + rows=1, + letters=True, + titles=False, + labelEdges=True, + margins=4, + spacing=4, + ticks="default", + ): + self.sequential_letters = string.ascii_uppercase + self.cols = cols + self.rows = rows + self.letters = letters + self.titles = titles + self.edges = labelEdges + self.margins = margins + self.spacing = spacing + self.rcmap = [None] * cols * rows + self.plots = None + self.win = win + self.ticks = ticks + self._makeLayout( + letters=letters, titles=titles, margins=margins, spacing=spacing + ) + # self.addLayout(win) + + # def addLayout(self, win=None): + # if win is not None: + # win.setLayout(self.gridLayout) + + def getCols(self): + return self.cols + + def getRows(self): + return self.rows + + def mapFromIndex(self, index): + """ + for a given index, return the row, col tuple associated with the index + """ + return self.rcmap[index] + + def getPlot(self, index): + """ + return the plot item in the list corresponding to the index n + """ + if isinstance(index, tuple): + r, c = index + elif isinstance(index, int): + r, c = self.rcmap[index] + else: + raise ValueError( + "pyqtgraphPlotHelpers, LayoutMaker plot: index must be int or tuple(r,c)" + ) + return self.plots[r][c] + + def plot(self, index, *args, **kwargs): + p = self.getPlot(index).plot(*args, **kwargs) + if self.ticks == "talbot": + talbotTicks(self.getPlot(index)) + return p + + def _makeLayout(self, letters=True, titles=True, margins=4, spacing=4): + """ + Create a multipanel plot. + The pyptgraph elements (widget, gridlayout, plots) are stored as class variables. + The layout is always a rectangular grid with shape (cols, rows) + if letters is true, then the plot is labeled "A, B, C..." Indices move horizontally first, then vertically + margins sets the margins around the outside of the plot + spacing sets the spacing between the elements of the grid + If a window was specified (self.win is not None) then the grid layout will derive from that window's central + item; otherwise we just make a gridLayout that can be put into another container somewhere. + """ + import string + + if self.win is not None: + self.gridLayout = ( + self.win.ci.layout + ) # the window's 'central item' is the main gridlayout. + else: + self.gridLayout = ( + pg.QtGui.QGridLayout() + ) # just create the grid layout to add to another item + self.gridLayout.setContentsMargins(margins, margins, margins, margins) + self.gridLayout.setSpacing(spacing) + self.plots = [[0 for x in xrange(self.cols)] for x in xrange(self.rows)] + i = 0 + for r in range(self.rows): + for c in range(self.cols): + self.plots[r][c] = self.win.addPlot(row=r, col=c) # pg.PlotWidget() + if letters: + labelPanels( + self.plots[r][c], + label=self.sequential_letters[i], + size="14pt", + bold=True, + ) + if titles: + labelTitles( + self.plots[r][c], + title=self.sequential_letters[i], + size="14pt", + bold=False, + ) + + self.rcmap[i] = (r, c) + i += 1 + if i > 25: + i = 0 + self.labelEdges("T(s)", "Y", edgeOnly=self.edges) + + def labelEdges(self, xlabel="T(s)", ylabel="Y", edgeOnly=True, **kwargs): + """ + label the axes on the outer edges of the gridlayout, leaving the interior axes clean + """ + (lastrow, lastcol) = self.rcmap[-1] + i = 0 + for (r, c) in self.rcmap: + if c == 0: + ylab = ylabel + elif edgeOnly: + ylab = "" + else: + ylab = ylabel + if r == self.rows - 1: # only the last row + xlab = xlabel + elif edgeOnly: # but not other rows + xlab = "" + else: + xlab = xlabel # otherwise, label it + labelAxes(self.plots[r][c], xlab, ylab, **kwargs) + i += 1 + + def axesEdges(self, edgeOnly=True): + """ + text labesls only on the axes on the outer edges of the gridlayout, + leaving the interior axes clean + """ + (lastrow, lastcol) = self.rcmap[-1] + i = 0 + for (r, c) in self.rcmap: + xshow = True + yshow = True + if edgeOnly and c > 0: + yshow = False + if edgeOnly and r < self.rows: # only the last row + yshow = False + ax = self.getPlot((r, c)) + leftaxis = ax.getAxis("left") + bottomaxis = ax.getAxis("bottom") + # print dir(self.plots[r][c]) + leftaxis.showValues = yshow + bottomaxis.showValues = xshow + i += 1 + + def columnAutoScale(self, col, axis="left"): + """ + autoscale the columns according to the max value in the column. + Finds outside range of column data, then sets the scale of all plots + in the column to that range + """ + atmax = None + atmin = None + for (r, c) in self.rcmap: + if c != col: + continue + ax = self.getPlot((r, c)) + thisaxis = ax.getAxis(axis) + amin, amax = thisaxis.range + if atmax is None: + atmax = amax + else: + if amax > atmax: + atmax = amax + if atmin is None: + atmin = amin + else: + if amin > atmin: + atmin = amin + + self.columnSetScale(col, axis=axis, range=(atmin, atmax)) + return (atmin, atmax) + + def columnSetScale(self, col, axis="left", range=(0.0, 1.0)): + """ + Set the column scale + """ + for (r, c) in self.rcmap: + if c != col: + continue + ax = self.getPlot((r, c)) + if axis == "left": + ax.setYRange(range[0], range[1]) + elif axis == "bottom": + ax.setXRange(range[0], range[1]) + + if self.ticks == "talbot": + talbotTicks(ax) + + def title(self, index, title="", **kwargs): + """ + add a title to a specific plot (specified by index) in the layout + """ + labelTitles(self.getPlot(index), title=title, **kwargs) + + +def figure(title=None, background="w"): + if background == "w": + pg.setConfigOption("background", "w") # set background to white + pg.setConfigOption("foreground", "k") + pg.mkQApp() + win = pg.GraphicsWindow(title=title) + return win + + +def show(): + pg.QApplication.instance().exec_() + + +def test_layout(win): + """ + Test the various plot types and modifications provided by the helpers above, + in the context of a layout with various kinds of plots. + """ + layout = LayoutMaker(cols=4, rows=2, win=win, labelEdges=True, ticks="talbot") + x = np.arange(0, 10.0, 0.1) + y = np.sin(x * 3.0) # make an interesting signal + r = np.random.random(10) # and a random signal + theta = np.linspace(0, 2.0 * np.pi, 10, endpoint=False) # r, theta for polar plots + for n in range(4 * 2): + if n not in [1, 2, 3, 4]: + layout.plot(n, x, y) + p = layout.getPlot(n) + if n == 0: # crossed axes plot + crossAxes( + p, + xyzero=[5.0, 0.0], + density=(0.75, 1.5), + tickPlacesAdd=(1, 0), + pointSize=12, + ) + layout.title(n, "Crossed Axes") + if n in [1, 2, 3]: # two differnt forms of polar plots + if n == 1: + po = polarPlot(p) + po.setAxes(rMax=np.max(r)) + po.plot(r, theta, pen=pg.mkPen("r")) + layout.title(n, "Polar Path") + + if n == 2: + po = polarPlot(p) + po.plot(r, theta, vectors=True, pen=pg.mkPen("k", width=2.0)) + po.setAxes(rMax=np.max(r)) + po.plot( + [np.mean(r)], + [po.circmean(theta)], + vectors=True, + pen=pg.mkPen("r", width=2.0), + ) + layout.title(n, "Polar Arrows") + if n == 3: + po = polarPlot(p) + po.hist( + r, + theta, + binwidth=np.pi / 6.0, + normalize=False, + density=False, + pen="r", + ) + po.hist( + r, + theta, + binwidth=np.pi / 6.0, + normalize=False, + density=False, + mode="arc", + pen="b", + ) + po.setAxes(rMax=None) + layout.title(n, "Polar Histogram") + + if n == 4: # violin plot with scatter plot data + data = { + 2: [3, 5, 7, 9, 2, 4, 6, 8, 7, 2, 3, 1, 2.5], + 3: [5, 6, 7, 9, 2, 8, 10, 9.5, 11], + } + violinPlotScatter(p, data, symbolColor="r") + p.setYRange(0, 12) + layout.title(n, "Violin Plots with PseudoScatter") + + if ( + n == 5 + ): # clean plot for physiology with baseline reference and a calibration bar + calbar( + p, + calbar=[7.0, -1.5, 2.0, 0.5], + axesoff=True, + orient="left", + unitNames={"x": "ms", "y": "nA"}, + ) + refline(p, refline=0.0, color=[64, 64, 64], linestyle="--", linewidth=0.5) + layout.title(n, "Calbar and Refline") + + # talbotTicks(layout.getPlot(1)) + layout.columnAutoScale(col=3, axis="left") + show() + + +def test_crossAxes(win): + layout = LayoutMaker(cols=1, rows=1, win=win, labelEdges=True) + x = np.arange(-1, 1.0, 0.01) + y = np.sin(x * 10.0) + layout.plot(0, x, y) + p = layout.getPlot(0) + crossAxes( + p, + xyzero=[0.0, 0.0], + limits=[None, None, None, None], + density=1.5, + tickPlacesAdd=1, + pointSize=12, + ) + show() + + +def test_polarPlot(win): + layout = LayoutMaker(cols=1, rows=1, win=win, labelEdges=True) + po = polarPlot(layout.getPlot((0, 0))) # convert rectangular plot to polar + po.setAxes(steps=4, rMax=100, makeGrid=True) # build the axes + nvecs = 50 + # th = np.linspace(-np.pi*2, np.pi*2-np.pi*2/nvecs, nvecs) + th = np.linspace(-np.pi * 4, 0, nvecs) + r = np.linspace(10, 100, nvecs) + po.plot( + r, th, vectors=True, arrowhead=True, symbols="o", pen=pg.mkPen("k", width=1.5) + ) # plot with arrowheads + nvecs = 8 + th = np.linspace(-np.pi * 2, np.pi * 2 - np.pi * 2 / nvecs, nvecs) + r = np.linspace(10, 100, nvecs) + # po.plot(r, th, vectors=True, arrowhead=False, symbols='o', pen=pg.mkPen('r', width=1.5)) # plot with just lines + + show() + + +if __name__ == "__main__": + win = figure(title="testing") + test_layout(win) + # test_crossAxes(win) + # test_polarPlot(win) diff --git a/cnmodel/util/random_seed.py b/cnmodel/util/random_seed.py new file mode 100644 index 0000000..44c2a6e --- /dev/null +++ b/cnmodel/util/random_seed.py @@ -0,0 +1,28 @@ +import numpy as np +import hashlib, struct + +_current_seed = 0 + + +def set_seed(seed): + """ + Set the random seed to be used globally. If a string is supplied, it + will be converted to int using hash(). + + This immediately seeds the numpy RNG. Any other RNGs must be seeded using + current_seed() + """ + if isinstance(seed, str): + seed = struct.unpack("=I", hashlib.md5(seed.encode("utf-8")).digest()[:4])[0] + np.random.seed(seed) + assert seed < 2 ** 64 # neuron RNG fails if seed is too large + global _current_seed + _current_seed = seed + return seed + + +def current_seed(): + """ + Return the currently-set global random seed. + """ + return _current_seed diff --git a/cnmodel/util/sound.py b/cnmodel/util/sound.py new file mode 100644 index 0000000..4126b02 --- /dev/null +++ b/cnmodel/util/sound.py @@ -0,0 +1,1415 @@ +""" +Tools for generating auditory stimuli. +""" +from __future__ import division +import numpy as np +import scipy +import scipy.io.wavfile +import resampy + + +def create(type, **kwds): + """ Create a Sound instance using a key returned by Sound.key(). + """ + cls = globals()[type] + return cls(**kwds) + + +class Sound(object): + """ + Base class for all sound stimulus generators. + """ + + def __init__(self, duration, rate=100e3, **kwds): + """ + Parameters + ---------- + duration: float (no default): + duration of the stimulus, in seconds + + rate : float (default: 100000.) + sample rate for sound generation + + """ + self.opts = {"rate": rate, "duration": duration} + self.opts.update(kwds) + self._time = None + self._sound = None + + @property + def sound(self): + """ + :obj:`array`: The generated sound array, expressed in Pascals. + """ + if self._sound is None: + self._sound = self.generate() + return self._sound + + @property + def time(self): + """ + :obj:`array`: The array of time values, expressed in seconds. + """ + if self._time is None: + self._time = np.linspace(0, self.opts["duration"], self.num_samples) + return self._time + + @property + def num_samples(self): + """ + int: The number of samples in the sound array. + """ + return 1 + int(self.opts["duration"] * self.opts["rate"]) + + @property + def dt(self): + """ + float: the sample period (time step between samples). + """ + return 1.0 / self.opts["rate"] + + @property + def duration(self): + """ + float: The duration of the sound + """ + return self.opts["duration"] + + def key(self): + """ + The sound can be recreated using ``create(**key)``. + :obj:`dict`: Return dict of parameters needed to completely describe this sound. + """ + k = self.opts.copy() + k["type"] = self.__class__.__name__ + return k + + def measure_dbspl(self, tstart, tend): + """ + Measure the sound pressure for the waveform in a window of time + + Parameters + ---------- + tstart : + time to start spl measurement (seconds). + + tend : + ending time for spl measurement (seconds). + + Returns + ------- + float : The measured amplitude (dBSPL) of the sound from tstart to tend + + """ + istart = int(tstart * self.opts["rate"]) + iend = int(tend * self.opts["rate"]) + return pa_to_dbspl(self.sound[istart:iend].std()) + + def generate(self): + """ + Generate and return the sound output. This method is defined by subclasses. + """ + raise NotImplementedError() + + def __getattr__(self, name): + if "opts" not in self.__dict__: + raise AttributeError(name) + if name in self.opts: + return self.opts[name] + else: + return object.__getattr__(self, name) + + +class TonePip(Sound): + """ Create one or more tone pips with cosine-ramped edges. + + Parameters + ---------- + rate : float + Sample rate in Hz + duration : float + Total duration of the sound + f0 : float or array-like + Tone frequency in Hz. Must be less than half of the sample rate. + dbspl : float + Maximum amplitude of tone in dB SPL. + pip_duration : float + Duration of each pip including ramp time. Must be at least + 2 * ramp_duration. + pip_start : array-like + Start times of each pip + ramp_duration : float + Duration of a single ramp period (from minimum to maximum). + This may not be more than half of pip_duration. + + """ + + def __init__(self, **kwds): + reqdWords = [ + "rate", + "duration", + "f0", + "dbspl", + "pip_duration", + "pip_start", + "ramp_duration", + ] + for k in reqdWords: + if k not in kwds.keys(): + raise TypeError("Missing required argument '%s'" % k) + if kwds["pip_duration"] < kwds["ramp_duration"] * 2: + raise ValueError("pip_duration must be greater than (2 * ramp_duration).") + if kwds["f0"] > kwds["rate"] * 0.5: + raise ValueError("f0 must be less than (0.5 * rate).") + Sound.__init__(self, **kwds) + + def generate(self): + """ + Call to compute the tone pips + + Returns + ------- + array : + generated waveform + + """ + o = self.opts + return piptone( + self.time, + o["ramp_duration"], + o["rate"], + o["f0"], + o["dbspl"], + o["pip_duration"], + o["pip_start"], + ) + + +class FMSweep(Sound): + """ Create an FM sweep with either linear or logarithmic rates, + of a specified duration between two frequencies. + + Parameters + ---------- + rate : float + Sample rate in Hz + duration : float + Total duration of the sweep + start : float + t times of each pip + freqs : list + [f0, f1]: the start and stop times for the sweep + ramp : string + valid input for type of sweep (linear, logarithmic, etc) + dbspl : float + Maximum amplitude of pip in dB SPL. + """ + + def __init__(self, **kwds): + for k in ["rate", "duration", "start", "freqs", "ramp", "dbspl"]: + if k not in kwds: + raise TypeError("Missing required argument '%s'" % k) + Sound.__init__(self, **kwds) + + def generate(self): + """ + Call to actually compute the the FM sweep + + Returns + ------- + array : + generated waveform + + """ + o = self.opts + return fmsweep( + self.time, o["start"], o["duration"], o["freqs"], o["ramp"], o["dbspl"] + ) + + +class NoisePip(Sound): + """ One or more noise pips with cosine-ramped edges. + + Parameters + ---------- + rate : float + Sample rate in Hz + duration : float + Total duration of the sound + seed : int >= 0 + Random seed + dbspl : float + Maximum amplitude of tone in dB SPL. + pip_duration : float + Duration of each pip including ramp time. Must be at least + 2 * ramp_duration. + pip_start : array-like + Start times of each pip + ramp_duration : float + Duration of a single ramp period (from minimum to maximum). + This may not be more than half of pip_duration. + + """ + + def __init__(self, **kwds): + for k in [ + "rate", + "duration", + "dbspl", + "pip_duration", + "pip_start", + "ramp_duration", + "seed", + ]: + if k not in kwds: + raise TypeError("Missing required argument '%s'" % k) + if kwds["pip_duration"] < kwds["ramp_duration"] * 2: + raise ValueError("pip_duration must be greater than (2 * ramp_duration).") + if kwds["seed"] < 0: + raise ValueError("Random seed must be integer > 0") + + Sound.__init__(self, **kwds) + + def generate(self): + """ + Call to compute the noise pips + + Returns + ------- + array : + generated waveform + + """ + o = self.opts + return pipnoise( + self.time, + o["ramp_duration"], + o["rate"], + o["dbspl"], + o["pip_duration"], + o["pip_start"], + o["seed"], + ) + + +class ClickTrain(Sound): + """ One or more clicks (rectangular pulses). + + Parameters + ---------- + rate : float + Sample rate in Hz + dbspl : float + Maximum amplitude of click in dB SPL. + click_duration : float + Duration of each click including ramp time. Must be at least + 1/rate. + click_starts : array-like + Start times of each click + """ + + def __init__(self, **kwds): + for k in ["rate", "duration", "dbspl", "click_duration", "click_starts"]: + if k not in kwds: + raise TypeError("Missing required argument '%s'" % k) + if kwds["click_duration"] < 1.0 / kwds["rate"]: + raise ValueError("click_duration must be greater than sample rate.") + + Sound.__init__(self, **kwds) + + def generate(self): + o = self.opts + return clicks( + self.time, o["rate"], o["dbspl"], o["click_duration"], o["click_starts"] + ) + + +class SAMNoise(Sound): + """ One or more gaussian noise pips with cosine-ramped edges. + + Parameters + ---------- + rate : float + Sample rate in Hz + duration : float + Total duration of the sound + seed : int >= 0 + Random seed + dbspl : float + Maximum amplitude of pip in dB SPL. + pip_duration : float + Duration of each pip including ramp time. Must be at least + 2 * ramp_duration. + pip_start : array-like + Start times of each pip + ramp_duration : float + Duration of a single ramp period (from minimum to maximum). + This may not be more than half of pip_duration. + fmod : float + SAM modulation frequency + dmod : float + Modulation depth + """ + + def __init__(self, **kwds): + parms = [ + "rate", + "duration", + "seed", + "pip_duration", + "pip_start", + "ramp_duration", + "fmod", + "dmod", + "seed", + ] + for k in parms: + if k not in kwds: + raise TypeError("Missing required argument '%s'" % k) + if kwds["pip_duration"] < kwds["ramp_duration"] * 2: + raise ValueError("pip_duration must be greater than (2 * ramp_duration).") + if kwds["seed"] < 0: + raise ValueError("Random seed must be integer > 0") + + Sound.__init__(self, **kwds) + + def generate(self): + """ + Call to compute the SAM noise + + Returns + ------- + array : + generated waveform + + """ + o = self.opts + o["phaseshift"] = 0.0 + return modnoise( + self.time, + o["ramp_duration"], + o["rate"], + o["f0"], + o["pip_duration"], + o["pip_start"], + o["dbspl"], + o["fmod"], + o["dmod"], + 0.0, + o["seed"], + ) + + +class SAMTone(Sound): + """ SAM tones with cosine-ramped edges. + + Parameters + ---------- + rate : float + Sample rate in Hz + duration : float + Total duration of the sound + f0 : float or array-like + Tone frequency in Hz. Must be less than half of the sample rate. + dbspl : float + Maximum amplitude of tone in dB SPL. + pip_duration : float + Duration of each pip including ramp time. Must be at least + 2 * ramp_duration. + pip_start : array-like + Start times of each pip + ramp_duration : float + Duration of a single ramp period (from minimum to maximum). + This may not be more than half of pip_duration. + fmod : float + SAM modulation frequency, Hz + dmod : float + Modulation depth, % + + """ + + def __init__(self, **kwds): + + for k in [ + "rate", + "duration", + "f0", + "dbspl", + "pip_duration", + "pip_start", + "ramp_duration", + "fmod", + "dmod", + ]: + if k not in kwds: + raise TypeError("Missing required argument '%s'" % k) + if kwds["pip_duration"] < kwds["ramp_duration"] * 2: + raise ValueError("pip_duration must be greater than (2 * ramp_duration).") + if kwds["f0"] > kwds["rate"] * 0.5: + raise ValueError("f0 must be less than (0.5 * rate).") + + Sound.__init__(self, **kwds) + + def generate(self): + """ + Call to compute a SAM tone + + Returns + ------- + array : + generated waveform + + """ + o = self.opts + basetone = piptone( + self.time, + o["ramp_duration"], + o["rate"], + o["f0"], + o["dbspl"], + o["pip_duration"], + o["pip_start"], + ) + return sinusoidal_modulation( + self.time, basetone, o["pip_start"], o["fmod"], o["dmod"], 0.0 + ) + + +def pa_to_dbspl(pa, ref=20e-6): + """ Convert Pascals (rms) to dBSPL. By default, the reference pressure is + 20 uPa. + """ + return 20 * np.log10(pa / ref) + + +def dbspl_to_pa(dbspl, ref=20e-6): + """ Convert dBSPL to Pascals (rms). By default, the reference pressure is + 20 uPa. + """ + return ref * 10 ** (dbspl / 20.0) + + +class SAMNoise(Sound): + """ One or more gaussian noise pips with cosine-ramped edges, sinusoidally modulated. + + Parameters + ---------- + rate : float + Sample rate in Hz + duration : float + Total duration of the sound + seed : int >= 0 + Random seed + dbspl : float + Maximum amplitude of pip in dB SPL. + pip_duration : float + Duration of each pip including ramp time. Must be at least + 2 * ramp_duration. + pip_start : array-like + Start times of each pip + ramp_duration : float + Duration of a single ramp period (from minimum to maximum). + This may not be more than half of pip_duration. + fmod : float + SAM modulation frequency + dmod : float + Modulation depth + + Returns + ------- + array : + waveform + + """ + + def __init__(self, **kwds): + for k in [ + "rate", + "duration", + "seed", + "pip_duration", + "pip_start", + "ramp_duration", + "fmod", + "dmod", + ]: + if k not in kwds: + raise TypeError("Missing required argument '%s'" % k) + if kwds["pip_duration"] < kwds["ramp_duration"] * 2: + raise ValueError("pip_duration must be greater than (2 * ramp_duration).") + if kwds["seed"] < 0: + raise ValueError("Random seed must be integer > 0") + + Sound.__init__(self, **kwds) + + def generate(self): + o = self.opts + basenoise = pipnoise( + self.time, + o["ramp_duration"], + o["rate"], + o["dbspl"], + o["pip_duration"], + o["pip_start"], + o["seed"], + ) + return sinusoidal_modulation( + self.time, basenoise, o["pip_start"], o["fmod"], o["dmod"], 0.0 + ) + + +class ComodulationMasking(Sound): + """ + Make a stimulus for comodulation masking release. + Note the parameter names are shortened so that the SGC generated filename + in cnmodel fits within system limits. + + Parameters + ---------- + rate : float + sample rate, in Hz + + dur : float + entire waveform duration in seconds + + pipst : float + time to start the test tone pips (seconds) + array, such as [0.25, 0.35, 0.45] + + pipdu : float + duration of the test (target) tone pips + + maskst : float + time to start the masker tones pips (seconds) + array, such as [0.1] + + maskdu : float + duration of the masker tone pips + + rf : float + rise/fall of the pips + + f0 : float (kHz) + Center frequency for the target tone, in kHz + + db : float + on-target masker and flankinb band intensity + In dB SPL (re 0.00002 dynes/cm2) + + s2n : float + signal re masker, in dbspl + + fmod : float + amplitude modulation frequency, in Hz + + dmod : float + amplitude modulation depth, in % + + fltype : string + Flanking type: + One of: + 'MultiTone' : multiple tones, with phase, spacing and # of bands specified as below + 'NBNoise' : the flanking stimulus is made up of narrow band noises (not implemented) + 'None' : no flanking sounds (just on-target stimuli) + + flspc : float + Spacing of flanking bands in octaves from the center frequency, f0 + + flgap : int + gap around the cf in flspc (e.g., 1 would skip the first adjacent band) + + flph : string + One of: + 'Comodulated': all of the flanking tones are comodulated in phase + with the target at the same frequency and depth + 'Codgh' : 'Grose and Hall codeviant': + The flanking bands have the same amplitude and frequency + as the target, but the phase of each band is different. Phases are + calculated so that all the bands wrap around 2*pi + 'Codvw' : 'Verhey and Winter codeviant': + The flanking bands have the same amplitude and frequency + as the target, but are out of phase with the on-frequency masker + 'Random': The phases are selected at random. This is probably best only + used when there are a large number of flanking bands. + + flspl : float + Flanking signal, in dbspl. + + flN : int + Number of flanking bands on either side of f0, spaced accordingly. + + Returns + ------- + array : + waveform + + """ + + def __init__(self, **kwds): + # print (kwds) + for k in [ + "rate", + "duration", + "pipdu", + "pipst", + "rf", + "maskst", + "maskdu", + # general: + "f0", + "dbspl", + "s2n", + "fmod", + "dmod", + # flankers: + "flgap", + "fltype", + "flspc", + "flph", + "flN", + ]: + if k not in kwds: + raise TypeError("Missing required argument '%s'" % k) + if "flspl" not in kwds: + kwds["flspl"] = kwds["dbspl"] + # if 'mask_spl' not in kwds: + # kwds['mask_spl'] = kwds['dbspl'] + # if kwds['mask_spl'] is None: + # kwds['mask_spl'] = 0. + if kwds["flspl"] is None: + raise ValueError() + + Sound.__init__(self, **kwds) + + def generate(self): + + o = self.opts + # start with center tone + onfreqmasker = piptone( + self.time, o["rf"], o["rate"], o["f0"], o["flspl"], o["maskdu"], o["maskst"] + ) + tardelay = ( + 0.0 + ) # 1.5/o['fmod'] # delay by one and one half cycles (no target in first dip) + target = piptone( + self.time, + o["rf"], + o["rate"], + o["f0"], + o["dbspl"] + o["s2n"], + o["pipdu"] - tardelay, + [p + tardelay for p in o["pipst"]], + ) + # target = shape_signal(onfreqmasker, self.time, o['rf'], o['rate'], o['f0'], + # o['dbspl']+o['s2n'], o['pipdu']-tardelay, [p + tardelay for p in o['pipst']]) + if (o["dbspl"] + o["s2n"]) <= 0.0: + target = np.zeros_like(target) + onfreqmasker = sinusoidal_modulation( + self.time, onfreqmasker, o["maskst"], o["fmod"], o["dmod"], 0.0 + ) + # print("o['dbspl']+o['s2n']: ", o['dbspl']+o['s2n']) + # print('np.max(target): ', np.max(target)) + + # target = sinusoidal_modulation(self.time, target, [p + tardelay for p in o['pip_start']], + # o['fmod'], o['dmod'], 0.) + self.onmask = onfreqmasker + self.target = target + if o["fltype"] not in ["None", "Ref", "NBN", "Tone"]: + raise ValueError("Unknown flanking_type: %s" % o["fltype"]) + if o["fltype"] in ["NBN"]: + raise ValueError('Flanking type "NBNoise" is not yet implemented') + elif o["fltype"] in ["None"]: + return (onfreqmasker + target) / 2.0 # scaling... + elif o["fltype"] in ["Tone"]: + nband = int(o["flN"]) + gap = int(o["flgap"]) + octspace = o["flspc"] + f0 = o["f0"] + flankfs = [f0 * (2 ** (octspace * (k + 1 + gap))) for k in range(nband)] + flankfs.extend( + [f0 / ((2 ** (octspace * (k + 1 + gap)))) for k in range(nband)] + ) + flankfs = sorted(flankfs) + flanktone = [[]] * len(flankfs) + for i, fs in enumerate(flankfs): + flanktone[i] = piptone( + self.time, + o["rf"], + o["rate"], + flankfs[i], + o["flspl"], + o["maskdu"], + o["maskst"], + ) + elif o["fltype"] in ["None", "Ref"]: + return (onfreqmasker + target) / 2.0 # scaling... + if o["fltype"] == "NBN": + raise ValueError("Flanking type nbnoise not yet implemented") + + ph = 0.0 + if o["flph"] == "Comod": + ph = np.zeros(len(flankfs)) + elif o["flph"] == "Codvw": # verhey and winter: just 180 out of phase + ph = np.pi * np.ones(len(flankfs)) + elif o["flph"] in ["Codgh", "Codev"]: # with precession: Grose and Hall 89 + ph = 2.0 * np.pi * np.arange(-o["flN"], o["flN"] + 1, 1) / o["flN"] + elif o["flph"] == "Random": + ph = 2.0 * np.pi * np.arange(-o["flN"], o["flN"] + 1, 1) / o["flN"] + raise ValueError("Random flanking phases not implemented") + else: + raise ValueError( + "Masker Phase pattern of type %s is not implemented" % o["flph"] + ) + # print(('flanking phases: ', ph)) + # print (len(flanktone)) + # print(('flanking freqs: ', flankfs)) + for i, fs in enumerate(flankfs): + flanktone[i] = sinusoidal_modulation( + self.time, flanktone[i], o["maskst"], o["fmod"], o["dmod"], ph[i] + ) + if i == 0: + maskers = flanktone[i] + else: + maskers = maskers + flanktone[i] + signal = (onfreqmasker + maskers + target) / (o["flN"] + 2) + return signal + + +class DynamicRipple(Sound): + def __init__(self, **kwds): + for k in ["rate", "duration"]: + if k not in kwds: + raise TypeError("Missing required argument '%s'" % k) + # if kwds['pip_duration'] < kwds['ramp_duration'] * 2: + # raise ValueError("pip_duration must be greater than (2 * ramp_duration).") + import DMR + + self.dmr = DMR.DMR() + Sound.__init__(self, **kwds) + + def generate(self): + """ + Call to compute a dynamic ripple stimulus + + Returns + ------- + array : + + generated waveform + """ + o = self.opts + self.dmr.set_params(Fs=o["rate"], duration=o["duration"] + 1.0 / o["rate"]) + self.dmr.make_waveform() + self._time = self.dmr.vTime # get time from the generator, not linspace + return self.dmr.vStim + + +class SpeechShapedNoise(Sound): + """ + Adapted from http://www.srmathias.com/speech-shaped-noise/ + """ + + def __init__(self, **kwds): + for k in ["rate", "duration", "waveform", "samplingrate"]: + if k not in kwds: + raise TypeError("Missing required argument '%s'" % k) + # if kwds['pip_duration'] < kwds['ramp_duration'] * 2: + # raise ValueError("pip_duration must be greater than (2 * ramp_duration).") + Sound.__init__(self, **kwds) + + def generate(self): + o = self.opts + print("opts: ", o) + ssn, t = make_ssn( + o["rate"], o["duration"], o["waveform"].sound, o["samplingrate"] + ) + self._time = t # override time array because we read a wave file + # if self.opts['duration'] == 0: + # self.opts['duration'] = np.max(t) - 1./o['rate'] + return ssn + + +class RandomSpectrumShape(Sound): + """ + Random Spectral Shape stimuli + log-spaced tones + Amplitudes adjusted in groups of 4 or 8 (amp_group_size) + Amplitude SD (amp_sd) + Frequency range (octaves above and below f0) (octaves) + spacing (fraction of octave: e.g, 1/8 or 1/64 as 8 or 64) (spacing) + + Generates one sample + + Young and Calhoun, 2005 + Yu and Young, 2000 + """ + + def __init__(self, **kwds): + for k in [ + "rate", + "duration", + "f0", + "dbspl", + "pip_duration", + "pip_start", + "ramp_duration", + "amp_group_size", + "amp_sd", + "spacing", + "octaves", + ]: + if k not in kwds: + raise TypeError("Missing required argument '%s'" % k) + if kwds["pip_duration"] < kwds["ramp_duration"] * 2: + raise ValueError("pip_duration must be greater than (2 * ramp_duration).") + if kwds["f0"] > kwds["rate"] * 0.5: + raise ValueError("f0 must be less than (0.5 * rate).") + + Sound.__init__(self, **kwds) + + def generate(self): + o = self.opts + octaves = o["octaves"] + lowf = o["f0"] / octaves + highf = o["f0"] * octaves + freqlist = np.logspace( + np.log2(lowf), + np.log2(highf), + num=o["spacing"] * octaves * 2, + endpoint=True, + base=2, + ) + amplist = np.zeros_like(freqlist) + db = o["dbspl"] + # assign amplitudes + if db == None: + db = 80.0 + groupsize = o["amp_group_size"] + for i in range(0, len(freqlist), groupsize): + if o["amp_sd"] > 0.0: + a = np.random.normal(scale=o["amp_sd"]) + else: + a = 0.0 + amplist[i : i + groupsize] = 20.0 * np.log10(a + db) + for i in range(len(freqlist)): + wave = piptone( + self.time, + o["ramp_duration"], + o["rate"], + freqlist[i], + amplist[i], + o["pip_duration"], + o["pip_start"], + pip_phase=np.pi * 2.0 * np.random.rand(), + ) + if i == 0: + result = wave + else: + result = result + wave + return result / (np.sqrt(np.mean(result ** 2.0))) # scale by rms level + + +class ReadWavefile(Sound): + """ Read a .wav file from disk, possibly converting the sample rate and the scale + for use in driving the auditory nerve fiber model. + + Parameters + ---------- + wavefile : str + name of the .wav file to read + rate : float + Sample rate in Hz (waveform will be resampled to this rate) + channel: int (default: 0) + If wavefile has 2 channels, select 0 or 1 for the channel to read + dbspl : float or None + If specified, the wave file is scaled such that its overall dBSPL + (measured from RMS of the entire waveform) is equal to this value. + Either ``dbspl`` or ``scale`` must be specified. + scale : float or None + If specified, the wave data is multiplied by this value to yield values in dBSPL. + Either ``dbspl`` or ``scale`` must be specified. + delay: float (default: 0.) + Silent delay time to start sound, in s. Allows anmodel and cells to run to steady-state + maxdur : float or None (default: None) + If specified, maxdur defines the total duration of generated waveform to return (in seconds). + If None, the generated waveform duration will be the sum of any delay value and + the duration of the waveform from the wavefile. + + Returns + ------- + array : + waveform + + """ + + def __init__( + self, wavefile, rate, channel=0, dbspl=None, scale=None, delay=0.0, maxdur=None + ): + if dbspl is not None and scale is not None: + raise ValueError('Only one of "dbspl" or "scale" can be set') + duration = ( + 0.0 + ) # forced because of the way num_samples has to be calculated first + if delay < 0.0: + raise ValueError("ReadWavefile: delay must be > 0., got: %f" % delay) + if maxdur is not None and maxdur < 0: + raise ValueError( + "ReadWavefile: maxdur must be None or > 0., got: %f" % maxdur + ) + Sound.__init__( + self, + duration, + rate, + wavefile=wavefile, + channel=channel, + dbspl=dbspl, + scale=scale, + maxdur=maxdur, + delay=delay, + ) + + def generate(self): + """ + Read the wave file from disk, clip duration, resample if necessary, and scale + + Returns + ------- + array : generated waveform + """ + [fs_wav, stimulus] = scipy.io.wavfile.read( + self.opts["wavefile"] + ) # raw is a numpy array of integer, representing the samples + if len(stimulus.shape) > 1 and stimulus.shape[1] > 0: + stimulus = stimulus[:, self.opts["channel"]] # just use selected channel + fs_wav = float(fs_wav) + maxdur = self.opts["maxdur"] + delay = self.opts["delay"] + delay_array = np.zeros( + int(delay * fs_wav) + ) # build delay array (may have 0 length) + if maxdur is None: + maxdur = delay + len(stimulus) / fs_wav # true total length + maxpts = int(maxdur * fs_wav) + stimulus = np.hstack((delay_array, stimulus))[:maxpts] + + if self.opts["rate"] != fs_wav: + stimulus = resampy.resample(stimulus, fs_wav, self.opts["rate"]) + self.opts["duration"] = (stimulus.shape[0] - 1) / self.opts[ + "rate" + ] # compute the duration, match for linspace calculation used in time. + self._time = None + self.time # requesting time should cause recalulation of the time + if self.opts["dbspl"] is not None: + rms = np.sqrt(np.mean(stimulus ** 2.0)) # find rms of the waveform + stimulus = ( + dbspl_to_pa(self.opts["dbspl"]) * stimulus / rms + ) # scale into Pascals + if self.opts["scale"] is not None: + stimulus = stimulus * self.opts["scale"] + return stimulus + + +def sinusoidal_modulation(t, basestim, tstart, fmod, dmod, phaseshift): + """ + Impose a sinusoidal amplitude-modulation on the input waveform. + For dmod=100%, the envelope max is 2, the min is 0; for dmod = 0, the max and min are 1 + maintains equal energy for all modulation depths. + Equation from Rhode and Greenberg, J. Neurophys, 1994 (adding missing parenthesis) and + Sayles et al. J. Physiol. 2013 + The envelope can be phase shifted (useful for co-deviant stimuli). + + Parameters + ---------- + t : array + array of waveform time values (seconds) + basestim : array + array of waveform values that will be subject to sinulsoidal envelope modulation + tstart : float + time at which the base sound starts (modulation starts then, with 0 phase crossing) + (seconds) + fmod : float + modulation frequency (Hz) + dmod : float + modulation depth (percent) + phaseshift : float + modulation phase shift (starting phase, radians) + + """ + + env = 1.0 + (dmod / 100.0) * np.sin( + (2.0 * np.pi * fmod * (t - tstart)) + phaseshift - np.pi / 2 + ) # envelope... + return basestim * env + + +def modnoise(t, rt, Fs, F0, dur, start, dBSPL, FMod, DMod, phaseshift, seed): + """ + Generate an amplitude-modulated noise with linear ramps. + + Parameters + ---------- + t : array + array of waveform time values + rt : float + ramp duration + Fs : float + sample rate + F0 : float + tone frequency + dur : float + duration of noise + start : float + start time for noise + dBSPL : float + sound pressure of stimulus + FMod : float + modulation frequency + DMod : float + modulation depth percent + phaseshift : float + modulation phase + seed : int + seed for random number generator + + Returns + ------- + array : + waveform + + """ + irpts = int(rt * Fs) + mxpts = len(t) + 1 + pin = pipnoise(t, rt, Fs, dBSPL, dur, start, seed) + env = 1 + (DMod / 100.0) * np.sin( + (2 * np.pi * FMod * t) - np.pi / 2 + phaseshift + ) # envelope... + + pin = linearramp(pin, mxpts, irpts) + env = linearramp(env, mxpts, irpts) + return pin * env + + +def linearramp(pin, mxpts, irpts): + """ + Apply linear ramps to *pin*. + + Parameters + ---------- + pin : array + input waveform to apply ramp to + + mxpts : int + point in array to start ramp down + + irpts : int + duration of the ramp + + Returns + ------- + array : + waveform + + + Original (adapted from Manis; makeANF_CF_RI.m):: + + function [out] = ramp(pin, mxpts, irpts) + out = pin; + out(1:irpts)=pin(1:irpts).*(0:(irpts-1))/irpts; + out((mxpts-irpts):mxpts)=pin((mxpts-irpts):mxpts).*(irpts:-1:0)/irpts; + return; + end + """ + out = pin.copy() + r = np.linspace(0, 1, irpts) + irpts = int(irpts) + # print 'irpts: ', irpts + # print len(out) + out[:irpts] = out[:irpts] * r + # print out[mxpts-irpts:mxpts].shape + # print r[::-1].shape + out[mxpts - irpts - 1 : mxpts] = out[mxpts - irpts - 1 : mxpts] * r[::-1] + return out + + +def pipnoise(t, rt, Fs, dBSPL, pip_dur, pip_start, seed): + """ + Create a waveform with multiple sine-ramped noise pips. Output is in + Pascals. + + Parameters + ---------- + t : array + array of time values + rt : float + ramp duration + Fs : float + sample rate + dBSPL : float + maximum sound pressure level of pip + pip_dur : float + duration of pip including ramps + pip_start : float + list of starting times for multiple pips + seed : int + random seed + + Returns + ------- + array : + waveform + + """ + rng = np.random.RandomState(seed) + pin = np.zeros(t.size) + for start in pip_start: + # make pip template + pip_pts = int(pip_dur * Fs) + 1 + pip = dbspl_to_pa(dBSPL) * rng.randn(pip_pts) # unramped stimulus + + # add ramp + ramp_pts = int(rt * Fs) + 1 + ramp = np.sin(np.linspace(0, np.pi / 2.0, ramp_pts)) ** 2 + pip[:ramp_pts] *= ramp + pip[-ramp_pts:] *= ramp[::-1] + + ts = int(np.floor(start * Fs)) + pin[ts : ts + pip.size] += pip + + return pin + + +def piptone(t, rt, Fs, F0, dBSPL, pip_dur, pip_start): + """ + Create a waveform with multiple sine-ramped tone pips. Output is in + Pascals. + + Parameters + ---------- + t : array + array of time values + rt : float + ramp duration + Fs : float + sample rate + F0 : float + pip frequency + dBSPL : float + maximum sound pressure level of pip + pip_dur : float + duration of pip including ramps + pip_start : float + list of starting times for multiple pips + + Returns + ------- + array : + waveform + + """ + # make pip template + pip_pts = int(pip_dur * Fs) + 1 + pip_t = np.linspace(0, pip_dur, pip_pts) + pip = ( + np.sqrt(2) * dbspl_to_pa(dBSPL) * np.sin(2 * np.pi * F0 * pip_t) + ) # unramped stimulus + + # add ramp + ramp_pts = int(rt * Fs) + 1 + ramp = np.sin(np.linspace(0, np.pi / 2.0, ramp_pts)) ** 2 + pip[:ramp_pts] *= ramp + pip[-ramp_pts:] *= ramp[::-1] + + # apply template to waveform + pin = np.zeros(t.size) + ps = pip_start + if ~isinstance(ps, list): + ps = [ps] + for start in pip_start: + ts = int(np.floor(start * Fs)) + pin[ts : ts + pip.size] += pip + + return pin + + +def shape_signal(signal, t, rt, Fs, F0, dBSPL, pip_dur, pip_start): + """ + Create a waveform with multiple sine-ramped tone pips, based on the + signal (so output is *always* in phase with the reference signal waveform) + Output is in Pascals. + + Parameters + ---------- + t : array + array of time values + rt : float + ramp duration (risetime) + Fs : float + sample rate + F0 : float + pip frequency + dBSPL : float + maximum sound pressure level of pip + pip_dur : float + duration of pip including ramps + pip_start : float + list of starting times for multiple pips + + Returns + ------- + array : + waveform + + """ + pip_t = t + pip_pts = pip_t.shape[0] + pip = np.sqrt(2) * dbspl_to_pa(dBSPL) * signal # referencestimulus + + # make envelope with cos2 rise-fall + ramp_pts = int(rt * Fs) + 1 + env_pts = int(pip_dur * Fs) + envelope = np.ones(env_pts) + ramp = np.sin(np.linspace(0, np.pi / 2.0, ramp_pts)) ** 2 + envelope[:ramp_pts] *= ramp + envelope[-ramp_pts:] *= ramp[::-1] + + # apply envelope template to waveform + pin = np.zeros(t.size) + ps = pip_start + if ~isinstance(ps, list): + ps = [ps] + for start in pip_start: + ts = int(np.floor(start * Fs)) + pin[ts : ts + envelope.size] += pip[ts : ts + envelope.size] * envelope + + return pin + + +def clicks(t, Fs, dBSPL, click_duration, click_starts): + """ + Create a waveform with multiple retangular clicks. Output is in + Pascals. + + Parameters + ---------- + t : array + array of time values + Fs : float + sample frequency (Hz) + click_start : float (seconds) + delay to first click in train + click_duration : float (seconds) + duration of each click + click_interval : float (seconds) + interval between click starts + nclicks : int + number of clicks in the click train + dspl : float + maximum sound pressure level of pip + + Returns + ------- + array : + waveform + + """ + swave = np.zeros(t.size) + amp = dbspl_to_pa(dBSPL) + td = int(np.floor(click_duration * Fs)) + nclicks = len(click_starts) + for n in range(nclicks): + t0s = click_starts[n] # time for nth click + t0 = int(np.floor(t0s * Fs)) # index + if t0 + td > t.size: + raise ValueError("Clicks: train duration exceeds waveform duration") + swave[t0 : t0 + td] = amp + return swave + + +def fmsweep(t, start, duration, freqs, ramp, dBSPL): + """ + Create a waveform for an FM sweep over time. Output is in + Pascals. + + Parameters + ---------- + t : array + time array for waveform + start : float (seconds) + start time for sweep + duration : float (seconds) + duration of sweep + freqs : array (Hz) + Two-element array specifying the start and end frequency of the sweep + ramp : str + The shape of time course of the sweep (linear, logarithmic) + dBSPL : float + maximum sound pressure level of sweep + + Returns + ------- + array : + waveform + + + """ + + sw = scipy.signal.chirp( + t, freqs[0], duration, freqs[1], method=ramp, phi=0, vertex_zero=True + ) + sw = np.sqrt(2) * dbspl_to_pa(dBSPL) * sw + return sw + + +def make_ssn(rate, duration, sig, samplingrate): + """ + Speech-shaped noise + Adapted from http://www.srmathias.com/speech-shaped-noise/ + Created on Thu Jun 26 12:42:08 2014 + @author: smathias + """ + # note rate is currently ignored... + sig = np.array(sig).astype("float64") + if ( + rate != samplingrate + ): # interpolate to the current system sampling rate from the original rate + sig = np.interp( + np.arange(0, len(sig) / rate, 1.0 / rate), + np.arange(0, len(sig) / samplingrate), + 1.0 / samplingrate, + ) + sig = 2 * sig / np.max(sig) + z, t = noise_from_signal(sig, rate, keep_env=True) + return z, t + + +def noise_from_signal(x, fs=40000, keep_env=True): + """Create a noise with same spectrum as the input signal. + Parameters + ---------- + x : array_like + Input signal. + fs : int + Sampling frequency of the input signal. (Default value = 40000) + keep_env : bool + Apply the envelope of the original signal to the noise. (Default + value = False) + Returns + ------- + ndarray + Noise signal. + """ + x = np.asarray(x) + n_x = x.shape[-1] + n_fft = next_pow_2(n_x) + X = np.fft.rfft(x, next_pow_2(n_fft)) + # Randomize phase. + noise_mag = np.abs(X) * np.exp(2.0 * np.pi * 1j * np.random.random(X.shape[-1])) + noise = np.real(np.fft.irfft(noise_mag, n_fft)) + out = noise[:n_x] + if keep_env: + env = np.abs(scipy.signal.hilbert(x)) + [bb, aa] = scipy.signal.butter(6.0, 50.0 / (fs / 2.0)) # 50 Hz LP filter + env = scipy.signal.filtfilt(bb, aa, env) + out *= env + t = np.arange(0, (len(out)) / fs, 1.0 / fs) + return out, t diff --git a/cnmodel/util/stim.py b/cnmodel/util/stim.py new file mode 100644 index 0000000..f6f0861 --- /dev/null +++ b/cnmodel/util/stim.py @@ -0,0 +1,87 @@ +import numpy as np + + +def make_pulse(stim): + """ + Generate a pulse train for current / voltage command. Returns a tuple. + + + Parameters + ---------- + stim : dict + Holds parameters that determine stimulus shape: + + * delay : time before first pulse + * Sfreq : frequency of pulses + * dur : duration of one pulse or main pulse + * predur : duration of prepulse (default should be 0 for no prepulse) + * amp : pulse amplitude + * preamp : amplitude of prepulse + * PT : delay between end of train and test pulse (0 for no test) + * NP : number of pulses + * hold : holding level (optional) + * dt : timestep + + Returns + ------- + w : stimulus waveform + maxt : duration of waveform + tstims : index of each pulse in the train + """ + defaults = { + "delay": 10, + "Sfreq": 50, + "dur": 100, + "predur": 0.0, + "post": 50.0, + "amp": None, + "preamp": 0.0, + "PT": 0, + "NP": 1, + "hold": 0.0, + "dt": None, + } + for k in stim: + if k not in defaults: + raise Exception("Stim parameter '%s' not accepted." % k) + defaults.update(stim) + stim = defaults + for k, v in stim.items(): + if v is None: + raise Exception("Must specify stim parameter '%s'." % k) + + dt = stim["dt"] + delay = int(np.floor(stim["delay"] / dt)) + ipi = int(np.floor((1000.0 / stim["Sfreq"]) / dt)) + pdur = int(np.floor(stim["dur"] / dt)) + posttest = int(np.floor(stim["PT"] / dt)) + ndur = 5 + if stim["predur"] > 0.0: + predur = int(np.floor(stim["predur"] / dt)) + else: + predur = 0.0 + if stim["PT"] == 0: + ndur = 1 + + maxt = dt * (delay + predur + (ipi * (stim["NP"] + 3)) + posttest + pdur * ndur) + hold = stim.get("hold", None) + + w = np.zeros(int(np.floor(maxt / dt))) + if hold is not None: + w += hold + + # make pulse + tstims = [0] * int(stim["NP"]) + for j in range(0, int(stim["NP"])): + prestart = delay + start = int(prestart + predur + j * ipi) + if predur > 0.0: + w[prestart : prestart + predur] = stim["preamp"] + w[start : start + pdur] = stim["amp"] + tstims[j] = start + if stim["PT"] > 0.0: + for i in range(start + posttest, start + posttest + pdur): + w[i] = stim["amp"] + w = np.append(w, 0.0) + maxt = maxt + dt + return (w, maxt, tstims) diff --git a/cnmodel/util/talbotetalTicks.py b/cnmodel/util/talbotetalTicks.py new file mode 100644 index 0000000..a86bd95 --- /dev/null +++ b/cnmodel/util/talbotetalTicks.py @@ -0,0 +1,208 @@ +import math +import numpy as np + +# import matplotlib +# import matplotlib.pyplot as plt +# import matplotlib.ticker as tckr +# import matplotlib.transforms as mtransforms +# import matplotlib.mlab as mlab + +# An alpha version of the Talbot, Lin, Hanrahan tick mark generator for matplotlib. +# Described in "An Extension of Wilkinson's Algorithm for Positioning Tick Labels on Axes" +# by Justin Talbot, Sharon Lin, and Pat Hanrahan, InfoVis 2010. + +# Implementation by Justin Talbot +# This implementation is in the public domain. +# Report bugs to jtalbot@stanford.edu + +# A shortcoming: +# The weights used in the paper were designed for static plots where the extent of +# the tick marks unioned with the extent of the data defines the extent of the plot. +# In a plot where the extent of the plot is defined by the user (e.g. an interactive +# plot supporting panning and zooming), the weights don't work as well. In particular, +# you would want to retune them assuming that the tick labels must be inside +# the provided view range. You probably want higher weighting on simplicity and lower +# on coverage and possibly density. But I haven't experimented in any detail with this. +# +# If you do intend on using this for static plots in matplotlib, you should set +# only_inside to False in the call to Extended.extended. And then you should +# manually set your view extent to include the min and max ticks if they are outside +# the data range. This should produce the same results as the paper. + +# class Extended(tckr.Locator): +class Extended: + # density is labels per inch + def __init__(self, density=1, steps=None, figure=None, range=(0, 1), axis="x"): + """ + Keyword args: + """ + self._density = density + self._figure = figure + self._axis = axis + self.range = range + + if steps is None: + self._steps = [1, 5, 2, 2.5, 4, 3] + else: + self._steps = steps + + def coverage(self, dmin, dmax, lmin, lmax): + range = dmax - dmin + return 1 - 0.5 * ( + math.pow(dmax - lmax, 2) + math.pow(dmin - lmin, 2) + ) / math.pow(0.1 * range, 2) + + def coverage_max(self, dmin, dmax, span): + range = dmax - dmin + if span > range: + half = (span - range) / 2.0 + return 1 - math.pow(half, 2) / math.pow(0.1 * range, 2) + else: + return 1 + + def density(self, k, m, dmin, dmax, lmin, lmax): + r = (k - 1.0) / (lmax - lmin) + rt = (m - 1.0) / (max(lmax, dmax) - min(lmin, dmin)) + return 2 - max(r / rt, rt / r) + + def density_max(self, k, m): + if k >= m: + return 2 - (k - 1.0) / (m - 1.0) + else: + return 1 + + def simplicity(self, q, Q, j, lmin, lmax, lstep): + eps = 1e-10 + n = len(Q) + i = Q.index(q) + 1 + v = ( + 1 + if ( + (lmin % lstep < eps or (lstep - lmin % lstep) < eps) + and lmin <= 0 + and lmax >= 0 + ) + else 0 + ) + return (n - i) / (n - 1.0) + v - j + + def simplicity_max(self, q, Q, j): + n = len(Q) + i = Q.index(q) + 1 + v = 1 + return (n - i) / (n - 1.0) + v - j + + def legibility(self, lmin, lmax, lstep): + return 1 + + def legibility_max(self, lmin, lmax, lstep): + return 1 + + def extended( + self, + dmin, + dmax, + m, + Q=[1, 5, 2, 2.5, 4, 3], + only_inside=False, + w=[0.25, 0.2, 0.5, 0.05], + ): + n = len(Q) + best_score = -2.0 + + j = 1.0 + while j < float("infinity"): + for q in Q: + sm = self.simplicity_max(q, Q, j) + + if w[0] * sm + w[1] + w[2] + w[3] < best_score: + j = float("infinity") + break + + k = 2.0 + while k < float("infinity"): + dm = self.density_max(k, m) + + if w[0] * sm + w[1] + w[2] * dm + w[3] < best_score: + break + + delta = (dmax - dmin) / (k + 1.0) / j / q + z = math.ceil(math.log(delta, 10)) + + while z < float("infinity"): + step = j * q * math.pow(10, z) + cm = self.coverage_max(dmin, dmax, step * (k - 1.0)) + + if w[0] * sm + w[1] * cm + w[2] * dm + w[3] < best_score: + break + + min_start = math.floor(dmax / step) * j - (k - 1.0) * j + max_start = math.ceil(dmin / step) * j + + if min_start > max_start: + z = z + 1 + break + + for start in range(int(min_start), int(max_start) + 1): + lmin = start * (step / j) + lmax = lmin + step * (k - 1.0) + lstep = step + + s = self.simplicity(q, Q, j, lmin, lmax, lstep) + c = self.coverage(dmin, dmax, lmin, lmax) + d = self.density(k, m, dmin, dmax, lmin, lmax) + l = self.legibility(lmin, lmax, lstep) + + score = w[0] * s + w[1] * c + w[2] * d + w[3] * l + + if score > best_score and ( + not only_inside or (lmin >= dmin and lmax <= dmax) + ): + best_score = score + best = (lmin, lmax, lstep, q, k) + z = z + 1 + k = k + 1 + j = j + 1 + return best + + def __call__(self): + vmin, vmax = self.range # self.axis.get_view_interval() + fsize = {"x": 5.0, "y": 4.0} + size = fsize[self._axis] # self._figure.get_size_inches()[self._axis] + # density * size gives target number of intervals, + # density * size + 1 gives target number of tick marks, + # the density function converts this back to a density in data units (not inches) + # should probably make this cleaner. + best = self.extended( + vmin, + vmax, + self._density * size + 1.0, + only_inside=True, + w=[0.25, 0.2, 0.5, 0.05], + ) + locs = np.arange(best[4]) * best[2] + best[0] + return locs + + +if __name__ == "__main__": + pass + # fig = plt.figure() + # ax = fig.add_subplot(111) + # ax.plot(10*np.random.randn(100), 10*np.random.randn(100), 'o') + # + # xmin, xmax = ax.xaxis.get_data_interval() + # xrange = xmax-xmin + # xmin, xmax = (xmin - xrange * 0.05, xmax + xrange * 0.05) + # + # ymin, ymax = ax.yaxis.get_data_interval() + # yrange = ymax-ymin + # ymin, ymax = (ymin - yrange * 0.05, ymax + yrange * 0.05) + # + # ax.xaxis.set_view_interval(xmin, xmax, ignore=True) + # ax.yaxis.set_view_interval(ymin, ymax, ignore=True) + # ax.xaxis.set_major_locator(Extended(density=0.5, figure=fig, which=0)) + # ax.yaxis.set_major_locator(Extended(density=0.5, figure=fig, which=1)) + # + # ax.set_title('Talbot, Lin, Hanrahan 2010') + # + # plt.show() diff --git a/cnmodel/util/tests/test_expfitting.py b/cnmodel/util/tests/test_expfitting.py new file mode 100644 index 0000000..cf81900 --- /dev/null +++ b/cnmodel/util/tests/test_expfitting.py @@ -0,0 +1,36 @@ +from __future__ import print_function +from cnmodel.util import ExpFitting +import numpy as np + + +def test_fit1(): + fit = ExpFitting(nexp=1) + x = np.linspace(0.0, 50, 500) + p = [-50.0, 4.0, 5.0] + y = p[0] + p[1] * np.exp(-x / p[2]) + res = fit.fit(x, y, fit.fitpars) + pr = [float(res[k].value) for k in res.keys()] + print("\noriginal: ", p) + print("fit res: ", pr) + for i, v in enumerate(p): + assert np.allclose(v, pr[i]) + + +def test_fit2(): + fit = ExpFitting(nexp=2) + x = np.linspace(0.0, 50, 500) + p = [ + -50.0, + 4.0, + 5.0, + 1.0, + 4.5, + ] # last term is ratio of the two time constants (t2 = delta*t1) + y = p[0] + p[1] * np.exp(-x / p[2]) + p[3] * np.exp(-x / (p[2] * p[4])) + res = fit.fit(x, y, fit.fitpars) + pr = [float(res[k].value) for k in res.keys()] + print("\noriginal: ", p) + print("fit res: ", pr) + # we can only do this approximately for 2 exp fits + for i, v in enumerate(p): # test each one individually + assert np.allclose(pr[i] / v, 1.0, atol=1e-4, rtol=1e-2) diff --git a/cnmodel/util/tests/test_matlab.py b/cnmodel/util/tests/test_matlab.py new file mode 100644 index 0000000..d240b23 --- /dev/null +++ b/cnmodel/util/tests/test_matlab.py @@ -0,0 +1,40 @@ +import pytest +import numpy as np + +# from cnmodel.util.matlab_proc import MatlabProcess +import matlab.engine + + +def test_matlab(): + global proc + try: + # proc = MatlabProcess() + proc = matlab.engine.start_matlab() + except RuntimeError: + # no matlab available; skip this test + pytest.skip("MATLAB unavailable") + + base_vcount = proc.who(nargout=1) # .shape[0] + assert len(base_vcount) == 0 + + e4 = np.array(proc.eye(4, nargout=1)) + + assert isinstance(e4, np.ndarray) + assert np.all(e4 == np.eye(4)) + # assert proc.who().shape[0] == base_vcount + + o6_ref = np.array(proc.ones(6, nargout=1)) # _transfer=False)) + # o6 = o6_ref.get() + o6 = np.array(proc.ones(6, nargout=1)) + assert np.all(o6 == np.ones(6)) + # print(proc.who(nargout=1)) + # assert proc.who(nargout=1) == base_vcount + 1 + + del o6_ref + # assert proc.who().shape[0] == base_vcount + + proc.close() + + +if __name__ == "__main__": + test_matlab() diff --git a/cnmodel/util/tests/test_sound.py b/cnmodel/util/tests/test_sound.py new file mode 100644 index 0000000..fe39007 --- /dev/null +++ b/cnmodel/util/tests/test_sound.py @@ -0,0 +1,98 @@ +import numpy as np +from cnmodel.util import sound + + +def test_conversions(): + pa = np.array([3990.5, 20, 0.3639, 2e-5]) + db = np.array([166, 120, 85.2, 0]) + + assert np.allclose(sound.pa_to_dbspl(pa), db, atol=0.1, rtol=0.002) + assert np.allclose(sound.dbspl_to_pa(db), pa, atol=0.1, rtol=0.002) + + +def test_tonepip(): + rate = 100000 + dur = 0.1 + ps = 0.01 + rd = 0.02 + pd = 0.08 + db = 60 + s1 = sound.TonePip( + rate=rate, + duration=dur, + f0=5321, + dbspl=db, + pip_duration=pd, + pip_start=[ps], + ramp_duration=rd, + ) + + # test array sizes + assert s1.sound.size == s1.time.size == int(dur * rate) + 1 + + # test for consistency + assert np.allclose( + [s1.sound.min(), s1.sound.mean(), s1.sound.max()], + [-0.028284253158247834, -1.0954891976168953e-10, 0.028284270354167296], + ) + + # test that we got the requested amplitude + assert np.allclose(s1.measure_dbspl(ps + rd, ps + pd - rd), db, atol=0.1, rtol=0.01) + + # test for quiet before and after pip + assert np.all(s1.sound[: int(ps * rate) - 1] == 0) + assert np.all(s1.sound[int((ps + pd) * rate) + 1 :] == 0) + + # test the sound can be recreated from its key + key = s1.key() + s2 = sound.create(**key) + assert np.all(s1.time == s2.time) + assert np.all(s1.sound == s2.sound) + + +def test_noisepip(): + rate = 100000 + dur = 0.1 + ps = 0.01 + rd = 0.02 + pd = 0.08 + db = 60 + s1 = sound.NoisePip( + rate=rate, + duration=dur, + seed=184724, + dbspl=db, + pip_duration=pd, + pip_start=[ps], + ramp_duration=rd, + ) + + # test array sizes + assert s1.sound.size == s1.time.size == int(dur * rate) + 1 + + # test for consistency + assert np.allclose( + [s1.sound.min(), s1.sound.mean(), s1.sound.max()], + [-0.082260796003197786, -0.00018484322982972046, 0.069160217220832404], + ) + + # test that we got the requested amplitude + assert np.allclose(s1.measure_dbspl(ps + rd, ps + pd - rd), db, atol=0.1, rtol=0.01) + + # test for quiet before and after pip + assert np.all(s1.sound[: int(ps * rate) - 1] == 0) + assert np.all(s1.sound[int((ps + pd) * rate) + 1 :] == 0) + + # test the sound can be recreated from its key + key = s1.key() + s2 = sound.create(**key) + # also test new seed works, and does not affect other sounds + key["seed"] += 1 + s3 = sound.create(**key) + s3.sound # generate here to advance rng before generating s2 + + assert np.all(s1.time == s2.time) + assert np.all(s1.sound == s2.sound) + start = int(ps * rate) + 1 + end = int((ps + pd) * rate) - 1 + assert not np.any(s1.sound[start:end] == s3.sound[start:end]) diff --git a/cnmodel/util/tests/test_stim.py b/cnmodel/util/tests/test_stim.py new file mode 100644 index 0000000..2991c92 --- /dev/null +++ b/cnmodel/util/tests/test_stim.py @@ -0,0 +1,29 @@ +import numpy as np +from numpy.testing import assert_raises + +from cnmodel.util import stim +from neuron import h + +h.dt = 0.025 + + +def test_make_pulse(): + params = dict(delay=10, Sfreq=50, dur=1, amp=15, PT=0, NP=5) + + assert_raises(Exception, lambda: stim.make_pulse(params)) + params["dt"] = 0.025 + + w, maxt, times = stim.make_pulse(params) + + assert w.min() == 0.0 + assert w.max() == 15 + assert w.dtype == np.float64 + + triggers = np.argwhere(np.diff(w) > 0)[:, 0] + 1 + assert np.all(triggers == times) + assert w.sum() == 15 * len(times) * int(1 / h.dt) + + params["PT"] = 100 + w, maxt, times = stim.make_pulse(params) + triggers = np.argwhere(np.diff(w) > 0)[:, 0] + 1 + assert triggers[-1] - triggers[-2] == 100 / h.dt diff --git a/cnmodel/util/user_tester.py b/cnmodel/util/user_tester.py new file mode 100644 index 0000000..f410f41 --- /dev/null +++ b/cnmodel/util/user_tester.py @@ -0,0 +1,205 @@ +from __future__ import print_function +import os, sys, pickle, pprint +import numpy as np +import pyqtgraph as pg +from .. import AUDIT_TESTS + + +class UserTester(object): + """ + Base class for testing when a human is required to verify the results. + + When a test is passed by the user, its output is saved and used as a basis + for future tests. If future test results do not match the stored results, + then the user is asked to decide whether to fail the test, or pass the + test and store new results. + + Subclasses must reimplement run_test() to return a dictionary of results + to store. Optionally, compare_results and audit_result may also be + reimplemented to customize the testing behavior. + + By default, test results are stored in a 'test_data' directory relative + to the file that defines the UserTester subclass in use. + """ + + data_dir = "test_data" + + def __init__(self, key, *args, **kwds): + """Initialize with a string *key* that provides a short, unique + description of this test. All other arguments are passed to run_test(). + + *key* is used to determine the file name for storing test results. + """ + self.audit = AUDIT_TESTS + self.key = key + self.rtol = 1e-3 + self.args = args + self.assert_test_info(*args, **kwds) + + def run_test(self, *args, **kwds): + """ + Exceute the test. All arguments are taken from __init__. + Return a picklable dictionary of test results. + """ + raise NotImplementedError() + + def compare_results(self, key, info, expect): + """ + Compare *result* of the current test against the previously stored + result *expect*. If *expect* is None, then no previous result was + stored. + + If *result* and *expect* do not match, then raise an exception. + """ + # Check test structures are the same + assert type(info) is type(expect) + if hasattr(info, "__len__"): + assert len(info) == len(expect) + + if isinstance(info, dict): + for k in info: + assert k in expect + for k in expect: + assert k in info + self.compare_results(k, info[k], expect[k]) + elif isinstance(info, list): + for i in range(len(info)): + self.compare_results(key, info[i], expect[i]) + elif isinstance(info, np.ndarray): + assert info.shape == expect.shape + if len(info) == 0: + return + # assert info.dtype == expect.dtype + if info.dtype.fields is None: + intnan = -9223372036854775808 # happens when np.nan is cast to int + inans = np.isnan(info) | (info == intnan) + enans = np.isnan(expect) | (expect == intnan) + assert np.all(inans == enans) + mask = ~inans + if not np.allclose(info[mask], expect[mask], rtol=self.rtol): + print( + "\nComparing data array, shapes match: ", + info.shape == expect.shape, + ) + print("Model tested: %s, measure: %s" % (self.key, key)) + # print( 'args: ', dir(self.args[0])) + print("Array expected: ", expect[mask]) + print("Array received: ", info[mask]) + try: + self.args[0].print_all_mechs() + except: + print("args[0] is string: ", self.args[0]) + assert np.allclose(info[mask], expect[mask], rtol=self.rtol) + else: + for k in info.dtype.fields.keys(): + self.compare_results(k, info[k], expect[k]) + elif np.isscalar(info): + if not np.allclose(info, expect, rtol=self.rtol): + print("Comparing Scalar data, model: %s, measure: %s" % (self.key, key)) + # print 'args: ', dir(self.args[0]) + print( + "Expected: ", + expect, + ", received: ", + info, + " relative tolerance: ", + self.rtol, + ) + if isinstance(self.args[0], str): + pass + # print ': ', str + else: + self.args[0].print_all_mechs() + assert np.allclose(info, expect, rtol=self.rtol) + else: + try: + assert info == expect + except AssertionError: + raise + except Exception: + raise NotImplementedError( + "Cannot compare objects of type %s" % type(info) + ) + + def audit_result(self, info, expect): + """ Display results and ask the user to decide whether the test passed. + Return True for pass, False for fail. + + If *expect* is None, then no previous test results were stored. + """ + app = pg.mkQApp() + print("\n=== New test results for %s: ===\n" % self.key) + pprint.pprint(info) + + # we use DiffTreeWidget to display differences between large data structures, but + # this is not present in mainline pyqtgraph yet + if hasattr(pg, "DiffTreeWidget"): + win = pg.DiffTreeWidget() + else: + from cnmodel.util.difftreewidget import DiffTreeWidget + + win = DiffTreeWidget() + + win.resize(800, 800) + win.setData(expect, info) + win.show() + print("Store new test results? [y/n]") + yn = raw_input() + win.hide() + return yn.lower().startswith("y") + + def assert_test_info(self, *args, **kwds): + """ + Test *cell* and raise exception if the results do not match prior + data. + """ + result = self.run_test(*args, **kwds) + expect = self.load_test_result() + try: + assert expect is not None + self.compare_results(None, result, expect) + except: + if not self.audit: + if expect is None: + raise Exception( + "No prior test results for test '%s'. " + "Run test.py --audit store new test data." % self.key + ) + else: + raise + + store = self.audit_result(result, expect) + if store: + self.save_test_result(result) + else: + raise Exception("Rejected test results for '%s'" % self.key) + + def result_file(self): + """ + Return a file name to be used for storing / retrieving test results + given *self.key*. + """ + modfile = sys.modules[self.__class__.__module__].__file__ + path = os.path.dirname(modfile) + return os.path.join(path, self.data_dir, self.key + ".pk") + + def load_test_result(self): + """ + Load prior test results for *self.key*. + If there are no prior results, return None. + """ + fn = self.result_file() + if os.path.isfile(fn): + return pickle.load(open(fn, "rb"), encoding="latin1") + return None + + def save_test_result(self, result): + """ + Store test results for *self.key*. + Th e*result* argument must be picklable. + """ + fn = self.result_file() + dirname = os.path.dirname(fn) + if not os.path.isdir(dirname): + os.mkdir(dirname) + pickle.dump(result, open(fn, "wb")) diff --git a/doc/Makefile b/doc/Makefile new file mode 100644 index 0000000..1eadde6 --- /dev/null +++ b/doc/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SPHINXPROJ = CNModel +SOURCEDIR = source +BUILDDIR = build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/doc/make.bat b/doc/make.bat new file mode 100644 index 0000000..b1825ae --- /dev/null +++ b/doc/make.bat @@ -0,0 +1,242 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source +set I18NSPHINXOPTS=%SPHINXOPTS% source +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. xml to make Docutils-native XML files + echo. pseudoxml to make pseudoxml-XML files for display purposes + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + + +%SPHINXBUILD% 2> nul +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\cnmodel.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\cnmodel.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdf" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdfja" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf-ja + cd %BUILDDIR%/.. + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +if "%1" == "xml" ( + %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The XML files are in %BUILDDIR%/xml. + goto end +) + +if "%1" == "pseudoxml" ( + %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. + goto end +) + +:end diff --git a/doc/numpydoc-0.5/LICENSE.txt b/doc/numpydoc-0.5/LICENSE.txt new file mode 100644 index 0000000..b15c699 --- /dev/null +++ b/doc/numpydoc-0.5/LICENSE.txt @@ -0,0 +1,94 @@ +------------------------------------------------------------------------------- + The files + - numpydoc.py + - docscrape.py + - docscrape_sphinx.py + - phantom_import.py + have the following license: + +Copyright (C) 2008 Stefan van der Walt , Pauli Virtanen + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING +IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------------------- + The files + - compiler_unparse.py + - comment_eater.py + - traitsdoc.py + have the following license: + +This software is OSI Certified Open Source Software. +OSI Certified is a certification mark of the Open Source Initiative. + +Copyright (c) 2006, Enthought, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of Enthought, Inc. nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +------------------------------------------------------------------------------- + The file + - plot_directive.py + originates from Matplotlib (http://matplotlib.sf.net/) which has + the following license: + +Copyright (c) 2002-2008 John D. Hunter; All Rights Reserved. + +1. This LICENSE AGREEMENT is between John D. Hunter (“JDH”), and the Individual or Organization (“Licensee”) accessing and otherwise using matplotlib software in source or binary form and its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, JDH hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use matplotlib 0.98.3 alone or in any derivative version, provided, however, that JDH’s License Agreement and JDH’s notice of copyright, i.e., “Copyright (c) 2002-2008 John D. Hunter; All Rights Reserved” are retained in matplotlib 0.98.3 alone or in any derivative version prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on or incorporates matplotlib 0.98.3 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to matplotlib 0.98.3. + +4. JDH is making matplotlib 0.98.3 available to Licensee on an “AS IS” basis. JDH MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, JDH MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIB 0.98.3 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. + +5. JDH SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB 0.98.3 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING MATPLOTLIB 0.98.3, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between JDH and Licensee. This License Agreement does not grant permission to use JDH trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using matplotlib 0.98.3, Licensee agrees to be bound by the terms and conditions of this License Agreement. + diff --git a/doc/numpydoc-0.5/MANIFEST.in b/doc/numpydoc-0.5/MANIFEST.in new file mode 100644 index 0000000..5176d48 --- /dev/null +++ b/doc/numpydoc-0.5/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include numpydoc/tests *.py +include *.txt diff --git a/doc/numpydoc-0.5/PKG-INFO b/doc/numpydoc-0.5/PKG-INFO new file mode 100644 index 0000000..c363407 --- /dev/null +++ b/doc/numpydoc-0.5/PKG-INFO @@ -0,0 +1,16 @@ +Metadata-Version: 1.1 +Name: numpydoc +Version: 0.5 +Summary: Sphinx extension to support docstrings in Numpy format +Home-page: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt +Author: Pauli Virtanen and others +Author-email: pav@iki.fi +License: BSD +Description: UNKNOWN +Keywords: sphinx numpy +Platform: UNKNOWN +Classifier: Development Status :: 3 - Alpha +Classifier: Environment :: Plugins +Classifier: License :: OSI Approved :: BSD License +Classifier: Topic :: Documentation +Requires: sphinx (>= 1.0.1) diff --git a/doc/numpydoc-0.5/README.rst b/doc/numpydoc-0.5/README.rst new file mode 100644 index 0000000..e2711e1 --- /dev/null +++ b/doc/numpydoc-0.5/README.rst @@ -0,0 +1,57 @@ +.. image:: https://travis-ci.org/numpy/numpydoc.png?branch=master + :target: https://travis-ci.org/numpy/numpydoc/ + +===================================== +numpydoc -- Numpy's Sphinx extensions +===================================== + +Numpy's documentation uses several custom extensions to Sphinx. These +are shipped in this ``numpydoc`` package, in case you want to make use +of them in third-party projects. + +The following extensions are available: + + - ``numpydoc``: support for the Numpy docstring format in Sphinx, and add + the code description directives ``np:function``, ``np-c:function``, etc. + that support the Numpy docstring syntax. + + - ``numpydoc.traitsdoc``: For gathering documentation about Traits attributes. + + - ``numpydoc.plot_directive``: Adaptation of Matplotlib's ``plot::`` + directive. Note that this implementation may still undergo severe + changes or eventually be deprecated. + +See `A Guide to NumPy/SciPy Documentation `_ +for how to write docs that use this extension. + + +numpydoc +======== + +Numpydoc inserts a hook into Sphinx's autodoc that converts docstrings +following the Numpy/Scipy format to a form palatable to Sphinx. + +Options +------- + +The following options can be set in conf.py: + +- numpydoc_use_plots: bool + + Whether to produce ``plot::`` directives for Examples sections that + contain ``import matplotlib``. + +- numpydoc_show_class_members: bool + + Whether to show all members of a class in the Methods and Attributes + sections automatically. + +- numpydoc_class_members_toctree: bool + + Whether to create a Sphinx table of contents for the lists of class + methods and attributes. If a table of contents is made, Sphinx expects + each entry to have a separate page. + +- numpydoc_edit_link: bool (DEPRECATED -- edit your HTML template instead) + + Whether to insert an edit link after docstrings. diff --git a/doc/numpydoc-0.5/numpydoc.egg-info/PKG-INFO b/doc/numpydoc-0.5/numpydoc.egg-info/PKG-INFO new file mode 100644 index 0000000..c363407 --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc.egg-info/PKG-INFO @@ -0,0 +1,16 @@ +Metadata-Version: 1.1 +Name: numpydoc +Version: 0.5 +Summary: Sphinx extension to support docstrings in Numpy format +Home-page: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt +Author: Pauli Virtanen and others +Author-email: pav@iki.fi +License: BSD +Description: UNKNOWN +Keywords: sphinx numpy +Platform: UNKNOWN +Classifier: Development Status :: 3 - Alpha +Classifier: Environment :: Plugins +Classifier: License :: OSI Approved :: BSD License +Classifier: Topic :: Documentation +Requires: sphinx (>= 1.0.1) diff --git a/doc/numpydoc-0.5/numpydoc.egg-info/SOURCES.txt b/doc/numpydoc-0.5/numpydoc.egg-info/SOURCES.txt new file mode 100644 index 0000000..b6246c0 --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc.egg-info/SOURCES.txt @@ -0,0 +1,23 @@ +LICENSE.txt +MANIFEST.in +README.rst +setup.py +numpydoc/__init__.py +numpydoc/comment_eater.py +numpydoc/compiler_unparse.py +numpydoc/docscrape.py +numpydoc/docscrape_sphinx.py +numpydoc/linkcode.py +numpydoc/numpydoc.py +numpydoc/phantom_import.py +numpydoc/plot_directive.py +numpydoc/traitsdoc.py +numpydoc.egg-info/PKG-INFO +numpydoc.egg-info/SOURCES.txt +numpydoc.egg-info/dependency_links.txt +numpydoc.egg-info/top_level.txt +numpydoc/tests/test_docscrape.py +numpydoc/tests/test_linkcode.py +numpydoc/tests/test_phantom_import.py +numpydoc/tests/test_plot_directive.py +numpydoc/tests/test_traitsdoc.py \ No newline at end of file diff --git a/doc/numpydoc-0.5/numpydoc.egg-info/dependency_links.txt b/doc/numpydoc-0.5/numpydoc.egg-info/dependency_links.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/doc/numpydoc-0.5/numpydoc.egg-info/top_level.txt b/doc/numpydoc-0.5/numpydoc.egg-info/top_level.txt new file mode 100644 index 0000000..a2954e3 --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc.egg-info/top_level.txt @@ -0,0 +1 @@ +numpydoc diff --git a/doc/numpydoc-0.5/numpydoc/__init__.py b/doc/numpydoc-0.5/numpydoc/__init__.py new file mode 100644 index 0000000..0fce2cf --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc/__init__.py @@ -0,0 +1,3 @@ +from __future__ import division, absolute_import, print_function + +from .numpydoc import setup diff --git a/doc/numpydoc-0.5/numpydoc/comment_eater.py b/doc/numpydoc-0.5/numpydoc/comment_eater.py new file mode 100644 index 0000000..f262c2d --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc/comment_eater.py @@ -0,0 +1,181 @@ +from __future__ import division, absolute_import, print_function + +import sys + +if sys.version_info[0] >= 3: + from io import StringIO +else: + from io import StringIO + +import compiler +import inspect +import textwrap +import tokenize + +from .compiler_unparse import unparse + + +class Comment(object): + """ A comment block. + """ + + is_comment = True + + def __init__(self, start_lineno, end_lineno, text): + # int : The first line number in the block. 1-indexed. + self.start_lineno = start_lineno + # int : The last line number. Inclusive! + self.end_lineno = end_lineno + # str : The text block including '#' character but not any leading spaces. + self.text = text + + def add(self, string, start, end, line): + """ Add a new comment line. + """ + self.start_lineno = min(self.start_lineno, start[0]) + self.end_lineno = max(self.end_lineno, end[0]) + self.text += string + + def __repr__(self): + return "%s(%r, %r, %r)" % ( + self.__class__.__name__, + self.start_lineno, + self.end_lineno, + self.text, + ) + + +class NonComment(object): + """ A non-comment block of code. + """ + + is_comment = False + + def __init__(self, start_lineno, end_lineno): + self.start_lineno = start_lineno + self.end_lineno = end_lineno + + def add(self, string, start, end, line): + """ Add lines to the block. + """ + if string.strip(): + # Only add if not entirely whitespace. + self.start_lineno = min(self.start_lineno, start[0]) + self.end_lineno = max(self.end_lineno, end[0]) + + def __repr__(self): + return "%s(%r, %r)" % ( + self.__class__.__name__, + self.start_lineno, + self.end_lineno, + ) + + +class CommentBlocker(object): + """ Pull out contiguous comment blocks. + """ + + def __init__(self): + # Start with a dummy. + self.current_block = NonComment(0, 0) + + # All of the blocks seen so far. + self.blocks = [] + + # The index mapping lines of code to their associated comment blocks. + self.index = {} + + def process_file(self, file): + """ Process a file object. + """ + if sys.version_info[0] >= 3: + nxt = file.__next__ + else: + nxt = file.next + for token in tokenize.generate_tokens(nxt): + self.process_token(*token) + self.make_index() + + def process_token(self, kind, string, start, end, line): + """ Process a single token. + """ + if self.current_block.is_comment: + if kind == tokenize.COMMENT: + self.current_block.add(string, start, end, line) + else: + self.new_noncomment(start[0], end[0]) + else: + if kind == tokenize.COMMENT: + self.new_comment(string, start, end, line) + else: + self.current_block.add(string, start, end, line) + + def new_noncomment(self, start_lineno, end_lineno): + """ We are transitioning from a noncomment to a comment. + """ + block = NonComment(start_lineno, end_lineno) + self.blocks.append(block) + self.current_block = block + + def new_comment(self, string, start, end, line): + """ Possibly add a new comment. + + Only adds a new comment if this comment is the only thing on the line. + Otherwise, it extends the noncomment block. + """ + prefix = line[: start[1]] + if prefix.strip(): + # Oops! Trailing comment, not a comment block. + self.current_block.add(string, start, end, line) + else: + # A comment block. + block = Comment(start[0], end[0], string) + self.blocks.append(block) + self.current_block = block + + def make_index(self): + """ Make the index mapping lines of actual code to their associated + prefix comments. + """ + for prev, block in zip(self.blocks[:-1], self.blocks[1:]): + if not block.is_comment: + self.index[block.start_lineno] = prev + + def search_for_comment(self, lineno, default=None): + """ Find the comment block just before the given line number. + + Returns None (or the specified default) if there is no such block. + """ + if not self.index: + self.make_index() + block = self.index.get(lineno, None) + text = getattr(block, "text", default) + return text + + +def strip_comment_marker(text): + """ Strip # markers at the front of a block of comment text. + """ + lines = [] + for line in text.splitlines(): + lines.append(line.lstrip("#")) + text = textwrap.dedent("\n".join(lines)) + return text + + +def get_class_traits(klass): + """ Yield all of the documentation for trait definitions on a class object. + """ + # FIXME: gracefully handle errors here or in the caller? + source = inspect.getsource(klass) + cb = CommentBlocker() + cb.process_file(StringIO(source)) + mod_ast = compiler.parse(source) + class_ast = mod_ast.node.nodes[0] + for node in class_ast.code.nodes: + # FIXME: handle other kinds of assignments? + if isinstance(node, compiler.ast.Assign): + name = node.nodes[0].name + rhs = unparse(node.expr).strip() + doc = strip_comment_marker(cb.search_for_comment(node.lineno, default="")) + yield name, rhs, doc diff --git a/doc/numpydoc-0.5/numpydoc/compiler_unparse.py b/doc/numpydoc-0.5/numpydoc/compiler_unparse.py new file mode 100644 index 0000000..b69c66e --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc/compiler_unparse.py @@ -0,0 +1,882 @@ +""" Turn compiler.ast structures back into executable python code. + + The unparse method takes a compiler.ast tree and transforms it back into + valid python code. It is incomplete and currently only works for + import statements, function calls, function definitions, assignments, and + basic expressions. + + Inspired by python-2.5-svn/Demo/parser/unparse.py + + fixme: We may want to move to using _ast trees because the compiler for + them is about 6 times faster than compiler.compile. +""" +from __future__ import division, absolute_import, print_function + +import sys +from compiler.ast import Const, Name, Tuple, Div, Mul, Sub, Add + +if sys.version_info[0] >= 3: + from io import StringIO +else: + from StringIO import StringIO + + +def unparse(ast, single_line_functions=False): + s = StringIO() + UnparseCompilerAst(ast, s, single_line_functions) + return s.getvalue().lstrip() + + +op_precedence = { + "compiler.ast.Power": 3, + "compiler.ast.Mul": 2, + "compiler.ast.Div": 2, + "compiler.ast.Add": 1, + "compiler.ast.Sub": 1, +} + + +class UnparseCompilerAst: + """ Methods in this class recursively traverse an AST and + output source code for the abstract syntax; original formatting + is disregarged. + """ + + ######################################################################### + # object interface. + ######################################################################### + + def __init__(self, tree, file=sys.stdout, single_line_functions=False): + """ Unparser(tree, file=sys.stdout) -> None. + + Print the source for tree to file. + """ + self.f = file + self._single_func = single_line_functions + self._do_indent = True + self._indent = 0 + self._dispatch(tree) + self._write("\n") + self.f.flush() + + ######################################################################### + # Unparser private interface. + ######################################################################### + + ### format, output, and dispatch methods ################################ + + def _fill(self, text=""): + "Indent a piece of text, according to the current indentation level" + if self._do_indent: + self._write("\n" + " " * self._indent + text) + else: + self._write(text) + + def _write(self, text): + "Append a piece of text to the current line." + self.f.write(text) + + def _enter(self): + "Print ':', and increase the indentation." + self._write(": ") + self._indent += 1 + + def _leave(self): + "Decrease the indentation level." + self._indent -= 1 + + def _dispatch(self, tree): + "_dispatcher function, _dispatching tree type T to method _T." + if isinstance(tree, list): + for t in tree: + self._dispatch(t) + return + meth = getattr(self, "_" + tree.__class__.__name__) + if tree.__class__.__name__ == "NoneType" and not self._do_indent: + return + meth(tree) + + ######################################################################### + # compiler.ast unparsing methods. + # + # There should be one method per concrete grammar type. They are + # organized in alphabetical order. + ######################################################################### + + def _Add(self, t): + self.__binary_op(t, "+") + + def _And(self, t): + self._write(" (") + for i, node in enumerate(t.nodes): + self._dispatch(node) + if i != len(t.nodes) - 1: + self._write(") and (") + self._write(")") + + def _AssAttr(self, t): + """ Handle assigning an attribute of an object + """ + self._dispatch(t.expr) + self._write("." + t.attrname) + + def _Assign(self, t): + """ Expression Assignment such as "a = 1". + + This only handles assignment in expressions. Keyword assignment + is handled separately. + """ + self._fill() + for target in t.nodes: + self._dispatch(target) + self._write(" = ") + self._dispatch(t.expr) + if not self._do_indent: + self._write("; ") + + def _AssName(self, t): + """ Name on left hand side of expression. + + Treat just like a name on the right side of an expression. + """ + self._Name(t) + + def _AssTuple(self, t): + """ Tuple on left hand side of an expression. + """ + + # _write each elements, separated by a comma. + for element in t.nodes[:-1]: + self._dispatch(element) + self._write(", ") + + # Handle the last one without writing comma + last_element = t.nodes[-1] + self._dispatch(last_element) + + def _AugAssign(self, t): + """ +=,-=,*=,/=,**=, etc. operations + """ + + self._fill() + self._dispatch(t.node) + self._write(" " + t.op + " ") + self._dispatch(t.expr) + if not self._do_indent: + self._write(";") + + def _Bitand(self, t): + """ Bit and operation. + """ + + for i, node in enumerate(t.nodes): + self._write("(") + self._dispatch(node) + self._write(")") + if i != len(t.nodes) - 1: + self._write(" & ") + + def _Bitor(self, t): + """ Bit or operation + """ + + for i, node in enumerate(t.nodes): + self._write("(") + self._dispatch(node) + self._write(")") + if i != len(t.nodes) - 1: + self._write(" | ") + + def _CallFunc(self, t): + """ Function call. + """ + self._dispatch(t.node) + self._write("(") + comma = False + for e in t.args: + if comma: + self._write(", ") + else: + comma = True + self._dispatch(e) + if t.star_args: + if comma: + self._write(", ") + else: + comma = True + self._write("*") + self._dispatch(t.star_args) + if t.dstar_args: + if comma: + self._write(", ") + else: + comma = True + self._write("**") + self._dispatch(t.dstar_args) + self._write(")") + + def _Compare(self, t): + self._dispatch(t.expr) + for op, expr in t.ops: + self._write(" " + op + " ") + self._dispatch(expr) + + def _Const(self, t): + """ A constant value such as an integer value, 3, or a string, "hello". + """ + self._dispatch(t.value) + + def _Decorators(self, t): + """ Handle function decorators (eg. @has_units) + """ + for node in t.nodes: + self._dispatch(node) + + def _Dict(self, t): + self._write("{") + for i, (k, v) in enumerate(t.items): + self._dispatch(k) + self._write(": ") + self._dispatch(v) + if i < len(t.items) - 1: + self._write(", ") + self._write("}") + + def _Discard(self, t): + """ Node for when return value is ignored such as in "foo(a)". + """ + self._fill() + self._dispatch(t.expr) + + def _Div(self, t): + self.__binary_op(t, "/") + + def _Ellipsis(self, t): + self._write("...") + + def _From(self, t): + """ Handle "from xyz import foo, bar as baz". + """ + # fixme: Are From and ImportFrom handled differently? + self._fill("from ") + self._write(t.modname) + self._write(" import ") + for i, (name, asname) in enumerate(t.names): + if i != 0: + self._write(", ") + self._write(name) + if asname is not None: + self._write(" as " + asname) + + def _Function(self, t): + """ Handle function definitions + """ + if t.decorators is not None: + self._fill("@") + self._dispatch(t.decorators) + self._fill("def " + t.name + "(") + defaults = [None] * (len(t.argnames) - len(t.defaults)) + list(t.defaults) + for i, arg in enumerate(zip(t.argnames, defaults)): + self._write(arg[0]) + if arg[1] is not None: + self._write("=") + self._dispatch(arg[1]) + if i < len(t.argnames) - 1: + self._write(", ") + self._write(")") + if self._single_func: + self._do_indent = False + self._enter() + self._dispatch(t.code) + self._leave() + self._do_indent = True + + def _Getattr(self, t): + """ Handle getting an attribute of an object + """ + if isinstance(t.expr, (Div, Mul, Sub, Add)): + self._write("(") + self._dispatch(t.expr) + self._write(")") + else: + self._dispatch(t.expr) + + self._write("." + t.attrname) + + def _If(self, t): + self._fill() + + for i, (compare, code) in enumerate(t.tests): + if i == 0: + self._write("if ") + else: + self._write("elif ") + self._dispatch(compare) + self._enter() + self._fill() + self._dispatch(code) + self._leave() + self._write("\n") + + if t.else_ is not None: + self._write("else") + self._enter() + self._fill() + self._dispatch(t.else_) + self._leave() + self._write("\n") + + def _IfExp(self, t): + self._dispatch(t.then) + self._write(" if ") + self._dispatch(t.test) + + if t.else_ is not None: + self._write(" else (") + self._dispatch(t.else_) + self._write(")") + + def _Import(self, t): + """ Handle "import xyz.foo". + """ + self._fill("import ") + + for i, (name, asname) in enumerate(t.names): + if i != 0: + self._write(", ") + self._write(name) + if asname is not None: + self._write(" as " + asname) + + def _Keyword(self, t): + """ Keyword value assignment within function calls and definitions. + """ + self._write(t.name) + self._write("=") + self._dispatch(t.expr) + + def _List(self, t): + self._write("[") + for i, node in enumerate(t.nodes): + self._dispatch(node) + if i < len(t.nodes) - 1: + self._write(", ") + self._write("]") + + def _Module(self, t): + if t.doc is not None: + self._dispatch(t.doc) + self._dispatch(t.node) + + def _Mul(self, t): + self.__binary_op(t, "*") + + def _Name(self, t): + self._write(t.name) + + def _NoneType(self, t): + self._write("None") + + def _Not(self, t): + self._write("not (") + self._dispatch(t.expr) + self._write(")") + + def _Or(self, t): + self._write(" (") + for i, node in enumerate(t.nodes): + self._dispatch(node) + if i != len(t.nodes) - 1: + self._write(") or (") + self._write(")") + + def _Pass(self, t): + self._write("pass\n") + + def _Printnl(self, t): + self._fill("print ") + if t.dest: + self._write(">> ") + self._dispatch(t.dest) + self._write(", ") + comma = False + for node in t.nodes: + if comma: + self._write(", ") + else: + comma = True + self._dispatch(node) + + def _Power(self, t): + self.__binary_op(t, "**") + + def _Return(self, t): + self._fill("return ") + if t.value: + if isinstance(t.value, Tuple): + text = ", ".join([name.name for name in t.value.asList()]) + self._write(text) + else: + self._dispatch(t.value) + if not self._do_indent: + self._write("; ") + + def _Slice(self, t): + self._dispatch(t.expr) + self._write("[") + if t.lower: + self._dispatch(t.lower) + self._write(":") + if t.upper: + self._dispatch(t.upper) + # if t.step: + # self._write(":") + # self._dispatch(t.step) + self._write("]") + + def _Sliceobj(self, t): + for i, node in enumerate(t.nodes): + if i != 0: + self._write(":") + if not (isinstance(node, Const) and node.value is None): + self._dispatch(node) + + def _Stmt(self, tree): + for node in tree.nodes: + self._dispatch(node) + + def _Sub(self, t): + self.__binary_op(t, "-") + + def _Subscript(self, t): + self._dispatch(t.expr) + self._write("[") + for i, value in enumerate(t.subs): + if i != 0: + self._write(",") + self._dispatch(value) + self._write("]") + + def _TryExcept(self, t): + self._fill("try") + self._enter() + self._dispatch(t.body) + self._leave() + + for handler in t.handlers: + self._fill("except ") + self._dispatch(handler[0]) + if handler[1] is not None: + self._write(", ") + self._dispatch(handler[1]) + self._enter() + self._dispatch(handler[2]) + self._leave() + + if t.else_: + self._fill("else") + self._enter() + self._dispatch(t.else_) + self._leave() + + def _Tuple(self, t): + + if not t.nodes: + # Empty tuple. + self._write("()") + else: + self._write("(") + + # _write each elements, separated by a comma. + for element in t.nodes[:-1]: + self._dispatch(element) + self._write(", ") + + # Handle the last one without writing comma + last_element = t.nodes[-1] + self._dispatch(last_element) + + self._write(")") + + def _UnaryAdd(self, t): + self._write("+") + self._dispatch(t.expr) + + def _UnarySub(self, t): + self._write("-") + self._dispatch(t.expr) + + def _With(self, t): + self._fill("with ") + self._dispatch(t.expr) + if t.vars: + self._write(" as ") + self._dispatch(t.vars.name) + self._enter() + self._dispatch(t.body) + self._leave() + self._write("\n") + + def _int(self, t): + self._write(repr(t)) + + def __binary_op(self, t, symbol): + # Check if parenthesis are needed on left side and then dispatch + has_paren = False + left_class = str(t.left.__class__) + if ( + left_class in op_precedence.keys() + and op_precedence[left_class] < op_precedence[str(t.__class__)] + ): + has_paren = True + if has_paren: + self._write("(") + self._dispatch(t.left) + if has_paren: + self._write(")") + # Write the appropriate symbol for operator + self._write(symbol) + # Check if parenthesis are needed on the right side and then dispatch + has_paren = False + right_class = str(t.right.__class__) + if ( + right_class in op_precedence.keys() + and op_precedence[right_class] < op_precedence[str(t.__class__)] + ): + has_paren = True + if has_paren: + self._write("(") + self._dispatch(t.right) + if has_paren: + self._write(")") + + def _float(self, t): + # if t is 0.1, str(t)->'0.1' while repr(t)->'0.1000000000001' + # We prefer str here. + self._write(str(t)) + + def _str(self, t): + self._write(repr(t)) + + def _tuple(self, t): + self._write(str(t)) + + ######################################################################### + # These are the methods from the _ast modules unparse. + # + # As our needs to handle more advanced code increase, we may want to + # modify some of the methods below so that they work for compiler.ast. + ######################################################################### + + +# # stmt +# def _Expr(self, tree): +# self._fill() +# self._dispatch(tree.value) +# +# def _Import(self, t): +# self._fill("import ") +# first = True +# for a in t.names: +# if first: +# first = False +# else: +# self._write(", ") +# self._write(a.name) +# if a.asname: +# self._write(" as "+a.asname) +# +## def _ImportFrom(self, t): +## self._fill("from ") +## self._write(t.module) +## self._write(" import ") +## for i, a in enumerate(t.names): +## if i == 0: +## self._write(", ") +## self._write(a.name) +## if a.asname: +## self._write(" as "+a.asname) +## # XXX(jpe) what is level for? +## +# +# def _Break(self, t): +# self._fill("break") +# +# def _Continue(self, t): +# self._fill("continue") +# +# def _Delete(self, t): +# self._fill("del ") +# self._dispatch(t.targets) +# +# def _Assert(self, t): +# self._fill("assert ") +# self._dispatch(t.test) +# if t.msg: +# self._write(", ") +# self._dispatch(t.msg) +# +# def _Exec(self, t): +# self._fill("exec ") +# self._dispatch(t.body) +# if t.globals: +# self._write(" in ") +# self._dispatch(t.globals) +# if t.locals: +# self._write(", ") +# self._dispatch(t.locals) +# +# def _Print(self, t): +# self._fill("print ") +# do_comma = False +# if t.dest: +# self._write(">>") +# self._dispatch(t.dest) +# do_comma = True +# for e in t.values: +# if do_comma:self._write(", ") +# else:do_comma=True +# self._dispatch(e) +# if not t.nl: +# self._write(",") +# +# def _Global(self, t): +# self._fill("global") +# for i, n in enumerate(t.names): +# if i != 0: +# self._write(",") +# self._write(" " + n) +# +# def _Yield(self, t): +# self._fill("yield") +# if t.value: +# self._write(" (") +# self._dispatch(t.value) +# self._write(")") +# +# def _Raise(self, t): +# self._fill('raise ') +# if t.type: +# self._dispatch(t.type) +# if t.inst: +# self._write(", ") +# self._dispatch(t.inst) +# if t.tback: +# self._write(", ") +# self._dispatch(t.tback) +# +# +# def _TryFinally(self, t): +# self._fill("try") +# self._enter() +# self._dispatch(t.body) +# self._leave() +# +# self._fill("finally") +# self._enter() +# self._dispatch(t.finalbody) +# self._leave() +# +# def _excepthandler(self, t): +# self._fill("except ") +# if t.type: +# self._dispatch(t.type) +# if t.name: +# self._write(", ") +# self._dispatch(t.name) +# self._enter() +# self._dispatch(t.body) +# self._leave() +# +# def _ClassDef(self, t): +# self._write("\n") +# self._fill("class "+t.name) +# if t.bases: +# self._write("(") +# for a in t.bases: +# self._dispatch(a) +# self._write(", ") +# self._write(")") +# self._enter() +# self._dispatch(t.body) +# self._leave() +# +# def _FunctionDef(self, t): +# self._write("\n") +# for deco in t.decorators: +# self._fill("@") +# self._dispatch(deco) +# self._fill("def "+t.name + "(") +# self._dispatch(t.args) +# self._write(")") +# self._enter() +# self._dispatch(t.body) +# self._leave() +# +# def _For(self, t): +# self._fill("for ") +# self._dispatch(t.target) +# self._write(" in ") +# self._dispatch(t.iter) +# self._enter() +# self._dispatch(t.body) +# self._leave() +# if t.orelse: +# self._fill("else") +# self._enter() +# self._dispatch(t.orelse) +# self._leave +# +# def _While(self, t): +# self._fill("while ") +# self._dispatch(t.test) +# self._enter() +# self._dispatch(t.body) +# self._leave() +# if t.orelse: +# self._fill("else") +# self._enter() +# self._dispatch(t.orelse) +# self._leave +# +# # expr +# def _Str(self, tree): +# self._write(repr(tree.s)) +## +# def _Repr(self, t): +# self._write("`") +# self._dispatch(t.value) +# self._write("`") +# +# def _Num(self, t): +# self._write(repr(t.n)) +# +# def _ListComp(self, t): +# self._write("[") +# self._dispatch(t.elt) +# for gen in t.generators: +# self._dispatch(gen) +# self._write("]") +# +# def _GeneratorExp(self, t): +# self._write("(") +# self._dispatch(t.elt) +# for gen in t.generators: +# self._dispatch(gen) +# self._write(")") +# +# def _comprehension(self, t): +# self._write(" for ") +# self._dispatch(t.target) +# self._write(" in ") +# self._dispatch(t.iter) +# for if_clause in t.ifs: +# self._write(" if ") +# self._dispatch(if_clause) +# +# def _IfExp(self, t): +# self._dispatch(t.body) +# self._write(" if ") +# self._dispatch(t.test) +# if t.orelse: +# self._write(" else ") +# self._dispatch(t.orelse) +# +# unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"} +# def _UnaryOp(self, t): +# self._write(self.unop[t.op.__class__.__name__]) +# self._write("(") +# self._dispatch(t.operand) +# self._write(")") +# +# binop = { "Add":"+", "Sub":"-", "Mult":"*", "Div":"/", "Mod":"%", +# "LShift":">>", "RShift":"<<", "BitOr":"|", "BitXor":"^", "BitAnd":"&", +# "FloorDiv":"//", "Pow": "**"} +# def _BinOp(self, t): +# self._write("(") +# self._dispatch(t.left) +# self._write(")" + self.binop[t.op.__class__.__name__] + "(") +# self._dispatch(t.right) +# self._write(")") +# +# boolops = {_ast.And: 'and', _ast.Or: 'or'} +# def _BoolOp(self, t): +# self._write("(") +# self._dispatch(t.values[0]) +# for v in t.values[1:]: +# self._write(" %s " % self.boolops[t.op.__class__]) +# self._dispatch(v) +# self._write(")") +# +# def _Attribute(self,t): +# self._dispatch(t.value) +# self._write(".") +# self._write(t.attr) +# +## def _Call(self, t): +## self._dispatch(t.func) +## self._write("(") +## comma = False +## for e in t.args: +## if comma: self._write(", ") +## else: comma = True +## self._dispatch(e) +## for e in t.keywords: +## if comma: self._write(", ") +## else: comma = True +## self._dispatch(e) +## if t.starargs: +## if comma: self._write(", ") +## else: comma = True +## self._write("*") +## self._dispatch(t.starargs) +## if t.kwargs: +## if comma: self._write(", ") +## else: comma = True +## self._write("**") +## self._dispatch(t.kwargs) +## self._write(")") +# +# # slice +# def _Index(self, t): +# self._dispatch(t.value) +# +# def _ExtSlice(self, t): +# for i, d in enumerate(t.dims): +# if i != 0: +# self._write(': ') +# self._dispatch(d) +# +# # others +# def _arguments(self, t): +# first = True +# nonDef = len(t.args)-len(t.defaults) +# for a in t.args[0:nonDef]: +# if first:first = False +# else: self._write(", ") +# self._dispatch(a) +# for a,d in zip(t.args[nonDef:], t.defaults): +# if first:first = False +# else: self._write(", ") +# self._dispatch(a), +# self._write("=") +# self._dispatch(d) +# if t.vararg: +# if first:first = False +# else: self._write(", ") +# self._write("*"+t.vararg) +# if t.kwarg: +# if first:first = False +# else: self._write(", ") +# self._write("**"+t.kwarg) +# +## def _keyword(self, t): +## self._write(t.arg) +## self._write("=") +## self._dispatch(t.value) +# +# def _Lambda(self, t): +# self._write("lambda ") +# self._dispatch(t.args) +# self._write(": ") +# self._dispatch(t.body) diff --git a/doc/numpydoc-0.5/numpydoc/docscrape.py b/doc/numpydoc-0.5/numpydoc/docscrape.py new file mode 100644 index 0000000..36328a9 --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc/docscrape.py @@ -0,0 +1,567 @@ +"""Extract reference documentation from the NumPy source tree. + +""" +from __future__ import division, absolute_import, print_function + +import inspect +import textwrap +import re +import pydoc +from warnings import warn +import collections +import sys + + +class Reader(object): + """A line-based string reader. + + """ + + def __init__(self, data): + """ + Parameters + ---------- + data : str + String with lines separated by '\n'. + + """ + if isinstance(data, list): + self._str = data + else: + self._str = data.split("\n") # store string as list of lines + + self.reset() + + def __getitem__(self, n): + return self._str[n] + + def reset(self): + self._l = 0 # current line nr + + def read(self): + if not self.eof(): + out = self[self._l] + self._l += 1 + return out + else: + return "" + + def seek_next_non_empty_line(self): + for l in self[self._l :]: + if l.strip(): + break + else: + self._l += 1 + + def eof(self): + return self._l >= len(self._str) + + def read_to_condition(self, condition_func): + start = self._l + for line in self[start:]: + if condition_func(line): + return self[start : self._l] + self._l += 1 + if self.eof(): + return self[start : self._l + 1] + return [] + + def read_to_next_empty_line(self): + self.seek_next_non_empty_line() + + def is_empty(line): + return not line.strip() + + return self.read_to_condition(is_empty) + + def read_to_next_unindented_line(self): + def is_unindented(line): + return line.strip() and (len(line.lstrip()) == len(line)) + + return self.read_to_condition(is_unindented) + + def peek(self, n=0): + if self._l + n < len(self._str): + return self[self._l + n] + else: + return "" + + def is_empty(self): + return not "".join(self._str).strip() + + +class NumpyDocString(object): + def __init__(self, docstring, config={}): + docstring = textwrap.dedent(docstring).split("\n") + + self._doc = Reader(docstring) + self._parsed_data = { + "Signature": "", + "Summary": [""], + "Extended Summary": [], + "Parameters": [], + "Returns": [], + "Raises": [], + "Warns": [], + "Other Parameters": [], + "Attributes": [], + "Methods": [], + "See Also": [], + "Notes": [], + "Warnings": [], + "References": "", + "Examples": "", + "index": {}, + } + + self._parse() + + def __getitem__(self, key): + return self._parsed_data[key] + + def __setitem__(self, key, val): + if key not in self._parsed_data: + warn("Unknown section %s" % key) + else: + self._parsed_data[key] = val + + def _is_at_section(self): + self._doc.seek_next_non_empty_line() + + if self._doc.eof(): + return False + + l1 = self._doc.peek().strip() # e.g. Parameters + + if l1.startswith(".. index::"): + return True + + l2 = self._doc.peek(1).strip() # ---------- or ========== + return l2.startswith("-" * len(l1)) or l2.startswith("=" * len(l1)) + + def _strip(self, doc): + i = 0 + j = 0 + for i, line in enumerate(doc): + if line.strip(): + break + + for j, line in enumerate(doc[::-1]): + if line.strip(): + break + + return doc[i : len(doc) - j] + + def _read_to_next_section(self): + section = self._doc.read_to_next_empty_line() + + while not self._is_at_section() and not self._doc.eof(): + if not self._doc.peek(-1).strip(): # previous line was empty + section += [""] + + section += self._doc.read_to_next_empty_line() + + return section + + def _read_sections(self): + while not self._doc.eof(): + data = self._read_to_next_section() + name = data[0].strip() + + if name.startswith(".."): # index section + yield name, data[1:] + elif len(data) < 2: + yield StopIteration + else: + yield name, self._strip(data[2:]) + + def _parse_param_list(self, content): + r = Reader(content) + params = [] + while not r.eof(): + header = r.read().strip() + if " : " in header: + arg_name, arg_type = header.split(" : ")[:2] + else: + arg_name, arg_type = header, "" + + desc = r.read_to_next_unindented_line() + desc = dedent_lines(desc) + + params.append((arg_name, arg_type, desc)) + + return params + + _name_rgx = re.compile( + r"^\s*(:(?P\w+):`(?P[a-zA-Z0-9_.-]+)`|" + r" (?P[a-zA-Z0-9_.-]+))\s*", + re.X, + ) + + def _parse_see_also(self, content): + """ + func_name : Descriptive text + continued text + another_func_name : Descriptive text + func_name1, func_name2, :meth:`func_name`, func_name3 + + """ + items = [] + + def parse_item_name(text): + """Match ':role:`name`' or 'name'""" + m = self._name_rgx.match(text) + if m: + g = m.groups() + if g[1] is None: + return g[3], None + else: + return g[2], g[1] + raise ValueError("%s is not a item name" % text) + + def push_item(name, rest): + if not name: + return + name, role = parse_item_name(name) + items.append((name, list(rest), role)) + del rest[:] + + current_func = None + rest = [] + + for line in content: + if not line.strip(): + continue + + m = self._name_rgx.match(line) + if m and line[m.end() :].strip().startswith(":"): + push_item(current_func, rest) + current_func, line = line[: m.end()], line[m.end() :] + rest = [line.split(":", 1)[1].strip()] + if not rest[0]: + rest = [] + elif not line.startswith(" "): + push_item(current_func, rest) + current_func = None + if "," in line: + for func in line.split(","): + if func.strip(): + push_item(func, []) + elif line.strip(): + current_func = line + elif current_func is not None: + rest.append(line.strip()) + push_item(current_func, rest) + return items + + def _parse_index(self, section, content): + """ + .. index: default + :refguide: something, else, and more + + """ + + def strip_each_in(lst): + return [s.strip() for s in lst] + + out = {} + section = section.split("::") + if len(section) > 1: + out["default"] = strip_each_in(section[1].split(","))[0] + for line in content: + line = line.split(":") + if len(line) > 2: + out[line[1]] = strip_each_in(line[2].split(",")) + return out + + def _parse_summary(self): + """Grab signature (if given) and summary""" + if self._is_at_section(): + return + + # If several signatures present, take the last one + while True: + summary = self._doc.read_to_next_empty_line() + summary_str = " ".join([s.strip() for s in summary]).strip() + if re.compile("^([\w., ]+=)?\s*[\w\.]+\(.*\)$").match(summary_str): + self["Signature"] = summary_str + if not self._is_at_section(): + continue + break + + if summary is not None: + self["Summary"] = summary + + if not self._is_at_section(): + self["Extended Summary"] = self._read_to_next_section() + + def _parse(self): + self._doc.reset() + self._parse_summary() + + for (section, content) in self._read_sections(): + if not section.startswith(".."): + section = " ".join([s.capitalize() for s in section.split(" ")]) + if section in ( + "Parameters", + "Returns", + "Raises", + "Warns", + "Other Parameters", + "Attributes", + "Methods", + ): + self[section] = self._parse_param_list(content) + elif section.startswith(".. index::"): + self["index"] = self._parse_index(section, content) + elif section == "See Also": + self["See Also"] = self._parse_see_also(content) + else: + self[section] = content + + # string conversion routines + + def _str_header(self, name, symbol="-"): + return [name, len(name) * symbol] + + def _str_indent(self, doc, indent=4): + out = [] + for line in doc: + out += [" " * indent + line] + return out + + def _str_signature(self): + if self["Signature"]: + return [self["Signature"].replace("*", "\*")] + [""] + else: + return [""] + + def _str_summary(self): + if self["Summary"]: + return self["Summary"] + [""] + else: + return [] + + def _str_extended_summary(self): + if self["Extended Summary"]: + return self["Extended Summary"] + [""] + else: + return [] + + def _str_param_list(self, name): + out = [] + if self[name]: + out += self._str_header(name) + for param, param_type, desc in self[name]: + if param_type: + out += ["%s : %s" % (param, param_type)] + else: + out += [param] + out += self._str_indent(desc) + out += [""] + return out + + def _str_section(self, name): + out = [] + if self[name]: + out += self._str_header(name) + out += self[name] + out += [""] + return out + + def _str_see_also(self, func_role): + if not self["See Also"]: + return [] + out = [] + out += self._str_header("See Also") + last_had_desc = True + for func, desc, role in self["See Also"]: + if role: + link = ":%s:`%s`" % (role, func) + elif func_role: + link = ":%s:`%s`" % (func_role, func) + else: + link = "`%s`_" % func + if desc or last_had_desc: + out += [""] + out += [link] + else: + out[-1] += ", %s" % link + if desc: + out += self._str_indent([" ".join(desc)]) + last_had_desc = True + else: + last_had_desc = False + out += [""] + return out + + def _str_index(self): + idx = self["index"] + out = [] + out += [".. index:: %s" % idx.get("default", "")] + for section, references in idx.items(): + if section == "default": + continue + out += [" :%s: %s" % (section, ", ".join(references))] + return out + + def __str__(self, func_role=""): + out = [] + out += self._str_signature() + out += self._str_summary() + out += self._str_extended_summary() + for param_list in ( + "Parameters", + "Returns", + "Other Parameters", + "Raises", + "Warns", + ): + out += self._str_param_list(param_list) + out += self._str_section("Warnings") + out += self._str_see_also(func_role) + for s in ("Notes", "References", "Examples"): + out += self._str_section(s) + for param_list in ("Attributes", "Methods"): + out += self._str_param_list(param_list) + out += self._str_index() + return "\n".join(out) + + +def indent(str, indent=4): + indent_str = " " * indent + if str is None: + return indent_str + lines = str.split("\n") + return "\n".join(indent_str + l for l in lines) + + +def dedent_lines(lines): + """Deindent a list of lines maximally""" + return textwrap.dedent("\n".join(lines)).split("\n") + + +def header(text, style="-"): + return text + "\n" + style * len(text) + "\n" + + +class FunctionDoc(NumpyDocString): + def __init__(self, func, role="func", doc=None, config={}): + self._f = func + self._role = role # e.g. "func" or "meth" + + if doc is None: + if func is None: + raise ValueError("No function or docstring given") + doc = inspect.getdoc(func) or "" + NumpyDocString.__init__(self, doc) + + if not self["Signature"] and func is not None: + func, func_name = self.get_func() + try: + # try to read signature + if sys.version_info[0] >= 3: + argspec = inspect.getfullargspec(func) + else: + argspec = inspect.getargspec(func) + argspec = inspect.formatargspec(*argspec) + argspec = argspec.replace("*", "\*") + signature = "%s%s" % (func_name, argspec) + except TypeError as e: + signature = "%s()" % func_name + self["Signature"] = signature + + def get_func(self): + func_name = getattr(self._f, "__name__", self.__class__.__name__) + if inspect.isclass(self._f): + func = getattr(self._f, "__call__", self._f.__init__) + else: + func = self._f + return func, func_name + + def __str__(self): + out = "" + + func, func_name = self.get_func() + signature = self["Signature"].replace("*", "\*") + + roles = {"func": "function", "meth": "method"} + + if self._role: + if self._role not in roles: + print("Warning: invalid role %s" % self._role) + out += ".. %s:: %s\n \n\n" % (roles.get(self._role, ""), func_name) + + out += super(FunctionDoc, self).__str__(func_role=self._role) + return out + + +class ClassDoc(NumpyDocString): + + extra_public_methods = ["__call__"] + + def __init__(self, cls, doc=None, modulename="", func_doc=FunctionDoc, config={}): + if not inspect.isclass(cls) and cls is not None: + raise ValueError("Expected a class or None, but got %r" % cls) + self._cls = cls + + if modulename and not modulename.endswith("."): + modulename += "." + self._mod = modulename + + if doc is None: + if cls is None: + raise ValueError("No class or documentation string given") + doc = pydoc.getdoc(cls) + + NumpyDocString.__init__(self, doc) + + if config.get("show_class_members", True): + + def splitlines_x(s): + if not s: + return [] + else: + return s.splitlines() + + for field, items in [ + ("Methods", self.methods), + ("Attributes", self.properties), + ]: + if not self[field]: + doc_list = [] + for name in sorted(items): + try: + doc_item = pydoc.getdoc(getattr(self._cls, name)) + doc_list.append((name, "", splitlines_x(doc_item))) + except AttributeError: + pass # method doesn't exist + self[field] = doc_list + + @property + def methods(self): + if self._cls is None: + return [] + return [ + name + for name, func in inspect.getmembers(self._cls) + if ( + (not name.startswith("_") or name in self.extra_public_methods) + and isinstance(func, collections.Callable) + ) + ] + + @property + def properties(self): + if self._cls is None: + return [] + return [ + name + for name, func in inspect.getmembers(self._cls) + if not name.startswith("_") + and ( + func is None + or isinstance(func, property) + or inspect.isgetsetdescriptor(func) + ) + ] diff --git a/doc/numpydoc-0.5/numpydoc/docscrape_sphinx.py b/doc/numpydoc-0.5/numpydoc/docscrape_sphinx.py new file mode 100644 index 0000000..9e2317e --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc/docscrape_sphinx.py @@ -0,0 +1,284 @@ +from __future__ import division, absolute_import, print_function + +import sys, re, inspect, textwrap, pydoc +import sphinx +import collections +from .docscrape import NumpyDocString, FunctionDoc, ClassDoc + +if sys.version_info[0] >= 3: + sixu = lambda s: s +else: + sixu = lambda s: unicode(s, "unicode_escape") + + +class SphinxDocString(NumpyDocString): + def __init__(self, docstring, config={}): + NumpyDocString.__init__(self, docstring, config=config) + self.load_config(config) + + def load_config(self, config): + self.use_plots = config.get("use_plots", False) + self.class_members_toctree = config.get("class_members_toctree", True) + + # string conversion routines + def _str_header(self, name, symbol="`"): + return [".. rubric:: " + name, ""] + + def _str_field_list(self, name): + return [":" + name + ":"] + + def _str_indent(self, doc, indent=4): + out = [] + for line in doc: + out += [" " * indent + line] + return out + + def _str_signature(self): + return [""] + if self["Signature"]: + return ["``%s``" % self["Signature"]] + [""] + else: + return [""] + + def _str_summary(self): + return self["Summary"] + [""] + + def _str_extended_summary(self): + return self["Extended Summary"] + [""] + + def _str_returns(self): + out = [] + if self["Returns"]: + out += self._str_field_list("Returns") + out += [""] + for param, param_type, desc in self["Returns"]: + if param_type: + out += self._str_indent( + ["**%s** : %s" % (param.strip(), param_type)] + ) + else: + out += self._str_indent([param.strip()]) + if desc: + out += [""] + out += self._str_indent(desc, 8) + out += [""] + return out + + def _str_param_list(self, name): + out = [] + if self[name]: + out += self._str_field_list(name) + out += [""] + for param, param_type, desc in self[name]: + if param_type: + out += self._str_indent( + ["**%s** : %s" % (param.strip(), param_type)] + ) + else: + out += self._str_indent(["**%s**" % param.strip()]) + if desc: + out += [""] + out += self._str_indent(desc, 8) + out += [""] + return out + + @property + def _obj(self): + if hasattr(self, "_cls"): + return self._cls + elif hasattr(self, "_f"): + return self._f + return None + + def _str_member_list(self, name): + """ + Generate a member listing, autosummary:: table where possible, + and a table where not. + + """ + out = [] + if self[name]: + out += [".. rubric:: %s" % name, ""] + prefix = getattr(self, "_name", "") + + if prefix: + prefix = "~%s." % prefix + + autosum = [] + others = [] + for param, param_type, desc in self[name]: + param = param.strip() + + # Check if the referenced member can have a docstring or not + param_obj = getattr(self._obj, param, None) + if not ( + callable(param_obj) + or isinstance(param_obj, property) + or inspect.isgetsetdescriptor(param_obj) + ): + param_obj = None + + if param_obj and (pydoc.getdoc(param_obj) or not desc): + # Referenced object has a docstring + autosum += [" %s%s" % (prefix, param)] + else: + others.append((param, param_type, desc)) + + if autosum: + out += [".. autosummary::"] + if self.class_members_toctree: + out += [" :toctree:"] + out += [""] + autosum + + if others: + maxlen_0 = max(3, max([len(x[0]) for x in others])) + hdr = sixu("=") * maxlen_0 + sixu(" ") + sixu("=") * 10 + fmt = sixu("%%%ds %%s ") % (maxlen_0,) + out += ["", hdr] + for param, param_type, desc in others: + desc = sixu(" ").join(x.strip() for x in desc).strip() + if param_type: + desc = "(%s) %s" % (param_type, desc) + out += [fmt % (param.strip(), desc)] + out += [hdr] + out += [""] + return out + + def _str_section(self, name): + out = [] + if self[name]: + out += self._str_header(name) + out += [""] + content = textwrap.dedent("\n".join(self[name])).split("\n") + out += content + out += [""] + return out + + def _str_see_also(self, func_role): + out = [] + if self["See Also"]: + see_also = super(SphinxDocString, self)._str_see_also(func_role) + out = [".. seealso::", ""] + out += self._str_indent(see_also[2:]) + return out + + def _str_warnings(self): + out = [] + if self["Warnings"]: + out = [".. warning::", ""] + out += self._str_indent(self["Warnings"]) + return out + + def _str_index(self): + idx = self["index"] + out = [] + if len(idx) == 0: + return out + + out += [".. index:: %s" % idx.get("default", "")] + for section, references in idx.items(): + if section == "default": + continue + elif section == "refguide": + out += [" single: %s" % (", ".join(references))] + else: + out += [" %s: %s" % (section, ",".join(references))] + return out + + def _str_references(self): + out = [] + if self["References"]: + out += self._str_header("References") + if isinstance(self["References"], str): + self["References"] = [self["References"]] + out.extend(self["References"]) + out += [""] + # Latex collects all references to a separate bibliography, + # so we need to insert links to it + if sphinx.__version__ >= "0.6": + out += [".. only:: latex", ""] + else: + out += [".. latexonly::", ""] + items = [] + for line in self["References"]: + m = re.match(r".. \[([a-z0-9._-]+)\]", line, re.I) + if m: + items.append(m.group(1)) + out += [" " + ", ".join(["[%s]_" % item for item in items]), ""] + return out + + def _str_examples(self): + examples_str = "\n".join(self["Examples"]) + + if ( + self.use_plots + and "import matplotlib" in examples_str + and "plot::" not in examples_str + ): + out = [] + out += self._str_header("Examples") + out += [".. plot::", ""] + out += self._str_indent(self["Examples"]) + out += [""] + return out + else: + return self._str_section("Examples") + + def __str__(self, indent=0, func_role="obj"): + out = [] + out += self._str_signature() + out += self._str_index() + [""] + out += self._str_summary() + out += self._str_extended_summary() + out += self._str_param_list("Parameters") + out += self._str_returns() + for param_list in ("Other Parameters", "Raises", "Warns"): + out += self._str_param_list(param_list) + out += self._str_warnings() + out += self._str_see_also(func_role) + out += self._str_section("Notes") + out += self._str_references() + out += self._str_examples() + for param_list in ("Attributes", "Methods"): + out += self._str_member_list(param_list) + out = self._str_indent(out, indent) + return "\n".join(out) + + +class SphinxFunctionDoc(SphinxDocString, FunctionDoc): + def __init__(self, obj, doc=None, config={}): + self.load_config(config) + FunctionDoc.__init__(self, obj, doc=doc, config=config) + + +class SphinxClassDoc(SphinxDocString, ClassDoc): + def __init__(self, obj, doc=None, func_doc=None, config={}): + self.load_config(config) + ClassDoc.__init__(self, obj, doc=doc, func_doc=None, config=config) + + +class SphinxObjDoc(SphinxDocString): + def __init__(self, obj, doc=None, config={}): + self._f = obj + self.load_config(config) + SphinxDocString.__init__(self, doc, config=config) + + +def get_doc_object(obj, what=None, doc=None, config={}): + if what is None: + if inspect.isclass(obj): + what = "class" + elif inspect.ismodule(obj): + what = "module" + elif isinstance(obj, collections.Callable): + what = "function" + else: + what = "object" + if what == "class": + return SphinxClassDoc(obj, func_doc=SphinxFunctionDoc, doc=doc, config=config) + elif what in ("function", "method"): + return SphinxFunctionDoc(obj, doc=doc, config=config) + else: + if doc is None: + doc = pydoc.getdoc(obj) + return SphinxObjDoc(obj, doc, config=config) diff --git a/doc/numpydoc-0.5/numpydoc/linkcode.py b/doc/numpydoc-0.5/numpydoc/linkcode.py new file mode 100644 index 0000000..6845720 --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc/linkcode.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- +""" + linkcode + ~~~~~~~~ + + Add external links to module code in Python object descriptions. + + :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS. + :license: BSD, see LICENSE for details. + +""" +from __future__ import division, absolute_import, print_function + +import warnings +import collections + +warnings.warn( + "This extension has been accepted to Sphinx upstream. " + "Use the version from there (Sphinx >= 1.2) " + "https://bitbucket.org/birkenfeld/sphinx/pull-request/47/sphinxextlinkcode", + FutureWarning, + stacklevel=1, +) + + +from docutils import nodes + +from sphinx import addnodes +from sphinx.locale import _ +from sphinx.errors import SphinxError + + +class LinkcodeError(SphinxError): + category = "linkcode error" + + +def doctree_read(app, doctree): + env = app.builder.env + + resolve_target = getattr(env.config, "linkcode_resolve", None) + if not isinstance(env.config.linkcode_resolve, collections.Callable): + raise LinkcodeError("Function `linkcode_resolve` is not given in conf.py") + + domain_keys = dict( + py=["module", "fullname"], c=["names"], cpp=["names"], js=["object", "fullname"] + ) + + for objnode in doctree.traverse(addnodes.desc): + domain = objnode.get("domain") + uris = set() + for signode in objnode: + if not isinstance(signode, addnodes.desc_signature): + continue + + # Convert signode to a specified format + info = {} + for key in domain_keys.get(domain, []): + value = signode.get(key) + if not value: + value = "" + info[key] = value + if not info: + continue + + # Call user code to resolve the link + uri = resolve_target(domain, info) + if not uri: + # no source + continue + + if uri in uris or not uri: + # only one link per name, please + continue + uris.add(uri) + + onlynode = addnodes.only(expr="html") + onlynode += nodes.reference("", "", internal=False, refuri=uri) + onlynode[0] += nodes.inline("", _("[source]"), classes=["viewcode-link"]) + signode += onlynode + + +def setup(app): + app.connect("doctree-read", doctree_read) + app.add_config_value("linkcode_resolve", None, "") diff --git a/doc/numpydoc-0.5/numpydoc/numpydoc.py b/doc/numpydoc-0.5/numpydoc/numpydoc.py new file mode 100644 index 0000000..81a4328 --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc/numpydoc.py @@ -0,0 +1,201 @@ +""" +======== +numpydoc +======== + +Sphinx extension that handles docstrings in the Numpy standard format. [1] + +It will: + +- Convert Parameters etc. sections to field lists. +- Convert See Also section to a See also entry. +- Renumber references. +- Extract the signature from the docstring, if it can't be determined otherwise. + +.. [1] https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt + +""" +from __future__ import division, absolute_import, print_function + +import os, sys, re, pydoc +import sphinx +import inspect +import collections + +if sphinx.__version__ < "1.0.1": + raise RuntimeError("Sphinx 1.0.1 or newer is required") + +from .docscrape_sphinx import get_doc_object, SphinxDocString +from sphinx.util.compat import Directive + +if sys.version_info[0] >= 3: + sixu = lambda s: s +else: + sixu = lambda s: unicode(s, "unicode_escape") + + +def mangle_docstrings(app, what, name, obj, options, lines, reference_offset=[0]): + + cfg = dict( + use_plots=app.config.numpydoc_use_plots, + show_class_members=app.config.numpydoc_show_class_members, + class_members_toctree=app.config.numpydoc_class_members_toctree, + ) + + if what == "module": + # Strip top title + title_re = re.compile( + sixu("^\\s*[#*=]{4,}\\n[a-z0-9 -]+\\n[#*=]{4,}\\s*"), re.I | re.S + ) + lines[:] = title_re.sub(sixu(""), sixu("\n").join(lines)).split(sixu("\n")) + else: + doc = get_doc_object(obj, what, sixu("\n").join(lines), config=cfg) + if sys.version_info[0] >= 3: + doc = str(doc) + else: + doc = unicode(doc) + lines[:] = doc.split(sixu("\n")) + + if app.config.numpydoc_edit_link and hasattr(obj, "__name__") and obj.__name__: + if hasattr(obj, "__module__"): + v = dict(full_name=sixu("%s.%s") % (obj.__module__, obj.__name__)) + else: + v = dict(full_name=obj.__name__) + lines += [sixu(""), sixu(".. htmlonly::"), sixu("")] + lines += [ + sixu(" %s") % x for x in (app.config.numpydoc_edit_link % v).split("\n") + ] + + # replace reference numbers so that there are no duplicates + references = [] + for line in lines: + line = line.strip() + m = re.match(sixu("^.. \\[([a-z0-9_.-])\\]"), line, re.I) + if m: + references.append(m.group(1)) + + # start renaming from the longest string, to avoid overwriting parts + references.sort(key=lambda x: -len(x)) + if references: + for i, line in enumerate(lines): + for r in references: + if re.match(sixu("^\\d+$"), r): + new_r = sixu("R%d") % (reference_offset[0] + int(r)) + else: + new_r = sixu("%s%d") % (r, reference_offset[0]) + lines[i] = lines[i].replace(sixu("[%s]_") % r, sixu("[%s]_") % new_r) + lines[i] = lines[i].replace( + sixu(".. [%s]") % r, sixu(".. [%s]") % new_r + ) + + reference_offset[0] += len(references) + + +def mangle_signature(app, what, name, obj, options, sig, retann): + # Do not try to inspect classes that don't define `__init__` + if inspect.isclass(obj) and ( + not hasattr(obj, "__init__") + or "initializes x; see " in pydoc.getdoc(obj.__init__) + ): + return "", "" + + if not ( + isinstance(obj, collections.Callable) or hasattr(obj, "__argspec_is_invalid_") + ): + return + if not hasattr(obj, "__doc__"): + return + + doc = SphinxDocString(pydoc.getdoc(obj)) + if doc["Signature"]: + sig = re.sub(sixu("^[^(]*"), sixu(""), doc["Signature"]) + return sig, sixu("") + + +def setup(app, get_doc_object_=get_doc_object): + if not hasattr(app, "add_config_value"): + return # probably called by nose, better bail out + + global get_doc_object + get_doc_object = get_doc_object_ + + app.connect("autodoc-process-docstring", mangle_docstrings) + app.connect("autodoc-process-signature", mangle_signature) + app.add_config_value("numpydoc_edit_link", None, False) + app.add_config_value("numpydoc_use_plots", None, False) + app.add_config_value("numpydoc_show_class_members", True, True) + app.add_config_value("numpydoc_class_members_toctree", True, True) + + # Extra mangling domains + app.add_domain(NumpyPythonDomain) + app.add_domain(NumpyCDomain) + + +# ------------------------------------------------------------------------------ +# Docstring-mangling domains +# ------------------------------------------------------------------------------ + +from docutils.statemachine import ViewList +from sphinx.domains.c import CDomain +from sphinx.domains.python import PythonDomain + + +class ManglingDomainBase(object): + directive_mangling_map = {} + + def __init__(self, *a, **kw): + super(ManglingDomainBase, self).__init__(*a, **kw) + self.wrap_mangling_directives() + + def wrap_mangling_directives(self): + for name, objtype in list(self.directive_mangling_map.items()): + self.directives[name] = wrap_mangling_directive( + self.directives[name], objtype + ) + + +class NumpyPythonDomain(ManglingDomainBase, PythonDomain): + name = "np" + directive_mangling_map = { + "function": "function", + "class": "class", + "exception": "class", + "method": "function", + "classmethod": "function", + "staticmethod": "function", + "attribute": "attribute", + } + indices = [] + + +class NumpyCDomain(ManglingDomainBase, CDomain): + name = "np-c" + directive_mangling_map = { + "function": "function", + "member": "attribute", + "macro": "function", + "type": "class", + "var": "object", + } + + +def wrap_mangling_directive(base_directive, objtype): + class directive(base_directive): + def run(self): + env = self.state.document.settings.env + + name = None + if self.arguments: + m = re.match(r"^(.*\s+)?(.*?)(\(.*)?", self.arguments[0]) + name = m.group(2).strip() + + if not name: + name = self.arguments[0] + + lines = list(self.content) + mangle_docstrings(env.app, objtype, name, None, None, lines) + self.content = ViewList(lines, self.content.parent) + + return base_directive.run(self) + + return directive diff --git a/doc/numpydoc-0.5/numpydoc/phantom_import.py b/doc/numpydoc-0.5/numpydoc/phantom_import.py new file mode 100644 index 0000000..7ef99c3 --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc/phantom_import.py @@ -0,0 +1,181 @@ +""" +============== +phantom_import +============== + +Sphinx extension to make directives from ``sphinx.ext.autodoc`` and similar +extensions to use docstrings loaded from an XML file. + +This extension loads an XML file in the Pydocweb format [1] and +creates a dummy module that contains the specified docstrings. This +can be used to get the current docstrings from a Pydocweb instance +without needing to rebuild the documented module. + +.. [1] http://code.google.com/p/pydocweb + +""" +from __future__ import division, absolute_import, print_function + +import imp, sys, compiler, types, os, inspect, re + + +def setup(app): + app.connect("builder-inited", initialize) + app.add_config_value("phantom_import_file", None, True) + + +def initialize(app): + fn = app.config.phantom_import_file + if fn and os.path.isfile(fn): + print("[numpydoc] Phantom importing modules from", fn, "...") + import_phantom_module(fn) + + +# ------------------------------------------------------------------------------ +# Creating 'phantom' modules from an XML description +# ------------------------------------------------------------------------------ +def import_phantom_module(xml_file): + """ + Insert a fake Python module to sys.modules, based on a XML file. + + The XML file is expected to conform to Pydocweb DTD. The fake + module will contain dummy objects, which guarantee the following: + + - Docstrings are correct. + - Class inheritance relationships are correct (if present in XML). + - Function argspec is *NOT* correct (even if present in XML). + Instead, the function signature is prepended to the function docstring. + - Class attributes are *NOT* correct; instead, they are dummy objects. + + Parameters + ---------- + xml_file : str + Name of an XML file to read + + """ + import lxml.etree as etree + + object_cache = {} + + tree = etree.parse(xml_file) + root = tree.getroot() + + # Sort items so that + # - Base classes come before classes inherited from them + # - Modules come before their contents + all_nodes = dict([(n.attrib["id"], n) for n in root]) + + def _get_bases(node, recurse=False): + bases = [x.attrib["ref"] for x in node.findall("base")] + if recurse: + j = 0 + while True: + try: + b = bases[j] + except IndexError: + break + if b in all_nodes: + bases.extend(_get_bases(all_nodes[b])) + j += 1 + return bases + + type_index = ["module", "class", "callable", "object"] + + def base_cmp(a, b): + x = cmp(type_index.index(a.tag), type_index.index(b.tag)) + if x != 0: + return x + + if a.tag == "class" and b.tag == "class": + a_bases = _get_bases(a, recurse=True) + b_bases = _get_bases(b, recurse=True) + x = cmp(len(a_bases), len(b_bases)) + if x != 0: + return x + if a.attrib["id"] in b_bases: + return -1 + if b.attrib["id"] in a_bases: + return 1 + + return cmp(a.attrib["id"].count("."), b.attrib["id"].count(".")) + + nodes = root.getchildren() + nodes.sort(base_cmp) + + # Create phantom items + for node in nodes: + name = node.attrib["id"] + doc = (node.text or "").decode("string-escape") + "\n" + if doc == "\n": + doc = "" + + # create parent, if missing + parent = name + while True: + parent = ".".join(parent.split(".")[:-1]) + if not parent: + break + if parent in object_cache: + break + obj = imp.new_module(parent) + object_cache[parent] = obj + sys.modules[parent] = obj + + # create object + if node.tag == "module": + obj = imp.new_module(name) + obj.__doc__ = doc + sys.modules[name] = obj + elif node.tag == "class": + bases = [object_cache[b] for b in _get_bases(node) if b in object_cache] + bases.append(object) + init = lambda self: None + init.__doc__ = doc + obj = type(name, tuple(bases), {"__doc__": doc, "__init__": init}) + obj.__name__ = name.split(".")[-1] + elif node.tag == "callable": + funcname = node.attrib["id"].split(".")[-1] + argspec = node.attrib.get("argspec") + if argspec: + argspec = re.sub("^[^(]*", "", argspec) + doc = "%s%s\n\n%s" % (funcname, argspec, doc) + obj = lambda: 0 + obj.__argspec_is_invalid_ = True + if sys.version_info[0] >= 3: + obj.__name__ = funcname + else: + obj.func_name = funcname + obj.__name__ = name + obj.__doc__ = doc + if inspect.isclass(object_cache[parent]): + obj.__objclass__ = object_cache[parent] + else: + + class Dummy(object): + pass + + obj = Dummy() + obj.__name__ = name + obj.__doc__ = doc + if inspect.isclass(object_cache[parent]): + obj.__get__ = lambda: None + object_cache[name] = obj + + if parent: + if inspect.ismodule(object_cache[parent]): + obj.__module__ = parent + setattr(object_cache[parent], name.split(".")[-1], obj) + + # Populate items + for node in root: + obj = object_cache.get(node.attrib["id"]) + if obj is None: + continue + for ref in node.findall("ref"): + if node.tag == "class": + if ref.attrib["ref"].startswith(node.attrib["id"] + "."): + setattr( + obj, ref.attrib["name"], object_cache.get(ref.attrib["ref"]) + ) + else: + setattr(obj, ref.attrib["name"], object_cache.get(ref.attrib["ref"])) diff --git a/doc/numpydoc-0.5/numpydoc/plot_directive.py b/doc/numpydoc-0.5/numpydoc/plot_directive.py new file mode 100644 index 0000000..2bb8797 --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc/plot_directive.py @@ -0,0 +1,697 @@ +""" +A special directive for generating a matplotlib plot. + +.. warning:: + + This is a hacked version of plot_directive.py from Matplotlib. + It's very much subject to change! + + +Usage +----- + +Can be used like this:: + + .. plot:: examples/example.py + + .. plot:: + + import matplotlib.pyplot as plt + plt.plot([1,2,3], [4,5,6]) + + .. plot:: + + A plotting example: + + >>> import matplotlib.pyplot as plt + >>> plt.plot([1,2,3], [4,5,6]) + +The content is interpreted as doctest formatted if it has a line starting +with ``>>>``. + +The ``plot`` directive supports the options + + format : {'python', 'doctest'} + Specify the format of the input + + include-source : bool + Whether to display the source code. Default can be changed in conf.py + +and the ``image`` directive options ``alt``, ``height``, ``width``, +``scale``, ``align``, ``class``. + +Configuration options +--------------------- + +The plot directive has the following configuration options: + + plot_include_source + Default value for the include-source option + + plot_pre_code + Code that should be executed before each plot. + + plot_basedir + Base directory, to which plot:: file names are relative to. + (If None or empty, file names are relative to the directoly where + the file containing the directive is.) + + plot_formats + File formats to generate. List of tuples or strings:: + + [(suffix, dpi), suffix, ...] + + that determine the file format and the DPI. For entries whose + DPI was omitted, sensible defaults are chosen. + + plot_html_show_formats + Whether to show links to the files in HTML. + +TODO +---- + +* Refactor Latex output; now it's plain images, but it would be nice + to make them appear side-by-side, or in floats. + +""" +from __future__ import division, absolute_import, print_function + +import sys, os, glob, shutil, imp, warnings, re, textwrap, traceback +import sphinx + +if sys.version_info[0] >= 3: + from io import StringIO +else: + from io import StringIO + +import warnings + +warnings.warn( + "A plot_directive module is also available under " + "matplotlib.sphinxext; expect this numpydoc.plot_directive " + "module to be deprecated after relevant features have been " + "integrated there.", + FutureWarning, + stacklevel=2, +) + + +# ------------------------------------------------------------------------------ +# Registration hook +# ------------------------------------------------------------------------------ + + +def setup(app): + setup.app = app + setup.config = app.config + setup.confdir = app.confdir + + app.add_config_value("plot_pre_code", "", True) + app.add_config_value("plot_include_source", False, True) + app.add_config_value("plot_formats", ["png", "hires.png", "pdf"], True) + app.add_config_value("plot_basedir", None, True) + app.add_config_value("plot_html_show_formats", True, True) + + app.add_directive( + "plot", plot_directive, True, (0, 1, False), **plot_directive_options + ) + + +# ------------------------------------------------------------------------------ +# plot:: directive +# ------------------------------------------------------------------------------ +from docutils.parsers.rst import directives +from docutils import nodes + + +def plot_directive( + name, + arguments, + options, + content, + lineno, + content_offset, + block_text, + state, + state_machine, +): + return run(arguments, content, options, state_machine, state, lineno) + + +plot_directive.__doc__ = __doc__ + + +def _option_boolean(arg): + if not arg or not arg.strip(): + # no argument given, assume used as a flag + return True + elif arg.strip().lower() in ("no", "0", "false"): + return False + elif arg.strip().lower() in ("yes", "1", "true"): + return True + else: + raise ValueError('"%s" unknown boolean' % arg) + + +def _option_format(arg): + return directives.choice(arg, ("python", "lisp")) + + +def _option_align(arg): + return directives.choice( + arg, ("top", "middle", "bottom", "left", "center", "right") + ) + + +plot_directive_options = { + "alt": directives.unchanged, + "height": directives.length_or_unitless, + "width": directives.length_or_percentage_or_unitless, + "scale": directives.nonnegative_int, + "align": _option_align, + "class": directives.class_option, + "include-source": _option_boolean, + "format": _option_format, +} + +# ------------------------------------------------------------------------------ +# Generating output +# ------------------------------------------------------------------------------ + +from docutils import nodes, utils + +try: + # Sphinx depends on either Jinja or Jinja2 + import jinja2 + + def format_template(template, **kw): + return jinja2.Template(template).render(**kw) + + +except ImportError: + import jinja + + def format_template(template, **kw): + return jinja.from_string(template, **kw) + + +TEMPLATE = """ +{{ source_code }} + +{{ only_html }} + + {% if source_link or (html_show_formats and not multi_image) %} + ( + {%- if source_link -%} + `Source code <{{ source_link }}>`__ + {%- endif -%} + {%- if html_show_formats and not multi_image -%} + {%- for img in images -%} + {%- for fmt in img.formats -%} + {%- if source_link or not loop.first -%}, {% endif -%} + `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__ + {%- endfor -%} + {%- endfor -%} + {%- endif -%} + ) + {% endif %} + + {% for img in images %} + .. figure:: {{ build_dir }}/{{ img.basename }}.png + {%- for option in options %} + {{ option }} + {% endfor %} + + {% if html_show_formats and multi_image -%} + ( + {%- for fmt in img.formats -%} + {%- if not loop.first -%}, {% endif -%} + `{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__ + {%- endfor -%} + ) + {%- endif -%} + {% endfor %} + +{{ only_latex }} + + {% for img in images %} + .. image:: {{ build_dir }}/{{ img.basename }}.pdf + {% endfor %} + +""" + + +class ImageFile(object): + def __init__(self, basename, dirname): + self.basename = basename + self.dirname = dirname + self.formats = [] + + def filename(self, format): + return os.path.join(self.dirname, "%s.%s" % (self.basename, format)) + + def filenames(self): + return [self.filename(fmt) for fmt in self.formats] + + +def run(arguments, content, options, state_machine, state, lineno): + if arguments and content: + raise RuntimeError("plot:: directive can't have both args and content") + + document = state_machine.document + config = document.settings.env.config + + options.setdefault("include-source", config.plot_include_source) + + # determine input + rst_file = document.attributes["source"] + rst_dir = os.path.dirname(rst_file) + + if arguments: + if not config.plot_basedir: + source_file_name = os.path.join(rst_dir, directives.uri(arguments[0])) + else: + source_file_name = os.path.join( + setup.confdir, config.plot_basedir, directives.uri(arguments[0]) + ) + code = open(source_file_name, "r").read() + output_base = os.path.basename(source_file_name) + else: + source_file_name = rst_file + code = textwrap.dedent("\n".join(map(str, content))) + counter = document.attributes.get("_plot_counter", 0) + 1 + document.attributes["_plot_counter"] = counter + base, ext = os.path.splitext(os.path.basename(source_file_name)) + output_base = "%s-%d.py" % (base, counter) + + base, source_ext = os.path.splitext(output_base) + if source_ext in (".py", ".rst", ".txt"): + output_base = base + else: + source_ext = "" + + # ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames + output_base = output_base.replace(".", "-") + + # is it in doctest format? + is_doctest = contains_doctest(code) + if "format" in options: + if options["format"] == "python": + is_doctest = False + else: + is_doctest = True + + # determine output directory name fragment + source_rel_name = relpath(source_file_name, setup.confdir) + source_rel_dir = os.path.dirname(source_rel_name) + while source_rel_dir.startswith(os.path.sep): + source_rel_dir = source_rel_dir[1:] + + # build_dir: where to place output files (temporarily) + build_dir = os.path.join( + os.path.dirname(setup.app.doctreedir), "plot_directive", source_rel_dir + ) + if not os.path.exists(build_dir): + os.makedirs(build_dir) + + # output_dir: final location in the builder's directory + dest_dir = os.path.abspath(os.path.join(setup.app.builder.outdir, source_rel_dir)) + + # how to link to files from the RST file + dest_dir_link = os.path.join( + relpath(setup.confdir, rst_dir), source_rel_dir + ).replace(os.path.sep, "/") + build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, "/") + source_link = dest_dir_link + "/" + output_base + source_ext + + # make figures + try: + results = makefig(code, source_file_name, build_dir, output_base, config) + errors = [] + except PlotError as err: + reporter = state.memo.reporter + sm = reporter.system_message( + 2, "Exception occurred in plotting %s: %s" % (output_base, err), line=lineno + ) + results = [(code, [])] + errors = [sm] + + # generate output restructuredtext + total_lines = [] + for j, (code_piece, images) in enumerate(results): + if options["include-source"]: + if is_doctest: + lines = [""] + lines += [row.rstrip() for row in code_piece.split("\n")] + else: + lines = [".. code-block:: python", ""] + lines += [" %s" % row.rstrip() for row in code_piece.split("\n")] + source_code = "\n".join(lines) + else: + source_code = "" + + opts = [ + ":%s: %s" % (key, val) + for key, val in list(options.items()) + if key in ("alt", "height", "width", "scale", "align", "class") + ] + + only_html = ".. only:: html" + only_latex = ".. only:: latex" + + if j == 0: + src_link = source_link + else: + src_link = None + + result = format_template( + TEMPLATE, + dest_dir=dest_dir_link, + build_dir=build_dir_link, + source_link=src_link, + multi_image=len(images) > 1, + only_html=only_html, + only_latex=only_latex, + options=opts, + images=images, + source_code=source_code, + html_show_formats=config.plot_html_show_formats, + ) + + total_lines.extend(result.split("\n")) + total_lines.extend("\n") + + if total_lines: + state_machine.insert_input(total_lines, source=source_file_name) + + # copy image files to builder's output directory + if not os.path.exists(dest_dir): + os.makedirs(dest_dir) + + for code_piece, images in results: + for img in images: + for fn in img.filenames(): + shutil.copyfile(fn, os.path.join(dest_dir, os.path.basename(fn))) + + # copy script (if necessary) + if source_file_name == rst_file: + target_name = os.path.join(dest_dir, output_base + source_ext) + f = open(target_name, "w") + f.write(unescape_doctest(code)) + f.close() + + return errors + + +# ------------------------------------------------------------------------------ +# Run code and capture figures +# ------------------------------------------------------------------------------ + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt +import matplotlib.image as image +from matplotlib import _pylab_helpers + +import exceptions + + +def contains_doctest(text): + try: + # check if it's valid Python as-is + compile(text, "", "exec") + return False + except SyntaxError: + pass + r = re.compile(r"^\s*>>>", re.M) + m = r.search(text) + return bool(m) + + +def unescape_doctest(text): + """ + Extract code from a piece of text, which contains either Python code + or doctests. + + """ + if not contains_doctest(text): + return text + + code = "" + for line in text.split("\n"): + m = re.match(r"^\s*(>>>|\.\.\.) (.*)$", line) + if m: + code += m.group(2) + "\n" + elif line.strip(): + code += "# " + line.strip() + "\n" + else: + code += "\n" + return code + + +def split_code_at_show(text): + """ + Split code at plt.show() + + """ + + parts = [] + is_doctest = contains_doctest(text) + + part = [] + for line in text.split("\n"): + if (not is_doctest and line.strip() == "plt.show()") or ( + is_doctest and line.strip() == ">>> plt.show()" + ): + part.append(line) + parts.append("\n".join(part)) + part = [] + else: + part.append(line) + if "\n".join(part).strip(): + parts.append("\n".join(part)) + return parts + + +class PlotError(RuntimeError): + pass + + +def run_code(code, code_path, ns=None): + # Change the working directory to the directory of the example, so + # it can get at its data files, if any. + pwd = os.getcwd() + old_sys_path = list(sys.path) + if code_path is not None: + dirname = os.path.abspath(os.path.dirname(code_path)) + os.chdir(dirname) + sys.path.insert(0, dirname) + + # Redirect stdout + stdout = sys.stdout + sys.stdout = StringIO() + + # Reset sys.argv + old_sys_argv = sys.argv + sys.argv = [code_path] + + try: + try: + code = unescape_doctest(code) + if ns is None: + ns = {} + if not ns: + exec(setup.config.plot_pre_code, ns) + exec(code, ns) + except (Exception, SystemExit) as err: + raise PlotError(traceback.format_exc()) + finally: + os.chdir(pwd) + sys.argv = old_sys_argv + sys.path[:] = old_sys_path + sys.stdout = stdout + return ns + + +# ------------------------------------------------------------------------------ +# Generating figures +# ------------------------------------------------------------------------------ + + +def out_of_date(original, derived): + """ + Returns True if derivative is out-of-date wrt original, + both of which are full file paths. + """ + return ( + not os.path.exists(derived) + or os.stat(derived).st_mtime < os.stat(original).st_mtime + ) + + +def makefig(code, code_path, output_dir, output_base, config): + """ + Run a pyplot script *code* and save the images under *output_dir* + with file names derived from *output_base* + + """ + + # -- Parse format list + default_dpi = {"png": 80, "hires.png": 200, "pdf": 50} + formats = [] + for fmt in config.plot_formats: + if isinstance(fmt, str): + formats.append((fmt, default_dpi.get(fmt, 80))) + elif type(fmt) in (tuple, list) and len(fmt) == 2: + formats.append((str(fmt[0]), int(fmt[1]))) + else: + raise PlotError('invalid image format "%r" in plot_formats' % fmt) + + # -- Try to determine if all images already exist + + code_pieces = split_code_at_show(code) + + # Look for single-figure output files first + all_exists = True + img = ImageFile(output_base, output_dir) + for format, dpi in formats: + if out_of_date(code_path, img.filename(format)): + all_exists = False + break + img.formats.append(format) + + if all_exists: + return [(code, [img])] + + # Then look for multi-figure output files + results = [] + all_exists = True + for i, code_piece in enumerate(code_pieces): + images = [] + for j in range(1000): + img = ImageFile("%s_%02d_%02d" % (output_base, i, j), output_dir) + for format, dpi in formats: + if out_of_date(code_path, img.filename(format)): + all_exists = False + break + img.formats.append(format) + + # assume that if we have one, we have them all + if not all_exists: + all_exists = j > 0 + break + images.append(img) + if not all_exists: + break + results.append((code_piece, images)) + + if all_exists: + return results + + # -- We didn't find the files, so build them + + results = [] + ns = {} + + for i, code_piece in enumerate(code_pieces): + # Clear between runs + plt.close("all") + + # Run code + run_code(code_piece, code_path, ns) + + # Collect images + images = [] + fig_managers = _pylab_helpers.Gcf.get_all_fig_managers() + for j, figman in enumerate(fig_managers): + if len(fig_managers) == 1 and len(code_pieces) == 1: + img = ImageFile(output_base, output_dir) + else: + img = ImageFile("%s_%02d_%02d" % (output_base, i, j), output_dir) + images.append(img) + for format, dpi in formats: + try: + figman.canvas.figure.savefig(img.filename(format), dpi=dpi) + except exceptions.BaseException as err: + raise PlotError(traceback.format_exc()) + img.formats.append(format) + + # Results + results.append((code_piece, images)) + + return results + + +# ------------------------------------------------------------------------------ +# Relative pathnames +# ------------------------------------------------------------------------------ + +try: + from os.path import relpath +except ImportError: + # Copied from Python 2.7 + if "posix" in sys.builtin_module_names: + + def relpath(path, start=os.path.curdir): + """Return a relative version of a path""" + from os.path import sep, curdir, join, abspath, commonprefix, pardir + + if not path: + raise ValueError("no path specified") + + start_list = abspath(start).split(sep) + path_list = abspath(path).split(sep) + + # Work out how much of the filepath is shared by start and path. + i = len(commonprefix([start_list, path_list])) + + rel_list = [pardir] * (len(start_list) - i) + path_list[i:] + if not rel_list: + return curdir + return join(*rel_list) + + elif "nt" in sys.builtin_module_names: + + def relpath(path, start=os.path.curdir): + """Return a relative version of a path""" + from os.path import ( + sep, + curdir, + join, + abspath, + commonprefix, + pardir, + splitunc, + ) + + if not path: + raise ValueError("no path specified") + start_list = abspath(start).split(sep) + path_list = abspath(path).split(sep) + if start_list[0].lower() != path_list[0].lower(): + unc_path, rest = splitunc(path) + unc_start, rest = splitunc(start) + if bool(unc_path) ^ bool(unc_start): + raise ValueError( + "Cannot mix UNC and non-UNC paths (%s and %s)" % (path, start) + ) + else: + raise ValueError( + "path is on drive %s, start on drive %s" + % (path_list[0], start_list[0]) + ) + # Work out how much of the filepath is shared by start and path. + for i in range(min(len(start_list), len(path_list))): + if start_list[i].lower() != path_list[i].lower(): + break + else: + i += 1 + + rel_list = [pardir] * (len(start_list) - i) + path_list[i:] + if not rel_list: + return curdir + return join(*rel_list) + + else: + raise RuntimeError("Unsupported platform (no relpath available!)") diff --git a/doc/numpydoc-0.5/numpydoc/tests/test_docscrape.py b/doc/numpydoc-0.5/numpydoc/tests/test_docscrape.py new file mode 100644 index 0000000..5976957 --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc/tests/test_docscrape.py @@ -0,0 +1,841 @@ +# -*- encoding:utf-8 -*- +from __future__ import division, absolute_import, print_function + +import sys, textwrap + +from numpydoc.docscrape import NumpyDocString, FunctionDoc, ClassDoc +from numpydoc.docscrape_sphinx import SphinxDocString, SphinxClassDoc +from nose.tools import * + +if sys.version_info[0] >= 3: + sixu = lambda s: s +else: + sixu = lambda s: unicode(s, "unicode_escape") + + +doc_txt = """\ + numpy.multivariate_normal(mean, cov, shape=None, spam=None) + + Draw values from a multivariate normal distribution with specified + mean and covariance. + + The multivariate normal or Gaussian distribution is a generalisation + of the one-dimensional normal distribution to higher dimensions. + + Parameters + ---------- + mean : (N,) ndarray + Mean of the N-dimensional distribution. + + .. math:: + + (1+2+3)/3 + + cov : (N, N) ndarray + Covariance matrix of the distribution. + shape : tuple of ints + Given a shape of, for example, (m,n,k), m*n*k samples are + generated, and packed in an m-by-n-by-k arrangement. Because + each sample is N-dimensional, the output shape is (m,n,k,N). + + Returns + ------- + out : ndarray + The drawn samples, arranged according to `shape`. If the + shape given is (m,n,...), then the shape of `out` is is + (m,n,...,N). + + In other words, each entry ``out[i,j,...,:]`` is an N-dimensional + value drawn from the distribution. + list of str + This is not a real return value. It exists to test + anonymous return values. + + Other Parameters + ---------------- + spam : parrot + A parrot off its mortal coil. + + Raises + ------ + RuntimeError + Some error + + Warns + ----- + RuntimeWarning + Some warning + + Warnings + -------- + Certain warnings apply. + + Notes + ----- + Instead of specifying the full covariance matrix, popular + approximations include: + + - Spherical covariance (`cov` is a multiple of the identity matrix) + - Diagonal covariance (`cov` has non-negative elements only on the diagonal) + + This geometrical property can be seen in two dimensions by plotting + generated data-points: + + >>> mean = [0,0] + >>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis + + >>> x,y = multivariate_normal(mean,cov,5000).T + >>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show() + + Note that the covariance matrix must be symmetric and non-negative + definite. + + References + ---------- + .. [1] A. Papoulis, "Probability, Random Variables, and Stochastic + Processes," 3rd ed., McGraw-Hill Companies, 1991 + .. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification," + 2nd ed., Wiley, 2001. + + See Also + -------- + some, other, funcs + otherfunc : relationship + + Examples + -------- + >>> mean = (1,2) + >>> cov = [[1,0],[1,0]] + >>> x = multivariate_normal(mean,cov,(3,3)) + >>> print x.shape + (3, 3, 2) + + The following is probably true, given that 0.6 is roughly twice the + standard deviation: + + >>> print list( (x[0,0,:] - mean) < 0.6 ) + [True, True] + + .. index:: random + :refguide: random;distributions, random;gauss + + """ +doc = NumpyDocString(doc_txt) + + +def test_signature(): + assert doc["Signature"].startswith("numpy.multivariate_normal(") + assert doc["Signature"].endswith("spam=None)") + + +def test_summary(): + assert doc["Summary"][0].startswith("Draw values") + assert doc["Summary"][-1].endswith("covariance.") + + +def test_extended_summary(): + assert doc["Extended Summary"][0].startswith("The multivariate normal") + + +def test_parameters(): + assert_equal(len(doc["Parameters"]), 3) + assert_equal([n for n, _, _ in doc["Parameters"]], ["mean", "cov", "shape"]) + + arg, arg_type, desc = doc["Parameters"][1] + assert_equal(arg_type, "(N, N) ndarray") + assert desc[0].startswith("Covariance matrix") + assert doc["Parameters"][0][-1][-2] == " (1+2+3)/3" + + +def test_other_parameters(): + assert_equal(len(doc["Other Parameters"]), 1) + assert_equal([n for n, _, _ in doc["Other Parameters"]], ["spam"]) + arg, arg_type, desc = doc["Other Parameters"][0] + assert_equal(arg_type, "parrot") + assert desc[0].startswith("A parrot off its mortal coil") + + +def test_returns(): + assert_equal(len(doc["Returns"]), 2) + arg, arg_type, desc = doc["Returns"][0] + assert_equal(arg, "out") + assert_equal(arg_type, "ndarray") + assert desc[0].startswith("The drawn samples") + assert desc[-1].endswith("distribution.") + + arg, arg_type, desc = doc["Returns"][1] + assert_equal(arg, "list of str") + assert_equal(arg_type, "") + assert desc[0].startswith("This is not a real") + assert desc[-1].endswith("anonymous return values.") + + +def test_notes(): + assert doc["Notes"][0].startswith("Instead") + assert doc["Notes"][-1].endswith("definite.") + assert_equal(len(doc["Notes"]), 17) + + +def test_references(): + assert doc["References"][0].startswith("..") + assert doc["References"][-1].endswith("2001.") + + +def test_examples(): + assert doc["Examples"][0].startswith(">>>") + assert doc["Examples"][-1].endswith("True]") + + +def test_index(): + assert_equal(doc["index"]["default"], "random") + assert_equal(len(doc["index"]), 2) + assert_equal(len(doc["index"]["refguide"]), 2) + + +def non_blank_line_by_line_compare(a, b): + a = textwrap.dedent(a) + b = textwrap.dedent(b) + a = [l.rstrip() for l in a.split("\n") if l.strip()] + b = [l.rstrip() for l in b.split("\n") if l.strip()] + for n, line in enumerate(a): + if not line == b[n]: + raise AssertionError( + "Lines %s of a and b differ: " "\n>>> %s\n<<< %s\n" % (n, line, b[n]) + ) + + +def test_str(): + non_blank_line_by_line_compare( + str(doc), + """numpy.multivariate_normal(mean, cov, shape=None, spam=None) + +Draw values from a multivariate normal distribution with specified +mean and covariance. + +The multivariate normal or Gaussian distribution is a generalisation +of the one-dimensional normal distribution to higher dimensions. + +Parameters +---------- +mean : (N,) ndarray + Mean of the N-dimensional distribution. + + .. math:: + + (1+2+3)/3 + +cov : (N, N) ndarray + Covariance matrix of the distribution. +shape : tuple of ints + Given a shape of, for example, (m,n,k), m*n*k samples are + generated, and packed in an m-by-n-by-k arrangement. Because + each sample is N-dimensional, the output shape is (m,n,k,N). + +Returns +------- +out : ndarray + The drawn samples, arranged according to `shape`. If the + shape given is (m,n,...), then the shape of `out` is is + (m,n,...,N). + + In other words, each entry ``out[i,j,...,:]`` is an N-dimensional + value drawn from the distribution. +list of str + This is not a real return value. It exists to test + anonymous return values. + +Other Parameters +---------------- +spam : parrot + A parrot off its mortal coil. + +Raises +------ +RuntimeError + Some error + +Warns +----- +RuntimeWarning + Some warning + +Warnings +-------- +Certain warnings apply. + +See Also +-------- +`some`_, `other`_, `funcs`_ + +`otherfunc`_ + relationship + +Notes +----- +Instead of specifying the full covariance matrix, popular +approximations include: + + - Spherical covariance (`cov` is a multiple of the identity matrix) + - Diagonal covariance (`cov` has non-negative elements only on the diagonal) + +This geometrical property can be seen in two dimensions by plotting +generated data-points: + +>>> mean = [0,0] +>>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis + +>>> x,y = multivariate_normal(mean,cov,5000).T +>>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show() + +Note that the covariance matrix must be symmetric and non-negative +definite. + +References +---------- +.. [1] A. Papoulis, "Probability, Random Variables, and Stochastic + Processes," 3rd ed., McGraw-Hill Companies, 1991 +.. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification," + 2nd ed., Wiley, 2001. + +Examples +-------- +>>> mean = (1,2) +>>> cov = [[1,0],[1,0]] +>>> x = multivariate_normal(mean,cov,(3,3)) +>>> print x.shape +(3, 3, 2) + +The following is probably true, given that 0.6 is roughly twice the +standard deviation: + +>>> print list( (x[0,0,:] - mean) < 0.6 ) +[True, True] + +.. index:: random + :refguide: random;distributions, random;gauss""", + ) + + +def test_sphinx_str(): + sphinx_doc = SphinxDocString(doc_txt) + non_blank_line_by_line_compare( + str(sphinx_doc), + """ +.. index:: random + single: random;distributions, random;gauss + +Draw values from a multivariate normal distribution with specified +mean and covariance. + +The multivariate normal or Gaussian distribution is a generalisation +of the one-dimensional normal distribution to higher dimensions. + +:Parameters: + + **mean** : (N,) ndarray + + Mean of the N-dimensional distribution. + + .. math:: + + (1+2+3)/3 + + **cov** : (N, N) ndarray + + Covariance matrix of the distribution. + + **shape** : tuple of ints + + Given a shape of, for example, (m,n,k), m*n*k samples are + generated, and packed in an m-by-n-by-k arrangement. Because + each sample is N-dimensional, the output shape is (m,n,k,N). + +:Returns: + + **out** : ndarray + + The drawn samples, arranged according to `shape`. If the + shape given is (m,n,...), then the shape of `out` is is + (m,n,...,N). + + In other words, each entry ``out[i,j,...,:]`` is an N-dimensional + value drawn from the distribution. + + list of str + + This is not a real return value. It exists to test + anonymous return values. + +:Other Parameters: + + **spam** : parrot + + A parrot off its mortal coil. + +:Raises: + + **RuntimeError** + + Some error + +:Warns: + + **RuntimeWarning** + + Some warning + +.. warning:: + + Certain warnings apply. + +.. seealso:: + + :obj:`some`, :obj:`other`, :obj:`funcs` + + :obj:`otherfunc` + relationship + +.. rubric:: Notes + +Instead of specifying the full covariance matrix, popular +approximations include: + + - Spherical covariance (`cov` is a multiple of the identity matrix) + - Diagonal covariance (`cov` has non-negative elements only on the diagonal) + +This geometrical property can be seen in two dimensions by plotting +generated data-points: + +>>> mean = [0,0] +>>> cov = [[1,0],[0,100]] # diagonal covariance, points lie on x or y-axis + +>>> x,y = multivariate_normal(mean,cov,5000).T +>>> plt.plot(x,y,'x'); plt.axis('equal'); plt.show() + +Note that the covariance matrix must be symmetric and non-negative +definite. + +.. rubric:: References + +.. [1] A. Papoulis, "Probability, Random Variables, and Stochastic + Processes," 3rd ed., McGraw-Hill Companies, 1991 +.. [2] R.O. Duda, P.E. Hart, and D.G. Stork, "Pattern Classification," + 2nd ed., Wiley, 2001. + +.. only:: latex + + [1]_, [2]_ + +.. rubric:: Examples + +>>> mean = (1,2) +>>> cov = [[1,0],[1,0]] +>>> x = multivariate_normal(mean,cov,(3,3)) +>>> print x.shape +(3, 3, 2) + +The following is probably true, given that 0.6 is roughly twice the +standard deviation: + +>>> print list( (x[0,0,:] - mean) < 0.6 ) +[True, True] +""", + ) + + +doc2 = NumpyDocString( + """ + Returns array of indices of the maximum values of along the given axis. + + Parameters + ---------- + a : {array_like} + Array to look in. + axis : {None, integer} + If None, the index is into the flattened array, otherwise along + the specified axis""" +) + + +def test_parameters_without_extended_description(): + assert_equal(len(doc2["Parameters"]), 2) + + +doc3 = NumpyDocString( + """ + my_signature(*params, **kwds) + + Return this and that. + """ +) + + +def test_escape_stars(): + signature = str(doc3).split("\n")[0] + assert_equal(signature, "my_signature(\*params, \*\*kwds)") + + +doc4 = NumpyDocString( + """a.conj() + + Return an array with all complex-valued elements conjugated.""" +) + + +def test_empty_extended_summary(): + assert_equal(doc4["Extended Summary"], []) + + +doc5 = NumpyDocString( + """ + a.something() + + Raises + ------ + LinAlgException + If array is singular. + + Warns + ----- + SomeWarning + If needed + """ +) + + +def test_raises(): + assert_equal(len(doc5["Raises"]), 1) + name, _, desc = doc5["Raises"][0] + assert_equal(name, "LinAlgException") + assert_equal(desc, ["If array is singular."]) + + +def test_warns(): + assert_equal(len(doc5["Warns"]), 1) + name, _, desc = doc5["Warns"][0] + assert_equal(name, "SomeWarning") + assert_equal(desc, ["If needed"]) + + +def test_see_also(): + doc6 = NumpyDocString( + """ + z(x,theta) + + See Also + -------- + func_a, func_b, func_c + func_d : some equivalent func + foo.func_e : some other func over + multiple lines + func_f, func_g, :meth:`func_h`, func_j, + func_k + :obj:`baz.obj_q` + :class:`class_j`: fubar + foobar + """ + ) + + assert len(doc6["See Also"]) == 12 + for func, desc, role in doc6["See Also"]: + if func in ( + "func_a", + "func_b", + "func_c", + "func_f", + "func_g", + "func_h", + "func_j", + "func_k", + "baz.obj_q", + ): + assert not desc + else: + assert desc + + if func == "func_h": + assert role == "meth" + elif func == "baz.obj_q": + assert role == "obj" + elif func == "class_j": + assert role == "class" + else: + assert role is None + + if func == "func_d": + assert desc == ["some equivalent func"] + elif func == "foo.func_e": + assert desc == ["some other func over", "multiple lines"] + elif func == "class_j": + assert desc == ["fubar", "foobar"] + + +def test_see_also_print(): + class Dummy(object): + """ + See Also + -------- + func_a, func_b + func_c : some relationship + goes here + func_d + """ + + pass + + obj = Dummy() + s = str(FunctionDoc(obj, role="func")) + assert ":func:`func_a`, :func:`func_b`" in s + assert " some relationship" in s + assert ":func:`func_d`" in s + + +doc7 = NumpyDocString( + """ + + Doc starts on second line. + + """ +) + + +def test_empty_first_line(): + assert doc7["Summary"][0].startswith("Doc starts") + + +def test_no_summary(): + str( + SphinxDocString( + """ + Parameters + ----------""" + ) + ) + + +def test_unicode(): + doc = SphinxDocString( + """ + öäöäöäöäöåååå + + öäöäöäööäååå + + Parameters + ---------- + ååå : äää + ööö + + Returns + ------- + ååå : ööö + äää + + """ + ) + assert isinstance(doc["Summary"][0], str) + assert doc["Summary"][0] == "öäöäöäöäöåååå" + + +def test_plot_examples(): + cfg = dict(use_plots=True) + + doc = SphinxDocString( + """ + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> plt.plot([1,2,3],[4,5,6]) + >>> plt.show() + """, + config=cfg, + ) + assert "plot::" in str(doc), str(doc) + + doc = SphinxDocString( + """ + Examples + -------- + .. plot:: + + import matplotlib.pyplot as plt + plt.plot([1,2,3],[4,5,6]) + plt.show() + """, + config=cfg, + ) + assert str(doc).count("plot::") == 1, str(doc) + + +def test_class_members(): + class Dummy(object): + """ + Dummy class. + + """ + + def spam(self, a, b): + """Spam\n\nSpam spam.""" + pass + + def ham(self, c, d): + """Cheese\n\nNo cheese.""" + pass + + @property + def spammity(self): + """Spammity index""" + return 0.95 + + class Ignorable(object): + """local class, to be ignored""" + + pass + + for cls in (ClassDoc, SphinxClassDoc): + doc = cls(Dummy, config=dict(show_class_members=False)) + assert "Methods" not in str(doc), (cls, str(doc)) + assert "spam" not in str(doc), (cls, str(doc)) + assert "ham" not in str(doc), (cls, str(doc)) + assert "spammity" not in str(doc), (cls, str(doc)) + assert "Spammity index" not in str(doc), (cls, str(doc)) + + doc = cls(Dummy, config=dict(show_class_members=True)) + assert "Methods" in str(doc), (cls, str(doc)) + assert "spam" in str(doc), (cls, str(doc)) + assert "ham" in str(doc), (cls, str(doc)) + assert "spammity" in str(doc), (cls, str(doc)) + + if cls is SphinxClassDoc: + assert ".. autosummary::" in str(doc), str(doc) + else: + assert "Spammity index" in str(doc), str(doc) + + +def test_duplicate_signature(): + # Duplicate function signatures occur e.g. in ufuncs, when the + # automatic mechanism adds one, and a more detailed comes from the + # docstring itself. + + doc = NumpyDocString( + """ + z(x1, x2) + + z(a, theta) + """ + ) + + assert doc["Signature"].strip() == "z(a, theta)" + + +class_doc_txt = """ + Foo + + Parameters + ---------- + f : callable ``f(t, y, *f_args)`` + Aaa. + jac : callable ``jac(t, y, *jac_args)`` + Bbb. + + Attributes + ---------- + t : float + Current time. + y : ndarray + Current variable values. + + Methods + ------- + a + b + c + + Examples + -------- + For usage examples, see `ode`. +""" + + +def test_class_members_doc(): + doc = ClassDoc(None, class_doc_txt) + non_blank_line_by_line_compare( + str(doc), + """ + Foo + + Parameters + ---------- + f : callable ``f(t, y, *f_args)`` + Aaa. + jac : callable ``jac(t, y, *jac_args)`` + Bbb. + + Examples + -------- + For usage examples, see `ode`. + + Attributes + ---------- + t : float + Current time. + y : ndarray + Current variable values. + + Methods + ------- + a + + b + + c + + .. index:: + + """, + ) + + +def test_class_members_doc_sphinx(): + doc = SphinxClassDoc(None, class_doc_txt) + non_blank_line_by_line_compare( + str(doc), + """ + Foo + + :Parameters: + + **f** : callable ``f(t, y, *f_args)`` + + Aaa. + + **jac** : callable ``jac(t, y, *jac_args)`` + + Bbb. + + .. rubric:: Examples + + For usage examples, see `ode`. + + .. rubric:: Attributes + + === ========== + t (float) Current time. + y (ndarray) Current variable values. + === ========== + + .. rubric:: Methods + + === ========== + a + b + c + === ========== + + """, + ) + + +if __name__ == "__main__": + import nose + + nose.run() diff --git a/doc/numpydoc-0.5/numpydoc/tests/test_linkcode.py b/doc/numpydoc-0.5/numpydoc/tests/test_linkcode.py new file mode 100644 index 0000000..340166a --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc/tests/test_linkcode.py @@ -0,0 +1,5 @@ +from __future__ import division, absolute_import, print_function + +import numpydoc.linkcode + +# No tests at the moment... diff --git a/doc/numpydoc-0.5/numpydoc/tests/test_phantom_import.py b/doc/numpydoc-0.5/numpydoc/tests/test_phantom_import.py new file mode 100644 index 0000000..75de7cc --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc/tests/test_phantom_import.py @@ -0,0 +1,14 @@ +from __future__ import division, absolute_import, print_function + +import sys +from nose import SkipTest + + +def test_import(): + if sys.version_info[0] >= 3: + raise SkipTest("phantom_import not ported to Py3") + + import numpydoc.phantom_import + + +# No tests at the moment... diff --git a/doc/numpydoc-0.5/numpydoc/tests/test_plot_directive.py b/doc/numpydoc-0.5/numpydoc/tests/test_plot_directive.py new file mode 100644 index 0000000..e6ed81c --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc/tests/test_plot_directive.py @@ -0,0 +1,15 @@ +from __future__ import division, absolute_import, print_function + +import sys +from nose import SkipTest + + +def test_import(): + if sys.version_info[0] >= 3: + raise SkipTest( + "plot_directive not ported to Python 3 (use the one from Matplotlib instead)" + ) + import numpydoc.plot_directive + + +# No tests at the moment... diff --git a/doc/numpydoc-0.5/numpydoc/tests/test_traitsdoc.py b/doc/numpydoc-0.5/numpydoc/tests/test_traitsdoc.py new file mode 100644 index 0000000..a4b8bd6 --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc/tests/test_traitsdoc.py @@ -0,0 +1,13 @@ +from __future__ import division, absolute_import, print_function + +import sys +from nose import SkipTest + + +def test_import(): + if sys.version_info[0] >= 3: + raise SkipTest("traitsdoc not ported to Python3") + import numpydoc.traitsdoc + + +# No tests at the moment... diff --git a/doc/numpydoc-0.5/numpydoc/traitsdoc.py b/doc/numpydoc-0.5/numpydoc/traitsdoc.py new file mode 100644 index 0000000..b17a89f --- /dev/null +++ b/doc/numpydoc-0.5/numpydoc/traitsdoc.py @@ -0,0 +1,143 @@ +""" +========= +traitsdoc +========= + +Sphinx extension that handles docstrings in the Numpy standard format, [1] +and support Traits [2]. + +This extension can be used as a replacement for ``numpydoc`` when support +for Traits is required. + +.. [1] http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines#docstring-standard +.. [2] http://code.enthought.com/projects/traits/ + +""" +from __future__ import division, absolute_import, print_function + +import inspect +import os +import pydoc +import collections + +from . import docscrape +from . import docscrape_sphinx +from .docscrape_sphinx import SphinxClassDoc, SphinxFunctionDoc, SphinxDocString + +from . import numpydoc + +from . import comment_eater + + +class SphinxTraitsDoc(SphinxClassDoc): + def __init__(self, cls, modulename="", func_doc=SphinxFunctionDoc): + if not inspect.isclass(cls): + raise ValueError("Initialise using a class. Got %r" % cls) + self._cls = cls + + if modulename and not modulename.endswith("."): + modulename += "." + self._mod = modulename + self._name = cls.__name__ + self._func_doc = func_doc + + docstring = pydoc.getdoc(cls) + docstring = docstring.split("\n") + + # De-indent paragraph + try: + indent = min(len(s) - len(s.lstrip()) for s in docstring if s.strip()) + except ValueError: + indent = 0 + + for n, line in enumerate(docstring): + docstring[n] = docstring[n][indent:] + + self._doc = docscrape.Reader(docstring) + self._parsed_data = { + "Signature": "", + "Summary": "", + "Description": [], + "Extended Summary": [], + "Parameters": [], + "Returns": [], + "Raises": [], + "Warns": [], + "Other Parameters": [], + "Traits": [], + "Methods": [], + "See Also": [], + "Notes": [], + "References": "", + "Example": "", + "Examples": "", + "index": {}, + } + + self._parse() + + def _str_summary(self): + return self["Summary"] + [""] + + def _str_extended_summary(self): + return self["Description"] + self["Extended Summary"] + [""] + + def __str__(self, indent=0, func_role="func"): + out = [] + out += self._str_signature() + out += self._str_index() + [""] + out += self._str_summary() + out += self._str_extended_summary() + for param_list in ("Parameters", "Traits", "Methods", "Returns", "Raises"): + out += self._str_param_list(param_list) + out += self._str_see_also("obj") + out += self._str_section("Notes") + out += self._str_references() + out += self._str_section("Example") + out += self._str_section("Examples") + out = self._str_indent(out, indent) + return "\n".join(out) + + +def looks_like_issubclass(obj, classname): + """ Return True if the object has a class or superclass with the given class + name. + + Ignores old-style classes. + """ + t = obj + if t.__name__ == classname: + return True + for klass in t.__mro__: + if klass.__name__ == classname: + return True + return False + + +def get_doc_object(obj, what=None, config=None): + if what is None: + if inspect.isclass(obj): + what = "class" + elif inspect.ismodule(obj): + what = "module" + elif isinstance(obj, collections.Callable): + what = "function" + else: + what = "object" + if what == "class": + doc = SphinxTraitsDoc(obj, "", func_doc=SphinxFunctionDoc, config=config) + if looks_like_issubclass(obj, "HasTraits"): + for name, trait, comment in comment_eater.get_class_traits(obj): + # Exclude private traits. + if not name.startswith("_"): + doc["Traits"].append((name, trait, comment.splitlines())) + return doc + elif what in ("function", "method"): + return SphinxFunctionDoc(obj, "", config=config) + else: + return SphinxDocString(pydoc.getdoc(obj), config=config) + + +def setup(app): + # init numpydoc + numpydoc.setup(app, get_doc_object) diff --git a/doc/numpydoc-0.5/setup.cfg b/doc/numpydoc-0.5/setup.cfg new file mode 100644 index 0000000..861a9f5 --- /dev/null +++ b/doc/numpydoc-0.5/setup.cfg @@ -0,0 +1,5 @@ +[egg_info] +tag_build = +tag_date = 0 +tag_svn_revision = 0 + diff --git a/doc/numpydoc-0.5/setup.py b/doc/numpydoc-0.5/setup.py new file mode 100644 index 0000000..0f12aed --- /dev/null +++ b/doc/numpydoc-0.5/setup.py @@ -0,0 +1,32 @@ +from __future__ import division, print_function + +import sys +import setuptools +from distutils.core import setup + +if sys.version_info[:2] < (2, 6) or (3, 0) <= sys.version_info[0:2] < (3, 3): + raise RuntimeError("Python version 2.6, 2.7 or >= 3.3 required.") + +version = "0.5" + +setup( + name="numpydoc", + packages=["numpydoc"], + version=version, + description="Sphinx extension to support docstrings in Numpy format", + # classifiers from http://pypi.python.org/pypi?%3Aaction=list_classifiers + classifiers=[ + "Development Status :: 3 - Alpha", + "Environment :: Plugins", + "License :: OSI Approved :: BSD License", + "Topic :: Documentation", + ], + keywords="sphinx numpy", + author="Pauli Virtanen and others", + author_email="pav@iki.fi", + url="https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt", + license="BSD", + requires=["sphinx (>= 1.0.1)"], + package_data={"numpydoc": ["tests/test_*.py"]}, + test_suite="nose.collector", +) diff --git a/doc/source/an_model.rst b/doc/source/an_model.rst new file mode 100644 index 0000000..6539d07 --- /dev/null +++ b/doc/source/an_model.rst @@ -0,0 +1,28 @@ +an_model +-------- + +.. automodule:: cnmodel.an_model + :members: + :undoc-members: + :show-inheritance: + + +cnmodel.an_model.cache +====================== + +.. automodule:: cnmodel.an_model.cache + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.an_model.wrapper +======================== + +.. automodule:: cnmodel.an_model.wrapper + :members: + :undoc-members: + :show-inheritance: + :noindex: + + diff --git a/doc/source/architecture.rst b/doc/source/architecture.rst new file mode 100644 index 0000000..f6b7a61 --- /dev/null +++ b/doc/source/architecture.rst @@ -0,0 +1,180 @@ +Architecture of CNModel +======================= + +CNModel is built in a layered architecture that provides both high-level tools +for constructing and simulating networks, as well as low-level access to the +individual components. The model consists of three major pieces: *cell types*, +which describe the morphology and membrane physiology of the various cell types +in the cochlear nucleus; *synapse types*, which describe the strength, kinetics, +and short-term plasticity of the many synaptic connections; and *populations*, +which describe the aggregate organization of cell types, including their +distribution within the nucleus and their patterns of connectivity. + + .. figure:: architecture.svg + + +Cells +----- + +The cell types found in the cochlear nucleus (bushy, t-stellate, etc.) are each +represented in CNModel as classes that inherit from the base `Cell` class. One +instance of any of these classes represents exactly one neuron, and internally +manages any number of NEURON sections and mechanisms. + +Each class is responsible for determining the morphology and intrinsic membrane +properties of the cell it represents. Additionally, cell classes define the +properties of their synapses in a cooperative manner: the pre- snd postsynaptic +cells each create half of the synapse. + +Morphology can be procedurally generated (usually a single somatic section, +perhaps with another for a dendrite and/or axon), or it can be loaded from an +SWC file. After the cell morphology is established, the membrane is "decorated" +with channels using a `ChannelDecorator` object. + +Cell classes may be further divided into a class hierarchy. For example, the +base `DStellate` class is further inherited by `DStellateRothman` and +`DStellateEager` classes that each implement different D-stellate models that +have been published previously. To simplify (and in many cases to automate) the +creation of cells each base cell class (`Bushy`, `SGC`, `TStellate`, etc.) +implements a `create` method that can be used to generate instances from any of +the subclasses. + + +Synapses +-------- + +Every synapse in CNModel is represented by an instance of the `Synapse` class. +This class contains two objects: a `Terminal`, and a `PSD`. Synapses are created +by calling the `connect` method of the presynaptic cell with the postsynaptic +cell as an argument:: + + pre_cell.connect(post_cell) + +When `connect` is called, the presynaptic terminal is created by calling +``pre_cell.make_terminal()``, and the postsynaptic receptors are created by +calling ``post_cell.make_psd()``. In this way, both pre- and postsynaptic +cells are given a chance to influence the creation of the synapse. + +CNModel implements most synapses in two different ways. The first is a simple +synapse that implements variable amplitude, short-term plasticity, and double- +exponential rise/fall kinetics. This synapse is relatively efficient to compute +and simple to configure. The second synapse implementation is a much more +physiologically detailed model that includes stochastic release from multiple +release zones per terminal, synaptic cleft diffusion, and state models of +postsynaptic receptors. This synapse is computationally expensive but may capture +important behaviors that are not possible with the simpler implementation. + + +Populations +----------- + +Populations are objects that encapsulate a group of cells sharing a common cell +class. Each base `Cell` class has a corresponding `Population` class that +implements the organization of many cells within the nucleus and the patterns +of connectivity between populations. + +Conceptually, a `Population` represents *all* cells of a particular type within +the nucleus. When a population is created, it initially decides how many cells +is will represent and how to distribute properties across those cells. For +example, an `SGC` population describes 10k cells distributed uniformly across +the tonotopic axis. Initially, none of these 10k cells are created; rather, +each cell is simply represented as a virtual placeholder, and only instantiated +when it is explicitly requested or when it is required to satisfy the input +requirements for another cell. + +Populations are connected to each other in much the same way cells are:: + + pre_pop.connect(post_pop) + +Like the virtual cells, however, this connection does not create any synapses, +but instead merely records the fact that one population of cells projects to +another. Once the populations of interest are created and connected, the user +then manually instantiates only the cells that they wish to record from, and +finally the entire network of presynaptic inputs is automatically instantiated. + +Because populations manage the creation of synaptic connections between large +groups of neurons, they are also responsible for ensuring that the appropriate +patterns of connectivity are followed. For example, this allows us to ensure +that bushy cells are automatically connected to auditory nerve fibers coming +from a relatively narrow window across the tonotopic axis, whereas D-stellate +cells integrate the same inputs across a broader window. + + +Physiological parameters +------------------------ + +Throughout the model we use physiological parameters (channel kinetics, +synaptic strengths, convergence ratios, etc.) that are often derived +from published reports. In an attempt to make the provenance of these +parameters clear, we have separated them from the source code and embedded +them in annotated tables. These tables are found in `cnmodel/data`, and are +automatically parsed by the model as they are needed. + +Morphology +---------- + +The model implements the ability to use morphological reconstructions of +cells, as rendered in hoc files, the native NEURON format. These reconstructions +can be decorated with ion channels and synapses according to pre-specified +tables or pre-defined rules. + +Unit testing +------------ + +CNModel attempts to reproduce several specific published observations. +The complexity of the model makes it quite fragile--small modifications to one +physiological parameter may have unexpected (and sometimes unnoticed) +consequences in the output of the model. + +To combat this unavoidable fragility, CNModel includes a large battery of unit +tests that are used to ensure the model output is stable across modifications +and platforms, and that it does reproduce our target observations within +reasonable limits. As such, any modification to the model should usually be +followed soon after by running the unit tests (these depend on the py.test +package and may be invoked by running the included `test.py` script). + + +Auditory nerve input +-------------------- + +CNModel builds from the auditory periphery model developed by Zilany et al. +(2014). The periphery model converts auditory stimuli into +spike trains for auditory nerve fibers of a specific CF and SR group. + +CNModel uses the Python version of the auditory periphery model +as implemented by Rudnicki and Hemmert (available from https://github.com/mrkrd/cochlea). +This version does not require MATLAB, and in some simulations may run slightly faster +because there is no delay associated with loading (and unloading) MATLAB. The +interface is otherwise exactly the same, and the model type can be selected +at runtime. + +An alternative approach is to use the original auditory periphery model. Because +this model was developed in MATLAB, CNModel uses a Python-to-MATLAB bridge +that transparently invokes the periphery model in a background process. +When using CNModel, is is generally not necessary to manually interact with +MATLAB in any way; this interaction is wrapped within functions in the +`cnmodel/an_model` subpackage. + +At present, there is no mechanism for feedback from the cochlear nucleus model +back into the auditory periphery model. As such, the output of the periphery +model is a convenient place to do some caching--we can precompute auditory +nerve spike trains in response to various sound stimuli and reuse those spike +trains to improve the computational performance of the nucleus model. This +caching is performed automatically, but relies on the use of `Sound` objects +(described below) as a mechanism for storing and retrieving cached spike trains. + + +Generating sound stimuli +------------------------ + +Sound stimuli are defined as subclasses of `cnmodel.util.sound.Sound`. Each +subclass (for example, `TonePip` and `NoisePip`) defines the function for +generating a sound waveform, but also provides a unique key that is used to +store and retrieve auditory nerve spike trains that were generated with +a particular stimulus. + +`Sound` objects may be passed directly to `SGC` cells or populations, and the +necessary spike trains will be automatically computed (or read from cache). + + + diff --git a/doc/source/architecture.svg b/doc/source/architecture.svg new file mode 100644 index 0000000..f097372 --- /dev/null +++ b/doc/source/architecture.svg @@ -0,0 +1,1740 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + Populations + + Cells + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Channels and + Receptors + + + + + + + + + + + + + + AMPA + + + + + + + + + + + + + NMDA + + + + + + + + + + + + + Gly + + + + + + + + + + + + + GABA + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Na + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + KLT + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + KHT + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Ih + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + KA + + + + NEURON + + + Python + + + + + + Bushy + + + + TStellate + + + + SGC + + + + Pyramidal + + + + Tuberculov. + + + + DStellate + + + + + + + + + + + + + + + + + + + + + + Octopus + + + + AuditoryPeripheryModel + + + + + diff --git a/doc/source/cells.rst b/doc/source/cells.rst new file mode 100644 index 0000000..dffda1e --- /dev/null +++ b/doc/source/cells.rst @@ -0,0 +1,106 @@ +Cell classes +------------ + +.. automodule:: cnmodel.cells + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: Cell + :members: + +Individual cell subclasses +-------------------------- + +cnmodel.cells.bushy +=================== + +.. automodule:: cnmodel.cells.bushy + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.cells.cartwheel +======================= + +.. automodule:: cnmodel.cells.cartwheel + :members: + :undoc-members: + :show-inheritance: + :noindex: + +.. cnmodel.cells.cell class +.. ------------------------- +.. +.. .. automodule:: cnmodel.cells.cell +.. :members: +.. :undoc-members: +.. :show-inheritance: +.. :noindex: + +cnmodel.cells.dstellate +======================= + +.. automodule:: cnmodel.cells.dstellate + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.cells.hh +================ + +.. automodule:: cnmodel.cells.hh + :members: + :undoc-members: + :noindex: + :show-inheritance: + +cnmodel.cells.octopus +===================== + +.. automodule:: cnmodel.cells.octopus + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.cells.pyramidal +======================= + +.. automodule:: cnmodel.cells.pyramidal + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.cells.sgc +================= + +.. automodule:: cnmodel.cells.sgc + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.cells.tstellate +======================= + +.. automodule:: cnmodel.cells.tstellate + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.cells.tuberculoventral +============================== + +.. automodule:: cnmodel.cells.tuberculoventral + :members: + :undoc-members: + :show-inheritance: + :noindex: + + + diff --git a/doc/source/conf.py b/doc/source/conf.py new file mode 100644 index 0000000..6af3c00 --- /dev/null +++ b/doc/source/conf.py @@ -0,0 +1,167 @@ +# -*- coding: utf-8 -*- +# +# CNModel documentation build configuration file, created by +# sphinx-quickstart on Sun Apr 2 15:20:59 2017. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import sys + +sys.path.insert(0, os.path.abspath("../..")) + + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.todo", + "sphinx.ext.coverage", + "sphinx.ext.mathjax", + "sphinx.ext.viewcode", + "sphinx.ext.napoleon", +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = ".rst" + +# The master toctree document. +master_doc = "index" +autoclass_content = "both" + +# General information about the project. +project = u"CNModel" +copyright = u"2017, 2018, Paul B. Manis and Luke Campagnola" +author = u"Paul B. Manis and Luke Campagnola" + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = u"0" +# The full version, including alpha/beta/rc tags. +release = u"0.2" + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = [] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +# html_theme = 'alabaster' +html_theme = "classic" +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + + +# -- Options for HTMLHelp output ------------------------------------------ + +# Output file base name for HTML help builder. +htmlhelp_basename = "CNModeldoc" + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "CNModel.tex", + u"CNModel Documentation", + u"Paul B. Manis and Luke Campagnola", + "manual", + ) +] + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [(master_doc, "cnmodel", u"CNModel Documentation", [author], 1)] + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "CNModel", + u"CNModel Documentation", + author, + "CNModel", + "One line description of project.", + "Miscellaneous", + ) +] diff --git a/doc/source/data.rst b/doc/source/data.rst new file mode 100644 index 0000000..3c852a7 --- /dev/null +++ b/doc/source/data.rst @@ -0,0 +1,37 @@ +cnmodel.data package +-------------------- + +.. autofunction:: cnmodel.data.get + +.. autofunction:: cnmodel.data.get_source + +.. autofunction:: cnmodel.data.add_table_data + +cnmodel.data.connectivity +========================= + +.. literalinclude:: ../../cnmodel/data/connectivity.py + :language: python + :linenos: + +cnmodel.data.synapses +===================== + +.. literalinclude:: ../../cnmodel/data/synapses.py + :language: python + :linenos: + +cnmodel.data.populations +======================== + +.. literalinclude:: ../../cnmodel/data/populations.py + :language: python + :linenos: + +cnmodel.data.ionchannels +======================== + +.. literalinclude:: ../../cnmodel/data/ionchannels.py + :language: python + :linenos: + \ No newline at end of file diff --git a/doc/source/decorator.rst b/doc/source/decorator.rst new file mode 100644 index 0000000..873b2f1 --- /dev/null +++ b/doc/source/decorator.rst @@ -0,0 +1,16 @@ +cnmodel.decorator package +------------------------- + +.. automodule:: cnmodel.decorator + :members: + :undoc-members: + :show-inheritance: + +cnmodel.decorator.decorator +============================ + +.. automodule:: cnmodel.decorator.decorator + :members: + :undoc-members: + :show-inheritance: + :noindex: diff --git a/doc/source/examples.rst b/doc/source/examples.rst new file mode 100644 index 0000000..aadd332 --- /dev/null +++ b/doc/source/examples.rst @@ -0,0 +1,31 @@ + +Examples +======== + + +Contents: + +.. toctree:: + :maxdepth: 0 + + examples/test_circuit + examples/test_mechanisms + examples/test_an_model + examples/test_bushy_variation + examples/test_simple_synapses + examples/test_mso_inputs + examples/test_sgc_input_phaselocking + examples/test_populations + examples/test_sgc_input + examples/test_cells + examples/test_physiology + examples/figures + examples/test_ccstim + examples/test_sounds + examples/toy_model + examples/test_sound_stim + examples/test_sgc_input_PSTH + examples/test_synapses + examples/test_decorator + examples/plot_hcno_kinetics + examples/play_test_sounds diff --git a/doc/source/examples/figures.rst b/doc/source/examples/figures.rst new file mode 100644 index 0000000..9c20471 --- /dev/null +++ b/doc/source/examples/figures.rst @@ -0,0 +1,22 @@ + +examples.figures +---------------- + +Plot selected figures from paper, Manis and Campagnola, Hearing Research, 2018. +To obtain the original results, this should be run after checking out the +"hearing-research-2018" tag available in the repository on github. + +From the main cnmodel directory:: + + $ ./examples figures.sh fignum + +where fignum is one of 2a, 2b, 2c, 3, 4, 5, 6a, 6b, or 7. + +Note that Figure 7 may take several **hours** to generate. + + + + +.. literalinclude:: ../../../examples/figures.py + :language: python + :linenos: diff --git a/doc/source/examples/play_test_sounds.rst b/doc/source/examples/play_test_sounds.rst new file mode 100644 index 0000000..23e57a6 --- /dev/null +++ b/doc/source/examples/play_test_sounds.rst @@ -0,0 +1,10 @@ + +examples.play_test_sounds +------------------------- + +.. automodule:: examples.play_test_sounds + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/plot_hcno_kinetics.rst b/doc/source/examples/plot_hcno_kinetics.rst new file mode 100644 index 0000000..8c6118b --- /dev/null +++ b/doc/source/examples/plot_hcno_kinetics.rst @@ -0,0 +1,10 @@ + +examples.plot_hcno_kinetics +--------------------------- + +.. automodule:: examples.plot_hcno_kinetics + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/test_an_model.rst b/doc/source/examples/test_an_model.rst new file mode 100644 index 0000000..0bbf84c --- /dev/null +++ b/doc/source/examples/test_an_model.rst @@ -0,0 +1,10 @@ + +examples.test_an_model +---------------------- + +.. automodule:: examples.test_an_model + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/test_bushy_variation.rst b/doc/source/examples/test_bushy_variation.rst new file mode 100644 index 0000000..1c17940 --- /dev/null +++ b/doc/source/examples/test_bushy_variation.rst @@ -0,0 +1,10 @@ + +examples.test_bushy_variation +----------------------------- + +.. automodule:: examples.test_bushy_variation + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/test_ccstim.rst b/doc/source/examples/test_ccstim.rst new file mode 100644 index 0000000..33d7512 --- /dev/null +++ b/doc/source/examples/test_ccstim.rst @@ -0,0 +1,10 @@ + +examples.test_ccstim +-------------------- + +.. automodule:: examples.test_ccstim + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/test_cells.rst b/doc/source/examples/test_cells.rst new file mode 100644 index 0000000..7ee35aa --- /dev/null +++ b/doc/source/examples/test_cells.rst @@ -0,0 +1,10 @@ + +examples.test_cells +------------------- + +.. automodule:: examples.test_cells + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/test_circuit.rst b/doc/source/examples/test_circuit.rst new file mode 100644 index 0000000..2e03092 --- /dev/null +++ b/doc/source/examples/test_circuit.rst @@ -0,0 +1,10 @@ + +examples.test_circuit +--------------------- + +.. automodule:: examples.test_circuit + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/test_decorator.rst b/doc/source/examples/test_decorator.rst new file mode 100644 index 0000000..48bb356 --- /dev/null +++ b/doc/source/examples/test_decorator.rst @@ -0,0 +1,10 @@ + +examples.test_decorator +----------------------- + +.. automodule:: examples.test_decorator + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/test_mechanisms.rst b/doc/source/examples/test_mechanisms.rst new file mode 100644 index 0000000..834d1ce --- /dev/null +++ b/doc/source/examples/test_mechanisms.rst @@ -0,0 +1,10 @@ + +examples.test_mechanisms +------------------------ + +.. automodule:: examples.test_mechanisms + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/test_mso_inputs.rst b/doc/source/examples/test_mso_inputs.rst new file mode 100644 index 0000000..6d27b5b --- /dev/null +++ b/doc/source/examples/test_mso_inputs.rst @@ -0,0 +1,10 @@ + +examples.test_mso_inputs +------------------------ + +.. automodule:: examples.test_mso_inputs + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/test_physiology.rst b/doc/source/examples/test_physiology.rst new file mode 100644 index 0000000..4ea046e --- /dev/null +++ b/doc/source/examples/test_physiology.rst @@ -0,0 +1,10 @@ + +examples.test_physiology +------------------------ + +.. automodule:: examples.test_physiology + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/test_populations.rst b/doc/source/examples/test_populations.rst new file mode 100644 index 0000000..e79b210 --- /dev/null +++ b/doc/source/examples/test_populations.rst @@ -0,0 +1,10 @@ + +examples.test_populations +------------------------- + +.. automodule:: examples.test_populations + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/test_sgc_input.rst b/doc/source/examples/test_sgc_input.rst new file mode 100644 index 0000000..b98447b --- /dev/null +++ b/doc/source/examples/test_sgc_input.rst @@ -0,0 +1,10 @@ + +examples.test_sgc_input +----------------------- + +.. automodule:: examples.test_sgc_input + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/test_sgc_input_PSTH.rst b/doc/source/examples/test_sgc_input_PSTH.rst new file mode 100644 index 0000000..9033450 --- /dev/null +++ b/doc/source/examples/test_sgc_input_PSTH.rst @@ -0,0 +1,10 @@ + +examples.test_sgc_input_PSTH +---------------------------- + +.. automodule:: examples.test_sgc_input_PSTH + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/test_sgc_input_phaselocking.rst b/doc/source/examples/test_sgc_input_phaselocking.rst new file mode 100644 index 0000000..2177ba6 --- /dev/null +++ b/doc/source/examples/test_sgc_input_phaselocking.rst @@ -0,0 +1,10 @@ + +examples.test_sgc_input_phaselocking +------------------------------------ + +.. automodule:: examples.test_sgc_input_phaselocking + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/test_simple_synapses.rst b/doc/source/examples/test_simple_synapses.rst new file mode 100644 index 0000000..e868225 --- /dev/null +++ b/doc/source/examples/test_simple_synapses.rst @@ -0,0 +1,10 @@ + +examples.test_simple_synapses +----------------------------- + +.. automodule:: examples.test_simple_synapses + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/test_sound_stim.rst b/doc/source/examples/test_sound_stim.rst new file mode 100644 index 0000000..549a16e --- /dev/null +++ b/doc/source/examples/test_sound_stim.rst @@ -0,0 +1,10 @@ + +examples.test_sound_stim +------------------------ + +.. automodule:: examples.test_sound_stim + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/test_sounds.rst b/doc/source/examples/test_sounds.rst new file mode 100644 index 0000000..fbbc88c --- /dev/null +++ b/doc/source/examples/test_sounds.rst @@ -0,0 +1,10 @@ + +examples.test_sounds +-------------------- + +.. automodule:: examples.test_sounds + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/test_synapses.rst b/doc/source/examples/test_synapses.rst new file mode 100644 index 0000000..623c2a8 --- /dev/null +++ b/doc/source/examples/test_synapses.rst @@ -0,0 +1,10 @@ + +examples.test_synapses +---------------------- + +.. automodule:: examples.test_synapses + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/examples/toy_model.rst b/doc/source/examples/toy_model.rst new file mode 100644 index 0000000..88cab37 --- /dev/null +++ b/doc/source/examples/toy_model.rst @@ -0,0 +1,10 @@ + +examples.toy_model +------------------ + +.. automodule:: examples.toy_model + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/index.rst b/doc/source/index.rst new file mode 100644 index 0000000..71df961 --- /dev/null +++ b/doc/source/index.rst @@ -0,0 +1,32 @@ +.. CNModel documentation master file, created by + sphinx-quickstart on Sun Apr 2 15:20:59 2017. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to CNModel's documentation! +=================================== + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + + readme + architecture + +.. toctree:: + :maxdepth: 1 + + examples + modules + +Indices and tables +================== + +* :ref:`modindex` +* :ref:`genindex` +* :ref:`search` + +.. automodule:: cnmodel + :members: + :show-inheritance: + :undoc-members: \ No newline at end of file diff --git a/doc/source/modules.rst b/doc/source/modules.rst new file mode 100644 index 0000000..5859ebf --- /dev/null +++ b/doc/source/modules.rst @@ -0,0 +1,18 @@ +API Reference +============= + +Contents: + +.. toctree:: + :maxdepth: 0 + + an_model + cells + data + decorator + morphology + synapses + populations + protocols + util + diff --git a/doc/source/morphology.rst b/doc/source/morphology.rst new file mode 100644 index 0000000..d5da5ff --- /dev/null +++ b/doc/source/morphology.rst @@ -0,0 +1,26 @@ +cnmodel.morphology package +-------------------------- + +.. automodule:: cnmodel.morphology + :members: + :undoc-members: + :show-inheritance: + +cnmodel.morphology.hoc_reader +============================= + +.. automodule:: cnmodel.morphology.hoc_reader + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.morphology.morphology +============================= + +.. automodule:: cnmodel.morphology.morphology + :members: + :undoc-members: + :show-inheritance: + :noindex: + diff --git a/doc/source/populations.rst b/doc/source/populations.rst new file mode 100644 index 0000000..258c70f --- /dev/null +++ b/doc/source/populations.rst @@ -0,0 +1,54 @@ +cnmodel.populations package +--------------------------- + + +.. automodule:: cnmodel.populations + :members: + :undoc-members: + :show-inheritance: + + +cnmodel.populations.population +=============================== + +.. automodule:: cnmodel.populations.population + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.populations.bushy +========================= + +.. automodule:: cnmodel.populations.bushy + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.populations.dstellate +============================= + +.. automodule:: cnmodel.populations.dstellate + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.populations.sgc +======================= + +.. automodule:: cnmodel.populations.sgc + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.populations.tstellate +============================= + +.. automodule:: cnmodel.populations.tstellate + :members: + :undoc-members: + :show-inheritance: + :noindex: diff --git a/doc/source/protocols.rst b/doc/source/protocols.rst new file mode 100644 index 0000000..4dd47eb --- /dev/null +++ b/doc/source/protocols.rst @@ -0,0 +1,72 @@ +cnmodel.protocols package +========================= + +.. automodule:: cnmodel.protocols + :members: + :undoc-members: + :show-inheritance: + +cnmodel.protocols.cc +-------------------- + +.. automodule:: cnmodel.protocols.cc + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.protocols.iv_curve +-------------------------- + +.. automodule:: cnmodel.protocols.iv_curve + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.protocols.population_test +--------------------------------- + +.. automodule:: cnmodel.protocols.population_test + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.protocols.protocol +-------------------------- + +.. automodule:: cnmodel.protocols.protocol + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.protocols.simple_synapse_test +------------------------------------- + +.. automodule:: cnmodel.protocols.simple_synapse_test + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.protocols.synapse_test +------------------------------ + +.. automodule:: cnmodel.protocols.synapse_test + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.protocols.vc_curve +-------------------------- + +.. automodule:: cnmodel.protocols.vc_curve + :members: + :undoc-members: + :show-inheritance: + :noindex: + + diff --git a/doc/source/readme.rst b/doc/source/readme.rst new file mode 100644 index 0000000..38ba804 --- /dev/null +++ b/doc/source/readme.rst @@ -0,0 +1 @@ +.. include:: ../../README.rst \ No newline at end of file diff --git a/doc/source/synapses.rst b/doc/source/synapses.rst new file mode 100644 index 0000000..1481f04 --- /dev/null +++ b/doc/source/synapses.rst @@ -0,0 +1,83 @@ +cnmodel.synapses package +======================== + +.. automodule:: cnmodel.synapses + :members: + :undoc-members: + :show-inheritance: + + +cnmodel.synapses.exp2_psd +------------------------- + +.. automodule:: cnmodel.synapses.exp2_psd + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.synapses.glu_psd +------------------------ + +.. automodule:: cnmodel.synapses.glu_psd + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.synapses.gly_psd +------------------------- + +.. automodule:: cnmodel.synapses.gly_psd + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.synapses.psd +-------------------- + +.. automodule:: cnmodel.synapses.psd + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.synapses.simple_terminal +-------------------------------- + +.. automodule:: cnmodel.synapses.simple_terminal + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.synapses.stochastic_terminal +------------------------------------ + +.. automodule:: cnmodel.synapses.stochastic_terminal + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.synapses.synapse +------------------------ + +.. automodule:: cnmodel.synapses.synapse + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.synapses.terminal +------------------------- + +.. automodule:: cnmodel.synapses.terminal + :members: + :undoc-members: + :show-inheritance: + :noindex: + + + diff --git a/doc/source/util.rst b/doc/source/util.rst new file mode 100644 index 0000000..02a5d30 --- /dev/null +++ b/doc/source/util.rst @@ -0,0 +1,147 @@ +cnmodel.util package +-------------------- + +Utility routines used within cnmodel + +.. automodule:: cnmodel.util + :members: + :undoc-members: + :show-inheritance: + + +cnmodel.util.Params +==================== + +.. automodule:: cnmodel.util.Params + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.util.ccstim +=================== + +.. automodule:: cnmodel.util.ccstim + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.util.expfitting +======================= + +.. automodule:: cnmodel.util.expfitting + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.util.filelock +===================== + +.. automodule:: cnmodel.util.filelock + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.util.find_point +======================= + +.. automodule:: cnmodel.util.find_point + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.util.fitting +==================== + +.. automodule:: cnmodel.util.fitting + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.util.get_anspikes +========================= + +.. automodule:: cnmodel.util.get_anspikes + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.util.matlab_proc +======================== + +.. automodule:: cnmodel.util.matlab_proc + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.util.nrnutils +===================== + +.. automodule:: cnmodel.util.nrnutils + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.util.process +==================== + +.. automodule:: cnmodel.util.process + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.util.pynrnutilities +=========================== + +.. automodule:: cnmodel.util.pynrnutilities + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.util.random_seed +======================== + +.. automodule:: cnmodel.util.random_seed + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.util.sound +================== + +.. automodule:: cnmodel.util.sound + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.util.stim +================= + +.. automodule:: cnmodel.util.stim + :members: + :undoc-members: + :show-inheritance: + :noindex: + +cnmodel.util.user_tester +======================== + +.. automodule:: cnmodel.util.user_tester + :members: + :undoc-members: + :show-inheritance: + :noindex: + + diff --git a/examples/LC_bushy.hoc b/examples/LC_bushy.hoc new file mode 100644 index 0000000..8ac0584 --- /dev/null +++ b/examples/LC_bushy.hoc @@ -0,0 +1,955 @@ +proc celldef() { + topol() +} + +create hillock[1], initialsegment[1], unmyelinatedaxon[1], soma[1], primarydendrite[100] + +proc topol() { local i + connect soma(0), hillock(0) + connect initialsegment(0), hillock(1) + connect unmyelinatedaxon(0), initialsegment(1) + connect primarydendrite(0), soma(1) + for i = 1, 7 connect primarydendrite[i](0), primarydendrite[i-1](1) + for i = 8, 9 connect primarydendrite[i](0), primarydendrite[i-8](1) + for i = 10, 13 connect primarydendrite[i](0), primarydendrite[i-1](1) + connect primarydendrite[14](0), primarydendrite[12](1) + connect primarydendrite[15](0), primarydendrite[11](1) + connect primarydendrite[16](0), primarydendrite[4](1) + for i = 17, 18 connect primarydendrite[i](0), primarydendrite[i-1](1) + for i = 19, 22 connect primarydendrite[i](0), primarydendrite[16](1) + connect primarydendrite[23](0), primarydendrite[2](1) + for i = 24, 25 connect primarydendrite[i](0), primarydendrite[23](1) + connect primarydendrite[26](0), primarydendrite[17](1) + for i = 27, 28 connect primarydendrite[i](0), primarydendrite[i-1](1) + for i = 29, 30 connect primarydendrite[i](0), primarydendrite[27](1) + connect primarydendrite[31](0), primarydendrite[26](1) + connect primarydendrite[32](0), primarydendrite[2](1) + for i = 33, 35 connect primarydendrite[i](0), primarydendrite[i-1](1) + for i = 36, 37 connect primarydendrite[i](0), primarydendrite[i-3](1) + for i = 38, 39 connect primarydendrite[i](0), primarydendrite[i-1](1) + connect primarydendrite[40](0), primarydendrite[38](1) + for i = 41, 42 connect primarydendrite[i](0), primarydendrite[40](1) + for i = 43, 44 connect primarydendrite[i](0), primarydendrite[42](1) + connect primarydendrite[45](0), primarydendrite[37](1) + for i = 46, 47 connect primarydendrite[i](0), primarydendrite[i-1](1) + connect primarydendrite[48](0), primarydendrite[46](1) + connect primarydendrite[49](0), primarydendrite[45](1) + connect primarydendrite[50](0), primarydendrite[32](1) + for i = 51, 53 connect primarydendrite[i](0), primarydendrite[i-1](1) + connect primarydendrite[54](0), primarydendrite[52](1) + connect primarydendrite[55](0), primarydendrite[51](1) + for i = 56, 57 connect primarydendrite[i](0), primarydendrite[55](1) + connect primarydendrite[58](0), primarydendrite[50](1) + for i = 59, 60 connect primarydendrite[i](0), primarydendrite[58](1) + connect primarydendrite[61](0), primarydendrite[51](1) + for i = 62, 63 connect primarydendrite[i](0), primarydendrite[61](1) + connect primarydendrite[64](0), primarydendrite[3](1) + for i = 65, 69 connect primarydendrite[i](0), primarydendrite[i-1](1) + connect primarydendrite[70](0), primarydendrite[68](1) + connect primarydendrite[71](0), primarydendrite[67](1) + connect primarydendrite[72](0), primarydendrite[65](1) + connect primarydendrite[73](0), primarydendrite[64](1) + connect primarydendrite[74](0), primarydendrite[66](1) + for i = 75, 76 connect primarydendrite[i](0), primarydendrite[74](1) + for i = 77, 78 connect primarydendrite[i](0), primarydendrite[76](1) + connect primarydendrite[79](0), primarydendrite[64](1) + for i = 80, 81 connect primarydendrite[i](0), primarydendrite[5](1) + for i = 82, 84 connect primarydendrite[i](0), primarydendrite[81](1) + for i = 85, 87 connect primarydendrite[i](0), primarydendrite[i-1](1) + connect primarydendrite[88](0), primarydendrite[86](1) + for i = 89, 90 connect primarydendrite[i](0), primarydendrite[88](1) + for i = 91, 92 connect primarydendrite[i](0), primarydendrite[i-7](1) + for i = 93, 94 connect primarydendrite[i](0), primarydendrite[92](1) + connect primarydendrite[95](0), primarydendrite[6](1) + for i = 96, 97 connect primarydendrite[i](0), primarydendrite[95](1) + for i = 98, 99 connect primarydendrite[i](0), primarydendrite[i-89](1) + basic_shape() +} +proc shape3d_1() { + hillock[0] {pt3dclear() + pt3dadd(61.38639625, 55.43400875, 0.0, 3.51044933) + pt3dadd(63.01466225, 55.28039875, 0.0, 1.23072332) + pt3dadd(63.963204, 55.2919195, 0.0, 0.67265819) + } + initialsegment[0] {pt3dclear() + pt3dadd(63.963204, 55.2919195, 0.0, 0.67265819) + pt3dadd(64.65060875, 55.35720375, 0.0, 0.30722) + } + unmyelinatedaxon[0] {pt3dclear() + pt3dadd(64.65060875, 55.35720375, 0.0, 0.30722) + pt3dadd(65.18824375, 55.5069735, 0.0, 0.370461237) + pt3dadd(66.24047225, 55.5991395, 0.0, 0.480123416) + pt3dadd(67.9493835, 55.75658975, 0.0, 0.489724041) + pt3dadd(69.13602075, 55.81803375, 0.0, 0.4211141345) + pt3dadd(69.953994, 55.714347, 0.0, 0.6103002105) + pt3dadd(71.83187625, 55.83339475, 0.0, 0.5677348795) + pt3dadd(73.901771, 55.51081375, 0.0, 0.615115884) + pt3dadd(75.50315525, 55.4301685, 0.0, 0.4713138825) + pt3dadd(76.15599775, 55.1843925, 0.0, 0.5377194855) + pt3dadd(77.03157475, 55.69514575, 0.0, 0.4454766805) + pt3dadd(77.49240475, 56.41711275, 0.0, 0.5473201105) + pt3dadd(77.7650625, 57.36949475, 0.0, 0.6737565015) + pt3dadd(77.910992, 57.8111235, 0.0, 0.296375134) + pt3dadd(78.54463325, 58.75198475, 0.0, 0.3572891795) + pt3dadd(79.0707475, 59.8080535, 0.0, 0.3138943545) + pt3dadd(79.50469575, 61.01773225, 0.0, 0.340922034) + pt3dadd(80.0077685, 62.10836325, 0.0, 0.3778575585) + pt3dadd(80.5300425, 63.10682825, 0.0, 0.3418667355) + pt3dadd(81.167524, 64.25890325, 0.0, 0.3259988225) + pt3dadd(81.67827725, 64.97318975, 0.0, 0.4713138825) + pt3dadd(82.043101, 65.5684285, 0.0, 0.487465974) + pt3dadd(82.442487, 66.37104075, 0.0, 0.489539709) + pt3dadd(82.57689575, 67.296541, 0.0, 0.5703308885) + pt3dadd(82.1583085, 67.6268025, 0.0, 0.4573200115) + pt3dadd(82.165989, 68.12987525, 0.0, 0.62411743) + pt3dadd(82.3119185, 68.64446875, 0.0, 0.7671513815) + pt3dadd(82.31575875, 69.04385475, 0.0, 0.251275238) + pt3dadd(82.5423335, 69.44324075, 0.0, 0.428172514) + pt3dadd(83.2028565, 70.04231975, 0.0, 0.4665980555) + pt3dadd(83.42175075, 70.983181, 0.0, 0.480891466) + pt3dadd(83.179815, 71.981646, 0.0, 0.56251982) + pt3dadd(82.396404, 72.75353625, 0.0, 0.5373815435) + pt3dadd(81.3748975, 72.949389, 0.0, 0.413272344) + pt3dadd(80.276586, 72.81498025, 0.0, 0.489724041) + pt3dadd(79.4394115, 73.7097585, 0.0, 0.556667279) + pt3dadd(78.8403325, 75.00392275, 0.0, 0.639509152) + } + soma[0] {pt3dclear() + pt3dadd(61.38639625, 55.43400875, 0.0, 3.51044933) + pt3dadd(59.3318625, 55.60682, 0.0, 8.66437205) + pt3dadd(57.1813225, 55.81803375, 0.0, 13.06222635) + pt3dadd(55.7220275, 56.144455, 0.0, 13.7619199) + pt3dadd(53.3410725, 56.81649875, 0.0, 13.8325805) + pt3dadd(50.84491, 58.16058625, 0.0, 13.90708135) + pt3dadd(47.44628875, 58.448605, 0.0, 11.5038529) + pt3dadd(44.56610125, 58.26811325, 0.0, 6.441097715) + pt3dadd(42.37715875, 57.6421525, 0.0, 2.400693885) + } + primarydendrite[0] {pt3dclear() + pt3dadd(42.37715875, 57.6421525, 0.0, 1.46344247) + pt3dadd(40.8525795, 57.23892625, 0.0, 1.46344247) + pt3dadd(39.68130325, 56.7204925, 0.0, 1.48648397) + pt3dadd(37.864865, 55.5991395, 0.0, 2.855533095) + pt3dadd(36.38636875, 54.62755625, 0.0, 3.01428903) + } + primarydendrite[1] {pt3dclear() + pt3dadd(36.38636875, 54.62755625, 0.0, 3.01428903) + pt3dadd(35.02308, 53.2949895, 0.0, 2.006223405) + pt3dadd(32.57991295, 48.5177185, 0.0, 1.446929395) + pt3dadd(32.286901875, 47.93784075, 0.0, 1.488557705) + } + primarydendrite[2] {pt3dclear() + pt3dadd(32.286901875, 47.93784075, 0.0, 1.488557705) + pt3dadd(31.634059375, 46.48622625, 0.0, 0.72381032) + pt3dadd(30.827606875, 44.8925225, 0.0, 0.704194323) + pt3dadd(30.405179375, 43.82877325, 0.0, 1.114670965) + pt3dadd(29.886745625, 42.76118375, 0.0, 1.479955545) + pt3dadd(29.445116875, 41.37101325, 0.0, 0.6679193215) + } + primarydendrite[3] {pt3dclear() + pt3dadd(29.445116875, 41.37101325, 0.0, 0.6679193215) + pt3dadd(28.6866675, 40.3610275, 0.0, 0.7336797625) + pt3dadd(27.601796875, 39.76578875, 0.0, 0.5964753105) + pt3dadd(26.57453, 38.970857, 0.0, 2.474273075) + } + primarydendrite[4] {pt3dclear() + pt3dadd(26.57453, 38.970857, 0.0, 2.474273075) + pt3dadd(26.17130375, 38.6713175, 0.0, 1.76528612) + } + primarydendrite[5] {pt3dclear() + pt3dadd(26.17130375, 38.6713175, 0.0, 1.76528612) + pt3dadd(25.912086875, 38.008874375, 0.0, 1.27742076) + pt3dadd(24.8464175, 37.394434375, 0.0, 0.4675811595) + } + primarydendrite[6] {pt3dclear() + pt3dadd(24.8464175, 37.394434375, 0.0, 0.4675811595) + pt3dadd(24.0015625, 36.799195625, 0.0, 0.3461524545) + pt3dadd(23.339119375, 36.472774375, 0.0, 1.634948035) + pt3dadd(22.79188375, 35.819931875, 0.0, 0.686160509) + pt3dadd(21.87022375, 35.243894375, 0.0, 0.3958452895) + pt3dadd(21.21738125, 34.552649375, 0.0, 1.3794178) + } + primarydendrite[7] {pt3dclear() + pt3dadd(21.21738125, 34.552649375, 0.0, 1.3794178) + pt3dadd(20.266919375, 33.938209375, 0.0, 0.480415275) + pt3dadd(19.095643125, 34.187825625, 0.0, 0.317834451) + pt3dadd(17.81876, 34.629454375, 0.0, 0.5170128575) + pt3dadd(17.05071, 34.96547625, 0.0, 0.4241709735) + pt3dadd(15.370600625, 35.407105, 0.0, 0.771199005) + pt3dadd(14.80416375, 35.282296875, 0.0, 1.237405355) + pt3dadd(14.13212, 34.437441875, 0.0, 0.638280272) + pt3dadd(13.2488625, 34.015014375, 0.0, 0.3688406515) + pt3dadd(12.519215, 33.592586875, 0.0, 0.298080205) + pt3dadd(11.61675625, 33.458178125, 0.0, 0.558157296) + pt3dadd(11.15592625, 33.563785, 0.0, 0.1920125) + } + primarydendrite[8] {pt3dclear() + pt3dadd(36.38636875, 54.62755625, 0.0, 3.01428903) + pt3dadd(37.754649825, 52.4501345, 0.0, 0.96451719) + pt3dadd(38.2058792, 50.7604245, 0.0, 0.30737361) + pt3dadd(38.61371375, 49.3472125, 0.0, 0.4036793995) + pt3dadd(39.1935915, 48.7634945, 0.0, 0.407435164) + pt3dadd(41.62831, 45.65673225, 0.0, 0.6537564795) + pt3dadd(43.0645635, 45.5376845, 0.0, 0.480123416) + } + primarydendrite[9] {pt3dclear() + pt3dadd(32.286901875, 47.93784075, 0.0, 1.488557705) + pt3dadd(33.64059, 46.5054275, 0.0, 0.384025) + pt3dadd(35.02308, 45.7373775, 0.0, 0.537635) + pt3dadd(36.09835, 45.8909875, 0.0, 0.7081036975) + } + primarydendrite[10] {pt3dclear() + pt3dadd(36.09835, 45.8909875, 0.0, 0.7081036975) + pt3dadd(37.096815, 46.467025, 0.0, 0.61444) + pt3dadd(38.4409025, 46.4286225, 0.0, 0.584931519) + pt3dadd(39.63138, 46.7358425, 0.0, 0.6192249515) + pt3dadd(40.629845, 48.54076, 0.0, 0.89569991) + pt3dadd(41.21740325, 48.9017435, 0.0, 0.6418056215) + } + primarydendrite[11] {pt3dclear() + pt3dadd(41.21740325, 48.9017435, 0.0, 0.6418056215) + pt3dadd(41.659032, 49.5008225, 0.0, 0.695761134) + } + primarydendrite[12] {pt3dclear() + pt3dadd(41.659032, 49.5008225, 0.0, 0.695761134) + pt3dadd(42.28499275, 50.092221, 0.0, 0.597558261) + } + primarydendrite[13] {pt3dclear() + pt3dadd(42.28499275, 50.092221, 0.0, 0.597558261) + pt3dadd(43.241215, 50.17286625, 0.0, 0.489539709) + pt3dadd(44.7389125, 50.57225225, 0.0, 0.355223125) + } + primarydendrite[14] {pt3dclear() + pt3dadd(42.28499275, 50.092221, 0.0, 0.597558261) + pt3dadd(42.580692, 50.937076, 0.0, 0.347880567) + pt3dadd(43.17593075, 51.41710725, 0.0, 0.401966648) + pt3dadd(43.70588525, 51.96242275, 0.0, 0.4129420825) + pt3dadd(44.070709, 52.626786, 0.0, 0.428710149) + pt3dadd(44.38944975, 53.19130275, 0.0, 0.418264669) + } + primarydendrite[15] {pt3dclear() + pt3dadd(41.659032, 49.5008225, 0.0, 0.695761134) + pt3dadd(42.765024, 49.48162125, 0.0, 0.441736277) + pt3dadd(45.222784, 49.477781, 0.0, 0.489724041) + pt3dadd(45.83338375, 49.18976225, 0.0, 0.355223125) + pt3dadd(46.77808525, 49.40481625, 0.0, 0.3085640875) + pt3dadd(47.5038925, 48.94398625, 0.0, 0.399554971) + pt3dadd(48.2719425, 49.0707145, 0.0, 0.5240942785) + pt3dadd(49.861806, 49.324171, 0.0, 0.3553536935) + } + primarydendrite[16] {pt3dclear() + pt3dadd(26.17130375, 38.6713175, 0.0, 1.76528612) + pt3dadd(26.78574375, 37.548044375, 0.0, 0.6454615395) + pt3dadd(27.467388125, 36.261560625, 0.0, 0.618326333) + pt3dadd(28.1828267, 35.527304825, 0.0, 0.652980749) + pt3dadd(28.57146, 34.792665, 0.0, 1.174886085) + } + primarydendrite[17] {pt3dclear() + pt3dadd(28.57146, 34.792665, 0.0, 1.174886085) + pt3dadd(28.72507, 33.65979125, 0.0, 0.4241709735) + pt3dadd(29.03229, 32.41171, 0.0, 0.462427544) + pt3dadd(29.3011075, 31.47084875, 0.0, 0.32811096) + pt3dadd(29.51232125, 31.077223125, 0.0, 0.5240942785) + pt3dadd(30.193965625, 29.560324375, 0.0, 0.631598237) + pt3dadd(30.616393125, 29.03229, 0.0, 0.3102077145) + pt3dadd(31.000418125, 28.427450625, 0.0, 0.455192513) + } + primarydendrite[18] {pt3dclear() + pt3dadd(31.000418125, 28.427450625, 0.0, 0.455192513) + pt3dadd(32.027685, 26.776143125, 0.0, 0.3418667355) + } + primarydendrite[19] {pt3dclear() + pt3dadd(28.57146, 34.792665, 0.0, 1.174886085) + pt3dadd(28.97468625, 35.915938125, 0.0, 0.618326333) + pt3dadd(29.233903125, 36.338365625, 0.0, 0.518787053) + pt3dadd(29.6851325, 37.2120225, 0.0, 0.485760903) + } + primarydendrite[20] {pt3dclear() + pt3dadd(28.57146, 34.792665, 0.0, 1.174886085) + pt3dadd(29.099494375, 34.25503, 0.0, 0.602627391) + pt3dadd(29.32030875, 33.73659625, 0.0, 0.4640174075) + pt3dadd(29.387513125, 33.266165625, 0.0, 0.2886562315) + } + primarydendrite[21] {pt3dclear() + pt3dadd(28.57146, 34.792665, 0.0, 1.174886085) + pt3dadd(27.928218125, 34.187825625, 0.0, 0.678864034) + pt3dadd(27.870614375, 33.39097375, 0.0, 0.3728191505) + pt3dadd(28.043425625, 32.651725625, 0.0, 0.256175397) + pt3dadd(28.081828125, 31.806870625, 0.0, 0.3314673385) + pt3dadd(28.033825, 30.942814375, 0.0, 0.4432954185) + pt3dadd(27.524991875, 30.030755, 0.0, 0.5607917075) + pt3dadd(27.313778125, 29.6083275, 0.0, 1.345854015) + pt3dadd(26.968155625, 28.87868, 0.0, 1.073349875) + pt3dadd(26.67053625, 28.16823375, 0.0, 0.570891565) + pt3dadd(26.3825175, 27.74580625, 0.0, 0.4640174075) + pt3dadd(26.161703125, 27.332979375, 0.0, 0.34024615) + pt3dadd(25.969690625, 26.958555, 0.0, 0.261167722) + pt3dadd(25.729675, 26.488124375, 0.0, 0.3125733085) + pt3dadd(25.624068125, 26.28651125, 0.0, 0.1770278445) + } + primarydendrite[22] {pt3dclear() + pt3dadd(28.57146, 34.792665, 0.0, 1.174886085) + pt3dadd(27.55379375, 34.859869375, 0.0, 0.51843375) + pt3dadd(27.025759375, 35.00387875, 0.0, 0.815745905) + pt3dadd(26.6897375, 35.11908625, 0.0, 0.78325739) + pt3dadd(26.57453, 34.667856875, 0.0, 0.406866807) + pt3dadd(25.9984925, 34.2166275, 0.0, 0.899770575) + pt3dadd(25.854483125, 33.62138875, 0.0, 0.40322625) + pt3dadd(25.624068125, 32.632524375, 0.0, 0.498495172) + pt3dadd(26.036895, 31.557254375, 0.0, 1.00015471) + pt3dadd(26.05609625, 30.635594375, 0.0, 1.121737025) + pt3dadd(25.662470625, 30.385978125, 0.0, 0.5101925735) + pt3dadd(25.422455, 29.541123125, 0.0, 0.5240942785) + pt3dadd(25.144036875, 29.291506875, 0.0, 0.81689798) + pt3dadd(24.913621875, 28.465853125, 0.0, 0.335883626) + pt3dadd(24.500795, 28.101029375, 0.0, 0.4753999085) + pt3dadd(24.4193817, 27.81800295, 0.0, 0.5671665225) + pt3dadd(24.42399, 25.638661075, 0.0, 0.3457530685) + pt3dadd(25.0768325, 24.606401875, 0.0, 0.4648161795) + pt3dadd(25.067231875, 23.051100625, 0.0, 0.3461524545) + } + primarydendrite[23] {pt3dclear() + pt3dadd(29.445116875, 41.37101325, 0.0, 0.6679193215) + pt3dadd(29.848343125, 40.48775575, 0.0, 0.515223301) + pt3dadd(30.347575625, 39.3164795, 0.0, 0.489539709) + pt3dadd(30.31877375, 38.311486075, 0.0, 0.45530004) + pt3dadd(30.2995725, 38.085679375, 0.0, 0.542074329) + } + primarydendrite[24] {pt3dclear() + pt3dadd(30.2995725, 38.085679375, 0.0, 0.542074329) + pt3dadd(29.51232125, 38.87485075, 0.0, 0.4353230595) + } + primarydendrite[25] {pt3dclear() + pt3dadd(30.2995725, 38.085679375, 0.0, 0.542074329) + pt3dadd(30.405179375, 37.759258125, 0.0, 0.549171111) + pt3dadd(30.789204375, 37.140209825, 0.0, 0.5485797125) + pt3dadd(31.168621075, 36.525769825, 0.0, 0.476759357) + pt3dadd(31.1444275, 35.253495, 0.0, 0.5198546425) + } +} +proc shape3d_2() { + primarydendrite[25] {pt3dclear() + pt3dadd(30.962015625, 34.5960442, 0.0, 0.529078923) + pt3dadd(30.904411875, 33.27115795, 0.0, 0.601475316) + pt3dadd(30.50617795, 32.128683575, 0.0, 0.6625122495) + pt3dadd(30.746193575, 31.730065625, 0.0, 0.528034375) + pt3dadd(31.4516475, 31.518851875, 0.0, 0.558157296) + pt3dadd(32.455104825, 30.707791075, 0.0, 0.5432648065) + pt3dadd(32.939744375, 30.213166875, 0.0, 0.638280272) + pt3dadd(33.73659625, 29.632521075, 0.0, 0.688372493) + pt3dadd(34.029607325, 29.1474975, 0.0, 0.903149995) + pt3dadd(34.164016075, 28.773073125, 0.0, 0.5725889555) + } + primarydendrite[26] {pt3dclear() + pt3dadd(31.000418125, 28.427450625, 0.0, 0.455192513) + pt3dadd(31.77806875, 28.41785, 0.0, 0.4687639565) + } + primarydendrite[27] {pt3dclear() + pt3dadd(31.77806875, 28.41785, 0.0, 0.4687639565) + pt3dadd(32.31570375, 27.78420875, 0.0, 0.5430958355) + pt3dadd(32.786134375, 27.236973125, 0.0, 0.6567825965) + pt3dadd(33.410175, 26.603331875, 0.0, 0.81029275) + pt3dadd(33.6789925, 25.48005875, 0.0, 0.884102355) + pt3dadd(33.81340125, 24.28958125, 0.0, 0.76805) + pt3dadd(33.919008125, 23.569534375, 0.0, 0.63625262) + pt3dadd(34.10142, 23.13750625, 0.0, 0.80737416) + pt3dadd(34.85026875, 22.494264375, 0.0, 0.5647241235) + pt3dadd(35.051881875, 21.98543125, 0.0, 0.5324660235) + pt3dadd(35.301498125, 21.361390625, 0.0, 0.42503887) + pt3dadd(35.762328125, 20.324523125, 0.0, 0.61981635) + pt3dadd(36.04074625, 19.7772875, 0.0, 0.276928108) + pt3dadd(36.77039375, 18.961234375, 0.0, 0.55683625) + pt3dadd(37.240824375, 18.37559625, 0.0, 0.975500305) + } + primarydendrite[28] {pt3dclear() + pt3dadd(37.240824375, 18.37559625, 0.0, 0.975500305) + pt3dadd(37.336830625, 17.72275375, 0.0, 0.4936641375) + pt3dadd(37.65365125, 16.7818925, 0.0, 0.5498393145) + pt3dadd(38.277691875, 15.57221375, 0.0, 0.399554971) + pt3dadd(38.72124075, 14.621751875, 0.0, 0.598019091) + pt3dadd(39.0860645, 13.469676875, 0.0, 0.498495172) + pt3dadd(39.247355, 12.13519, 0.0, 0.5760375) + pt3dadd(39.60449825, 10.61829125, 0.0, 1.00599189) + pt3dadd(39.80419125, 9.50461875, 0.0, 0.5051080825) + pt3dadd(40.476235, 8.496553125, 0.0, 0.506928361) + pt3dadd(41.4670195, 7.574893125, 0.0, 0.598019091) + pt3dadd(42.734302, 6.3364125, 0.0, 0.6451696805) + pt3dadd(44.009265, 4.91552, 0.0, 0.5457993715) + pt3dadd(44.9232445, 3.273813125, 0.0, 0.5598086035) + } + primarydendrite[29] {pt3dclear() + pt3dadd(37.240824375, 18.37559625, 0.0, 0.975500305) + pt3dadd(37.92246875, 18.500404375, 0.0, 0.44162875) + pt3dadd(38.52922825, 18.558008125, 0.0, 0.6102234055) + pt3dadd(39.4700895, 18.817225, 0.0, 0.4263368745) + pt3dadd(40.25734075, 18.730819375, 0.0, 0.6102234055) + pt3dadd(40.68744875, 18.60601125, 0.0, 0.82903317) + pt3dadd(41.3594925, 18.385196875, 0.0, 0.410476642) + } + primarydendrite[30] {pt3dclear() + pt3dadd(37.240824375, 18.37559625, 0.0, 0.975500305) + pt3dadd(36.626384375, 17.962769375, 0.0, 0.4353230595) + pt3dadd(36.069548125, 18.154781875, 0.0, 0.535576626) + pt3dadd(35.08068375, 18.7020175, 0.0, 0.500707156) + pt3dadd(34.303033125, 19.690881875, 0.0, 0.862596955) + pt3dadd(33.976611875, 21.37099125, 0.0, 0.3728191505) + } + primarydendrite[31] {pt3dclear() + pt3dadd(31.77806875, 28.41785, 0.0, 0.4687639565) + pt3dadd(32.632524375, 28.36024625, 0.0, 0.4228652885) + pt3dadd(33.12215625, 28.465853125, 0.0, 0.4193629805) + pt3dadd(33.6021875, 28.033825, 0.0, 0.462427544) + pt3dadd(34.437441875, 27.13136625, 0.0, 0.4228652885) + pt3dadd(35.109485625, 26.28651125, 0.0, 0.7258456525) + pt3dadd(35.762328125, 25.278445625, 0.0, 1.11336528) + pt3dadd(36.280761875, 24.63520375, 0.0, 0.2930955605) + } + primarydendrite[32] {pt3dclear() + pt3dadd(29.445116875, 41.37101325, 0.0, 0.6679193215) + pt3dadd(30.24196875, 40.890982, 0.0, 0.32642125) + pt3dadd(31.365241875, 40.0538075, 0.0, 0.3958452895) + pt3dadd(31.874075, 39.093745, 0.0, 0.5498393145) + pt3dadd(33.400574375, 38.11448125, 0.0, 0.5170128575) + pt3dadd(34.5238475, 37.548044375, 0.0, 0.506928361) + pt3dadd(35.531913125, 36.55918, 0.0, 0.686160509) + pt3dadd(36.357566875, 36.55918, 0.0, 0.931414235) + } + primarydendrite[33] {pt3dclear() + pt3dadd(36.357566875, 36.55918, 0.0, 0.931414235) + pt3dadd(37.9800725, 37.02001, 0.0, 0.5760375) + pt3dadd(39.201272, 37.404035, 0.0, 0.6440329665) + pt3dadd(40.41095075, 37.548044375, 0.0, 0.442043497) + } + primarydendrite[34] {pt3dclear() + pt3dadd(40.41095075, 37.548044375, 0.0, 0.442043497) + pt3dadd(41.63983075, 37.125616875, 0.0, 0.647742648) + } + primarydendrite[35] {pt3dclear() + pt3dadd(41.63983075, 37.125616875, 0.0, 0.647742648) + pt3dadd(42.4654845, 38.008874375, 0.0, 0.718956244) + } + primarydendrite[36] {pt3dclear() + pt3dadd(40.41095075, 37.548044375, 0.0, 0.442043497) + pt3dadd(40.4685545, 37.864865, 0.0, 0.3286716365) + pt3dadd(40.41863125, 38.510027, 0.0, 0.499601164) + pt3dadd(40.4685545, 39.14366825, 0.0, 0.751060734) + pt3dadd(41.01387, 39.95780125, 0.0, 0.5223277635) + pt3dadd(41.48622075, 40.67976825, 0.0, 0.6875045965) + } + primarydendrite[37] {pt3dclear() + pt3dadd(41.63983075, 37.125616875, 0.0, 0.647742648) + pt3dadd(42.6190945, 36.856799375, 0.0, 0.442043497) + pt3dadd(43.02232075, 36.568780625, 0.0, 0.4519436615) + } + primarydendrite[38] {pt3dclear() + pt3dadd(43.02232075, 36.568780625, 0.0, 0.4519436615) + pt3dadd(43.702045, 36.607183125, 0.0, 0.5607917075) + pt3dadd(44.577622, 36.607183125, 0.0, 0.572827051) + } + primarydendrite[39] {pt3dclear() + pt3dadd(44.577622, 36.607183125, 0.0, 0.572827051) + pt3dadd(45.82570325, 35.92553875, 0.0, 0.3418667355) + pt3dadd(46.54383, 35.2918975, 0.0, 0.5430958355) + pt3dadd(46.93937575, 34.77346375, 0.0, 0.99201338) + pt3dadd(47.6882245, 34.264630625, 0.0, 0.489539709) + } + primarydendrite[40] {pt3dclear() + pt3dadd(44.577622, 36.607183125, 0.0, 0.572827051) + pt3dadd(45.1536595, 38.239289375, 0.0, 0.6102234055) + pt3dadd(45.51848325, 39.093745, 0.0, 0.864901105) + } + primarydendrite[41] {pt3dclear() + pt3dadd(45.51848325, 39.093745, 0.0, 0.864901105) + pt3dadd(45.97931325, 39.42016625, 0.0, 0.4753999085) + pt3dadd(46.5054275, 39.95780125, 0.0, 0.7603310975) + pt3dadd(46.85105, 40.30342375, 0.0, 0.4344782045) + } + primarydendrite[42] {pt3dclear() + pt3dadd(45.51848325, 39.093745, 0.0, 0.864901105) + pt3dadd(44.777315, 39.41248575, 0.0, 0.3958452895) + pt3dadd(44.22047875, 40.14981375, 0.0, 0.787942495) + } + primarydendrite[43] {pt3dclear() + pt3dadd(44.22047875, 40.14981375, 0.0, 0.787942495) + pt3dadd(43.62524, 40.87946125, 0.0, 0.4082262555) + } + primarydendrite[44] {pt3dclear() + pt3dadd(44.22047875, 40.14981375, 0.0, 0.787942495) + pt3dadd(43.963182, 39.56609575, 0.0, 0.4073199565) + pt3dadd(43.5100325, 39.01694, 0.0, 0.896544765) + pt3dadd(43.16441, 38.258490625, 0.0, 0.3418667355) + } + primarydendrite[45] {pt3dclear() + pt3dadd(43.02232075, 36.568780625, 0.0, 0.4519436615) + pt3dadd(43.3103395, 36.146353125, 0.0, 0.678864034) + pt3dadd(43.36794325, 35.560715, 0.0, 0.7114831175) + pt3dadd(42.933995, 35.253495, 0.0, 0.364316837) + pt3dadd(43.13752825, 34.792665, 0.0, 0.78817291) + pt3dadd(43.49083125, 34.6006525, 0.0, 1.08417938) + pt3dadd(44.039987, 34.35103625, 0.0, 0.3418667355) + pt3dadd(44.41249125, 33.938209375, 0.0, 0.6989331805) + pt3dadd(45.4301575, 33.4485775, 0.0, 0.384025) + pt3dadd(46.159805, 33.00694875, 0.0, 0.4992325) + pt3dadd(47.3041995, 32.901341875, 0.0, 0.640876281) + } + primarydendrite[46] {pt3dclear() + pt3dadd(47.3041995, 32.901341875, 0.0, 0.640876281) + pt3dadd(48.01464575, 33.16055875, 0.0, 0.4332032415) + } + primarydendrite[47] {pt3dclear() + pt3dadd(48.01464575, 33.16055875, 0.0, 0.4332032415) + pt3dadd(48.16825575, 33.2181625, 0.0, 0.3102077145) + pt3dadd(48.71357125, 33.362171875, 0.0, 0.4432954185) + pt3dadd(49.44321875, 33.42937625, 0.0, 0.462427544) + pt3dadd(50.184387, 33.256565, 0.0, 0.528295512) + pt3dadd(51.30574, 32.96854625, 0.0, 0.3456225) + } + primarydendrite[48] {pt3dclear() + pt3dadd(48.01464575, 33.16055875, 0.0, 0.4332032415) + pt3dadd(48.28346325, 32.9109425, 0.0, 0.261167722) + pt3dadd(48.47547575, 32.344505625, 0.0, 0.442043497) + } + primarydendrite[49] {pt3dclear() + pt3dadd(47.3041995, 32.901341875, 0.0, 0.640876281) + pt3dadd(47.5038925, 32.267700625, 0.0, 0.4432954185) + pt3dadd(47.6882245, 31.720465, 0.0, 0.5324660235) + pt3dadd(48.48315625, 31.12522625, 0.0, 0.6869669615) + pt3dadd(49.6083495, 30.39557875, 0.0, 0.352488867) + pt3dadd(50.31879575, 29.85794375, 0.0, 0.686160509) + pt3dadd(51.44014875, 29.55072375, 0.0, 0.577312463) + pt3dadd(52.24660125, 29.416315, 0.0, 0.2688175) + } + primarydendrite[50] {pt3dclear() + pt3dadd(36.357566875, 36.55918, 0.0, 0.931414235) + pt3dadd(36.453573125, 35.781529375, 0.0, 0.5216211575) + pt3dadd(36.69358875, 35.147888125, 0.0, 0.7145860395) + } + primarydendrite[51] {pt3dclear() + pt3dadd(36.69358875, 35.147888125, 0.0, 0.7145860395) + pt3dadd(37.250425, 34.86947, 0.0, 0.4687639565) + pt3dadd(38.6713175, 34.226228125, 0.0, 0.498126508) + pt3dadd(39.30495875, 33.611788125, 0.0, 0.6230805625) + pt3dadd(39.87331575, 33.33337, 0.0, 1.143242425) + } + primarydendrite[52] {pt3dclear() + pt3dadd(39.87331575, 33.33337, 0.0, 1.143242425) + pt3dadd(40.44935325, 33.02615, 0.0, 0.7031420945) + pt3dadd(40.94858575, 32.478914375, 0.0, 0.381137132) + } + primarydendrite[53] {pt3dclear() + pt3dadd(40.94858575, 32.478914375, 0.0, 0.381137132) + pt3dadd(41.41709625, 32.2965025, 0.0, 0.2924657595) + pt3dadd(42.22354875, 31.806870625, 0.0, 0.4228652885) + pt3dadd(43.22201375, 30.731600625, 0.0, 0.4482570215) + pt3dadd(43.502352, 29.569925, 0.0, 0.3353383105) + pt3dadd(43.502352, 28.811475625, 0.0, 0.4036793995) + } + primarydendrite[54] {pt3dclear() + pt3dadd(40.94858575, 32.478914375, 0.0, 0.381137132) + pt3dadd(40.7757745, 31.81647125, 0.0, 0.3728191505) + pt3dadd(41.18668125, 31.096424375, 0.0, 0.405054209) + pt3dadd(41.4362975, 30.47238375, 0.0, 0.395376779) + pt3dadd(41.9278495, 29.6083275, 0.0, 0.48156735) + pt3dadd(42.06993875, 29.022689375, 0.0, 0.808526235) + pt3dadd(42.196667, 28.3794475, 0.0, 0.32642125) + } + primarydendrite[55] {pt3dclear() + pt3dadd(39.87331575, 33.33337, 0.0, 1.143242425) + pt3dadd(39.56609575, 32.690128125, 0.0, 0.4742324725) + pt3dadd(39.3932845, 32.2196975, 0.0, 0.9416293) + pt3dadd(38.7481225, 32.056486875, 0.0, 0.5915137075) + pt3dadd(38.7481225, 31.33644, 0.0, 0.46083) + } + primarydendrite[56] {pt3dclear() + pt3dadd(38.7481225, 31.33644, 0.0, 0.46083) + pt3dadd(38.92093375, 30.654795625, 0.0, 0.3958452895) + pt3dadd(39.26655625, 30.059556875, 0.0, 0.4211141345) + pt3dadd(39.57377625, 29.12829625, 0.0, 0.2924657595) + pt3dadd(40.34182625, 28.39864875, 0.0, 0.4378576245) + pt3dadd(40.7450525, 28.043425625, 0.0, 0.89339576) + pt3dadd(41.0522725, 27.55379375, 0.0, 0.395376779) + } + primarydendrite[57] {pt3dclear() + pt3dadd(38.7481225, 31.33644, 0.0, 0.46083) + pt3dadd(38.2872925, 31.39404375, 0.0, 0.6528425) + pt3dadd(37.80726125, 31.566855, 0.0, 0.581137352) + } + primarydendrite[58] {pt3dclear() + pt3dadd(36.69358875, 35.147888125, 0.0, 0.7145860395) + pt3dadd(36.511176875, 34.6774575, 0.0, 0.456406032) + pt3dadd(36.280761875, 34.053416875, 0.0, 0.678864034) + pt3dadd(35.9831425, 33.381373125, 0.0, 0.659862477) + pt3dadd(36.04074625, 32.85333875, 0.0, 0.6539715335) + pt3dadd(36.146353125, 32.2965025, 0.0, 0.32642125) + } + primarydendrite[59] {pt3dclear() + pt3dadd(36.146353125, 32.2965025, 0.0, 0.32642125) + pt3dadd(36.175155, 31.9124775, 0.0, 0.4241709735) + pt3dadd(36.069548125, 31.346040625, 0.0, 1.01781986) + pt3dadd(35.88713625, 30.81800625, 0.0, 0.3859374445) + } + primarydendrite[60] {pt3dclear() + pt3dadd(36.146353125, 32.2965025, 0.0, 0.32642125) + pt3dadd(35.608718125, 32.23889875, 0.0, 0.3125733085) + pt3dadd(35.23429375, 32.2196975, 0.0, 0.5430958355) + pt3dadd(34.821466875, 32.2196975, 0.0, 0.92027751) + pt3dadd(34.648655625, 32.9877475, 0.0, 0.78817291) + } + primarydendrite[61] {pt3dclear() + pt3dadd(39.87331575, 33.33337, 0.0, 1.143242425) + pt3dadd(40.37254825, 33.92860875, 0.0, 0.399554971) + pt3dadd(40.5914425, 34.2934325, 0.0, 0.4750158835) + pt3dadd(41.10219575, 33.7942, 0.0, 0.697880952) + pt3dadd(41.3594925, 33.48698, 0.0, 0.4153844815) + } +} +proc shape3d_3() { + primarydendrite[61] { } + primarydendrite[62] {pt3dclear() + pt3dadd(41.3594925, 33.48698, 0.0, 0.4153844815) + pt3dadd(42.319555, 34.19742625, 0.0, 0.4241709735) + } + primarydendrite[63] {pt3dclear() + pt3dadd(41.3594925, 33.48698, 0.0, 0.4153844815) + pt3dadd(41.858725, 32.93014375, 0.0, 0.6629269965) + pt3dadd(42.3579575, 33.1413575, 0.0, 0.79170594) + pt3dadd(42.9263145, 32.728530625, 0.0, 0.489539709) + pt3dadd(44.02846625, 32.334905, 0.0, 0.384025) + pt3dadd(44.90404325, 31.8356725, 0.0, 0.3688406515) + pt3dadd(45.62217, 31.2980375, 0.0, 0.4344782045) + pt3dadd(46.5822325, 30.750801875, 0.0, 0.4228652885) + pt3dadd(47.36948375, 30.04995625, 0.0, 0.3801617085) + pt3dadd(48.20665825, 29.464318125, 0.0, 0.4036793995) + pt3dadd(48.63676625, 29.176299375, 0.0, 0.82657541) + pt3dadd(49.078395, 29.58912625, 0.0, 0.2999312055) + } + primarydendrite[64] {pt3dclear() + pt3dadd(26.57453, 38.970857, 0.0, 2.474273075) + pt3dadd(25.28804625, 40.09221, 0.0, 0.6606996515) + pt3dadd(24.039965, 40.967787, 0.0, 0.831874955) + pt3dadd(23.71354375, 41.0522725, 0.0, 1.306222635) + } + primarydendrite[65] {pt3dclear() + pt3dadd(23.71354375, 41.0522725, 0.0, 1.306222635) + pt3dadd(22.98389625, 41.07147375, 0.0, 1.3963149) + pt3dadd(22.0814375, 41.79344075, 0.0, 1.167512805) + pt3dadd(21.207780625, 42.64597625, 0.0, 0.470722484) + } + primarydendrite[66] {pt3dclear() + pt3dadd(21.207780625, 42.64597625, 0.0, 0.470722484) + pt3dadd(19.498869375, 43.33722125, 0.0, 0.6135413815) + } + primarydendrite[67] {pt3dclear() + pt3dadd(19.498869375, 43.33722125, 0.0, 0.6135413815) + pt3dadd(18.3179925, 43.10680625, 0.0, 0.46083) + } + primarydendrite[68] {pt3dclear() + pt3dadd(18.3179925, 43.10680625, 0.0, 0.46083) + pt3dadd(17.45393625, 43.0108, 0.0, 0.325852893) + pt3dadd(16.0138425, 42.3579575, 0.0, 0.4750158835) + } + primarydendrite[69] {pt3dclear() + pt3dadd(16.0138425, 42.3579575, 0.0, 0.4750158835) + pt3dadd(15.101783125, 42.9263145, 0.0, 0.489539709) + pt3dadd(14.0169125, 43.83645375, 0.0, 0.462427544) + pt3dadd(12.663224375, 44.70051, 0.0, 0.719724294) + pt3dadd(11.443945, 45.5837675, 0.0, 0.577312463) + pt3dadd(10.92551125, 45.499282, 0.0, 1.05606875) + pt3dadd(10.42627875, 45.545365, 0.0, 0.3456225) + } + primarydendrite[70] {pt3dclear() + pt3dadd(16.0138425, 42.3579575, 0.0, 0.4750158835) + pt3dadd(15.6298175, 41.3134095, 0.0, 0.456406032) + pt3dadd(15.1689875, 40.8218575, 0.0, 0.429355311) + pt3dadd(15.274594375, 39.354882, 0.0, 0.365330663) + } + primarydendrite[71] {pt3dclear() + pt3dadd(18.3179925, 43.10680625, 0.0, 0.46083) + pt3dadd(17.97237, 43.59835825, 0.0, 0.81029275) + pt3dadd(16.964304375, 44.3088045, 0.0, 0.442043497) + pt3dadd(15.601015625, 45.56456625, 0.0, 0.4846165085) + pt3dadd(14.468141875, 46.98545875, 0.0, 0.5170128575) + pt3dadd(14.372135625, 47.9954445, 0.0, 0.438694799) + } + primarydendrite[72] {pt3dclear() + pt3dadd(21.207780625, 42.64597625, 0.0, 0.470722484) + pt3dadd(21.361390625, 43.48315075, 0.0, 0.63625262) + pt3dadd(20.727749375, 44.28960325, 0.0, 0.3314673385) + pt3dadd(20.209315625, 44.52769875, 0.0, 0.3708375815) + pt3dadd(19.806089375, 44.316485, 0.0, 1.05253572) + pt3dadd(19.83489125, 43.72124625, 0.0, 0.4378576245) + } + primarydendrite[73] {pt3dclear() + pt3dadd(23.71354375, 41.0522725, 0.0, 1.306222635) + pt3dadd(23.886355, 41.8971275, 0.0, 0.4241709735) + pt3dadd(23.895955625, 44.116792, 0.0, 0.5216211575) + pt3dadd(23.454326875, 44.623705, 0.0, 0.5839868175) + pt3dadd(22.705478125, 44.6928295, 0.0, 0.518787053) + } + primarydendrite[74] {pt3dclear() + pt3dadd(19.498869375, 43.33722125, 0.0, 0.6135413815) + pt3dadd(18.385196875, 45.24966575, 0.0, 0.317834451) + pt3dadd(17.9339675, 45.74889825, 0.0, 0.399554971) + } + primarydendrite[75] {pt3dclear() + pt3dadd(17.9339675, 45.74889825, 0.0, 0.399554971) + pt3dadd(18.173983125, 46.190527, 0.0, 0.4955228185) + pt3dadd(18.922831875, 46.25581125, 0.0, 0.554178797) + pt3dadd(19.729284375, 46.13292325, 0.0, 0.442043497) + pt3dadd(20.132510625, 45.78730075, 0.0, 0.751060734) + pt3dadd(20.353325, 45.74889825, 0.0, 0.32642125) + } + primarydendrite[76] {pt3dclear() + pt3dadd(17.9339675, 45.74889825, 0.0, 0.399554971) + pt3dadd(17.137115625, 46.37101875, 0.0, 0.48003125) + pt3dadd(16.657084375, 46.927855, 0.0, 0.91781975) + pt3dadd(15.9370375, 47.2734775, 0.0, 0.4378576245) + } + primarydendrite[77] {pt3dclear() + pt3dadd(15.9370375, 47.2734775, 0.0, 0.4378576245) + pt3dadd(15.03457875, 47.7650295, 0.0, 0.3149235415) + pt3dadd(14.1705225, 48.44475375, 0.0, 0.384025) + pt3dadd(13.51768, 48.82109825, 0.0, 0.51843375) + pt3dadd(12.490413125, 49.28960875, 0.0, 0.384501191) + pt3dadd(11.96237875, 49.13599875, 0.0, 0.820968645) + pt3dadd(11.36714, 49.6851545, 0.0, 0.4644167935) + pt3dadd(9.9462475, 50.17286625, 0.0, 0.2924657595) + pt3dadd(8.707766875, 50.53769, 0.0, 0.2749234975) + pt3dadd(7.5652925, 50.7604245, 0.0, 1.17695982) + pt3dadd(6.691635625, 50.89483325, 0.0, 0.5598086035) + } + primarydendrite[78] {pt3dclear() + pt3dadd(15.9370375, 47.2734775, 0.0, 0.4378576245) + pt3dadd(16.0906475, 48.0722495, 0.0, 0.307819079) + pt3dadd(15.581814375, 48.63676625, 0.0, 0.321874394) + pt3dadd(15.389801875, 49.74275825, 0.0, 0.5072893445) + pt3dadd(15.101783125, 50.12678325, 0.0, 0.918818215) + pt3dadd(14.76576125, 50.51848875, 0.0, 0.378218542) + pt3dadd(14.516145, 51.09452625, 0.0, 0.77757382) + pt3dadd(14.160921875, 51.6513625, 0.0, 0.3607607655) + pt3dadd(13.757695625, 52.6037445, 0.0, 0.82765068) + pt3dadd(13.872903125, 53.5714875, 0.0, 0.3728191505) + pt3dadd(13.53688125, 54.27425325, 0.0, 0.3125733085) + pt3dadd(13.047249375, 55.81803375, 0.0, 0.3688406515) + } + primarydendrite[79] {pt3dclear() + pt3dadd(23.71354375, 41.0522725, 0.0, 1.306222635) + pt3dadd(23.1567075, 40.26502125, 0.0, 0.4640174075) + pt3dadd(23.02229875, 39.585297, 0.0, 0.3005456455) + pt3dadd(21.841421875, 38.2872925, 0.0, 0.319570244) + pt3dadd(21.37099125, 37.07761375, 0.0, 0.625146617) + pt3dadd(21.0829725, 36.760793125, 0.0, 0.841552385) + pt3dadd(20.766151875, 36.511176875, 0.0, 0.455192513) + pt3dadd(20.2381175, 35.992743125, 0.0, 0.399554971) + pt3dadd(20.48773375, 37.15441875, 0.0, 0.4687639565) + pt3dadd(20.44933125, 38.354496875, 0.0, 0.4211141345) + pt3dadd(20.247718125, 39.3625625, 0.0, 0.635960761) + pt3dadd(20.074906875, 39.95780125, 0.0, 0.96175221) + pt3dadd(19.738885, 41.0829945, 0.0, 0.87004704) + pt3dadd(19.710083125, 41.41709625, 0.0, 0.4675811595) + } + primarydendrite[80] {pt3dclear() + pt3dadd(24.8464175, 37.394434375, 0.0, 0.4675811595) + pt3dadd(24.529596875, 37.567245625, 0.0, 0.5437717195) + pt3dadd(24.395188125, 37.96087125, 0.0, 0.845085415) + pt3dadd(24.414389375, 38.335295625, 0.0, 0.5216211575) + } + primarydendrite[81] {pt3dclear() + pt3dadd(24.8464175, 37.394434375, 0.0, 0.4675811595) + pt3dadd(24.90402125, 36.549579375, 0.0, 0.6989331805) + pt3dadd(24.500795, 35.96394125, 0.0, 0.876575465) + pt3dadd(24.02076375, 35.147888125, 0.0, 0.5434337775) + pt3dadd(23.473528125, 34.46624375, 0.0, 0.5501772565) + pt3dadd(22.897490625, 33.5253825, 0.0, 0.98602259) + pt3dadd(23.13750625, 32.2581, 0.0, 0.998465) + pt3dadd(22.2350475, 31.35564125, 0.0, 0.6517134665) + pt3dadd(21.5054, 30.0691575, 0.0, 0.512350794) + pt3dadd(21.35179, 28.59066125, 0.0, 0.4224275) + pt3dadd(21.169378125, 26.372916875, 0.0, 0.787481665) + pt3dadd(21.073371875, 25.182439375, 0.0, 0.365330663) + pt3dadd(21.169378125, 23.550333125, 0.0, 0.442043497) + } + primarydendrite[82] {pt3dclear() + pt3dadd(21.169378125, 23.550333125, 0.0, 0.442043497) + pt3dadd(21.111774375, 22.033434375, 0.0, 0.4036793995) + pt3dadd(21.0061675, 20.60294125, 0.0, 0.3166746955) + pt3dadd(20.036504375, 18.817225, 0.0, 0.3461524545) + pt3dadd(19.60447625, 17.425134375, 0.0, 1.241552825) + pt3dadd(17.905165625, 16.8586975, 0.0, 1.007451185) + pt3dadd(16.119449375, 17.26192375, 0.0, 0.95330366) + pt3dadd(15.898635, 17.99157125, 0.0, 0.4992325) + pt3dadd(15.898635, 19.825290625, 0.0, 0.456406032) + pt3dadd(17.002706875, 21.246183125, 0.0, 0.598019091) + pt3dadd(17.91476625, 22.455861875, 0.0, 0.6654308395) + pt3dadd(19.767686875, 22.878289375, 0.0, 0.602934611) + } + primarydendrite[83] {pt3dclear() + pt3dadd(21.169378125, 23.550333125, 0.0, 0.442043497) + pt3dadd(20.64134375, 23.67514125, 0.0, 0.516651874) + pt3dadd(20.33412375, 23.09910375, 0.0, 0.5760375) + pt3dadd(20.58374, 22.398258125, 0.0, 0.5338485135) + } + primarydendrite[84] {pt3dclear() + pt3dadd(21.169378125, 23.550333125, 0.0, 0.442043497) + pt3dadd(21.60140625, 23.0030975, 0.0, 0.570891565) + pt3dadd(22.263849375, 22.86868875, 0.0, 0.7299009565) + } + primarydendrite[85] {pt3dclear() + pt3dadd(22.263849375, 22.86868875, 0.0, 0.7299009565) + pt3dadd(22.974295625, 22.043035, 0.0, 0.5310835335) + } + primarydendrite[86] {pt3dclear() + pt3dadd(22.974295625, 22.043035, 0.0, 0.5310835335) + pt3dadd(24.0015625, 20.670145625, 0.0, 0.386421316) + pt3dadd(24.241578125, 19.134045625, 0.0, 0.2937253615) + pt3dadd(24.433590625, 17.9339675, 0.0, 0.290568676) + pt3dadd(24.98082625, 16.983505625, 0.0, 0.456406032) + pt3dadd(25.278445625, 16.196254375, 0.0, 1.118664825) + pt3dadd(25.604866875, 15.409003125, 0.0, 0.7530192615) + pt3dadd(26.44012125, 13.488878125, 0.0, 0.5338485135) + pt3dadd(26.756941875, 12.80723375, 0.0, 1.157988985) + pt3dadd(26.929753125, 12.03918375, 0.0, 0.4466133945) + pt3dadd(27.86101375, 9.437414375, 0.0, 0.5927579485) + pt3dadd(28.446651875, 8.92858125, 0.0, 1.24454822) + pt3dadd(28.93628375, 8.054924375, 0.0, 0.6497318975) + pt3dadd(29.310708125, 6.7204375, 0.0, 0.638280272) + pt3dadd(30.385978125, 5.28034375, 0.0, 0.4769513695) + pt3dadd(31.250034375, 4.5698975, 0.0, 1.26451752) + } + primarydendrite[87] {pt3dclear() + pt3dadd(31.250034375, 4.5698975, 0.0, 1.26451752) + pt3dadd(32.363706875, 4.329881875, 0.0, 0.489539709) + pt3dadd(33.630989375, 3.888253125, 0.0, 0.5754000185) + pt3dadd(35.474309375, 2.160140625, 0.0, 0.5804998705) + pt3dadd(36.328765, 1.814518125, 0.0, 0.3353383105) + } + primarydendrite[88] {pt3dclear() + pt3dadd(31.250034375, 4.5698975, 0.0, 1.26451752) + pt3dadd(31.12522625, 3.6482375, 0.0, 0.4224275) + pt3dadd(31.259635, 3.0337975, 0.0, 0.5760375) + } + primarydendrite[89] {pt3dclear() + pt3dadd(31.259635, 3.0337975, 0.0, 0.5760375) + pt3dadd(31.49005, 2.236945625, 0.0, 0.768280415) + pt3dadd(31.614858125, -0.067204375, 0.0, 0.7230499505) + } + primarydendrite[90] {pt3dclear() + pt3dadd(31.259635, 3.0337975, 0.0, 0.5760375) + pt3dadd(32.16209375, 2.947391875, 0.0, 0.3286716365) + pt3dadd(33.227763125, 2.4193575, 0.0, 0.528295512) + pt3dadd(34.226228125, 2.09293625, 0.0, 0.4906687425) + pt3dadd(35.704724375, 1.008065625, 0.0, 0.5437717195) + } + primarydendrite[91] {pt3dclear() + pt3dadd(22.263849375, 22.86868875, 0.0, 0.7299009565) + pt3dadd(22.33105375, 23.425525, 0.0, 0.384025) + pt3dadd(22.3118525, 24.087968125, 0.0, 0.352488867) + pt3dadd(21.96623, 24.63520375, 0.0, 0.462427544) + } + primarydendrite[92] {pt3dclear() + pt3dadd(22.974295625, 22.043035, 0.0, 0.5310835335) + pt3dadd(23.435125625, 22.475063125, 0.0, 0.81505466) + pt3dadd(24.241578125, 22.17744375, 0.0, 0.712519985) + pt3dadd(24.808015, 22.014233125, 0.0, 0.7145860395) + pt3dadd(25.44165625, 21.553403125, 0.0, 1.29447147) + pt3dadd(25.78727875, 21.14057625, 0.0, 0.5223277635) + pt3dadd(27.006558125, 20.190114375, 0.0, 0.4036793995) + pt3dadd(27.448186875, 19.498869375, 0.0, 0.461628772) + } + primarydendrite[93] {pt3dclear() + pt3dadd(27.448186875, 19.498869375, 0.0, 0.461628772) + pt3dadd(27.659400625, 18.9324325, 0.0, 0.298080205) + pt3dadd(28.648265, 17.386731875, 0.0, 0.406866807) + pt3dadd(29.1474975, 16.580279375, 0.0, 0.4332032415) + pt3dadd(29.445116875, 14.76576125, 0.0, 0.36482375) + pt3dadd(29.790739375, 13.49847875, 0.0, 0.558157296) + } + primarydendrite[94] {pt3dclear() + pt3dadd(27.448186875, 19.498869375, 0.0, 0.461628772) + pt3dadd(28.09142875, 19.498869375, 0.0, 0.48156735) + pt3dadd(28.792274375, 18.942033125, 0.0, 0.4036793995) + pt3dadd(29.33951, 18.500404375, 0.0, 0.224746791) + pt3dadd(29.74273625, 18.3179925, 0.0, 0.2999312055) + } +} +proc shape3d_4() { + primarydendrite[94] {pt3dclear() + pt3dadd(31.077223125, 17.3963325, 0.0, 0.4753999085) + } + primarydendrite[95] {pt3dclear() + pt3dadd(21.21738125, 34.552649375, 0.0, 1.3794178) + pt3dadd(21.0061675, 33.6789925, 0.0, 1.38464054) + pt3dadd(21.04457, 32.50771625, 0.0, 0.5430958355) + pt3dadd(21.207780625, 31.326839375, 0.0, 0.34024615) + pt3dadd(20.727749375, 30.70279875, 0.0, 0.85975517) + pt3dadd(20.506935, 29.675531875, 0.0, 0.5170128575) + pt3dadd(20.420529375, 28.715469375, 0.0, 0.256175397) + pt3dadd(19.81569, 27.851413125, 0.0, 0.921890415) + pt3dadd(19.364460625, 27.24657375, 0.0, 0.393978928) + pt3dadd(18.961234375, 26.958555, 0.0, 0.352488867) + pt3dadd(18.1643825, 26.651335, 0.0, 0.81013914) + pt3dadd(17.72275375, 27.20817125, 0.0, 0.500707156) + pt3dadd(17.14671625, 27.544193125, 0.0, 0.4122661985) + } + primarydendrite[96] {pt3dclear() + pt3dadd(17.14671625, 27.544193125, 0.0, 0.4122661985) + pt3dadd(16.513075, 27.9186175, 0.0, 0.447849955) + pt3dadd(15.946638125, 28.235438125, 0.0, 0.480415275) + pt3dadd(13.88250375, 28.16823375, 0.0, 0.625146617) + } + primarydendrite[97] {pt3dclear() + pt3dadd(17.14671625, 27.544193125, 0.0, 0.4122661985) + pt3dadd(16.868298125, 27.18897, 0.0, 0.4122661985) + pt3dadd(16.68588625, 26.814545625, 0.0, 0.7145860395) + pt3dadd(16.465071875, 26.47852375, 0.0, 0.366836041) + } + primarydendrite[98] {pt3dclear() + pt3dadd(36.09835, 45.8909875, 0.0, 0.7081036975) + pt3dadd(36.482375, 45.41095625, 0.0, 0.3461524545) + pt3dadd(36.876000625, 45.1536595, 0.0, 0.353011141) + pt3dadd(37.413635625, 44.8003565, 0.0, 0.985484955) + pt3dadd(37.620241075, 44.63522575, 0.0, 0.631383183) + pt3dadd(37.92246875, 44.14367375, 0.0, 0.5457993715) + pt3dadd(38.463944, 43.6021985, 0.0, 0.3490710445) + } + primarydendrite[99] {pt3dclear() + pt3dadd(41.21740325, 48.9017435, 0.0, 0.6418056215) + pt3dadd(41.54766475, 48.3794695, 0.0, 0.373441271) + pt3dadd(42.227389, 47.8418345, 0.0, 0.340922034) + pt3dadd(42.8802315, 47.53845475, 0.0, 0.4261218205) + pt3dadd(43.2642565, 47.3041995, 0.0, 0.607573633) + pt3dadd(43.963182, 46.989299, 0.0, 0.586897727) + pt3dadd(44.32032525, 46.90865375, 0.0, 0.4060757155) + pt3dadd(44.78115525, 46.9048135, 0.0, 0.3918667905) + pt3dadd(44.946286, 47.5653365, 0.0, 0.3405149675) + pt3dadd(45.21894375, 47.79191125, 0.0, 0.499601164) + pt3dadd(45.54920525, 47.6191, 0.0, 0.468863803) + pt3dadd(45.8295435, 47.3041995, 0.0, 0.3629266665) + pt3dadd(46.1214025, 46.943216, 0.0, 0.48433233) + pt3dadd(46.7972865, 46.3825395, 0.0, 0.458925236) + pt3dadd(47.4885315, 46.05611825, 0.0, 0.518525916) + pt3dadd(48.294984, 45.4147965, 0.0, 0.4488714615) + pt3dadd(48.709731, 44.82723825, 0.0, 0.3870127145) + pt3dadd(49.2704075, 43.42938725, 0.0, 0.452857641) + pt3dadd(50.000055, 42.503887, 0.0, 0.6517134665) + pt3dadd(50.952437, 41.62446975, 0.0, 0.3462907035) + pt3dadd(51.720487, 39.17055, 0.0, 0.4466133945) + pt3dadd(52.97624875, 37.048811875, 0.0, 0.6654308395) + pt3dadd(54.6467575, 35.647120625, 0.0, 0.85806546) + pt3dadd(56.605285, 33.074153125, 0.0, 0.97096881) + pt3dadd(57.12371875, 32.16209375, 0.0, 0.876575465) + pt3dadd(57.96857375, 31.4516475, 0.0, 0.7143249025) + pt3dadd(58.479327, 30.16055545, 0.0, 0.4540788405) + pt3dadd(58.75198475, 29.464318125, 0.0, 1.239248675) + pt3dadd(59.02080225, 28.77806545, 0.0, 0.7408072665) + } +} +proc basic_shape() { + shape3d_1() + shape3d_2() + shape3d_3() + shape3d_4() +} +access soma + +celldef() diff --git a/examples/__init__.py b/examples/__init__.py new file mode 100644 index 0000000..79fb492 --- /dev/null +++ b/examples/__init__.py @@ -0,0 +1 @@ +# empty init to make examples importable (for sphinx) diff --git a/examples/figures.py b/examples/figures.py new file mode 100644 index 0000000..f9e14f3 --- /dev/null +++ b/examples/figures.py @@ -0,0 +1,64 @@ +from __future__ import print_function + +""" + +""" +import sys +import subprocess + +if len(sys.argv) < 2: # if no argument, print helpful message + print( + "Plot selected figures from paper, Manis and Campagnola, Hearing Research. 2018" + ) + print("Usage: figures.py [2a | 2b | 2c | 3 | 4 | 5 | 6a | 6d | 7]") + exit(1) + +arg = sys.argv[1] # get argument, check that it is valid +if arg not in ["2a", "2b", "2c", "3", "4", "5", "6a", "6d", "7"]: + print("Usage: figures.py [2a | 2b | 2c | 3 | 4 | 5 | 6a | 6d | 7]") + exit(1) + +if arg == "2a": + proc = subprocess.Popen( + ["python", "examples/test_mechanisms.py", "klt"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + proc.wait() + print(proc.stdout.read()) + # ;; + # 2b) + # python examples/test_mechanisms.py kht + # ;; + # 2c) + # python examples/test_mechanisms.py ka + # ;; + # 3) + # python examples/toy_model.py + # ;; + # 4) + # python examples/test_synapses.py sgc bushy + # ;; + # 5) + # python examples/test_decorator.py + # ;; + # 6a) + # python examples/test_bushy_variation.py a + # ;; + # 6d) + # python examples/test_bushy_variation.py d + # ;; + # + # 7) + # while true; do + # echo "This figure may take hours to generate!" + # read -p "Are you sure you want to run the script?" yn + # case $yn in + # [Yy]* ) python examples/test_physiology.py; break;; + # [Nn]* ) exit;; + # * ) echo "Please answer yes or no.";; + # esac + # done + # ;; + # diff --git a/examples/figures.sh b/examples/figures.sh new file mode 100755 index 0000000..f213934 --- /dev/null +++ b/examples/figures.sh @@ -0,0 +1,44 @@ +case $1 in + 2a) + python examples/test_mechanisms.py klt + ;; + 2b) + python examples/test_mechanisms.py kht + ;; + 2c) + python examples/test_mechanisms.py ka + ;; + 3) + python examples/toy_model.py + ;; + 4) + python examples/test_synapses.py sgc bushy + ;; + 5) + python examples/test_decorator.py + ;; + 6a) + python examples/test_bushy_variation.py a + ;; + 6d) + python examples/test_bushy_variation.py d + ;; + + 7) + while true; do + echo "This figure may take hours to generate!" + read -p "Are you sure you want to run the script?" yn + case $yn in + [Yy]* ) python examples/test_physiology.py; break;; + [Nn]* ) exit;; + * ) echo "Please answer yes or no.";; + esac + done + ;; + + *) + echo $"Plot selected figures from paper" + echo $"Usage: $0 {2a | 2b | 2c | 3 | 4 | 5 | 6a | 6d | 7}" + exit 1 +esac + diff --git a/examples/gif b/examples/gif new file mode 100755 index 0000000..45822f2 --- /dev/null +++ b/examples/gif @@ -0,0 +1 @@ +/Users/pbmanis/Desktop/Python/GIFFittingToolbox/src \ No newline at end of file diff --git a/examples/play_test_sounds.py b/examples/play_test_sounds.py new file mode 100644 index 0000000..70a64cc --- /dev/null +++ b/examples/play_test_sounds.py @@ -0,0 +1,146 @@ +""" +Test sounds and plot waveforms. + +This script tests the sound waveform generator for a variety of sounds + +""" +import numpy as np +import pyqtgraph as pg +from cnmodel.util import sound +from collections import OrderedDict +import scipy.signal +import sys + +try: + import PySounds + + HAVE_PYSOUNDS = True +except ImportError: + HAVE_PYSOUNDS = False + + +def play(): + if len(sys.argv) >= 2: + stimarg = sys.argv[1] + else: + exit() + + plots = True + + if HAVE_PYSOUNDS: + PS = PySounds.PySounds() + + cf = 2e3 + Fs = 44100 # sample frequency + level = 80.0 + seed = 34978 + fmod = 20.0 + dmod = 20.0 + + if plots: + # waveforms + win = pg.GraphicsWindow() + pipwin = win.addPlot(title="sound pip", row=0, col=0) + pipmodwin = win.addPlot(title="100 \% SAM modulated pip", row=1, col=0) + noisewin = win.addPlot(title="WB noise", row=2, col=0) + noisemodwin = win.addPlot(title="100 \% SAM Modulated WB Noise", row=3, col=0) + clickwin = win.addPlot(title="clicks", row=4, col=0) + fmwin = win.addPlot(title="fmsweep", row=5, col=0) + # spectra + pipwins = win.addPlot(title="sound pip Spec", row=0, col=1) + pipmodwins = win.addPlot(title="100 \% SAM modulated pip", row=1, col=1) + noisewins = win.addPlot(title="WB noise", row=2, col=1) + noisemodwins = win.addPlot(title="100 \% SAM Modulated WB Noise", row=3, col=1) + clickwins = win.addPlot(title="click spec", row=4, col=1) + fmwins = win.addPlot(title="fmsweep spec", row=5, col=1) + else: + pipwin = None + pipmodwin = None + noisewin = None + noisemodwin = None + clickwin = None + pipwins = None + pipmodwins = None + noisewins = None + noisemodwins = None + clickwins = None + fmwins = None + + stims = OrderedDict( + [ + ("pip", (pipwin, sound.TonePip)), + ("pipmod", (pipmodwin, sound.SAMTone)), + ("noise", (noisewin, sound.NoisePip)), + ("noisemod", (noisemodwin, sound.SAMNoise)), + ("clicks", (clickwin, sound.ClickTrain)), + ("fmsweep", (fmwins, sound.FMSweep)), + ] + ) + + specs = OrderedDict( + [ + ("pip", (pipwins, sound.TonePip)), + ("pipmod", (pipmodwins, sound.SAMTone)), + ("noise", (noisewins, sound.NoisePip)), + ("noisemod", (noisemodwins, sound.SAMNoise)), + ("clicks", (clickwins, sound.ClickTrain)), + ("fmsweep", (fmwins, sound.FMSweep)), + ] + ) + if stimarg == "all": + stimlist = list(stims.keys()) + else: + stimlist = [stimarg] + for stim in stimlist: + print(stim) + if stim in ["clicks"]: + wave = stims[stim][1]( + rate=Fs, + duration=1.0, + dbspl=level, + click_duration=1e-4, + click_starts=1e-3 * np.linspace(10, 500, 10), + ) + elif stim in ["fmsweep"]: + wave = stims[stim][1]( + rate=Fs, + duration=0.5, + dbspl=level, + start=0.0, + ramp="linear", + freqs=[16000, 200], + ) + elif stim in ["pip", "pipmod", "noise", "noisemod"]: + wave = stims[stim][1]( + rate=Fs, + duration=2.0, + f0=cf, + dbspl=level, + pip_duration=1.8, + pip_start=[10e-3], + ramp_duration=2.5e-3, + fmod=fmod, + dmod=dmod, + seed=seed, + ) + if plots: + stims[stim][0].plot(wave.time, wave.sound) + f, Pxx_spec = scipy.signal.periodogram( + wave.sound, Fs + ) # , window='flattop', nperseg=8192, + # noverlap=512, scaling='spectrum') + specs[stim][0].plot(f, np.sqrt(Pxx_spec)) + if HAVE_PYSOUNDS: + + print("Playing %s" % stim) + + PS.playSound(wave.sound, wave.sound, Fs) + + if plots and sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() + + +if __name__ == "__main__": + if not HAVE_PYSOUNDS: + print("Could not import PySounds; will not play audio.") + play() diff --git a/examples/plot_hcno_kinetics.py b/examples/plot_hcno_kinetics.py new file mode 100755 index 0000000..e15a7d7 --- /dev/null +++ b/examples/plot_hcno_kinetics.py @@ -0,0 +1,81 @@ +#!/usr/bin/python +""" +test and plot hcno stuff + +""" +import numpy as np +import matplotlib.pyplot as plt + +# Parameters# +gbar = 0.0005 # (mho/cm2) + +vhalf1 = -50 # (mV) # v 1/2 for forward +vhalf2 = -84 # (mV) # v 1/2 for backward +gm1 = 0.3 ## (mV) # slope for forward +gm2 = 0.6 # # (mV) # slope for backward +zeta1 = 3 # (/ms) +# zeta2 = 3 # (/ms) +a01 = 0.008 # (/ms) +a02 = 0.0029 # (/ms) +frac = 0.0 +c0 = 273.16 # (degC) +thinf = -66 # (mV) # inact inf slope +qinf = 7 # (mV) # inact inf slope +q10tau = 4.5 # from Magee (1998) +# v # (mV) +q10g = 4.5 # Cao and Oertel +celsius = 35.0 + +F = 9.648e4 +R = 8.314 + +ct = 1e-3 * zeta1 * F / (R * (c0 + celsius)) + +q10 = q10tau ** ( + (celsius - 33.0) / 10.0 +) # (degC)) : if you don't like room temp, it can be changed! + + +def rates(v): # (mV)) { + tau1 = bet1(v) / (q10 * a01 * (1.0 + alp1(v))) + tau2 = bet2(v) / (q10 * a02 * (1.0 + alp2(v))) + hinf = 1.0 / (1.0 + np.exp((v - thinf) / qinf)) + return tau1, tau2, hinf + + +def alp1(v): # (mV)) { + alp1 = np.exp((v - vhalf1) * ct) + return alp1 + + +def bet1(v): # (mV)) { + bet1 = np.exp(gm1 * (v - vhalf1) * ct) + return bet1 + + +def alp2(v): # (mV)) { + alp2 = np.exp((v - vhalf2) * ct) + return alp2 + + +def bet2(v): # (mV)) { + bet2 = np.exp(gm2 * (v - vhalf2) * ct) + return bet2 + + +def plots(): + v = np.linspace(-120.0, 0.0, 120) + + t1, t2, hi = rates(v) + # print(v) + plt.figure(1) + plt.plot(v, t1) + plt.plot(v, t2) + plt.figure(2) + plt.plot(v, hi) + plt.show() + + +# prevent sphinx from running this script at first build +if __name__ == "__main__": + plots() diff --git a/examples/stim172_geese.wav b/examples/stim172_geese.wav new file mode 100755 index 0000000..4fd9af9 Binary files /dev/null and b/examples/stim172_geese.wav differ diff --git a/examples/test_adex.py b/examples/test_adex.py new file mode 100755 index 0000000..9e19f8b --- /dev/null +++ b/examples/test_adex.py @@ -0,0 +1,340 @@ +#!/usr/bin/python + + +""" +Test adex model + +""" + +import numpy as np +from neuron import h +import neuron +import matplotlib.pyplot as plt +from collections import OrderedDict +import weave +from .gif.Filter_Rect_LogSpaced import * + + +class AdEx: + def __init__(self): + pass + self.dt = 0.025 + self.tstop = 250.0 + self.eta = ( + Filter_Rect_LogSpaced() + ) # nA, spike-triggered current (must be instance of class Filter) + self.gamma = ( + Filter_Rect_LogSpaced() + ) # mV, spike-triggered movement of the firing threshold (must be instance of class Filter) + + def runone(self, pars, dt=0.025, tstop=250): + + self.cell = self.create_Adex_model(pars) + self.dt = 0.025 + self.tstop = tstop + + # for inj in np.linspace(pars['I']*0.5, pars['I']*2.0, 3): + inj = pars["I"] + stim = h.Vector() + self.Vm = h.Vector() + self.Vm.record(self.cell(0.5)._ref_Vm_AdEx, sec=self.cell) + istim = h.iStim(0.5, sec=self.cell) + istim.delay = 5.0 + istim.dur = 1e9 # these actually do not matter... + istim.iMax = 0.0 + stim = np.zeros(int(tstop / h.dt)) + stim[int(20 / h.dt) : int(220 / h.dt)] = inj + cmd = h.Vector(stim) + # cmd.play(istim._ref_i, h.dt, 0, sec=cell) + cmd.play(self.cell(0.5)._ref_is_AdEx, h.dt, 0, sec=self.cell) + + rtime = h.Vector() + rtime.record(h._ref_t) + h.finitialize() + h.t = 0.0 + h.dt = self.dt + while h.t < self.tstop: + h.fadvance() + + tb = np.array(rtime) + vcell = self.Vm.to_python() + + return (tb, vcell) + + def run_gifAI(self, pars, dt=0.025, tstep=250.0): + # Model parameters + self.simulate(pars["I"], -65.0, pars) + + def plot_trace(self, i, panel, tb, vcell): + axi = self.ax[i] + axi.plot(tb, vcell) + axi.set_ylim([-100, 10]) + axi.set_title(panel) + + def create_Adex_model(self, pars): + cell = h.Section() + cell.L = 50 + + cell.insert("AdEx") + + cell(0.5).cm_AdEx = pars["cm"] + cell(0.5).gl_AdEx = pars["gl"] + cell(0.5).el_AdEx = pars["el"] + cell(0.5).vt_AdEx = pars["Vt"] + cell(0.5).delt_AdEx = pars["dt"] + cell(0.5).a_AdEx = pars["a"] + cell(0.5).tauw_AdEx = pars["tauw"] + cell(0.5).b_AdEx = pars["b"] + cell(0.5).vr_AdEx = pars["Vr"] + cell(0.5).refract_AdEx = 0.025 + return cell + + def create_GIF_model(self, pars): + cell = h.Section() + cell.L = 50 + cell.insert("GIF") + cell(0.5).cm_GIF = pars["cm"] + cell(0.5).gl_GIF = pars["gl"] + cell(0.5).el_GIF = pars["el"] + cell(0.5).vt_GIF = pars["Vt_star"] + cell(0.5).vr_GIF = pars["Vr"] + cell(0.5).refract_GIF = pars["Tref"] + cell(0.5).DV_GIF = pars["DV"] + cell(0.5).lambda0_GIF = pars["lambda0"] + cell(0.5).b_GIF = pars["b"] + return cell + + # + # The following are from Gif.py... + def simulate(self, I, V0, pars): + + """ + Simulate the spiking response of the GIF model to an input current I (nA) with time step dt. + V0 indicate the initial condition V(0)=V0. + The function returns: + - time : ms, support for V, eta_sum, V_T, spks + - V : mV, membrane potential + - eta_sum : nA, adaptation current + - V_T : mV, firing threshold + - spks : ms, list of spike times + """ + + # Input parameters + p_T = len(I) + p_dt = self.dt + + # Model parameters + p_gl = pars["gl"] + p_C = pars["cm"] + p_El = pars["el"] + p_Vr = pars["Vr"] + p_Tref = pars["Tref"] + p_Vt_star = pars["Vt_star"] + p_DV = pars["DV"] + p_lambda0 = pars["lambda0"] + + # Model kernels + (p_eta_support, p_eta) = self.eta.getInterpolatedFilter(self.dt) + p_eta = p_eta.astype("double") + p_eta_l = len(p_eta) + + (p_gamma_support, p_gamma) = self.gamma.getInterpolatedFilter(self.dt) + p_gamma = p_gamma.astype("double") + p_gamma_l = len(p_gamma) + + # Define arrays + V = np.array(np.zeros(p_T), dtype="double") + I = np.array(I, dtype="double") + spks = np.array(np.zeros(p_T), dtype="double") + eta_sum = np.array(np.zeros(p_T + 2 * p_eta_l), dtype="double") + gamma_sum = np.array(np.zeros(p_T + 2 * p_gamma_l), dtype="double") + + # Set initial condition + V[0] = V0 + + code = """ + #include + + int T_ind = int(p_T); + float dt = float(p_dt); + + float gl = float(p_gl); + float C = float(p_C); + float El = float(p_El); + float Vr = float(p_Vr); + int Tref_ind = int(float(p_Tref)/dt); + float Vt_star = float(p_Vt_star); + float DeltaV = float(p_DV); + float lambda0 = float(p_lambda0); + + int eta_l = int(p_eta_l); + int gamma_l = int(p_gamma_l); + + + float rand_max = float(RAND_MAX); + float p_dontspike = 0.0 ; + float lambda = 0.0 ; + float r = 0.0; + + + for (int t=0; t p_dontspike) { + + if (t+1 < T_ind-1) + spks[t+1] = 1.0; + + t = t + Tref_ind; + + if (t+1 < T_ind-1) + V[t+1] = Vr; + + + // UPDATE ADAPTATION PROCESSES + for(int j=0; j 1: + dst = np.diff(spikeTimes) + st = np.array(spikeTimes[0]) # get first spike + sok = np.where(dst > mindT) + st = np.append(st, [spikeTimes[s + 1] for s in sok]) + # print st + spikeTimes = st + return spikeTimes + + +def showplots(name): + """ + Show traces from sound stimulation - without current injection + """ + f = open(name, "rb") + d = pickle.load(f) + f.close() + ncells = len(d["results"]) + stiminfo = d["stim"] + dur = stiminfo["rundur"] * 1000.0 + print("dur: ", dur) + print("stim info: ") + print(" fmod: ", stiminfo["fmod"]) + print(" dmod: ", stiminfo["dmod"]) + print(" f0: ", stiminfo["f0"]) + print(" cf: ", stiminfo["cf"]) + varsg = np.linspace(0.25, 2.0, int((2.0 - 0.25) / 0.25) + 1) # was not stored... + fig, ax = mpl.subplots(ncells + 1, 2, figsize=(8.5, 11.0)) + spikelists = [[]] * ncells + prespikes = [[]] * ncells + xmin = 50.0 + for i in range(ncells): + vdat = d["results"][i]["v"] + idat = d["results"][i]["i"] + tdat = d["results"][i]["t"] + pdat = d["results"][i]["pre"] + PH.noaxes(ax[i, 0]) + # if i == 0: + # PH.calbar(ax[0, 0], calbar=[120., -120., 25., 20.], axesoff=True, orient='left', + # unitNames={'x': 'ms', 'y': 'mV'}, fontsize=9, weight='normal', font='Arial') + for j in range(len(vdat)): + if j == 2: + ax[i, 0].plot(tdat - xmin, vdat[j], "k", linewidth=0.5) + if j == 0: + ax[i, 0].annotate("%.2f" % varsg[i], (180.0, 20.0)) + + ax[i, 0].set_xlim([0, dur - xmin]) + ax[i, 0].set_ylim([-75, 50]) + PH.referenceline( + ax[i, 0], + reference=-62.0, + limits=None, + color="0.33", + linestyle="--", + linewidth=0.5, + dashes=[3, 3], + ) + + for j in range(len(vdat)): + detected = PU.findspikes(tdat, vdat[j], -20.0) + detected = clean_spiketimes(detected) + spikelists[i].extend(detected) + if j == 0: + n, bins = np.histogram( + detected, np.linspace(0.0, dur, 201), density=False + ) + else: + m, bins = np.histogram( + detected, np.linspace(0.0, dur, 201), density=False + ) + n += m + prespikes[i].extend(pdat) + if j == 0: + n, bins = np.histogram(pdat, np.linspace(0.0, dur, 201), density=False) + else: + m, bins = np.histogram(pdat, np.linspace(0.0, dur, 201), density=False) + n += m + + ax[i, 1].bar(bins[:-1] - xmin, n, width=bins[1], facecolor="k", alpha=0.75) + ax[i, 1].set_xlim([0, dur - xmin]) + ax[i, 1].set_ylim([0, 30]) + vs = PU.vector_strength(spikelists[i], stiminfo["fmod"]) + pre_vs = PU.vector_strength(prespikes[i], stiminfo["fmod"]) + # print 'pre: ', pre_vs + # print 'post: ', vs + # apos = ax[i,1].get_position() + # ax[i, 1].set_title('VS = %4.3f' % pre_vs['r']) + # # vector_plot(fig, vs['ph'], np.ones(len(vs['ph'])), yp = apos) + # phase_hist(fig, vs['ph'], yp=apos) + # phase_hist(fig, pre_vs['ph'], yp=apos) + prot = Variations(runtype, runname, "cochlea") + # stim_info = {'nreps': nrep, 'cf': cf, 'f0': f0, 'rundur': rundur, 'pipdur': pipdur, 'dbspl': dbspl, 'fmod': fmod, 'dmod': dmod} + if stiminfo["dmod"] > 0: + stimulus = "SAM" + else: + stimulus = "tone" + prot.make_stimulus( + stimulus=stimulus, + cf=stiminfo["cf"], + f0=stiminfo["f0"], + simulator=None, + rundur=stiminfo["rundur"], + pipdur=stiminfo["pipdur"], + dbspl=stiminfo["dbspl"], + fmod=stiminfo["fmod"], + dmod=stiminfo["dmod"], + ) + ax[-1, 1].plot( + prot.stim.time * 1000.0 - xmin, prot.stim.sound, "k-", linewidth=0.75 + ) + ax[-1, 1].set_xlim([0, (dur - xmin)]) + + PH.noaxes(ax[-1, 0]) + ax[-1, 0].set_xlim([0, dur - xmin]) + ax[-1, 0].set_ylim([-75, 50]) + # PH.referenceline(ax[-1, 0], reference=-62.0, limits=None, color='0.33', linestyle='--' ,linewidth=0.5, dashes=[3, 3]) + PH.calbar( + ax[-1, 0], + calbar=[20.0, 0.0, 25.0, 20.0], + axesoff=True, + orient="left", + unitNames={"x": "ms", "y": "mV"}, + fontsize=9, + weight="normal", + font="Arial", + ) + + PH.cleanAxes(ax.ravel().tolist()) + + mpl.show() + + +if __name__ == "__main__": + runname = None + panel = None + if len(sys.argv) == 2: + panel = sys.argv[1] + if panel == "a": + runtype = "IV" + runname = "Figure6_IV" + elif panel == "d": + runtype = "sound" + runname = "Figure6_AN" + else: + runtype = panel + if panel is None: + raise ValueError("Must specify figure panel to generate: 'a', 'b'") + if runtype in ["sound", "IV"]: + prot = Variations(runtype, runname, "cochlea") + if runtype == "IV": + start_time = timeit.default_timer() + prot.runIV(parallelize=True) + elapsed = timeit.default_timer() - start_time + print(("Elapsed time for IV simulations: %f" % (elapsed))) + showpicklediv(runname) + if runtype == "sound": + start_time = timeit.default_timer() + prot.runSound(parallelize=True) + elapsed = timeit.default_timer() - start_time + print(("Elapsed time for AN simulations: %f" % (elapsed))) + showplots(runname) + # pg.show() + # if sys.flags.interactive == 0: + # pg.QtGui.QApplication.exec_() + + elif runtype in ["showiv"]: + showpicklediv(runname) + + elif runtype in ["plots"]: + showplots(runname) + else: + print("run type should be one of sound, IV, showiv, plots") diff --git a/examples/test_ccstim.py b/examples/test_ccstim.py new file mode 100644 index 0000000..63cf595 --- /dev/null +++ b/examples/test_ccstim.py @@ -0,0 +1,77 @@ +""" +Test the ccstim generator. + +Usage: python test_ccstim.py + +This script runs ccstim for each of it's potential inputs, and plots the resulting waveforms. +""" + +import sys +import numpy as np +from cnmodel.util import ccstim +import pyqtgraph as pg + +pulsetypes = ["square", "hyp", "timedSpikes", "exp"] + + +def test_cc_stim(): + """ + stim: a dictionary with keys [required] + delay (delay to start of pulse train, msec [all] + duration: duration of pulses in train, msec [all] + Sfreq: stimulus train frequency (Hz) [timedSpikes] + PT: post-train test delay [all] + NP: number of pulses in the train [timedSpikes, exp] + amp: amplitude of the pulses in the train [all] + hypamp: amplitude of prehyperpolarizing pulse [hyp] + hypdur: duration of prehyperpolarizing pulse [hyp] + spikeTimes" times of spikes [timedSpikes] + """ + stim = { + "square": { + "delay": 10, + "duration": 100, + "Sfreq": 10, + "PT": 0, + "NP": 1, + "amp": 100.0, + }, + "hyp": { + "delay": 10, + "duration": 100, + "Sfreq": 10, + "PT": 0, + "NP": 1, + "amp": 100.0, + "hypamp": -50, + "hypdur": 50, + }, + "timedSpikes": { + "delay": 10, + "duration": 1, + "PT": 0, + "amp": 100.0, + "spikeTimes": [10.0, 20, 30, 40.0, 50.0], + }, + "exp": { + "delay": 10, + "duration": 3, + "Sfreq": 20, + "PT": 0, + "NP": 4, + "amp": 100.0, + }, + } + + dt = 0.1 + + for p in pulsetypes: + (w, tmax, ts) = ccstim.ccstim(stim[p], dt, pulsetype=p) + tb = np.arange(0, w.shape[0] * dt, dt) + pg.plot(tb, w, title=p) + + +if __name__ == "__main__": + test_cc_stim() + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() diff --git a/examples/test_cells.py b/examples/test_cells.py new file mode 100755 index 0000000..e66d5a1 --- /dev/null +++ b/examples/test_cells.py @@ -0,0 +1,515 @@ +#!/usr/bin/python + +""" +Test the basic membrane physiology of cell types. + +Basic Usage: python test_cells.py celltype species [--cc | --vc] + +This script generates a cell of the specified type and species, then tests the +cell with a series of current/voltage pulses to produce I/V, F/I, and spike +latency analyses. + +""" + +import argparse +import os, sys +from neuron import h +import pyqtgraph as pg +import cnmodel +import cnmodel.cells as cells +from cnmodel.protocols import IVCurve, VCCurve + +debugFlag = True +ax = None +h.celsius = 22 +default_durs = [10.0, 100.0, 20.0] +cclamp = False + +cellinfo = { + "types": [ + "bushy", + "bushycoop", + "tstellate", + "tstellatenav11", + "dstellate", + "dstellateeager", + "sgc", + "cartwheel", + "pyramidal", + "octopus", + "tuberculoventral", + "mso", + ], + "morphology": ["point", "waxon", "stick"], + "nav": ["std", "jsrna", "nav11", "nacncoop"], + "species": ["guineapig", "cat", "rat", "mouse"], + "pulse": ["step", "pulse"], +} + +# Format for ivranges is list of tuples. This allows finer increments in selected ranges, such as close to rest +ccivrange = { + "mouse": { + "bushy": {"pulse": [(-1, 1.2, 0.05)]}, + "bushycoop": {"pulse": [(-0.5, 0.7, 0.02)]}, + "tstellate": {"pulse": [(-1.0, 1.01, 0.05), (-0.015, 0, 0.005)]}, + "tstellatenav11": {"pulse": [(-1, 1.0, 0.1)]}, + "dstellate": {"pulse": [(-0.3, 0.301, 0.015)]}, + "octopus": {"pulse": [(-1.0, 1.0, 0.05)]}, + "sgc": {"pulse": [(-0.3, 0.6, 0.02)]}, + "cartwheel": {"pulse": [(-0.5, 0.5, 0.05)]}, + "pyramidal": { + "pulse": [(-0.3, 0.3, 0.025), (-0.040, 0.025, 0.005)] + }, # , 'prepulse': [(-0.25, -0.25, 0.25)]}, + "tuberculoventral": {"pulse": [(-0.35, 1.0, 0.05), (-0.040, 0.01, 0.005)]}, + }, + "guineapig": { + "bushy": {"pulse": [(-1, 1.2, 0.05)]}, + "tstellate": {"pulse": [(-0.15, 0.15, 0.01)]}, + "dstellate": {"pulse": [(-0.25, 0.25, 0.025)]}, + "dstellateeager": {"pulse": [(-0.6, 1.0, 0.025)]}, + "octopus": {"pulse": [(-2.0, 6.0, 0.2)]}, + "sgc": {"pulse": [(-0.3, 0.6, 0.02)]}, + "mso": {"pulse": [(-1, 1.2, 0.05)]}, + }, + "rat": { + "pyramidal": { + "pulse": [(-0.3, 0.3, 0.025), (-0.040, 0.025, 0.005)] + } # 'prepulse': [(-0.25, -0.25, 0.25)]}, + }, +} + +# scales holds some default scaling to use in the cciv plots +# argument is {cellname: (xmin, xmax, IVymin, IVymax, FIspikemax, +# offset(for spikes), crossing (for IV) )} +## the "offset" refers to setting the axes back a bit +scale = { + "bushy": (-1.0, -160.0, 1.0, -40, 0, 40, "offset", 5, "crossing", [0, -60]), + "bushycoop": (-1.0, -160.0, 1.0, -40, 0, 40, "offset", 5, "crossing", [0, -60]), + "tstellate": (-1.0, -160.0, 1.0, -40, 0, 40, "offset", 5, "crossing", [0, -60]), + "tstellatenav11": ( + -1.0, + -160.0, + 1.0, + -40, + 0, + 40, + "offset", + 5, + "crossing", + [0, -60], + ), + "tstellatedend": (-1.0, -160.0, 1.0, -40, 0, 40, "offset", 5, "crossing", [0, -60]), + "dstellate": (-1.0, -160.0, 1.0, -40, 0, 40, "offset", 5, "crossing", [0, -60]), + "dstellateeager": ( + -1.0, + -160.0, + 1.0, + -40, + 0, + 40, + "offset", + 5, + "crossing", + [0, -60], + ), + "sgc:": (-1.0, -160.0, 1.0, -40, 0, 40, "offset", 5, "crossing", [0, -60]), + "cartwheel": (-1.0, -160.0, 1.0, -40, 0, 40, "offset", 5, "crossing", [0, -60]), + "pyramidal": (-1.0, -160.0, 1.0, -40, 0, 40, "offset", 5, "crossing", [0, -60]), + "tuberculoventral": ( + -1.0, + -160.0, + 1.0, + -40, + 0, + 40, + "offset", + 5, + "crossing", + [0, -60], + ), + "octopus": (-1.0, -160.0, 1.0, -40, 0, 40, "offset", 5, "crossing", [0, -60]), + "mso": (-1.0, -160.0, 1.0, -40, 0, 40, "offset", 5, "crossing", [0, -60]), +} + + +class Tests: + """ + Class to select cells for tests + """ + + def __init__(self): + pass + + def selectCell(self, args): + """ + Parameters + ---------- + args : argparse args from command line + + Returns + ------- + cell + Instantiated cell of the selected celltype + """ + h.celsius = float(args.temp) + # + # Spiral Ganglion cell tests + # + if args.celltype == "sgc": # morphology is always "point" for SGCs + cell = cells.SGC.create( + debug=debugFlag, + species=args.species, + nach=args.nav, + ttx=args.ttx, + modelType=args.type, + ) + + # + # Bushy tests + # + elif args.celltype == "bushy" and args.morphology == "point": + cell = cells.Bushy.create( + model="RM03", + species=args.species, + modelType=args.type, + ttx=args.ttx, + nach=args.nav, + debug=debugFlag, + ) + # cell.soma().klt.gbar = 0.0003 + + elif args.celltype == "bushy" and args.morphology == "waxon": + cell = cells.Bushy.create( + model="RM03", + species=args.species, + modelType=args.type, + nach=args.nav, + ttx=args.ttx, + debug=debugFlag, + ) + cell.add_axon() + + elif args.celltype == "bushy" and args.morphology == "stick": + cell = cells.Bushy.create( + model="RM03", + species=args.species, + modelType=args.type, + morphology="cnmodel/morphology/bushy_stick.hoc", + decorator=True, + nach=args.nav, + ttx=args.ttx, + debug=debugFlag, + ) + h.topology() + + elif args.celltype == "bushycoop" and args.morphology == "point": + cell = cells.Bushy.create( + model="RM03", + species=args.species, + modelType=args.type, + ttx=args.ttx, + nach=args.nav, + debug=debugFlag, + ) + + # + # T-stellate tests + # + elif args.celltype == "tstellate" and args.morphology == "point": + cell = cells.TStellate.create( + model="RM03", + species=args.species, + modelType=args.type, + nach=args.nav, + ttx=args.ttx, + debug=debugFlag, + ) + + elif args.celltype == "tstellate" and args.morphology == "stick": + cell = cells.TStellate.create( + model="RM03", + species=args.species, + modelType=args.type, + nach=args.nav, + ttx=args.ttx, + debug=debugFlag, + morphology="cnmodel/morphology/tstellate_stick.hoc", + decorator=True, + ) + + elif ( + args.celltype == "tstellatenav11" and args.morphology == "point" + ): # note this uses a different model... + print("test_cells: Stellate NAV11") + cell = cells.TStellateNav11.create( + model="Nav11", + species=args.species, + modelType=None, + ttx=args.ttx, + debug=debugFlag, + ) + + elif ( + args.celltype == "tstellatenav11" and args.morphology == "stick" + ): # note this uses a different model... + cell = cells.TStellateNav11.create( + model="Nav11", + species=args.species, + modelType=None, + morphology="cnmodel/morphology/tstellate_stick.hoc", + decorator=True, + ttx=args.ttx, + debug=debugFlag, + ) + h.topology() + + # + # Octopus cell tests + # + elif args.celltype == "octopus" and args.morphology == "point": + cell = cells.Octopus.create( + species=args.species, + modelType="RM03", # args.type, + nach=args.nav, + ttx=args.ttx, + debug=debugFlag, + ) + + elif ( + args.celltype == "octopus" and args.morphology == "stick" + ): # Go to spencer et al. model + cell = cells.Octopus.create( + modelType="Spencer", + species=args.species, + morphology="cnmodel/morphology/octopus_spencer_stick.hoc", + decorator=True, + nach=args.nav, + ttx=args.ttx, + debug=debugFlag, + ) + h.topology() + + # + # D-stellate tests + # + elif args.celltype == "dstellate": + cell = cells.DStellate.create( + debug=debugFlag, species=args.species, ttx=args.ttx, modelType=args.type + ) + + elif args.celltype == "dstellateeager": + cell = cells.DStellateEager.create( + debug=debugFlag, ttx=args.ttx, modelType=args.type + ) + + # + # DCN pyramidal cell tests + # + elif args.celltype == "pyramidal": + cell = cells.Pyramidal.create( + modelType=args.type, ttx=args.ttx, debug=debugFlag + ) + + # + # DCN tuberculoventral cell tests + # + elif args.celltype == "tuberculoventral" and args.morphology == "point": + cell = cells.Tuberculoventral.create( + species="mouse", + modelType="TVmouse", + ttx=args.ttx, + nach=args.nav, + debug=debugFlag, + ) + + elif args.celltype == "tuberculoventral" and args.morphology == "stick": + cell = cells.Tuberculoventral.create( + species="mouse", + modelType="TVmouse", + morphology="cnmodel/morphology/tv_stick.hoc", + decorator=True, + ttx=args.ttx, + debug=debugFlag, + ) + h.topology() + + # + # DCN cartwheel cell tests + # + elif args.celltype == "cartwheel": + cell = cells.Cartwheel.create( + modelType=args.type, ttx=args.ttx, debug=debugFlag + ) + + # + # MSO principal neuron tests + # + elif args.celltype == "mso" and args.morphology == "point": + cell = cells.MSO.create( + model="RM03", + species=args.species, + modelType=args.type, + ttx=args.ttx, + nach=args.nav, + debug=debugFlag, + ) + + else: + raise ValueError( + "Cell Type %s and configurations nav=%s or config=%s are not available" + % (args.celltype, args.nav, args.morphology) + ) + + print(cell.__doc__) + self.cell = cell + + def run_test(self, sites, ptype, args): + """ + Run either vc or cc test, and plot the result + + Parameters + ---------- + args : argparse args from command line + + """ + self.cell.set_temperature(float(args.temp)) + print(self.cell.status) + V0 = self.cell.find_i0(showinfo=True) + # self.cell.cell_initialize() + print( + "Currents at nominal Vrest= %.2f I = 0: I = %g " + % (V0, self.cell.i_currents(V=V0)) + ) + self.cell.print_mechs(self.cell.soma) + instant = self.cell.compute_rmrintau(auto_initialize=False, vrange=None) + print( + " From Inst: Rin = {:7.1f} Tau = {:7.1f} Vm = {:7.1f}".format( + instant["Rin"], instant["tau"], instant["v"] + ) + ) + if args.cc is True: + # define the current clamp electrode and default settings + self.iv = IVCurve() + self.iv.run( + ccivrange[args.species][args.celltype], + self.cell, + durs=default_durs, + sites=sites, + reppulse=ptype, + temp=float(args.temp), + ) + ret = self.iv.input_resistance_tau() + print( + " From IV: Rin = {:7.1f} Tau = {:7.1f} Vm = {:7.1f}".format( + ret["slope"], ret["tau"], ret["intercept"] + ) + ) + self.iv.show(cell=self.cell) + + elif args.rmp is True: + print("temperature: ", self.cell.status["temperature"]) + self.iv = IVCurve() + self.iv.run( + {"pulse": (0, 0, 1)}, + self.cell, + durs=default_durs, + sites=sites, + reppulse=ptype, + temp=float(args.temp), + ) + self.iv.show(cell=self.cell, rmponly=True) + + elif args.vc is True: + # define the voltage clamp electrode and default settings + self.vc = VCCurve() + self.vc.run((-120, 40, 5), self.cell) + self.vc.show(cell=self.cell) + + else: + raise ValueError("Nothing to run. Specify one of --cc, --vc, --rmp.") + + +def main(): + parser = argparse.ArgumentParser( + description=( + "test_cells.py:", + " Biophysical representations of neurons (mostly auditory), test file", + ) + ) + parser.add_argument("celltype", action="store") + parser.add_argument("species", action="store", default="guineapig") + parser.add_argument("--type", action="store", default=None) + parser.add_argument( + "--temp", action="store", default=22.0, help=("Temp DegC (22 default)") + ) + # species is an optional option.... + parser.add_argument( + "-m", + action="store", + dest="morphology", + default="point", + help=("Set morphology: %s " % [morph for morph in cellinfo["morphology"]]), + ) + parser.add_argument( + "--nav", + action="store", + dest="nav", + default=None, + help=("Choose sodium channel: %s " % [ch for ch in cellinfo["nav"]]), + ) + parser.add_argument( + "--ttx", + action="store_true", + dest="ttx", + default=False, + help=("Use TTX (no sodium current"), + ) + parser.add_argument( + "-p", + action="store", + dest="pulsetype", + default="step", + help=("Set CCIV pulse to step or repeated pulse"), + ) + clampgroup = parser.add_mutually_exclusive_group() + clampgroup.add_argument( + "--vc", action="store_true", help="Run in voltage clamp mode" + ) + clampgroup.add_argument( + "--cc", action="store_true", help="Run in current clamp mode" + ) + clampgroup.add_argument( + "--rmp", action="store_true", help="Run to get RMP in current clamp mode" + ) + + args = parser.parse_args() + if args.celltype not in cellinfo["types"]: + print("cell: %s is not in our list of cell types" % (args.celltype)) + print("celltypes: ", cellinfo["types"]) + sys.exit(1) + + path = os.path.dirname(cnmodel.__file__) + # h.load_file("stdrun.hoc") + # h.load_file(os.path.join(path, "custom_init.hoc")) # replace init with one that gets closer to steady state + + # print 'Species: ', args.species + # print 'Morphology configuration: ', args.morphology + sites = None + if args.pulsetype == "step": + ptype = None + else: + ptype = "pulses" + if args.morphology in cellinfo["morphology"]: + print("Morphological configuration %s is ok" % args.morphology) + + t = Tests() + t.selectCell(args) + app = pg.mkQApp() + t.run_test(sites, ptype, args) + + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() + + +if __name__ == "__main__": + main() diff --git a/examples/test_circuit.py b/examples/test_circuit.py new file mode 100644 index 0000000..c915e85 --- /dev/null +++ b/examples/test_circuit.py @@ -0,0 +1,60 @@ +""" +Test construction of a complete circuit build from cell populations. + +This script: + +1. Creates populations of sgc, bushy, and stellate cells. +2. Connects the populations together. +3. Instantiates 10 bushy and 10 t-stellate cells near 16kHz. +4. Resolves all required synaptic dependencies. + +No simulation is executed; this is meant to be run interactively to allow +introspection of the circuit that was generated. +""" + +from cnmodel import populations + + +def testcircuit(): + # Create cell populations. + # This creates a complete set of _virtual_ cells for each population. No + # cells are instantiated at this point. + sgc = populations.SGC() + bushy = populations.Bushy() + dstellate = populations.DStellate() + tstellate = populations.TStellate() + + # Connect populations. + # This only records the connections between populations; no synapses are + # created at this stage. + sgc.connect(bushy, tstellate, dstellate) + dstellate.connect(tstellate, bushy) + # tstellate.connect(bushy) # this will fail - we don't know about this connection yet. + + # Select cells to record from. + # At this time, we actually instantiate the selected cells. + # select 10 bushy cells closest to 16kHz + bushy_cell_ids = bushy.select(10, cf=16e3, create=True) + # select 10 stellate cells closest to 16kHz + tstel_cell_ids = tstellate.select(10, cf=16e3, create=True) + + # Now create the supporting circuitry needed to drive the cells we selected. + # At this time, cells are created in all populations and automatically + # connected with synapses. + bushy.resolve_inputs(depth=2) + tstellate.resolve_inputs(depth=2) + # Note that using depth=2 indicates the level of recursion to use when + # resolving inputs. For example, resolving inputs for the bushy cell population + # (level 1) creates presynaptic cells in the dstellate population, and resolving + # inputs for the dstellate population (level 2) creates presynaptic cells in the + # sgc population. + + # TODO: + # - specify which parameters to record (Vm, spike times, per-synapse currents, etc) + # - run simulation and display / analyze results + # - add examples of modifying circuitry to search parameter spaces, test + # hypotheses, etc. + + +if __name__ == "__main__": + testcircuit() diff --git a/examples/test_decorator.py b/examples/test_decorator.py new file mode 100755 index 0000000..a5ddaea --- /dev/null +++ b/examples/test_decorator.py @@ -0,0 +1,151 @@ +#!/usr/bin/python +""" +Basic test of cnmodel decorator on simple cell +Users LC_bushy.hoc and XM13 mechanisms. + +""" +from __future__ import print_function + + +__author__ = "pbmanis" + + +__author__ = "pbmanis" + + +import sys +import numpy as np +import cnmodel.cells as cells +import cnmodel.decorator as Decorator +from cnmodel.util import pyqtgraphPlotHelpers as PH +from cnmodel.protocols import IVCurve +import pyqtgraph as pg +import timeit + + +class F5: + def __init__(self, filename): + # build plotting area + # + self.filename = filename + self.iv = IVCurve() # use standard IVCurve here... + self.temperature = 34 + self.initdelay = 150.0 + + def run(self): + self.post_cell = cells.Bushy.create( + morphology=self.filename, + decorator=Decorator, + species="mouse", + modelName="XM13", + modelType="II", + ) + self.post_cell.set_temperature(float(self.temperature)) + self.post_cell.set_d_lambda( + freq=2000.0 + ) # necessary to ensure appropriate spatial + self.iv.reset() + irange = self.post_cell.i_test_range + # irange = {'pulse': (-0.6, 1.1, 0.2)} for Figure 5 of paper + irange = {"pulse": (-0.5, 1.5, 0.25)} + self.durs = (self.initdelay + 20.0, 100.0, 50.0) + self.iv.run( + irange, + self.post_cell, + durs=self.durs, + temp=float(self.temperature), + initdelay=self.initdelay, + ) + + def plot(self): + pg.setConfigOption("background", "w") # set background to white + pg.setConfigOption("foreground", "k") + self.app = pg.mkQApp() + + wintitle = "test_decorator" + self.view = pg.GraphicsView() + self.layout = pg.GraphicsLayout() # (border=(100,100,100)) + self.view.setCentralItem(self.layout) + self.view.resize(800, 600) + self.view.show() + self.plots = {} + nr1 = 6 + nc = 10 + for i in range(1, nr1): + self.plots["p%d" % i] = None + for i in range(1, nr1 + 1): + self.layout.addLayout(row=i, col=nc) + for i in range(1, nc + 1): + self.layout.addLayout(row=nr1 + 2, col=i) + + self.plots["p1"] = self.layout.addPlot( + row=1, + col=1, + rowspan=6, + colspan=9, + labels={"left": "V (mV)", "bottom": "Time (ms)"}, + ) + self.plots["p2"] = self.layout.addPlot( + row=7, + col=1, + rowspan=1, + colspan=9, + labels={"left": "I (nA)", "bottom": "Time (ms)"}, + ) + + for k in range(len(self.iv.voltage_traces)): + self.plots["p1"].plot( + self.iv.time_values, + np.array(self.iv.voltage_traces[k]), + pen=pg.mkPen("k", width=0.75), + ) + self.plots["p2"].plot( + self.iv.time_values, + np.array(self.iv.current_traces[k]), + pen=pg.mkPen("k", width=0.75), + ) + self.plots["p1"].setRange( + xRange=(0.0, np.sum(self.durs) - self.initdelay), yRange=(-160.0, 40.0) + ) + self.plots["p2"].setRange( + xRange=(0.0, np.sum(self.durs) - self.initdelay), yRange=(-1, 1) + ) + PH.noaxes(self.plots["p1"]) + PH.calbar( + self.plots["p1"], + calbar=[125.0, -120.0, 10.0, 20.0], + unitNames={"x": "ms", "y": "mV"}, + ) + PH.noaxes(self.plots["p2"]) + PH.calbar( + self.plots["p2"], + calbar=[125, 0.1, 0.0, 0.5], + unitNames={"x": "ms", "y": "nA"}, + ) + + text = "{0:2d}\u00b0C {1:.2f}-{2:.2f} nA".format( + int(self.temperature), + np.min(self.iv.current_cmd), + np.max(self.iv.current_cmd), + ) + ti = pg.TextItem(text, anchor=(1, 0)) + ti.setFont(pg.QtGui.QFont("Arial", 9)) + ti.setPos(120.0, -120.0) + self.plots["p1"].addItem(ti) + + +if __name__ == "__main__": + if len(sys.argv) == 1: + fig5 = F5("examples/LC_bushy.hoc") + else: + fn = "/Users/pbmanis/Desktop/Python/VCNModel/VCN_Cells/VCN_c{0:02d}/Morphology/VCN_c{0:02d}.hoc".format( + int(sys.argv[1]) + ) + fig5 = F5(fn) + start_time = timeit.default_timer() + fig5.run() + elapsed = timeit.default_timer() - start_time + print("Elapsed time for simulation: %f" % (elapsed)) + fig5.plot() + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() diff --git a/examples/test_mechanisms.py b/examples/test_mechanisms.py new file mode 100644 index 0000000..9b23ffe --- /dev/null +++ b/examples/test_mechanisms.py @@ -0,0 +1,317 @@ +""" +test_mechanisms.py + +This program displays the results of inserting NEURON mechaanisms from .mod files +into a point cell to voltage steps in voltage clamp. +This code is primarily for visual verification of model function. + +Usage: python test_mechanisms.py + +Available mechanisms:: + + CaPCalyx bkpkj hcno hcnobo hpkj + ihpyr ihsgcApical ihsgcBasalMiddle ihvcn jsrna + ka kcnq kdpyr kht kif + kis klt kpkj kpkj2 kpkjslow + kpksk leak lkpkj na naRsg + nacn nacncoop nap napyr nav11 + +Note: only modfiles that implement voltage-dependent ion channel models make sense to run +with this routine. the list "nottestablemechs" in the file defines mechanisms provided +with cnmodel that cannot be run with this program. + +""" +import sys +from neuron import h +from neuron import nrn + +import gc +import numpy as np + +# import scipy as sp +import cnmodel.util +import pyqtgraph as pg +import pyqtgraph.exporters +from pyqtgraph.Qt import QtCore, QtGui +import cnmodel.util.pynrnutilities as Util + +nottestablemechs = [ + "cadyn", + "ca_ion", + "cadiff", + "cadifpmp", + "Mechanism", + "capmp", + "capump", + "cl_ion", + "extracellular", + "fastpas", + "k_ion", + "KIR", + "hh", + "na_ion", + "narsg", + "pas", + "cap", +] # cap uses "pcabar" + + +class ChannelKinetics: + def __init__(self, args, export=False): + modfile = [] + if isinstance(args, list): + for arg in args: + modfile.append(arg) # must be string, not list... + else: + modfile.append(args) # 'CaPCalyx' + print("modfile: ", modfile) + colors = ["b", "r", "g", "y", "c", "m", "w"] + if len(modfile) > len(colors): + print("Too many modfiles... keep it simple!") + exit() + # if isinstance(args, list) and len(args) > 1: + # modfile2 = args[1] + doKinetics = False + self.app = pg.mkQApp() + self.win = pg.GraphicsWindow() + self.win.setWindowTitle("VC Plots") + self.win.resize(600, 800) + # cw = QtGui.QWidget() + # self.win.setCentralWidget(cw) + # self.gridLayout = QtGui.QGridLayout() + # cw.setLayout(self.gridLayout) + # self.gridLayout.setContentsMargins(9, 9, 4, 4) + # self.gridLayout.setSpacing(1) + self.p1 = self.win.addPlot(title="I (VC)") + # self.gridLayout.addWidget(self.p1, 0, 0, 1, 1) + self.p2 = self.win.addPlot(title="I_ss, I_max") + # self.gridLayout.addWidget(self.p2, 0, 1, 1, 1) + self.win.nextRow() + self.p3 = self.win.addPlot(title="V command") + # self.gridLayout.addWidget(self.p3, 1, 0, 1, 1) + self.p5 = self.win.addPlot(title="I_min") + # self.gridLayout.addWidget(self.p5, 1, 1, 1, 1) + self.win.show() + QtGui.QApplication.processEvents() + # + # self.tdur is a table of durations for the pulse and post-pulse for each channel type (best to highlight features + # on appropriate time scales) + # + self.tdur = { + "CaPCalyx": [20.0, 10.0], + "nav11": [10.0, 5.0], + "jsrna": [10.0, 5.0], + "ichanWT2005": [10.0, 5.0], + "nacn": [10.0, 5.0], + "nacncoop": [10.0, 5.0], + "nabu": [10.0, 5.0], + "kht": [200.0, 20.0], + "klt": [200.0, 20.0], + "ka": [25.0, 5.0], + "hcno": [1000.0, 200.0], + "ih": [1000.0, 200.0], + "ihvcn": [1000.0, 200.0], + "hcnobo": [1000.0, 200.0], + "ihsgcBasalMiddle": [1000.0, 200.0], + "ihsgcApical": [1000.0, 200.0], + "kif": [100.0, 100.0], + "kis": [100.0, 10.0], + "napyr": [10, 5.0], + "ihpyr": [1000.0, 200.0], + "kdpyr": [200.0, 20.0], + "kcnq": [200, 20], + "nap": [200.0, 100.0], + } + for i, mfile in enumerate(modfile): + self.run(modfile=mfile, color=colors[i], export=export) + s = "" + # self.win.setWindowTitle('VC Plots: ' + [s+sn+'; ' for sn in modfile]) + gc.collect() + + if doKinetics: + self.win2 = pg.GraphicsWindow(title="KineticPlots") + self.win2.resize(800, 600) + self.kp1 = self.win.addPlot(title="htau") + self.computeKinetics("nav11") + + # self.win.show() + + def run(self, modfile="CaPCalyx", color="r", export=False): + if isinstance(modfile, list): + modfile = modfile[0] + + if modfile in self.tdur: + tstep = self.tdur[modfile] + else: + tstep = [200.0, 50.0] + tdelay = 5.0 + Channel = cnmodel.util.Mechanism(modfile) + leak = cnmodel.util.Mechanism("leak") + Channel.set_parameters({"gbar": 1}) + leak.set_parameters({"gbar": 1e-12}) + # if modfile == 'nacncoop': + # self.soma().nacncoop.p = 0. + # self.soma().nacncoop.KJ = 0. + # # Channel.set_parameters({'p': 0., 'KJ': 000.}) + + self.soma = cnmodel.util.Section(L=10, diam=10, mechanisms=[Channel, leak]) + if modfile == "bkpjk": + ca_init = 100e-6 + self.soma().cai = ca_init + else: + ca_init = 70e-6 + if modfile == "nacncoop": + self.soma().nacncoop.p = 0.1 + self.soma().nacncoop.KJ = 1000.0 + # Channel.set_parameters({'p': 0., 'KJ': 000.}) + h.celsius = 37.0 # set the temperature. + self.vec = {} + for var in ["time", "V", "IChan", "Vcmd"]: + self.vec[var] = h.Vector() + + h.dt = 0.025 + v_init = -65.0 + + clampV = v_init + self.vcPost = h.SEClamp(0.5, sec=self.soma) + self.vcPost.dur1 = tdelay + self.vcPost.amp1 = clampV + self.vcPost.dur2 = tstep[0] + self.vcPost.amp2 = clampV - 0.0 # just a tiny step to keep the system honest + self.vcPost.dur3 = tstep[1] + self.vcPost.amp3 = clampV + self.vcPost.rs = 1e-9 + print("soma: ", self.soma, end=" ") + # print(dir(self.vcPost)) + # print(' vcpost sec: ', self.vcPost.Section()) + + if modfile[0:2] == "ih": + stimamp = np.linspace(-140, -40, num=21, endpoint=True) + else: + stimamp = np.linspace(-100, 60, num=35, endpoint=True) + self.ivss = np.zeros((2, stimamp.shape[0])) + self.ivmin = np.zeros((2, stimamp.shape[0])) + self.ivmax = np.zeros((2, stimamp.shape[0])) + print( + ( + "I range = %6.1f-%6.1f, T = %4.1f" + % (np.min(stimamp), np.max(stimamp), h.celsius) + ) + ) + + for i, V in enumerate(stimamp): + stim = {} + stim["NP"] = 1 + stim["Sfreq"] = 1 # stimulus frequency + stim["delay"] = 5 + stim["dur"] = 100 + stim["amp"] = V + stim["PT"] = 0.0 + self.vcPost.amp2 = V + self.vec["IChan"].record(self.vcPost._ref_i, sec=self.soma) + self.vec["V"].record(self.soma()._ref_v, sec=self.soma) + self.vec["time"].record(h._ref_t) + # print + h.tstop = self.vcPost.dur1 + self.vcPost.dur2 + self.vcPost.dur3 + h.finitialize(v_init) + h.run() + self.t = np.array(self.vec["time"]) + self.ichan = np.array(self.vec["IChan"]) + self.v = np.array(self.vec["V"]) + self.p1.plot(self.t, self.ichan, pen=pg.mkPen((i, len(stimamp) * 1.5))) + self.p3.plot(self.t, self.v, pen=pg.mkPen((i, len(stimamp) * 1.5))) + (self.ivss[1, i], r2) = Util.measure( + "mean", self.t, self.ichan, tdelay + tstep[0] - 10.0, tdelay + tstep[0] + ) + (self.ivmin[1, i], r2) = Util.measure( + "min", self.t, self.ichan, tdelay + 0.1, tdelay + tstep[0] / 5.0 + ) + (self.ivmax[1, i], r2) = Util.measure( + "max", self.t, self.ichan, tdelay + 0.1, tdelay + tstep[0] / 5.0 + ) + self.ivss[0, i] = V + self.ivmin[0, i] = V + self.ivmax[0, i] = V + self.p2.plot( + self.ivss[0, :], + self.ivss[1, :], + symbol="o", + symbolSize=4.0, + pen=pg.mkPen(color), + ) + self.p2.plot( + self.ivmax[0, :], + self.ivmax[1, :], + symbol="t", + symbolSize=4.0, + pen=pg.mkPen(color), + ) + self.p5.plot( + self.ivmin[0, :], + self.ivmin[1, :], + symbol="s", + symbolSize=4.0, + pen=pg.mkPen(color), + ) + + print(export) + if export: + exporter = pg.exporters.MatplotlibExporter(self.p1) + print("exporting: " + "%s_traces.svg" % modfile) + exporter.export(fileName="%s_traces.pdf" % modfile) + exporter = pg.exporters.MatplotlibExporter(self.p3) + exporter.export("%s_command.pdf" % modfile) + exporter = pg.exporters.MatplotlibExporter(self.p2) + exporter.export("%s_IV.pdf" % modfile) + + def computeKinetics(self, ch): + pass + + +def getmechs(): + mechs = [] + for n in dir(nrn): + o = getattr(nrn, n) + if str(o) == str(nrn.Mechanism): + mechs.append(n) + return mechs + + +if __name__ == "__main__": + mechs = getmechs() + if len(sys.argv) < 2: + + print("\n\nUsage: python test_mechanisms.py ") + print(" Available mechanisms:") + + linelen = 0 + for i, n in enumerate(mechs): + if n in nottestablemechs: # 'Mechanism': + continue + print("%20s" % n, end=" ") + linelen += 20 + if linelen > 80: + print("") + + linelen = 0 + sys.exit(1) + + if sys.argv[1:] in nottestablemechs: + exit() + export = False + if len(sys.argv) > 2: + if sys.argv[2] == "export": + export = True + + if sys.argv[1] == "all": + for n in mechs: + if n in nottestablemechs: + print(("Skipping %s" % n)) + continue + else: + ck = ChannelKinetics(n) + else: + ck = ChannelKinetics(sys.argv[1], export=export) + + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() diff --git a/examples/test_mso_inputs.py b/examples/test_mso_inputs.py new file mode 100644 index 0000000..d7a683e --- /dev/null +++ b/examples/test_mso_inputs.py @@ -0,0 +1,208 @@ +""" +Test generating a series of EPSPs in a MSO cell in response to tone pip. This +test demonstrates how a binaural circuit can be constructed. + +This script: + +1. Creates multiple SGCs (base instance has 3) converging onto two bushy cells. + The 2 bushy cells then converge onto one MSO cell +2. Connects the group of sgc cells from one ear to one bushy cell, and the + other sgcs from the other ear to the + other bushy cell. +3. Specifies the CFs of the SGC cells individually. Also specifies the frequency of + and stimuli by ear allowing for "binaural beats" +4. Records the bushy and MSO cell membrane voltages, sgc spike time, and calculates + vector strengths. + +The auditory nerve spike train is generated automatically by the DummySGC class +using the tone pip. For lower-level access to the auditory nerve model, see the +test_an_model.py and test_sound_stim.py examples. + + +Usage: + python examples/test_mso_inputs.py [cochlea | matlab] + + The AN simulator that is run depends on what is available and how the script is called. + python examples/test_mso_inputs.py [cochlea | matlab] will try to use the specified + simulator. If no simulator is specified, it will try to use cochlea or matlab, in + that order. + +""" +import sys +import numpy as np +import pyqtgraph as pg +from neuron import h +from cnmodel.protocols import Protocol +from cnmodel import cells +from cnmodel.util import sound +from cnmodel.util import custom_init +import cnmodel.util.pynrnutilities as PU + + +class MSOBinauralTest(Protocol): + def run(self, temp=38.0, dt=0.025, seed=575982035, simulator=None): + ears = {"left": [500.0, 502, 498], "right": [500.0, 502.0, 498]} + + self.beatfreq = 0.0 + self.f0 = 500.0 + f0 = {"left": self.f0, "right": self.f0 + self.beatfreq} + nsgc = len(list(ears.keys())) + sgcCell = {} + bushyCell = {} + msoCell = {} + synapse = {} + self.stim = {} + self.ears = ears + self.stimdur = 0.2 + self.stimdelay = 0.02 + self.rundur = self.stimdelay + self.stimdur + 0.02 + + for i, ear in enumerate(ears.keys()): + nsgc = len(ears[ear]) # how many sgcs are specified for this ear + sgcCell[ear] = [cells.DummySGC(cf=ears[ear][k], sr=2) for k in range(nsgc)] + bushyCell[ear] = [cells.Bushy.create(temperature=temp)] + synapse[ear] = [ + sgcCell[ear][k].connect(bushyCell[ear][0]) for k in range(nsgc) + ] + self.stim[ear] = [ + sound.TonePip( + rate=100e3, + duration=self.stimdur + 0.1, + f0=f0[ear], + dbspl=80, + ramp_duration=2.5e-3, + pip_duration=self.stimdur, + pip_start=[self.stimdelay], + ) + for k in range(nsgc) + ] + for k in range(len(self.stim[ear])): + sgcCell[ear][k].set_sound_stim( + self.stim[ear][k], seed=seed + i * seed + k, simulator=simulator + ) + self["vm_bu_%s" % ear] = bushyCell[ear][0].soma(0.5)._ref_v + for k in range(30): + self["xmtr%d_%s" % (k, ear)] = synapse[ear][ + 0 + ].terminal.relsite._ref_XMTR[k] + for k in range(len(synapse[ear])): + synapse[ear][k].terminal.relsite.Dep_Flag = False # turn off depression + + msoCell = cells.MSO.create(temperature=temp) # one target MSO cell + msosyn = {} + for ear in ears: + msosyn[ear] = bushyCell[ear][0].connect(msoCell) + self.sgc_cells = sgcCell + self.bushy_cells = bushyCell + self.synapses = synapse + self.msyns = msosyn + self.msoCell = msoCell + self.all_cells = [] # hold all "real" cells (DummySGC does not have mechanisms) + for ear in list(ears.keys()): + self.all_cells.append([c for c in self.bushy_cells[ear]]) + self.all_cells.append([self.msoCell]) + + self["vm_mso"] = self.msoCell.soma(0.5)._ref_v + for k, ear in enumerate(ears.keys()): + for i in range(30): + self["mso_xmtr%d_%s" % (i, ear)] = msosyn[ + ear + ].terminal.relsite._ref_XMTR[i] + msosyn[ear].terminal.relsite.Dep_Flag = False # turn off depression + + self["t"] = h._ref_t + + h.tstop = self.rundur * 1e3 # duration of a run + h.celsius = temp + h.dt = dt + + custom_init() + # confirm that all cells are ok + for cg in self.all_cells: + for c in cg: + c.check_all_mechs() + while h.t < h.tstop: + h.fadvance() + + def show(self): + self.win = pg.GraphicsWindow() + + p5 = self.win.addPlot(title="stim") + p5.plot(self.stim["left"][0].time * 1000.0, self.stim["left"][0].sound) + + p1 = self.win.addPlot(title="Bushy Vm", row=1, col=0) + for k, ear in enumerate(self.ears.keys()): + p1.plot(self["t"], self["vm_bu_%s" % ear], pen=(k, 15)) + + p2 = self.win.addPlot(title="SGC-BU xmtr left", row=0, col=1) + for i in range(30): + p2.plot(self["t"], self["xmtr%d_left" % i], pen=(i, 15)) + p2.setXLink(p1) + p2r = self.win.addPlot(title="SGC-BU xmtr right", row=1, col=1) + for i in range(30): + p2r.plot(self["t"], self["xmtr%d_right" % i], pen=(i, 15)) + p2r.setXLink(p1) + + p3 = self.win.addPlot(title="MSO Vm", row=2, col=0) + p3.plot(self["t"], self["vm_mso"]) + p3.setXLink(p1) + + p4 = self.win.addPlot(title="BU-MSO xmtr", row=2, col=1) + for k, ear in enumerate(self.ears.keys()): + for i in range(30): + p2.plot(self["t"], self["mso_xmtr%d_%s" % (i, ear)], pen=(i, 15)) + p4.setXLink(p1) + + p4 = self.win.addPlot(title="AN spikes", row=3, col=0) + ntrain = len(self.sgc_cells["left"]) + for k in range(ntrain): + yr = [k / float(ntrain), (k + 0.8) / float(ntrain)] + vt = pg.VTickGroup( + self.sgc_cells["left"][k]._spiketrain, yrange=yr, pen=(k, 15) + ) + p4.addItem(vt) + p4.setXLink(p1) + p5.setXLink(p1) + + # phaselocking calculations + phasewin = [self.stimdelay + 0.2 * self.stimdur, self.stimdelay + self.stimdur] + msospk = PU.findspikes(self["t"], self["vm_mso"], -30.0) + + spkin = msospk[np.where(msospk > phasewin[0] * 1e3)] + spikesinwin = spkin[np.where(spkin <= phasewin[1] * 1e3)[0]] + + # set freq for VS calculation + f0 = self.f0 + fb = self.beatfreq + vs = PU.vector_strength(spikesinwin, f0) + + print( + "MSO Vector Strength at %.1f: %7.3f, d=%.2f (us) Rayleigh: %7.3f p = %.3e n = %d" + % (f0, vs["r"], vs["d"] * 1e6, vs["R"], vs["p"], vs["n"]) + ) + if fb > 0: + vsb = PU.vector_strength(spikesinwin, fb) + print( + "MSO Vector Strength to beat at %.1f: %7.3f, d=%.2f (us) Rayleigh: %7.3f p = %.3e n = %d" + % (fb, vsb["r"], vsb["d"] * 1e6, vsb["R"], vsb["p"], vsb["n"]) + ) + (hist, binedges) = np.histogram(vs["ph"]) + p6 = self.win.addPlot(title="VS", row=3, col=1) + p6.plot( + binedges, hist, stepMode=True, fillBrush=(100, 100, 255, 150), fillLevel=0 + ) + p6.setXRange(0.0, 2 * np.pi) + + self.win.show() + + +if __name__ == "__main__": + simulator = None + if len(sys.argv) > 1: + simulator = sys.argv[1] + prot = MSOBinauralTest() + prot.run(simulator=simulator) + prot.show() + + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() diff --git a/examples/test_physiology.py b/examples/test_physiology.py new file mode 100644 index 0000000..c315aba --- /dev/null +++ b/examples/test_physiology.py @@ -0,0 +1,704 @@ +""" +Test principal cell responses to tone pips of varying frequency and intensity. + +This is an example of model construction from a very high level--we specify +only which populations of cells are present and which ones should be connected. +The population and cell classes take care of all the details of generating the +network needed to support a small number of output cells. + +Note: run time for this example can be very long. To speed things up, reduce +n_frequencies or n_levels, or reduce the number of selected output cells (see +cells_per_band). + +""" + +import os, sys, time +from collections import OrderedDict +import numpy as np +import scipy.stats +from neuron import h +import pyqtgraph as pg +import pyqtgraph.multiprocess as mp +from pyqtgraph.Qt import QtGui, QtCore +from cnmodel import populations +from cnmodel.util import sound, random_seed +from cnmodel.protocols import Protocol +import timeit + + +class CNSoundStim(Protocol): + def __init__(self, seed, temp=34.0, dt=0.025, synapsetype="simple"): + Protocol.__init__(self) + + self.seed = seed + self.temp = temp + self.dt = dt + # self.synapsetype = synapsetype # simple or multisite + + # Seed now to ensure network generation is stable + random_seed.set_seed(seed) + # Create cell populations. + # This creates a complete set of _virtual_ cells for each population. No + # cells are instantiated at this point. + self.sgc = populations.SGC(model="dummy") + self.bushy = populations.Bushy() + self.dstellate = populations.DStellate() + self.tstellate = populations.TStellate() + self.tuberculoventral = populations.Tuberculoventral() + + pops = [ + self.sgc, + self.dstellate, + self.tuberculoventral, + self.tstellate, + self.bushy, + ] + self.populations = OrderedDict([(pop.type, pop) for pop in pops]) + + # set synapse type to use in the sgc population - simple is fast, multisite is slower + # (eventually, we could do this for all synapse types..) + self.sgc._synapsetype = synapsetype + + # Connect populations. + # This only defines the connections between populations; no synapses are + # created at this stage. + self.sgc.connect( + self.bushy, self.dstellate, self.tuberculoventral, self.tstellate + ) + self.dstellate.connect( + self.bushy, self.tstellate + ) # should connect to dstellate as well? + self.tuberculoventral.connect(self.bushy, self.tstellate) + self.tstellate.connect(self.bushy) + + # Select cells to record from. + # At this time, we actually instantiate the selected cells. + + # Pick a single bushy cell near 16kHz, with medium-SR inputs + bc = self.bushy.cells + msr_cells = bc[bc["sgc_sr"] == 1] # filter for msr cells + ind = np.argmin(np.abs(msr_cells["cf"] - 16e3)) # find the one closest to 16kHz + cell_id = msr_cells[ind]["id"] + self.bushy.create_cells([cell_id]) # instantiate just one cell + + # Now create the supporting circuitry needed to drive the cells we selected. + # At this time, cells are created in all populations and automatically + # connected with synapses. + self.bushy.resolve_inputs(depth=2) + # self.tstellate.resolve_inputs(depth=2) + # Note that using depth=2 indicates the level of recursion to use when + # resolving inputs. For example, resolving inputs for the bushy cell population + # (level 1) creates presynaptic cells in the dstellate population, and resolving + # inputs for the dstellate population (level 2) creates presynaptic cells in the + # sgc population. + + def run(self, stim, seed): + """Run the network simulation with *stim* as the sound source and a unique + *seed* used to configure the random number generators. + """ + self.reset() + + # Generate 2 new seeds for the SGC spike generator and for the NEURON simulation + rs = np.random.RandomState() + rs.seed(self.seed ^ seed) + seed1, seed2 = rs.randint(0, 2 ** 32, 2) + random_seed.set_seed(seed1) + self.sgc.set_seed(seed2) + + self.sgc.set_sound_stim(stim, parallel=False) + + # set up recording vectors + for pop in self.bushy, self.dstellate, self.tstellate, self.tuberculoventral: + for ind in pop.real_cells(): + cell = pop.get_cell(ind) + self[cell] = cell.soma(0.5)._ref_v + self["t"] = h._ref_t + + h.tstop = stim.duration * 1000 + h.celsius = self.temp + h.dt = self.dt + + print("init..") + self.custom_init() + print("start..") + last_update = time.time() + while h.t < h.tstop: + h.fadvance() + now = time.time() + if now - last_update > 1.0: + print("%0.2f / %0.2f" % (h.t, h.tstop)) + last_update = now + + # record vsoma and spike times for all cells + vec = {} + for k in self._vectors: + v = self[k].copy() + if k == "t": + vec[k] = v + continue + spike_inds = np.argwhere((v[1:] > -20) & (v[:-1] <= -20))[:, 0] + spikes = self["t"][spike_inds] + pop = k.type + cell_ind = getattr(self, pop).get_cell_index(k) + vec[(pop, cell_ind)] = [v, spikes] + + # record SGC spike trains + for ind in self.sgc.real_cells(): + cell = self.sgc.get_cell(ind) + vec[("sgc", ind)] = [None, cell._spiketrain] + + return vec + + +class NetworkSimDisplay(pg.QtGui.QSplitter): + def __init__(self, prot, results, baseline, response): + pg.QtGui.QSplitter.__init__(self, QtCore.Qt.Horizontal) + self.selected_cell = None + + self.prot = prot + self.baseline = baseline # (start, stop) + self.response = response # (start, stop) + + self.ctrl = QtGui.QWidget() + self.layout = pg.QtGui.QVBoxLayout() + self.layout.setContentsMargins(0, 0, 0, 0) + self.ctrl.setLayout(self.layout) + self.addWidget(self.ctrl) + + self.nv = NetworkVisualizer(prot.populations) + self.layout.addWidget(self.nv) + self.nv.cell_selected.connect(self.nv_cell_selected) + + self.stim_combo = pg.QtGui.QComboBox() + self.layout.addWidget(self.stim_combo) + self.trial_combo = pg.QtGui.QComboBox() + self.layout.addWidget(self.trial_combo) + self.results = OrderedDict() + self.stim_order = [] + freqs = set() + levels = set() + max_iter = 0 + for k, v in list(results.items()): + f0, dbspl, iteration = k + max_iter = max(max_iter, iteration) + stim, result = v + key = "f0: %0.0f dBspl: %0.0f" % (f0, dbspl) + self.results.setdefault(key, [stim, {}]) + self.results[key][1][iteration] = result + self.stim_order.append((f0, dbspl)) + freqs.add(f0) + levels.add(dbspl) + self.stim_combo.addItem(key) + self.freqs = sorted(list(freqs)) + self.levels = sorted(list(levels)) + self.iterations = max_iter + 1 + self.trial_combo.addItem("all trials") + for i in range(self.iterations): + self.trial_combo.addItem(str(i)) + + self.stim_combo.currentIndexChanged.connect(self.stim_selected) + self.trial_combo.currentIndexChanged.connect(self.trial_selected) + + self.tuning_plot = pg.PlotWidget() + self.tuning_plot.setLogMode(x=True, y=False) + self.tuning_plot.scene().sigMouseClicked.connect(self.tuning_plot_clicked) + self.layout.addWidget(self.tuning_plot) + + self.tuning_img = pg.ImageItem() + self.tuning_plot.addItem(self.tuning_img) + + df = np.log10(self.freqs[1]) - np.log10(self.freqs[0]) + dl = self.levels[1] - self.levels[0] + self.stim_rect = QtGui.QGraphicsRectItem(QtCore.QRectF(0, 0, df, dl)) + self.stim_rect.setPen(pg.mkPen("c")) + self.stim_rect.setZValue(20) + self.tuning_plot.addItem(self.stim_rect) + + # self.network_tree = NetworkTree(self.prot) + # self.layout.addWidget(self.network_tree) + + self.pw = pg.GraphicsLayoutWidget() + self.addWidget(self.pw) + + self.stim_plot = self.pw.addPlot() + self.pw.ci.layout.setRowFixedHeight(0, 100) + + self.pw.nextRow() + self.cell_plot = self.pw.addPlot(labels={"left": "Vm"}) + + self.pw.nextRow() + self.input_plot = self.pw.addPlot( + labels={"left": "input #", "bottom": "time"}, title="Input spike times" + ) + self.input_plot.setXLink(self.cell_plot) + self.stim_plot.setXLink(self.cell_plot) + + self.stim_selected() + + def update_stim_plot(self): + stim = self.selected_stim + self.stim_plot.plot(stim.time * 1000, stim.sound, clear=True, antialias=True) + + def update_raster_plot(self): + self.input_plot.clear() + if self.selected_cell is None: + return + pop, ind = self.selected_cell + + rec = pop._cells[ind] + i = 0 + plots = [] + # plot spike times for all presynaptic cells + labels = [] + if rec["connections"] == 0: + return + + pop_colors = { + "dstellate": "y", + "tuberculoventral": "r", + "sgc": "g", + "tstellate": "b", + } + pop_symbols = { + "dstellate": "x", + "tuberculoventral": "+", + "sgc": "t", + "tstellate": "o", + } + pop_order = [self.prot.sgc, self.prot.dstellate, self.prot.tuberculoventral] + trials = self.selected_trials() + for pop in pop_order: + pre_inds = rec["connections"].get(pop, []) + for preind in pre_inds: + # iterate over all trials + for j in trials: + result = self.selected_results[j] + spikes = result[(pop.type, preind)][1] + y = np.ones(len(spikes)) * i + j / ( + 2.0 * len(self.selected_results) + ) + self.input_plot.plot( + spikes, + y, + pen=None, + symbolBrush=pop_colors[pop.type], + symbol="+", + symbolPen=None, + ) + i += 1 + labels.append(pop.type + " " + str(preind)) + self.input_plot.getAxis("left").setTicks([list(enumerate(labels))]) + + def update_cell_plot(self): + self.cell_plot.clear() + if self.selected_cell is None: + return + pop, cell_ind = self.selected_cell + + self.cell_plot.setTitle( + "%s %d %s" % (pop.type, cell_ind, str(self.stim_combo.currentText())) + ) + trials = self.selected_trials() + for i in trials: + result = self.selected_results[i] + y = result[(pop.type, cell_ind)][0] + if y is not None: + p = self.cell_plot.plot( + self.selected_results[0]["t"], + y, + name="%s-%d" % self.selected_cell, + antialias=True, + pen=(i, len(self.selected_results) * 1.5), + ) + # p.curve.setClickable(True) + # p.sigClicked.connect(self.cell_curve_clicked) + # p.cell_ind = ind + + def tuning_plot_clicked(self, event): + spos = event.scenePos() + stimpos = self.tuning_plot.plotItem.vb.mapSceneToView(spos) + x = 10 ** stimpos.x() + y = stimpos.y() + + best = None + for stim, result in list(self.results.values()): + f0 = stim.opts["f0"] + dbspl = stim.opts["dbspl"] + if x < f0 or y < dbspl: + continue + if best is None: + best = stim + continue + if f0 > best.opts["f0"] or dbspl > best.opts["dbspl"]: + best = stim + continue + + if best is None: + return + self.select_stim(best.opts["f0"], best.opts["dbspl"]) + + def nv_cell_selected(self, nv, cell): + self.select_cell(*cell) + + def stim_selected(self): + key = str(self.stim_combo.currentText()) + results = self.results[key] + self.selected_results = results[1] + self.selected_stim = results[0] + self.update_stim_plot() + self.update_raster_plot() + self.update_cell_plot() + + self.stim_rect.setPos(np.log10(results[0].opts["f0"]), results[0].opts["dbspl"]) + + def trial_selected(self): + self.update_raster_plot() + self.update_cell_plot() + self.update_tuning() + + def selected_trials(self): + if self.trial_combo.currentIndex() == 0: + return list(range(self.iterations)) + else: + return [self.trial_combo.currentIndex() - 1] + + def select_stim(self, f0, dbspl): + i = self.stim_order.index((f0, dbspl)) + self.stim_combo.setCurrentIndex(i) + + def select_cell(self, pop, cell_id): + self.selected_cell = pop, cell_id + self.update_tuning() + self.update_cell_plot() + self.update_raster_plot() + + # def cell_curve_clicked(self, c): + # if self.selected is not None: + # pen = self.selected.curve.opts['pen'] + # pen.setWidth(1) + # self.selected.setPen(pen) + + # pen = c.curve.opts['pen'] + # pen.setWidth(3) + # c.setPen(pen) + # self.selected = c + + # self.show_cell(c.cell_ind) + + def update_tuning(self): + # update matrix image + if self.selected_cell is None: + return + + pop, ind = self.selected_cell + fvals = set() + lvals = set() + + # first get lists of all frequencies and levels in the matrix + for stim, vec in list(self.results.values()): + fvals.add(stim.key()["f0"]) + lvals.add(stim.key()["dbspl"]) + fvals = sorted(list(fvals)) + lvals = sorted(list(lvals)) + + # Get spontaneous rate statistics + spont_spikes = 0 + spont_time = 0 + for stim, iterations in list(self.results.values()): + for vec in list(iterations.values()): + spikes = vec[(pop.type, ind)][1] + spont_spikes += ( + (spikes >= self.baseline[0]) & (spikes < self.baseline[1]) + ).sum() + spont_time += self.baseline[1] - self.baseline[0] + spont_rate = spont_spikes / spont_time + + # next count the number of spikes for the selected cell at each point in the matrix + matrix = np.zeros((len(fvals), len(lvals))) + trials = self.selected_trials() + for stim, iteration in list(self.results.values()): + for i in trials: + vec = iteration[i] + spikes = vec[(pop.type, ind)][1] + n_spikes = ( + (spikes >= self.response[0]) & (spikes < self.response[1]) + ).sum() + i = fvals.index(stim.key()["f0"]) + j = lvals.index(stim.key()["dbspl"]) + matrix[i, j] += n_spikes - spont_rate * ( + self.response[1] - self.response[0] + ) + matrix /= self.iterations + + # plot and scale the matrix image + # note that the origin (lower left) of each image pixel indicates its actual test freq/level. + self.tuning_img.setImage(matrix) + self.tuning_img.resetTransform() + self.tuning_img.setPos(np.log10(min(fvals)), min(lvals)) + self.tuning_img.scale( + (np.log10(max(fvals)) - np.log10(min(fvals))) / (len(fvals) - 1), + (max(lvals) - min(lvals)) / (len(lvals) - 1), + ) + + +class NetworkTree(QtGui.QTreeWidget): + def __init__(self, prot): + self.prot = prot + QtGui.QTreeWidget.__init__(self) + self.setColumnCount(2) + + self.update_tree() + + def update_tree(self): + for pop_name in ["bushy", "tstellate", "dstellate", "tuberculoventral", "sgc"]: + if not hasattr(self.prot, pop_name): + continue + pop = getattr(self.prot, pop_name) + grp = QtGui.QTreeWidgetItem([pop_name]) + self.addTopLevelItem(grp) + for cell in pop.real_cells(): + self.add_cell(grp, pop, cell) + + def add_cell(self, grp_item, pop, cell): + item = QtGui.QTreeWidgetItem([str(cell)]) + grp_item.addChild(item) + all_conns = pop.cell_connections(cell) + if all_conns == 0: + return + for cpop, conns in list(all_conns.items()): + pop_grp = QtGui.QTreeWidgetItem([cpop.type, str(conns)]) + item.addChild(pop_grp) + + +class NetworkVisualizer(pg.PlotWidget): + + cell_selected = pg.QtCore.Signal(object, object) + + def __init__(self, populations): + self.pops = populations + pg.PlotWidget.__init__(self) + self.setLogMode(x=True, y=False) + + self.cells = pg.ScatterPlotItem(clickable=True) + self.cells.setZValue(10) + self.addItem(self.cells) + self.cells.sigClicked.connect(self.cells_clicked) + + self.selected = pg.ScatterPlotItem() + self.selected.setZValue(20) + self.addItem(self.selected) + + self.connections = pg.PlotCurveItem() + self.addItem(self.connections) + + # first assign positions of all cells + cells = [] + for y, pop in enumerate(self.pops.values()): + pop.cell_spots = [] + pop.fwd_connections = {} + for i, cell in enumerate(pop._cells): + pos = (np.log10(cell["cf"]), y) + real = cell["cell"] != 0 + if not real: + pop.cell_spots.append(None) + continue + brush = pg.mkBrush("b") if real else pg.mkBrush(255, 255, 255, 30) + spot = { + "x": pos[0], + "y": pos[1], + "symbol": "o" if real else "x", + "brush": brush, + "pen": None, + "data": (pop, i), + } + cells.append(spot) + pop.cell_spots.append(spot) + + self.cells.setData(cells) + + self.getAxis("left").setTicks([list(enumerate(self.pops.keys()))]) + + # now assign connection lines and record forward connectivity + con_x = [] + con_y = [] + for pop in list(self.pops.values()): + for i, cell in enumerate(pop._cells): + conns = cell["connections"] + if conns == 0: + continue + for prepop, precells in list(conns.items()): + spot = pop.cell_spots[i] + if spot is None: + continue + p1 = spot["x"], spot["y"] + for j in precells: + prepop.fwd_connections.setdefault(j, []) + prepop.fwd_connections[j].append((pop, i)) + spot2 = prepop.cell_spots[j] + if spot2 is None: + return + p2 = spot2["x"], spot2["y"] + con_x.extend([p1[0], p2[0]]) + con_y.extend([p1[1], p2[1]]) + self.connections.setData( + x=con_x, y=con_y, connect="pairs", pen=(255, 255, 255, 60) + ) + + def cells_clicked(self, *args): + selected = None + for spot in args[1]: + # find the first real cell + pop, i = spot.data() + if pop._cells[i]["cell"] != 0: + selected = spot + break + if selected is None: + self.selected.hide() + return + + rec = pop._cells[i] + pos = selected.pos() + spots = [ + { + "x": pos.x(), + "y": pos.y(), + "size": 15, + "symbol": "o", + "pen": "y", + "brush": "b", + } + ] + + # display presynaptic cells + if rec["connections"] != 0: + for prepop, preinds in list(rec["connections"].items()): + for preind in preinds: + spot = prepop.cell_spots[preind].copy() + spot["size"] = 15 + spot["brush"] = "r" + spots.append(spot) + + # display postsynaptic cells + for postpop, postind in pop.fwd_connections.get(i, []): + spot = postpop.cell_spots[postind].copy() + spot["size"] = 15 + spot["brush"] = "g" + spots.append(spot) + + self.selected.setData(spots) + self.selected.show() + + self.cell_selected.emit(self, selected.data()) + + +if __name__ == "__main__": + import pickle, os, sys + + app = pg.mkQApp() + pg.dbg() + + # Create a sound stimulus and use it to generate spike trains for the SGC + # population + stims = [] + parallel = True + + nreps = 5 + fmin = 4e3 + fmax = 32e3 + octavespacing = 1 / 8.0 + # octavespacing = 1. + n_frequencies = int(np.log2(fmax / fmin) / octavespacing) + 1 + fvals = ( + np.logspace( + np.log2(fmin / 1000.0), + np.log2(fmax / 1000.0), + num=n_frequencies, + endpoint=True, + base=2, + ) + * 1000.0 + ) + + n_levels = 11 + # n_levels = 3 + levels = np.linspace(20, 100, n_levels) + + print(("Frequencies:", fvals / 1000.0)) + print(("Levels:", levels)) + + syntype = "multisite" + path = os.path.dirname(__file__) + cachepath = os.path.join(path, "cache") + if not os.path.isdir(cachepath): + os.mkdir(cachepath) + + seed = 34657845 + prot = CNSoundStim(seed=seed, synapsetype=syntype) + i = 0 + + start_time = timeit.default_timer() + + # stimpar = {'dur': 0.06, 'pip': 0.025, 'start': [0.02], 'baseline': [10, 20], 'response': [20, 45]} + stimpar = { + "dur": 0.2, + "pip": 0.04, + "start": [0.1], + "baseline": [50, 100], + "response": [100, 140], + } + tasks = [] + for f in fvals: + for db in levels: + for i in range(nreps): + tasks.append((f, db, i)) + + results = {} + workers = 1 if not parallel else None + tot_runs = len(fvals) * len(levels) * nreps + with mp.Parallelize( + enumerate(tasks), + results=results, + progressDialog="Running parallel simulation..", + workers=workers, + ) as tasker: + for i, task in tasker: + f, db, iteration = task + stim = sound.TonePip( + rate=100e3, + duration=stimpar["dur"], + f0=f, + dbspl=db, # dura 0.2, pip_start 0.1 pipdur 0.04 + ramp_duration=2.5e-3, + pip_duration=stimpar["pip"], + pip_start=stimpar["start"], + ) + + print(("=== Start run %d/%d ===" % (i + 1, tot_runs))) + cachefile = os.path.join( + cachepath, + "seed=%d_f0=%f_dbspl=%f_syntype=%s_iter=%d.pk" + % (seed, f, db, syntype, iteration), + ) + if "--ignore-cache" in sys.argv or not os.path.isfile(cachefile): + result = prot.run(stim, seed=i) + pickle.dump(result, open(cachefile, "wb")) + else: + print(" (Loading cached results)") + result = pickle.load(open(cachefile, "rb")) + tasker.results[(f, db, iteration)] = (stim, result) + print(("--- finished run %d/%d ---" % (i + 1, tot_runs))) + + # get time of run before display + elapsed = timeit.default_timer() - start_time + print( + "Elapsed time for %d stimuli: %f (%f sec per stim), synapses: %s" + % (len(tasks), elapsed, elapsed / len(tasks), prot.bushy._synapsetype) + ) + + nd = NetworkSimDisplay( + prot, results, baseline=stimpar["baseline"], response=stimpar["response"] + ) + nd.show() + + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() diff --git a/examples/test_populations.py b/examples/test_populations.py new file mode 100644 index 0000000..6103c82 --- /dev/null +++ b/examples/test_populations.py @@ -0,0 +1,59 @@ +""" +Test connection between two cell populations. + +Usage: python test_populations.py + +This script: + +1. Creates two cell populations (pop1 and pop2) +2. Connects pop1 => pop2 +3. Instantiates a single cell in pop2 +4. Automatically generates presynaptic cells and synapses from pop1 +5. Stimulates presynaptic cells and records postsynaptically + +This is a high-level approach to generating networks in that the supporting +cells (those in pop1) are created automatically based on expected patterns +of connectivity in the cochlear nucleus. A lower-level approach is demonstrated +in test_synapses.py, in which the individual pre- and postsynaptic cells are +manually created and connected. +""" +from cnmodel import populations +from cnmodel.protocols import PopulationTest +import pyqtgraph as pg +import sys + + +def testpopulation(): + if len(sys.argv) < 3: + print("Usage: python test_populations.py ") + sys.exit(1) + + pop_types = { + "sgc": populations.SGC, + "bushy": populations.Bushy, + "tstellate": populations.TStellate, + "dstellate": populations.DStellate, + "pyramidal": populations.Pyramidal, + "tuberculoventral": populations.Tuberculoventral, + } + + pops = [] + for cell_type in sys.argv[1:3]: + if cell_type not in pop_types: + print( + '\nUnsupported cell type: "%s". Options are %s' + % (cell_type, list(pop_types.keys())) + ) + sys.exit(-1) + pops.append(pop_types[cell_type]()) + + pt = PopulationTest() + pt.run(pops) + pt.show() + + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() + + +if __name__ == "__main__": + testpopulation() diff --git a/examples/test_sgc_input.py b/examples/test_sgc_input.py new file mode 100644 index 0000000..5c72e2f --- /dev/null +++ b/examples/test_sgc_input.py @@ -0,0 +1,96 @@ +""" +Test generating a series of EPSPs in a bushy cell in response to tone pip. + +This script: + +1. Creates one SGC and one bushy cell. +2. Connects the two cells with a synapse. +3. Specifies a tone pip input to the SGC cell. +4. Records the bushy cell Vm. + +The auditory nerve spike train is generated automatically by the DummySGC class +using the tone pip. For lower-level access to the auditory nerve model, see the +test_an_model.py and test_sound_stim.py examples. + +The simulator that is run depends on what is available and how the script is called. +python examples/test_sgc_input.py [cochlea | matlab] will try to use the specified +simulator. If no simulator is specified, it will try to use cochlea or matlab, in +that order. + +""" +import sys +import numpy as np +import pyqtgraph as pg +from neuron import h +from cnmodel.protocols import Protocol +from cnmodel import cells +from cnmodel.util import sound +from cnmodel.util import custom_init + + +class SGCInputTest(Protocol): + def run(self, temp=34.0, dt=0.025, seed=575982035, simulator=None): + preCell = cells.DummySGC(cf=4000, sr=2) + postCell = cells.Bushy.create() + synapse = preCell.connect(postCell) + self.pre_cell = preCell + self.post_cell = postCell + self.synapse = synapse + + self.stim = sound.TonePip( + rate=100e3, + duration=0.1, + f0=4000, + dbspl=80, + ramp_duration=2.5e-3, + pip_duration=0.04, + pip_start=[0.02], + ) + + preCell.set_sound_stim(self.stim, seed=seed, simulator=simulator) + + self["vm"] = postCell.soma(0.5)._ref_v + # self['prevm'] = preCell.soma(0.5)._ref_v + for i in range(30): + self["xmtr%d" % i] = synapse.terminal.relsite._ref_XMTR[i] + synapse.terminal.relsite.Dep_Flag = False + self["t"] = h._ref_t + + h.tstop = 100.0 # duration of a run + h.celsius = temp + h.dt = dt + + custom_init() + h.run() + + def show(self): + self.win = pg.GraphicsWindow() + + p1 = self.win.addPlot(title="Bushy Vm") + p1.plot(self["t"], self["vm"]) + p2 = self.win.addPlot(title="xmtr", row=1, col=0) + for i in range(30): + p2.plot(self["t"], self["xmtr%d" % i], pen=(i, 15)) + p2.setXLink(p1) + + p3 = self.win.addPlot(title="AN spikes", row=2, col=0) + vt = pg.VTickGroup(self.pre_cell._spiketrain) + p3.addItem(vt) + p3.setXLink(p1) + + p4 = self.win.addPlot(title="stim", row=3, col=0) + p4.plot(self.stim.time * 1000, self.stim.sound) + p4.setXLink(p1) + self.win.show() + + +if __name__ == "__main__": + simulator = None + if len(sys.argv) > 1: + simulator = sys.argv[1] + prot = SGCInputTest() + prot.run(simulator=simulator) + prot.show() + + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() diff --git a/examples/test_sgc_input_PSTH.py b/examples/test_sgc_input_PSTH.py new file mode 100644 index 0000000..b7173f6 --- /dev/null +++ b/examples/test_sgc_input_PSTH.py @@ -0,0 +1,431 @@ +import sys +import argparse +import numpy as np +import pyqtgraph as pg +from neuron import h +from cnmodel.protocols import Protocol +from cnmodel import cells +from cnmodel.util import sound +from cnmodel.util import custom_init +import cnmodel.util.pynrnutilities as PU +from cnmodel import data + +species = "mouse" # tables for other species do not yet exist + + +def runTrial(cell, info): + """ + info is a dict + """ + if cell == "bushy": + post_cell = cells.Bushy.create(species=species) + elif cell == "tstellate": + post_cell = cells.TStellate.create(species=species) + elif cell == "octopus": + post_cell = cells.Octopus.create(species=species) + elif cell == "dstellate": + post_cell = cells.DStellate.create(species=species) + elif cell == "tuberculoventral": + post_cell = cells.DStellate.create(species=species) + elif cell == "pyramidal": + post_cell = cells.DStellate.create(species=species) + else: + raise ValueError("cell %s is not yet implemented for PSTH testing" % self.cell) + pre_cells = [] + synapses = [] + j = 0 + xmtr = {} + for nsgc, sgc in enumerate(range(info["n_sgc"])): + pre_cells.append(cells.DummySGC(cf=info["cf"], sr=info["sr"])) + if synapseType == "simple": + synapses.append(pre_cells[-1].connect(post_cell, type=synapseType)) + synapses[-1].terminal.netcon.weight[0] = info["gmax"] + elif synapseType == "multisite": + synapses.append( + pre_cells[-1].connect( + post_cell, + post_opts={"AMPAScale": 1.0, "NMDAScale": 1.0}, + type=synapseType, + ) + ) + for i in range(synapses[-1].terminal.n_rzones): + xmtr["xmtr%04d" % j] = h.Vector() + xmtr["xmtr%04d" % j].record(synapses[-1].terminal.relsite._ref_XMTR[i]) + j = j + 1 + synapses[ + -1 + ].terminal.relsite.Dep_Flag = False # no depression in these simulations + pre_cells[-1].set_sound_stim( + info["stim"], seed=info["seed"] + nsgc, simulator=info["simulator"] + ) + Vm = h.Vector() + Vm.record(post_cell.soma(0.5)._ref_v) + rtime = h.Vector() + rtime.record(h._ref_t) + h.tstop = 1e3 * info["run_duration"] # duration of a run + h.celsius = info["temp"] + h.dt = info["dt"] + post_cell.cell_initialize() + info["init"]() + h.t = 0.0 + h.run() + return { + "time": np.array(rtime), + "vm": Vm.to_python(), + "xmtr": xmtr, + "pre_cells": pre_cells, + "post_cell": post_cell, + "synapses": synapses, + } + + +class SGCInputTestPSTH(Protocol): + def set_cell(self, cell="bushy"): + self.cell = cell + + def run( + self, + temp=34.0, + dt=0.025, + seed=575982035, + reps=10, + stimulus="tone", + simulator="cochlea", + parallelize=False, + ): + assert stimulus in ["tone", "SAM", "clicks"] # cases available + assert self.cell in [ + "bushy", + "tstellate", + "octopus", + "dstellate", + "tuberculoventral", + "pyramidal", + ] + self.nrep = reps + self.stimulus = stimulus + self.run_duration = 0.20 # in seconds + self.pip_duration = 0.05 # in seconds + self.pip_start = [0.1] # in seconds + self.Fs = 100e3 # in Hz + self.f0 = 4000.0 # stimulus in Hz + self.cf = 4000.0 # SGCs in Hz + self.fMod = 100.0 # mod freq, Hz + self.dMod = 0.0 # % mod depth, Hz + self.dbspl = 50.0 + self.simulator = simulator + self.sr = 2 # set SR group + if self.stimulus == "SAM": + self.dMod = 100.0 + self.stim = sound.SAMTone( + rate=self.Fs, + duration=self.run_duration, + f0=self.f0, + fmod=self.fMod, + dmod=self.dMod, + dbspl=self.dbspl, + ramp_duration=2.5e-3, + pip_duration=self.pip_duration, + pip_start=self.pip_start, + ) + if self.stimulus == "tone": + self.f0 = 4000.0 + self.cf = 4000.0 + self.stim = sound.TonePip( + rate=self.Fs, + duration=self.run_duration, + f0=self.f0, + dbspl=self.dbspl, + ramp_duration=2.5e-3, + pip_duration=self.pip_duration, + pip_start=self.pip_start, + ) + + if self.stimulus == "clicks": + self.click_rate = 0.020 # msec + self.stim = sound.ClickTrain( + rate=self.Fs, + duration=self.run_duration, + f0=self.f0, + dbspl=self.dbspl, + click_start=0.010, + click_duration=100.0e-6, + click_interval=self.click_rate, + nclicks=int((self.run_duration - 0.01) / self.click_rate), + ramp_duration=2.5e-3, + ) + + n_sgc = data.get( + "convergence", species=species, post_type=self.cell, pre_type="sgc" + )[0] + self.n_sgc = int(np.round(n_sgc)) + # for simple synapses, need this value: + self.AMPA_gmax = ( + data.get( + "sgc_synapse", species=species, post_type=self.cell, field="AMPA_gmax" + )[0] + / 1e3 + ) # convert nS to uS for NEURON + self.vms = [None for n in range(self.nrep)] + self.synapses = [None for n in range(self.nrep)] + self.xmtrs = [None for n in range(self.nrep)] + self.pre_cells = [None for n in range(self.nrep)] + self.time = [None for n in range(self.nrep)] + info = { + "n_sgc": self.n_sgc, + "gmax": self.AMPA_gmax, + "stim": self.stim, + "simulator": self.simulator, + "cf": self.cf, + "sr": self.sr, + "seed": seed, + "run_duration": self.run_duration, + "temp": temp, + "dt": dt, + "init": custom_init, + } + if not parallelize: + for nr in range(self.nrep): + info["seed"] = seed + 3 * self.n_sgc * nr + res = runTrial(self.cell, info) + # res contains: {'time': time, 'vm': Vm, 'xmtr': xmtr, 'pre_cells': pre_cells, 'post_cell': post_cell} + self.pre_cells[nr] = res["pre_cells"] + self.time[nr] = res["time"] + self.xmtr = {k: v.to_python() for k, v in list(res["xmtr"].items())} + self.vms[nr] = res["vm"] + self.synapses[nr] = res["synapses"] + self.xmtrs[nr] = self.xmtr + + if parallelize: + pass + + def show(self): + self.win = pg.GraphicsWindow() + self.win.setBackground("w") + Fs = self.Fs + p1 = self.win.addPlot( + title="Stimulus", row=0, col=0, labels={"bottom": "T (ms)", "left": "V"} + ) + p1.plot(self.stim.time * 1000, self.stim.sound, pen=pg.mkPen("k", width=0.75)) + p1.setXLink(p1) + + p2 = self.win.addPlot( + title="AN spikes", + row=1, + col=0, + labels={"bottom": "T (ms)", "left": "AN spikes (first trial)"}, + ) + for nr in range(self.nrep): + xan = [] + yan = [] + for k in range(len(self.pre_cells[nr])): + r = self.pre_cells[nr][k]._spiketrain + xan.extend(r) + yr = k + np.zeros_like(r) + 0.2 + yan.extend(yr) + c = pg.PlotCurveItem() + xp = np.repeat(np.array(xan), 2) + yp = np.repeat(np.array(yan), 2) + yp[1::2] = yp[::2] + 0.6 + c.setData( + xp.flatten(), + yp.flatten(), + connect="pairs", + pen=pg.mkPen(pg.intColor(nr, self.nrep), hues=self.nrep, width=1.0), + ) + p2.addItem(c) + p2.setXLink(p1) + + p3 = self.win.addPlot( + title="%s Spikes" % self.cell, + row=2, + col=0, + labels={"bottom": "T (ms)", "left": "Trial #"}, + ) + xcn = [] + ycn = [] + xspks = [] + for k in range(self.nrep): + bspk = PU.findspikes(self.time[k], self.vms[k], -35.0) + xcn.extend(bspk) + yr = k + np.zeros_like(bspk) + 0.2 + ycn.extend(yr) + d = pg.PlotCurveItem() + xp = np.repeat(np.array(xcn), 2) + yp = np.repeat(np.array(ycn), 2) + yp[1::2] = yp[::2] + 0.6 + d.setData( + xp.flatten(), yp.flatten(), connect="pairs", pen=pg.mkPen("k", width=1.5) + ) + p3.addItem(d) + p3.setXLink(p1) + + p4 = self.win.addPlot( + title="%s Vm" % self.cell, + row=3, + col=0, + labels={"bottom": "T (ms)", "left": "Vm (mV)"}, + ) + for nr in range(self.nrep): + p4.plot( + self.time[nr], + self.vms[nr], + pen=pg.mkPen(pg.intColor(nr, self.nrep), hues=self.nrep, width=1.0), + ) + p4.setXLink(p1) + + p5 = self.win.addPlot( + title="xmtr", row=0, col=1, labels={"bottom": "T (ms)", "left": "gSyn"} + ) + if synapseType == "multisite": + for nr in [0]: + syn = self.synapses[nr] + j = 0 + for k in range(self.n_sgc): + synapse = syn[k] + for i in range(synapse.terminal.n_rzones): + p5.plot( + self.time[nr], + self.xmtrs[nr]["xmtr%04d" % j], + pen=pg.mkPen( + pg.intColor(nr, self.nrep), hues=self.nrep, width=1.0 + ), + ) + j = j + 1 + p5.setXLink(p1) + + p6 = self.win.addPlot( + title="AN PSTH", + row=1, + col=1, + labels={"bottom": "T (ms)", "left": "Sp/ms/trial"}, + ) + bins = np.arange(0, 200, 1) + (hist, binedges) = np.histogram(xan, bins) + curve6 = p6.plot( + binedges, + hist, + stepMode=True, + fillBrush=(0, 0, 0, 255), + brush=pg.mkBrush("k"), + fillLevel=0, + ) + + p7 = self.win.addPlot( + title="%s PSTH" % self.cell, + row=2, + col=1, + labels={"bottom": "T (ms)", "left": "Sp/ms/trial"}, + ) + bins = np.arange(0, 200, 1) + (hist, binedges) = np.histogram(xcn, bins) + curve7 = p7.plot( + binedges, + hist, + stepMode=True, + fillBrush=(0, 0, 0, 255), + brush=pg.mkBrush("k"), + fillLevel=0, + ) + + # p6 = self.win.addPlot(title='AN phase', row=1, col=1) + # phasewin = [self.pip_start[0] + 0.25*self.pip_duration, self.pip_start[0] + self.pip_duration] + # prespk = self.pre_cells[0]._spiketrain # just sample one... + # spkin = prespk[np.where(prespk > phasewin[0]*1e3)] + # spikesinwin = spkin[np.where(spkin <= phasewin[1]*1e3)] + # print "\nCell type: %s" % self.cell + # print "Stimulus: " + # + # # set freq for VS calculation + # if self.stimulus == 'tone': + # f0 = self.f0 + # print "Tone: f0=%.3f at %3.1f dbSPL, cell CF=%.3f" % (self.f0, self.dbspl, self.cf) + # if self.stimulus == 'SAM': + # f0 = self.fMod + # print ("SAM Tone: f0=%.3f at %3.1f dbSPL, fMod=%3.1f dMod=%5.2f, cell CF=%.3f" % + # (self.f0, self.dbspl, self.fMod, self.dMod, self.cf)) + # if self.stimulus == 'clicks': + # f0 = 1./self.click_rate + # print "Clicks: interval %.3f at %3.1f dbSPL, cell CF=%.3f " % (self.click_rate, self.dbspl, self.cf) + # vs = PU.vector_strength(spikesinwin, f0) + # + # print 'AN Vector Strength: %7.3f, d=%.2f (us) Rayleigh: %7.3f p = %.3e n = %d' % (vs['r'], vs['d']*1e6, vs['R'], vs['p'], vs['n']) + # (hist, binedges) = np.histogram(vs['ph']) + # curve = p6.plot(binedges, hist, stepMode=True, fillBrush=(100, 100, 255, 150), fillLevel=0) + # p6.setXRange(0., 2*np.pi) + # + # p7 = self.win.addPlot(title='%s phase' % self.cell, row=2, col=1) + # spkin = bspk[np.where(bspk > phasewin[0]*1e3)] + # spikesinwin = spkin[np.where(spkin <= phasewin[1]*1e3)] + # vs = PU.vector_strength(spikesinwin, f0) + # print '%s Vector Strength: %7.3f, d=%.2f (us) Rayleigh: %7.3f p = %.3e n = %d' % (self.cell, vs['r'], vs['d']*1e6, vs['R'], vs['p'], vs['n']) + # (hist, binedges) = np.histogram(vs['ph']) + # curve = p7.plot(binedges, hist, stepMode=True, fillBrush=(100, 100, 255, 150), fillLevel=0) + # p7.setXRange(0., 2*np.pi) + # p7.setXLink(p6) + + self.win.show() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Compute AN only PSTH in postsynaptic cell" + ) + parser.add_argument( + type=str, + dest="cell", + default="bushy", + choices=[ + "bushy", + "tstellate", + "dstellate", + "octopus", + "tuberculoventral", + "pyramida", + ], + help="Select target cell", + ) + parser.add_argument( + "-s", + "--stimulus", + type=str, + dest="stimulus", + default="tone", + choices=["tone", "SAM", "clicks"], + help="Select stimulus from ['tone', 'SAM', 'clicks']", + ) + parser.add_argument( + "-t", + "--type", + type=str, + dest="syntype", + default="simple", + choices=["simple", "multisite"], + help="Set synapse type (simple, multisite)", + ) + parser.add_argument( + "-n", + "--nrep", + type=int, + dest="nrep", + default=10, + help="Set number of repetitions", + ) + + args = parser.parse_args() + + cell = args.cell + stimulus = args.stimulus + nrep = args.nrep + synapseType = args.syntype + + print("cell type: ", cell) + prot = SGCInputTestPSTH() + prot.set_cell(cell) + prot.run(stimulus=stimulus, reps=nrep) + prot.show() + + import sys + + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() diff --git a/examples/test_sgc_input_phaselocking.py b/examples/test_sgc_input_phaselocking.py new file mode 100644 index 0000000..2e81dbf --- /dev/null +++ b/examples/test_sgc_input_phaselocking.py @@ -0,0 +1,248 @@ +""" +test_sgc_input_phaselocking.py + +Test phase locking from an input sgc to a target cell type. Runs simulations +with AN input, and plots the results, including PSTH and phase histogram. + +Usage: python test_sgc_input_phaselocking.py celltype stimulus species + where: + celltype is one of [bushy, tstellate, octopus, dstellate] (default: bushy) + stimulus is one of [tone, SAM, clicks] (default: tone) + species is one of [guineapig, mouse] (default: guineapig) + +""" + +import sys +import numpy as np +import pyqtgraph as pg +from neuron import h +from cnmodel.protocols import Protocol +from cnmodel import cells +from cnmodel.util import sound +import cnmodel.util.pynrnutilities as PU +from cnmodel import data + + +class SGCInputTestPL(Protocol): + def set_cell(self, cell="bushy"): + self.cell = cell + + def run( + self, temp=34.0, dt=0.025, seed=575982035, stimulus="tone", species="mouse" + ): + assert stimulus in ["tone", "SAM", "clicks"] # cases available + if self.cell == "bushy": + postCell = cells.Bushy.create(species=species) + elif self.cell == "tstellate": + postCell = cells.TStellate.create(species=species) + elif self.cell == "octopus": + postCell = cells.Octopus.create(species=species) + elif self.cell == "dstellate": + postCell = cells.DStellate.create(species=species) + else: + raise ValueError( + "cell %s is not yet implemented for phaselocking" % self.cell + ) + self.post_cell = postCell + self.stimulus = stimulus + self.run_duration = 1.0 # in seconds + self.pip_duration = 0.8 # in seconds + self.pip_start = [0.02] # in seconds + self.Fs = 100e3 # in Hz + self.f0 = 4000.0 # stimulus in Hz + self.cf = 4000.0 # SGCs in Hz + self.fMod = 100.0 # mod freq, Hz + self.dMod = 50.0 # % mod depth, Hz + self.dbspl = 60.0 + if self.stimulus == "SAM": + self.stim = sound.SAMTone( + rate=self.Fs, + duration=self.run_duration, + f0=self.f0, + fmod=self.fMod, + dmod=self.dMod, + dbspl=self.dbspl, + ramp_duration=2.5e-3, + pip_duration=self.pip_duration, + pip_start=self.pip_start, + ) + if self.stimulus == "tone": + self.f0 = 1000.0 + self.cf = 1000.0 + self.stim = sound.TonePip( + rate=self.Fs, + duration=self.run_duration, + f0=self.f0, + dbspl=self.dbspl, + ramp_duration=2.5e-3, + pip_duration=self.pip_duration, + pip_start=self.pip_start, + ) + + if self.stimulus == "clicks": + self.click_rate = 0.020 # msec + self.stim = sound.ClickTrain( + rate=self.Fs, + duration=self.run_duration, + f0=self.f0, + dbspl=self.dbspl, + click_start=0.010, + click_duration=100.0e-6, + click_interval=self.click_rate, + nclicks=int((self.run_duration - 0.01) / self.click_rate), + ramp_duration=2.5e-3, + ) + + n_sgc = data.get( + "convergence", species=species, post_type=postCell.type, pre_type="sgc" + )[0] + self.n_sgc = int(np.round(n_sgc)) + + self.pre_cells = [] + self.synapses = [] + j = 0 + for k in range(self.n_sgc): + seed = seed + k + preCell = cells.DummySGC(cf=self.cf, sr=2) + synapse = preCell.connect(postCell) + for i in range(synapse.terminal.n_rzones): + self["xmtr%03d" % j] = synapse.terminal.relsite._ref_XMTR[i] + j = j + 1 + synapse.terminal.relsite.Dep_Flag = False + preCell.set_sound_stim(self.stim, seed=seed) + self.pre_cells.append(preCell) + self.synapses.append(synapse) + + self["vm"] = postCell.soma(0.5)._ref_v + # self['prevm'] = preCell.soma(0.5)._ref_v + self["t"] = h._ref_t + postCell.cell_initialize() + h.tstop = 1e3 * self.run_duration # duration of a run + h.celsius = temp + h.dt = dt + + self.custom_init() + h.run() + + def show(self): + self.win = pg.GraphicsWindow() + p1 = self.win.addPlot(title="stim", row=0, col=0) + p1.plot(self.stim.time * 1000, self.stim.sound) + p1.setXLink(p1) + + p2 = self.win.addPlot(title="AN spikes", row=1, col=0) + vt = pg.VTickGroup(self.pre_cells[0]._spiketrain) + p2.addItem(vt) + p2.setXLink(p1) + + p3 = self.win.addPlot(title="%s Spikes" % self.cell, row=2, col=0) + bspk = PU.findspikes(self["t"], self["vm"], -30.0) + bspktick = pg.VTickGroup(bspk) + p3.addItem(bspktick) + p3.setXLink(p1) + + p4 = self.win.addPlot(title="%s Vm" % self.cell, row=3, col=0) + p4.plot(self["t"], self["vm"]) + p4.setXLink(p1) + + p5 = self.win.addPlot(title="xmtr", row=0, col=1) + j = 0 + for k in range(self.n_sgc): + synapse = self.synapses[k] + for i in range(synapse.terminal.n_rzones): + p5.plot(self["t"], self["xmtr%03d" % j], pen=(i, 15)) + j = j + 1 + p5.setXLink(p1) + + p6 = self.win.addPlot(title="AN phase", row=1, col=1) + phasewin = [ + self.pip_start[0] + 0.25 * self.pip_duration, + self.pip_start[0] + self.pip_duration, + ] + prespk = self.pre_cells[0]._spiketrain # just sample one... + spkin = prespk[np.where(prespk > phasewin[0] * 1e3)] + spikesinwin = spkin[np.where(spkin <= phasewin[1] * 1e3)] + print("\nCell type: %s" % self.cell) + print("Stimulus: ") + + # set freq for VS calculation + if self.stimulus == "tone": + f0 = self.f0 + print( + "Tone: f0=%.3f at %3.1f dbSPL, cell CF=%.3f" + % (self.f0, self.dbspl, self.cf) + ) + if self.stimulus == "SAM": + f0 = self.fMod + print( + ( + "SAM Tone: f0=%.3f at %3.1f dbSPL, fMod=%3.1f dMod=%5.2f, cell CF=%.3f" + % (self.f0, self.dbspl, self.fMod, self.dMod, self.cf) + ) + ) + if self.stimulus == "clicks": + f0 = 1.0 / self.click_rate + print( + "Clicks: interval %.3f at %3.1f dbSPL, cell CF=%.3f " + % (self.click_rate, self.dbspl, self.cf) + ) + vs = PU.vector_strength(spikesinwin, f0) + + print( + "AN Vector Strength at %.1f: %7.3f, d=%.2f (us) Rayleigh: %7.3f p = %.3e n = %d" + % (f0, vs["r"], vs["d"] * 1e6, vs["R"], vs["p"], vs["n"]) + ) + (hist, binedges) = np.histogram(vs["ph"]) + p6.plot( + binedges, hist, stepMode=True, fillBrush=(100, 100, 255, 150), fillLevel=0 + ) + p6.setXRange(0.0, 2 * np.pi) + + p7 = self.win.addPlot(title="%s phase" % self.cell, row=2, col=1) + spkin = bspk[np.where(bspk > phasewin[0] * 1e3)] + spikesinwin = spkin[np.where(spkin <= phasewin[1] * 1e3)] + vs = PU.vector_strength(spikesinwin, f0) + print( + "%s Vector Strength: %7.3f, d=%.2f (us) Rayleigh: %7.3f p = %.3e n = %d" + % (self.cell, vs["r"], vs["d"] * 1e6, vs["R"], vs["p"], vs["n"]) + ) + (hist, binedges) = np.histogram(vs["ph"]) + p7.plot( + binedges, hist, stepMode=True, fillBrush=(100, 100, 255, 150), fillLevel=0 + ) + p7.setXRange(0.0, 2 * np.pi) + p7.setXLink(p6) + + self.win.show() + + +if __name__ == "__main__": + if len(sys.argv) > 1 and sys.argv[1] in ["help", "-h", "--help"]: + print( + "\nUsage: python test_sgc_input_phaselocking.py\n celltype [bushy, tstellate, octopus, dstellate] (default: bushy)" + ) + print(" stimulus [tone, SAM, clicks] (default: tone)") + print(" species [guineapig mouse] (default: guineapig)\n") + exit(0) + if len(sys.argv) > 1: + cell = sys.argv[1] + else: + cell = "bushy" + if len(sys.argv) > 2: + stimulus = sys.argv[2] + else: + stimulus = "tone" + if len(sys.argv) > 3: + species = sys.argv[3] + else: + species = "guineapig" + print("cell type: ", cell) + prot = SGCInputTestPL() + prot.set_cell(cell) + prot.run(stimulus=stimulus, species=species) + prot.show() + + import sys + + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() diff --git a/examples/test_simple_synapses.py b/examples/test_simple_synapses.py new file mode 100644 index 0000000..e69d85a --- /dev/null +++ b/examples/test_simple_synapses.py @@ -0,0 +1,97 @@ +""" +test_simple_synapses + +Test synapses between cell types. + +Usage: + python test_synapses.py + Supported cell types: sgc, bushy, tstellate, dstellate, tuberculoventral, pyramidal +""" +import sys +import pyqtgraph as pg +from cnmodel.protocols.simple_synapse_test import SimpleSynapseTest +from cnmodel import cells +from cnmodel.synapses import Synapse + + +def runtest(): + if len(sys.argv) < 3: + print("Usage: python test_synapses.py ") + print( + " Supported cell types: sgc, bushy, tstellate, dstellate, tuberculoventral, pyramidal" + ) + sys.exit(1) + + convergence = { + "sgc": { + "bushy": 1, + "tstellate": 6, + "dstellate": 10, + "dstellate_eager": 10, + "tuberculoventral": 6, + "pyramidal": 5, + }, + "dstellate": { + "bushy": 10, + "tstellate": 15, + "dstellate": 5, + "tuberculoventral": 10, + "pyramidal": 10, + }, + "tuberculoventral": { + "bushy": 6, + "tstellate": 3, + "dstellate": 0, + "tuberculoventral": 2, + "pyramidal": 10, + }, + } + + c = [] + for cellType in sys.argv[1:3]: + if cellType == "sgc": + cell = cells.SGC.create() + elif cellType == "tstellate": + cell = cells.TStellate.create(debug=True, ttx=False) + elif ( + cellType == "dstellate" + ): # Type I-II Rothman model, similiar excitability (Xie/Manis, unpublished) + cell = cells.DStellate.create(model="RM03", debug=True, ttx=False) + elif cellType == "dstellate_eager": # From Eager et al. + cell = cells.DStellate.create(model="Eager", debug=True, ttx=False) + elif cellType == "bushy": + cell = cells.Bushy.create(debug=True, ttx=True) + elif cellType == "tuberculoventral": + cell = cells.Tuberculoventral.create(debug=True, ttx=False) + elif cellType == "pyramidal": + cell = cells.Pyramidal.create(debug=True, ttx=False) + else: + raise ValueError("Unknown cell type '%s'" % cellType) + c.append(cell) + + preCell, postCell = c + + nTerminals = convergence.get(sys.argv[1], {}).get(sys.argv[2], None) + if nTerminals is None: + nTerminals = 1 + print( + "Warning: Unknown convergence for %s => %s, assuming %d" + % (sys.argv[1], sys.argv[2], nTerminals) + ) + + if sys.argv[1:3] == ["sgc", "bushy"]: + niter = 1 + else: + niter = 20 + + st = SimpleSynapseTest() + st.run(preCell.soma, postCell.soma, iterations=niter) + st.show() + return st # keep in memory + + +if __name__ == "__main__": + r = runtest() + print("runtest done") + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() diff --git a/examples/test_sound_stim.py b/examples/test_sound_stim.py new file mode 100644 index 0000000..6cbca0b --- /dev/null +++ b/examples/test_sound_stim.py @@ -0,0 +1,116 @@ +""" +Test using sound stimulation to generate SGC spike trains. + +This script uses an_model.get_spiketrain(), which internally calls MATLAB to +generate spike trains and caches the output. A higher-level approach is to use +DummySGC, which will automatically feed the spike train into a synapse for +input to downstream neurons (see test_sgc_input.py). Lower-level access to the +auditory nerve model is demonstrated in test_an_model.py. + +This script also can measure the time required to generate the spike trains, or +to retrieve them from the cache. In addition, it can access a second interface +to the Zilany et al. mode that is in pure python ("cochlea") for comparison. +In general the speed to compute the spike trains for the same sets of stimuli +is faster with the pure Python interface than with the Matlab interface, and +fastest for retrieval of pre-computed trains. Note that changing the value +of "seed" will force a recomputation of the spike trains. +""" +import numpy as np +import pyqtgraph as pg +from cnmodel import an_model +from cnmodel.util import sound +import cochlea + +import time + +seed = 34986 + + +def time_usage(func): + def wrapper(*args, **kwargs): + beg_ts = time.time() + res = func(*args, **kwargs) + end_ts = time.time() + print(("** Elapsed time: %f" % (end_ts - beg_ts))) + return res + + return wrapper + + +def set_dbspl(signal, dbspl): + """Scale the level of `signal` to the given dB_SPL.""" + p0 = 20e-6 + rms = np.sqrt(np.sum(signal ** 2) / signal.size) + scaled = signal * 10 ** (dbspl / 20.0) * p0 / rms + return scaled + + +@time_usage +def sound_stim(seed, useMatlab=True): + cf = 1.5e3 + levels = list(range(-10, 101, 10)) + + result = {} + if useMatlab: + simulator = "matlab" + else: + simulator = "cochlea" + for sr in 1, 2, 3: + spikes = [] + for level in levels: + stim = sound.TonePip( + rate=100e3, + duration=0.5, + f0=cf, + dbspl=level, + pip_duration=0.5, + pip_start=[0], + ramp_duration=2.5e-3, + ) + if simulator == "cochlea": + stim._sound = set_dbspl(stim.sound, level) # adjust scaling here + spikes.append( + an_model.get_spiketrain( + cf=cf, sr=sr, seed=seed, stim=stim, simulator=simulator + ) + ) + seed += 1 + result[sr] = {"levels": levels, "spikes": spikes} + return result + + +import sys + + +def runtest(): + usematlab = True + if len(sys.argv) > 0: + if len(sys.argv) == 1: + print( + 'Call requires argument, must be either "matlab" or "cochlea"; default is "matlab"' + ) + exit() + flag = sys.argv[1] + if flag not in ["matlab", "cochlea"]: + print('Flag must be either "matlab" or "cochlea"; default is "matlab"') + exit() + if flag == "cochlea": + usematlab = False + if usematlab: + print("Running with matlab simulator") + else: + print("Running with MR cochlea simulator") + + result = sound_stim(seed, useMatlab=usematlab) + + win = pg.GraphicsWindow() + p1 = win.addPlot(title="Rate-level function") + for i, x in enumerate(result.keys()): + p1.plot(result[x]["levels"], [s.size for s in result[x]["spikes"]], pen=(x, 6)) + return win + + +if __name__ == "__main__": + win = runtest() + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() diff --git a/examples/test_sounds.py b/examples/test_sounds.py new file mode 100644 index 0000000..3d18aea --- /dev/null +++ b/examples/test_sounds.py @@ -0,0 +1,70 @@ +""" +Test sounds and plot waveforms. + +This script tests the sound waveform generator for a variety of sounds + +""" +import sys +import numpy as np +import pyqtgraph as pg +from cnmodel.util import sound +from collections import OrderedDict +from scipy import signal + +class test_sounds(): + def __init__(self): + cf = 2e3 + Fs = 100e3 # sample frequency + level = 80. + seed = 34978 + fmod = 10. + dmod = 100. + win = pg.GraphicsWindow() + pipwin = win.addPlot(title='sound pip', row=0, col=0) + pipmodwin = win.addPlot(title='100 % SAM modulated pip', row=1, col=0) + noisewin = win.addPlot(title='WB noise', row=2, col=0) + noisemodwin = win.addPlot(title='100 % SAM Modulated WB Noise', row=3, col=0) + clickwin = win.addPlot(title='clicks', row=4, col=0) + wavewin = win.addPlot(title='wavefile', row=5, col=0) + + pipwins = win.addPlot(title='sound pip Spec', row=0, col=1) + pipmodwins = win.addPlot(title='100 % SAM modulated pip', row=1, col=1) + noisewins = win.addPlot(title='WB noise', row=2, col=1) + noisemodwins = win.addPlot(title='100 % SAM Modulated WB Noise', row=3, col=1) + clickwins = win.addPlot(title='click spec', row=4, col=1) + wavewins = win.addPlot(title='Wavefile spec', row=5, col=1) + + stims = OrderedDict([('pip', (pipwin, sound.TonePip)), ('pipmod', (pipmodwin, sound.SAMTone)), + ('noise', (noisewin, sound.NoisePip)), ('noisemod', (noisemodwin, sound.SAMNoise)), + ('clicks', (clickwin, sound.ClickTrain)), + ('wavefile', (wavewin, sound.ReadWavefile))]) + + specs = OrderedDict([('pip', (pipwins, sound.TonePip)), ('pipmod', (pipmodwins, sound.SAMTone)), + ('noise', (noisewins, sound.NoisePip)), ('noisemod', (noisemodwins, sound.SAMNoise)), + ('clicks', (clickwins, sound.ClickTrain)), + ('wavefile', (wavewins, sound.ReadWavefile))]) + + + for stim in stims: + print(stim) + if stim in ['clicks']: + wave = stims[stim][1](rate=Fs, duration=1.0, dbspl=level, + click_duration=1e-4, click_starts=1e-3*np.linspace(10, 500, 50)) + # wave = stims[stim][1](rate=Fs, dbspl=level, click_interval=10., nclicks=10, + # click_duration=1e-4, click_start=10.) + elif stim in ['wavefile']: + wave = stims[stim][1](wavefile='cnmodel/examples/stim172_geese.wav', rate=Fs, dbspl=level) + wave.sound # force generation here + print('time shape test: ', wave.time.shape) + else: + wave = stims[stim][1](rate=Fs, duration=1.0, f0=cf, dbspl=level, + pip_duration=0.8, pip_start=[10e-3], ramp_duration=2.5e-3, + fmod=fmod, dmod=dmod, seed=seed) + + stims[stim][0].plot(wave.time, wave.sound) + f, Pxx_spec = signal.periodogram(wave.sound, Fs) # window='flattop', nperseg=8192, noverlap=512, scaling='spectrum') + specs[stim][0].plot(f, np.sqrt(Pxx_spec)) + + +if __name__ == '__main__': + test_sounds() diff --git a/examples/test_synapses.py b/examples/test_synapses.py new file mode 100644 index 0000000..fe4f0c2 --- /dev/null +++ b/examples/test_synapses.py @@ -0,0 +1,210 @@ +""" +Test synaptic connections between two different cell types. + +usage: test_synapses.py [-h] [-t {simple,multisite}] [-c] + {sgc,tstellate,dstellate,tuberculoventral} + {bushy,tstellate,dstellate,octopus,tuberculoventral,pyramidal} + +Compute AN only PSTH in postsynaptic cell + +positional arguments: + {sgc,tstellate,dstellate,tuberculoventral} + Select presynaptic cell type + {bushy,tstellate,dstellate,octopus,tuberculoventral,pyramidal} + Select postsynaptic cell type + +optional arguments: + -h, --help show this help message and exit + -t {simple,multisite}, --type {simple,multisite} + Set synapse type (simple, multisite) + -c, --convergence Use convergence = 1 for comparision between simple and + multi, instead of default table + + +This script: + +1. Creates single pre- and postsynaptic cells +2. Creates multiple synaptic terminals between the two cells. + (the convergence is hard-coded below). +3. Stimulates the presynaptic cell by current injection. +4. Records and analyzes the resulting post-synaptic events. + +This is used mainly to check that the strength, kinetics, and dynamics of +each synapse type is working as expected. A higher-level approach is +demonstrated in test_populations.py, in which the presynaptic cells are +automatically generated using expected patterns of connectivity. +""" + +import argparse +import pyqtgraph as pg +from cnmodel.protocols import SynapseTest +from cnmodel import cells +from cnmodel.synapses import Synapse + + +import sys + + +def runtest(): + parser = argparse.ArgumentParser( + description="Compute AN only PSTH in postsynaptic cell" + ) + parser.add_argument( + type=str, + dest="precell", + default="sgc", + choices=["sgc", "tstellate", "dstellate", "tuberculoventral"], + help="Select presynaptic cell type", + ) + parser.add_argument( + type=str, + dest="postcell", + default="bushy", + choices=[ + "bushy", + "tstellate", + "dstellate", + "octopus", + "tuberculoventral", + "pyramidal", + ], + help="Select postsynaptic cell type", + ) + parser.add_argument( + "-t", + "--type", + type=str, + dest="syntype", + default="multisite", + choices=["simple", "multisite"], + help="Set synapse type (simple, multisite)", + ) + parser.add_argument( + "-c", + "--convergence", + action="store_true", + dest="convergence", + help="Use convergence = 1 for comparision between simple and multi, instead of default table", + ) + + args = parser.parse_args() + + precell = args.precell + postcell = args.postcell + synapseType = args.syntype + use_conv_table = args.convergence + + # These must be se3t to 1 to match data in original tables. Otherwise, it would be better + # to use the original tables. + + if not use_conv_table: + convergence = { + "sgc": { + "bushy": 1, + "tstellate": 1, + "dstellate": 1, + "dstellate_eager": 10, + "octopus": 10, + "tuberculoventral": 1, + "pyramidal": 1, + "cartwheel": 0, + }, + "dstellate": {"bushy": 10, "tstellate": 15, "dstellate": 5}, + } + else: + convergence = { + "sgc": { + "bushy": 1, + "tstellate": 1, + "dstellate": 1, + "dstellate_eager": 1, + "octopus": 1, + "tuberculoventral": 1, + "pyramidal": 1, + "cartwheel": 0, + }, + "dstellate": { + "bushy": 1, + "tstellate": 1, + "dstellate": 0, + "tuberculoventral": 1, + "pyramidal": 1, + "cartwheel": 0, + }, + "tuberculoventral": { + "bushy": 1, + "tstellate": 1, + "dstellate": 0, + "tuberculoventral": 1, + "pyramidal": 1, + "cartwheel": 0, + }, + } + + c = [] + for cellType in [precell, postcell]: + if cellType == "sgc": + cell = cells.SGC.create() + elif cellType == "tstellate": + cell = cells.TStellate.create(debug=True, ttx=False) + elif ( + cellType == "dstellate" + ): # Type I-II Rothman model, similiar excitability (Xie/Manis, unpublished) + cell = cells.DStellate.create(model="RM03", debug=True, ttx=False) + elif cellType == "dstellate_eager": # From Eager et al. + cell = cells.DStellate.create(model="Eager", debug=True, ttx=False) + elif cellType == "bushy": + cell = cells.Bushy.create(debug=True, ttx=True) + elif cellType == "tuberculoventral": + cell = cells.Tuberculoventral.create(debug=True, ttx=True) + elif cellType == "pyramidal": + cell = cells.Pyramidal.create(debug=True, ttx=True) + elif cellType == "octopus": + cell = cells.Octopus.create(debug=True, ttx=True) + else: + raise ValueError("Unknown cell type '%s'" % cellType) + c.append(cell) + + preCell, postCell = c + + if not use_conv_table: + nTerminals = convergence.get(precell, {}).get(postcell, None) + else: + nTerminals = 1 + # print("Warning: Unknown convergence for %s => %s, assuming %d" % (precell, postcell, nTerminals)) + + if [precell, postcell] == ["sgc", "bushy"]: + niter = 5 + else: + niter = 20 + # syntype = 'multisite' + # if len(sys.argv) > 3: + # syntype = sys.argv[3] + # assert(syntype in ['simple', 'multisite']) + if synapseType == "simple": + niter = 1 + + st = SynapseTest() + st.run( + preCell.soma, + postCell.soma, + nTerminals, + vclamp=-65.0, + iterations=niter, + synapsetype=synapseType, + ) + st.show_result() + st.plots["VPre"].setYRange(-70.0, 10.0) + st.plots["EPSC"].setYRange(-2.0, 0.5) + st.plots["latency2080"].setYRange(0.0, 1.0) + st.plots["halfwidth"].setYRange(0.0, 1.0) + st.plots["RT"].setYRange(0.0, 0.2) + st.plots["latency"].setYRange(0.0, 1.0) + st.plots["latency_distribution"].setYRange(0.0, 1.0) + return st # need to keep st alive in memory + + +if __name__ == "__main__": + st = runtest() + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() diff --git a/examples/toy_model.py b/examples/toy_model.py new file mode 100755 index 0000000..ffe725d --- /dev/null +++ b/examples/toy_model.py @@ -0,0 +1,312 @@ +#!/usr/bin/python +""" +Basic test of initialization of multiple cells in the model, and running multiple cells at one time. +Plots the resposnes to a series of current injections for most implemented baseic cell types in +in cnmodel. + +Usage: + python examples/toy_model.py (no arguments) + +""" + +from __future__ import print_function + + +import sys +from neuron import h +import numpy as np +import cnmodel.cells as cells +from cnmodel.protocols import Protocol +from cnmodel.util import custom_init +from collections import OrderedDict +import re +import pyqtgraph.exporters +from cnmodel.util import pyqtgraphPlotHelpers as PH +from cnmodel.protocols import IVCurve + + +try: # check for pyqtgraph install + import pyqtgraph as pg +except ImportError: + raise ImportError("This model requires pyqtgraph") + +from cnmodel.util.stim import make_pulse + + +def autorowcol(n): + """ + return a reasonable layout (cols, rows) for n plots on a page + up to 16. + Otherwise return floor(sqrt(n)) + 1 for both r and c. + """ + nmap = { + 1: (1, 1), + 2: (2, 1), + 3: (3, 1), + 4: (2, 2), + 5: (3, 2), + 6: (3, 2), + 7: (3, 3), + 8: (3, 3), + 9: (3, 3), + 10: (3, 4), + 11: (3, 4), + 12: (3, 4), + 13: (4, 4), + 14: (4, 4), + 15: (4, 4), + 16: (4, 4), + } + if n <= 16: + return nmap[n][0], nmap[n][1] + else: + nx = np.floor(np.sqrt(n)) + 1 + return nx, nx + + +def makeLayout(cols=1, rows=1, letters=True, margins=4, spacing=4, nmax=None): + """ + Create a multipanel plot, returning the various pyptgraph elements. + The layout is always a rectangular grid with shape (cols, rows) + if letters is true, then the plot is labeled "A, B, C..." + margins sets the margins around the outside of the plot + spacing sets the spacing between the elements of the grid + """ + import string + + letters = string.ascii_uppercase + widget = pg.QtGui.QWidget() + gridLayout = pg.QtGui.QGridLayout() + widget.setLayout(gridLayout) + gridLayout.setContentsMargins(margins, margins, margins, margins) + gridLayout.setSpacing(spacing) + plots = [[0 for x in range(cols)] for x in range(rows)] + i = 0 + for c in range(cols): + for r in range(rows): + plots[r][c] = pg.PlotWidget() + gridLayout.addWidget(plots[r][c], r, c) + # labelUp(plots[r][c], 'T(s)', 'Y', title = letters[i]) + i += 1 + if i > 25: + i = 0 + if nmax is not None and i >= nmax: + break # that's all - leave out empty plots + + return (plots, widget, gridLayout) + + +def getnextrowcol(plx, row, col, cols): + col += 1 + if col >= cols: + col = 0 + row += 1 + return (plx[row][col], row, col) + + +class Toy(Protocol): + """ + Calls to encapsulate the model runs + Run a set of cells with defined parameters to show excitability patterns. + Note that cells from Rothman and Manis are run at 22C; others at various + temperatures depending on how they were initially measured and defined. + + """ + + def __init__(self): + super(Toy, self).__init__() + + def current_name(self, name, n): + """ + From the name of the current model, get the current injection information + + Parameters + --------- + name : str (no default) + name of the cell type + n : int (no default) + """ + if len(self.celltypes[name][3]) > 2: + injs = self.celltypes[name][3] + injarr = np.linspace(injs[0], injs[1], injs[2], endpoint=True) + return "%.3f" % injarr[n] + else: + return "%.3f" % self.celltypes[name][3][n] + + def getname(self, cell, ninj): + name = self.make_name(cell) + iname = self.current_name(name, ninj) + nname = name + " " + iname + return name, nname + + def make_name(self, cell): + return cell + ", " + self.celltypes[cell][1] + ":" + + def run(self): + sre = re.compile( + "(?P\w+)(?:[, ]*)(?P[\w-]*)(?:[, ]*)(?P[\w-]*)" + ) # regex for keys in cell types + self.celltypes = OrderedDict( + [ + ("Bushy, II", (cells.Bushy, "II", "guineapig", (-0.5, 0.5, 11), 22)), + ( + "Bushy, II-I", + (cells.Bushy, "II-I", "guineapig", (-0.5, 0.5, 11), 22), + ), + ( + "DStellate, I-II", + (cells.DStellate, "I-II", "guineapig", (-0.3, 0.3, 9), 22), + ), + ( + "TStellate, I-c", + (cells.TStellate, "I-c", "guineapig", (-0.15, 0.15, 9), 22), + ), + ( + "TStellate, I-t", + (cells.TStellate, "I-t", "guineapig", (-0.15, 0.15, 9), 22), + ), + ( + "Octopus, II-o", + (cells.Octopus, "II-o", "guineapig", (-2.5, 2.5, 11), 22), + ), + ("Bushy, II, Mouse", (cells.Bushy, "II", "mouse", (-1, 1.2, 13), 34)), + ( + "TStellate, I-c, Mouse", + (cells.TStellate, "I-c", "mouse", (-1, 1, 9), 34), + ), + ( + "DStellate, I-II, Mouse", + (cells.DStellate, "I-II", "mouse", (-0.5, 0.5, 9), 34), + ), + ( + "Pyramidal, I, Rat", + (cells.Pyramidal, "I", "rat", (-0.3, 0.4, 11), 34), + ), + ( + "Cartwheel, I, Mouse", + (cells.Cartwheel, "I", "mouse", (-0.5, 0.5, 9), 34), + ), + ( + "Tuberculoventral, I, Mouse", + (cells.Tuberculoventral, "I", "mouse", (-0.35, 1, 11), 34), + ), + ("SGC, bm, Mouse", (cells.SGC, "bm", "mouse", (-0.2, 0.6, 9), 34)), + ("SGC, a, Mouse", (cells.SGC, "a", "mouse", (-0.2, 0.6, 9), 34)), + ] + ) + + dt = 0.025 + h.dt = dt + h.celsius = 22 + + stim = {"NP": 1, "delay": 10, "dur": 100, "amp": 0.0, "dt": h.dt} + tend = stim["delay"] + stim["dur"] + 20.0 + + netcells = {} + for c in list(self.celltypes.keys()): + g = sre.match(c) + cellname = g.group("cell") + modelType = g.group("type") + species = self.celltypes[c][2] + if g.group("type") == "": + netcells[c] = self.celltypes[c][0].create() + else: + netcells[c] = self.celltypes[c][0].create( + modelType=modelType, species=species, debug=False + ) + # dicts to hold data + pl = OrderedDict([]) + pl2 = OrderedDict([]) + rvec = OrderedDict([]) + vec = OrderedDict([]) + istim = OrderedDict([]) + ncells = len(list(self.celltypes.keys())) + # + # build plotting area + # + app = pg.mkQApp() + self.win = pg.GraphicsWindow() + self.win.setBackground("w") + self.win.resize(800, 600) + cols, rows = autorowcol(ncells) + + row = 0 + col = 0 + labelStyle = {"color": "#000", "font-size": "9pt", "weight": "normal"} + tickStyle = pg.QtGui.QFont("Arial", 9, pg.QtGui.QFont.Light) + self.iv = IVCurve() # use standard IVCurve here... + for n, name in enumerate(self.celltypes.keys()): + nrn_cell = netcells[ + name + ] # get the Neuron object we are using for this cell class + injcmds = list(self.celltypes[name][3]) # list of injections + injcmds[2] = (injcmds[1] - injcmds[0]) / ( + float(injcmds[2] - 1) + ) # convert to pulse format for IVCurve + temperature = self.celltypes[name][4] + nrn_cell.set_temperature(float(temperature)) + ninjs = len(injcmds) + print("cell: ", name) + # print( 'injs: ', injcmds) + pl[name] = self.win.addPlot( + labels={"left": "V (mV)", "bottom": "Time (ms)"} + ) + PH.nice_plot(pl[name]) + pl[name].setTitle(title=name, font=pg.QtGui.QFont("Arial", 10)) + col += 1 + if col >= cols: + col = 0 + self.win.nextRow() + row += 1 + self.iv.reset() + self.iv.run( + {"pulse": [injcmds]}, + nrn_cell, + durs=(stim["delay"], stim["dur"], 20.0), + sites=None, + reppulse=None, + temp=float(temperature), + ) + for k in range(len(self.iv.voltage_traces)): + pl[name].plot( + self.iv.time_values, + self.iv.voltage_traces[k], + pen=pg.mkPen("k", width=0.75), + ) + pl[name].setRange(xRange=(0.0, 130.0), yRange=(-160.0, 40.0)) + PH.noaxes(pl[name]) + PH.calbar( + pl[list(self.celltypes.keys())[0]], + calbar=[0, -120.0, 10.0, 20.0], + unitNames={"x": "ms", "y": "mV"}, + ) + + text = u"{0:2d}\u00b0C {1:.2f}-{2:.2f} nA".format( + int(temperature), + np.min(self.iv.current_cmd), + np.max(self.iv.current_cmd), + ) + ti = pg.TextItem(text, anchor=(1, 0)) + ti.setFont(pg.QtGui.QFont("Arial", 9)) + ti.setPos(120.0, -120.0) + pl[name].addItem(ti) + # get overall Rin, etc; need to initialize all cells + nrn_cell.cell_initialize() + for n, name in enumerate(self.celltypes.keys()): + nrn_cell = netcells[name] + nrn_cell.vm0 = nrn_cell.soma.v + pars = nrn_cell.compute_rmrintau(auto_initialize=False) + print( + "{0:>14s} [{1:>24s}] *** Rin = {2:6.1f} M\ohm Tau = {3:6.1f} ms Vm = {4:6.1f} mV".format( + nrn_cell.status["name"], name, pars["Rin"], pars["tau"], pars["v"] + ) + ) + + +if __name__ == "__main__": + t = Toy() + t.run() + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() + # exporter = pg.exporters.ImageExporter(t.win.scene()) + # exporter.export('~/Desktop/Model_Figure2.svg') diff --git a/modified_dend/hoc_trial_run_dendrites.py b/modified_dend/hoc_trial_run_dendrites.py new file mode 100644 index 0000000..5345ea1 --- /dev/null +++ b/modified_dend/hoc_trial_run_dendrites.py @@ -0,0 +1,178 @@ +from multiprocessing import Pool +from random import randint +from cnmodel import cells +from neuron import h, gui +from tqdm import tqdm +# from pprint import pprint + + +def run(run_input, processes): + results = [] + if processes == 1: + for input in run_input: + results.append(_run_trial(input)) + else: + p = Pool(processes) + for res in tqdm(p.imap_unordered(_run_trial, run_input)): + results.append(res) + return results + + +def add_pyramidal_cell(): + pyramidal = cells.Pyramidal.create(species="rat") + + return pyramidal + +def add_pyram_dend(pyramidal): + pyramidal.add_dendrites() + apical_dend = pyramidal.maindend[0] + basal_dend = pyramidal.maindend[1] + apical_dend.L = 1 + basal_dend.L = 179 + return apical_dend,basal_dend + + +def add_tuberculoventral_cell(): + tuberculoventral_1 = cells.Tuberculoventral.create() + tuberculoventral_2 = cells.Tuberculoventral.create() + return tuberculoventral_1, tuberculoventral_2 + + +def add_dstellate_cell(): + dstellate = cells.DStellateEager.create() + return dstellate + +def add_dstel_dend(dstellate): + dstellate.add_dendrites() + d_apic_dend = dstellate.maindend[0] + d_basal_dend = dstellate.maindend[1] + + return d_apic_dend,d_basal_dend + +def add_dstel_axon(dstellate): + dstellate.add_axon() + d_axon = dstellate.axon + # d_axon.L = 2 + + return d_axon + + +def _run_trial(run_input): + seed, info, run_number = run_input + """ + info is a dict + """ + pyramidal = add_pyramidal_cell() + tuberculoventral_1, tuberculoventral_2 = add_tuberculoventral_cell() + dstellate = add_dstellate_cell() + + d_apic_dend,d_basal_dend = add_dstel_dend(dstellate) + pyram_apical,pyram_basal = add_pyram_dend(pyramidal) + + d_axon = add_dstel_axon(dstellate) + + + auditory_nerve_cells = [] + synapses = [] + inhib_synapses = [] + # auditory nerve attachments + # attach to pyramidal cell + for nsgc in range(48): + auditory_nerve_cells.append(cells.DummySGC(cf=info["cf"], sr=info["sr"])) + synapses.append(auditory_nerve_cells[-1].connect(pyramidal, post_opts={"postsite":[pyram_basal, 1]}, type="multisite")) + auditory_nerve_cells[-1].set_sound_stim( + info["stim"], + seed=seed + nsgc + randint(0, 80000), + simulator=info["simulator"], + ) + attach to tuberculoventral 1 + for nsgc in range(18): + # attach to tb cell + auditory_nerve_cells.append(cells.DummySGC(cf=info["cf"], sr=info["sr"])) + synapses.append(auditory_nerve_cells[-1].connect(tuberculoventral_1, type="multisite")) + auditory_nerve_cells[-1].set_sound_stim( + info["stim"], + seed=seed + nsgc + randint(0, 80000), + simulator=info["simulator"], + ) + # attach to tuberculoventral 2 + for nsgc in range(18): + # attach to tb cell + auditory_nerve_cells.append(cells.DummySGC(cf=info["cf"], sr=info["sr"])) + synapses.append(auditory_nerve_cells[-1].connect(tuberculoventral_2, type="multisite")) + auditory_nerve_cells[-1].set_sound_stim( + info["stim"], + seed=seed + nsgc + randint(0, 80000), + simulator=info["simulator"], + ) + for nsgc in range(24): + # attach to dstellate cell + auditory_nerve_cells.append(cells.DummySGC(cf=info["cf"], sr=info["sr"])) + synapses.append(auditory_nerve_cells[-1].connect(dstellate, post_opts={"postsite":[d_apic_dend, 1]}, type="multisite")) + auditory_nerve_cells[-1].set_sound_stim( + info["stim"], + seed=seed + nsgc + randint(0, 80000), + simulator=info["simulator"], + ) + Connections between network cells + for _ in range(5): + inhib_synapses.append(cartwheel.connect(pyramidal, type="simple")) + for _ in range(21): + inhib_synapses.append(tuberculoventral_1.connect(pyramidal, post_opts={"postsite":[pyram_basal, 1]}, type="multisite")) + inhib_synapses.append(tuberculoventral_2.connect(pyramidal, post_opts={"postsite":[pyram_basal, 1]}, type="multisite")) + for _ in range(15): + inhib_synapses.append(dstellate.connect(pyramidal, post_opts={"postsite":[pyram_basal, 1], "presite":[d_axon, 1]}, type="multisite")) + inhib_synapses.append(dstellate.connect(tuberculoventral_1, type='simple')) + inhib_synapses.append(dstellate.connect(tuberculoventral_2, type='simple')) + for _ in range(3): + inhib_synapses.append(dstellate.connect(dstellate, post_opts={"postsite":[d_basal_dend, 1], "presite":[d_axon, 1]}, type="simple")) + stim = insert_current_clamp(pyramidal.soma) + + # set up our recording vectors for each cell + Vm = h.Vector() + Vm.record(pyramidal.soma(0.5)._ref_v) + Vmtb = h.Vector() + Vmtb.record(tuberculoventral_1.soma(0.5)._ref_v) + Vmds = h.Vector() + Vmds.record(dstellate.soma(0.5)._ref_v) + rtime = h.Vector() + rtime.record(h._ref_t) + # hoc trial run + h.tstop = 1e3 * info["run_duration"] # duration of a run + h.celsius = info["temp"] + h.dt = info["dt"] + init_cells([pyramidal, tuberculoventral_1, tuberculoventral_2, dstellate]) + info["init"]() + h.t = 0.0 + # h.run() + + # dtime = time.time() - start + # print(f"Trial {run_number} completed after {dtime} secs") + + return { + "time": list(rtime), + "vm": list(Vm), + "auditory_nerve_cells": [x._spiketrain.tolist() for x in auditory_nerve_cells], + "vmtb": list(Vmtb), + "vmds": list(Vmds), + } + + +def insert_current_clamp(sec): + """ + :param sec: to attach too + dur: ms + amp: nA + delay: ms + :return: stim needs to be put in a variable to stay alive + """ + stim = h.IClamp(0.5, sec=sec) + stim.dur = 30 + stim.amp = -0.2 + stim.delay = 120 + return stim + + +def init_cells(cell: list): + for x in cell: + x.cell_initialize() diff --git a/modified_dend/network_pauser_prototype_dendrites.py b/modified_dend/network_pauser_prototype_dendrites.py new file mode 100644 index 0000000..09b5a6b --- /dev/null +++ b/modified_dend/network_pauser_prototype_dendrites.py @@ -0,0 +1,298 @@ +""" +Layout: + + if __name__==__main__ handles cmd args, instantiates test, runs it, displays results + + run_trial(): defines a model and then runs the test using preset params in hoc and return the info to the class + SGCInputTest: + __init__ : defines many static variables + run(): calls delivers information to the run_trial() function and the recieved information of a single run + back and stores it as an extensible list in the class + show(): displays graphs depending on the graph options selected below it and displayed in a printout + +""" +import os +import argparse +import time +import json +import sys +from random import randint +from cnmodel.protocols import Protocol +from cnmodel.util import sound +from cnmodel.util import custom_init +from graphs import * +from hoc_trial_run_dendrites import run + + +class NetworkSimulation(Protocol): + """ + Tests a Single cell with input recieved from the SGC + + __init__: almost all parameters can be modified + run(): simply loops over the run_trial() function and stores the results just + show(): constructs the graphs using other functions + + """ + + def __init__( + self, + temp=34.0, + seed=randint(2500, 400000), + nrep=10, + stimulus="tone", + simulator="cochlea", + debug=True, + dt=0.025 + ): + """ + :param temp: (float) must be at 34 for default pyramidal cells + :param dt: (float) determine hoc resolution + :param seed: (int) contributes to randomization, needs to be changed to see different results (reduce this + number if you keep getting a timeout error + :param nrep: (int) number of presentations !!must be changed in the __name__ function if not calling from cmd line!! + :param stimulus: (str) must be 'tone' + :param simulator: (str) currently using cochlea instead of matlab + :param n_sgc:(int) This is the number of SGC fibers that connect to the post synaptic cell + :param debug: (bool) controls most of the terminal printouts is on by default + :param cell: (str) cell type !!must be changed in the __name__ function if not calling from cmd line!! + """ + super().__init__() + # + self.debug = debug + self.nrep = nrep + self.stimulus = stimulus + self.run_duration = 0.3 # in seconds + # stim parameters + self.pip_duration = 0.05 # in seconds + self.pip_start = [0.14] # in seconds + self.Fs = 100e3 # in Hz + self.f0 = 14013.0 # stimulus in Hz + self.cf = 14013.0 # SGCs in Hz + self.fMod = 100.0 # mod freq, Hz + self.dMod = 0.0 # % mod depth, Hz + self.dbspl = 55.0 + # usually cochlea + self.simulator = simulator + self.sr = 2 # set SR group + self.seed = seed + # physiological parameters + self.temp = temp + self.dt = dt + self.synapse_type = "multisite" + self.species = "rat" + + if self.stimulus == "tone": + self.stim = sound.TonePip( + rate=self.Fs, + duration=self.run_duration, + f0=self.f0, + dbspl=self.dbspl, + ramp_duration=5e-3, + pip_duration=self.pip_duration, + pip_start=self.pip_start, + ) + # result containers + self.vms = [] + self.vmtbs = [] + self.vmdss = [] + self.vmcar = [] + self.synapses = [] + self.auditory_nerve_cells = [] + self.time = [] + # debug function reports a print out of various information about the run + if self.debug: + print("Small Network Test Created") + print("#" * 70) + print(f"Running Test of Network with Simulated SGC fibers") + print() + print(f"Run Conditions: Run Time: {self.run_duration}s,") + print(f" Run Temp: {self.temp} ") + print(f" Number of Presentations: {nrep}") + print() + print(f"Stimulus Conditions: Type: {stimulus}") + print(f" Stim Duration: {self.pip_duration}s") + print(f" Characteristic F: {self.cf}hz") + print(f" Stim Start:{str(self.pip_start)}s") + + def run(self, processes=1, **kwargs): + """ + Runs the trials with the number of nreps set for the trial, calls a multiprocess run of however many trials + are needed. + If processes set to one then the it will run without the multiprocessing library(more reliable) + """ + super().run() + info = { + "stim": self.stim, + "simulator": self.simulator, + "cf": self.cf, + "sr": self.sr, + "run_duration": self.run_duration, + "synapse_type": self.synapse_type, + "temp": self.temp, + "dt": self.dt, + "init": custom_init, + } + # Generate inputs + b = [(self.seed + randint(0, 80000)) for _ in range(self.nrep)] + c = [info for _ in range(self.nrep)] + d = range(1, self.nrep+1) + + run_input = zip(b, c, d) + self.all_results = run(run_input, processes=processes) + self.unpack_data(self.all_results) + + def unpack_data(self, run_data): + len_of_data = 0 + for nr, res in enumerate(run_data): + try: + len_of_data += 1 + # res contains: {'time': time, 'vm': list(Vm), 'auditory_nerve_cells': auditory_nerve_cells._spiketrain,'vmtb': list(Vmtb)} + self.auditory_nerve_cells.append(res["auditory_nerve_cells"]) + self.time.append(res["time"]) + self.vms.append(res["vm"]) + self.vmtbs.append(res["vmtb"]) + self.vmdss.append(res["vmds"]) + self.vmcar.append(res["vmcar"]) + except(KeyError): + continue + self.nrep = len_of_data + + def show(self): + """ + Creates a single page graph that contains all of the graphs based on the graphical functions in the class + """ + self.win = pg.GraphicsWindow() + self.win.setBackground("w") + p2 = an_spike_graph(self.win, self.auditory_nerve_cells, 0, 0) + p3 = spike_graph(self.win, self.time, self.vms, 1, 0, title="Pyramidal") + p5 = spike_graph( + self.win, self.time, self.vmtbs, 2, 0, title="Tuberculoventral" + ) + p6 = spike_graph(self.win, self.time, self.vmdss, 3, 0, title="D-Stellate") + p1 = stimulus_graph(self.win, self.stim, 0, 1) + p4 = voltage_graph(self.win, self.time, self.vms, 1, 1) + p7 = an_psth_graph( + self.win, self.auditory_nerve_cells, 2, 1 + ) + p8 = cell_psth_graph( + self.win, self.time, self.vms, 3, 1, title="Pyramidal" + ) + + # links x axis + p1.setXLink(p1) + p2.setXLink(p1) + p3.setXLink(p1) + p4.setXLink(p1) + p5.setXLink(p1) + p6.setXLink(p1) + p7.setXLink(p1) + p8.setXLink(p1) + + self.win.show() + if self.debug: + print("finished") + + def export(self): + if self.debug: + print("Exporting File Binary") + t = time.gmtime() + destination_name = f"{os.path.basename(__file__).strip('.py')}_{t.tm_mday}-{t.tm_mon}-{t.tm_year}_{t.tm_hour}_{t.tm_min}.json" + os.scandir() + dirname = os.path.join(os.path.dirname(__file__), "run_data") + if not os.path.isdir(dirname): + os.mkdir(dirname) + filepath = os.path.join(dirname, destination_name) + with open(filepath, "w") as f: + json.dump(self.all_results, f) + if self.debug: + print(f"Run saved to {filepath}") + + def load(self, load_file=None): + with open(load_file, "r") as file_in: + data_list = json.load(file_in) + self.unpack_data(data_list) + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Compute Neuron response for small network of DCN" + ) + # parser.add_argument(type=str, dest='cell', default='pyramidal', + # choices=['bushy', 'tstellate', 'dstellate', 'octopus', + # 'tuberculoventral', 'pyramidal'], + # help='Select target cell') + parser.add_argument( + "-n", + "--nrep", + type=int, + dest="nrep", + default=4, + help="Set number of repetitions", + ) + parser.add_argument( + "-l", + "--load", + type=str, + dest="load_file", + default=None, + help="Load data from a previous run pickle", + ) + parser.add_argument( + "-s", + "--save", + type=str, + dest="save_flag", + default=True, + help="If you do not want to export file set flag to False", + ) + parser.add_argument( + "-d", + "--debug", + type=str, + dest="debug_flag", + default=True, + help="If you do not want to see debug text or GUI set to False", + ) + parser.add_argument( + "-p", + "--process", + type=int, + dest="processes", + default=1, + help="Set the number of processes that the run will be run across", + ) + args = parser.parse_args() + start = time.time() + nrep = args.nrep + processes = args.processes + load_file = args.load_file + + # manages how options affect the class that is created to manage the trial run + if args.save_flag == "False": + save = False + else: + save = True + if args.debug_flag == "False": + debug_flag = False + else: + debug_flag = True + + if not load_file: + test = NetworkSimulation(nrep=nrep, debug=debug_flag) + test.run(processes=processes) + if debug_flag: + test.show() + if save: + test.export() + else: + if os.path.exists(load_file): + test = NetworkSimulation(nrep=nrep, debug=False) + test.load(load_file) + test.show() + else: + raise FileNotFoundError(f"{load_file} does not exist") + dtime = time.time() - start + print("#" * 70) + print(f"Total Elapsed Time {dtime/60} mins") + + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() diff --git a/project/Figures/3 presentation pyramidal cell.png b/project/Figures/3 presentation pyramidal cell.png new file mode 100644 index 0000000..b7d5e52 Binary files /dev/null and b/project/Figures/3 presentation pyramidal cell.png differ diff --git a/project/Figures/Final graph.png b/project/Figures/Final graph.png new file mode 100644 index 0000000..e9b4dc1 Binary files /dev/null and b/project/Figures/Final graph.png differ diff --git a/project/Figures/Network with TV DS 200 presentations.png b/project/Figures/Network with TV DS 200 presentations.png new file mode 100644 index 0000000..1de0042 Binary files /dev/null and b/project/Figures/Network with TV DS 200 presentations.png differ diff --git a/project/Figures/Network with TV DS and Clamp 200 presentations 4-1.png b/project/Figures/Network with TV DS and Clamp 200 presentations 4-1.png new file mode 100644 index 0000000..971f07f Binary files /dev/null and b/project/Figures/Network with TV DS and Clamp 200 presentations 4-1.png differ diff --git a/project/Figures/examples.png b/project/Figures/examples.png new file mode 100644 index 0000000..2be7f5b Binary files /dev/null and b/project/Figures/examples.png differ diff --git a/project/Figures/examples2.png b/project/Figures/examples2.png new file mode 100644 index 0000000..bd6d0f0 Binary files /dev/null and b/project/Figures/examples2.png differ diff --git a/project/Figures/pyram synapse 500 presentations test_sgc_psth.png b/project/Figures/pyram synapse 500 presentations test_sgc_psth.png new file mode 100644 index 0000000..bd49b2d Binary files /dev/null and b/project/Figures/pyram synapse 500 presentations test_sgc_psth.png differ diff --git a/project/Figures/test 1 pres.png b/project/Figures/test 1 pres.png new file mode 100644 index 0000000..bbf7621 Binary files /dev/null and b/project/Figures/test 1 pres.png differ diff --git a/project/__init__.py b/project/__init__.py new file mode 100644 index 0000000..2237cc8 --- /dev/null +++ b/project/__init__.py @@ -0,0 +1 @@ +from network_pauser_prototype import NetworkSimulation \ No newline at end of file diff --git a/project/graphs.py b/project/graphs.py new file mode 100644 index 0000000..2118af9 --- /dev/null +++ b/project/graphs.py @@ -0,0 +1,167 @@ +""" +These are the graphs that can be used to present certain graphs through the pyqtgraph window +""" + +import pyqtgraph as pg +import numpy as np +import cnmodel.util.pynrnutilities as PU + + +def stimulus_graph(win, stim, row, col): + """ + Presents a graph of + win: pg.GraphicsWindow() + stim:(list) dummy sgc stim results + """ + p1 = win.addPlot( + title="Stimulus", row=row, col=col, labels={"bottom": "T (ms)", "left": "V"} + ) + data = zip(stim.time, stim.sound) + time = [] + stim = [] + for x, y in data: + if 0.1 < x < 0.25: + time.append(x * 1000) + stim.append(y) + p1.plot(time, stim, pen=pg.mkPen("k", width=0.75)) + return p1 + + +def an_spike_graph(win, pre_cells, row, col): + """ + Displays the spikes over time as lines with each cell representing a single row a single trial presentation + :param win: pg.GraphicsWindow() + :param pre_cells: (list) spike train time values + :return: exists to allow for further modifications on the pg.GraphicsWindow object + """ + p2 = win.addPlot( + title="AN spikes", + row=row, + col=col, + labels={"bottom": "T (ms)", "left": "AN spikes (first trial)"}, + ) + xan = [] + yan = [] + for k in range(len(pre_cells[0])): + r = pre_cells[0][k] + xan.extend(r) + yr = k + np.zeros_like(r) + 0.2 + yan.extend(yr) + c = pg.PlotCurveItem() + xp = np.repeat(np.array(xan), 2) + yp = np.repeat(np.array(yan), 2) + yp[1::2] = yp[::2] + 0.6 + c.setData( + xp.flatten(), + yp.flatten(), + connect="pairs", + width=1.0, + pen=pg.mkPen("k", width=1.5), + ) + p2.addItem(c) + return p2 + + +def spike_graph(win, time, vms, row, col, title="cell"): + """ + Displays the spikes over time as lines with each cell representing a single row a single trial presentation + :param win: pg.GraphicsWindow() + :param time: (list) of time that lines up with Vms + :param vms: voltage trace data as a list + :return: exists to allow for further modifications on the pg.GraphicsWindow object + """ + p3 = win.addPlot( + title=f"{title} Spikes", + row=row, + col=col, + labels={"bottom": "T (ms)", "left": "Trial #"}, + ) + xcn = [] + ycn = [] + for k in range(len(time)): + bspk = PU.findspikes(time[k], vms[k], -35.0) + xcn.extend(bspk) + yr = k + np.zeros_like(bspk) + 0.2 + ycn.extend(yr) + d = pg.PlotCurveItem() + xp = np.repeat(np.array(xcn), 2) + yp = np.repeat(np.array(ycn), 2) + yp[1::2] = yp[::2] + 0.6 + d.setData(xp.flatten(), yp.flatten(), connect="pairs", pen=pg.mkPen("k", width=1.5)) + p3.addItem(d) + + return p3 + + +def voltage_graph(win, time, vms, row, col): + """ + Actually displays the voltage trace + :param win: pg.GraphicsWindow() + :param time: (list) of time that lines up with Vms + :param vms: voltage trace data as a list + :return: exists to allow for further modifications on the pg.GraphicsWindow object + """ + p4 = win.addPlot( + title="Pyramidal Vm", + row=row, + col=col, + labels={"bottom": "T (ms)", "left": "Vm (mV)"}, + ) + nrep = len(time) + if nrep > 3: + display = 3 + else: + display = nrep + for nr in range(display): + p4.plot( + time[nr], vms[nr], pen=pg.mkPen(pg.intColor(nr, nrep), hues=nrep, width=1.0) + ) + return p4 + + +def an_psth_graph(win, pre_cells, row, col): + p6 = win.addPlot( + title="AN PSTH", + row=row, + col=col, + labels={"bottom": "T (ms)", "left": "Sp/ms/trial"}, + ) + bins = np.arange(100, 250, 1) + all_xan = [] + for x in range(len(pre_cells)): + for y in range(len(pre_cells[x])): + all_xan.extend(pre_cells[x][y]) + (hist, binedges) = np.histogram(all_xan, bins) + curve6 = p6.plot( + binedges, + hist, + stepMode=True, + fillBrush=(0, 0, 0, 255), + brush=pg.mkBrush("k"), + fillLevel=0, + ) + return p6 + + +def cell_psth_graph(win, time, vms, row, col, title="cell"): + p7 = win.addPlot( + title=f"{title} PSTH", + row=row, + col=col, + labels={"bottom": "T (ms)", "left": "Sp/ms/trial"}, + ) + spike_times = [] + for k in range(len(time)): + bspk = PU.findspikes(time[k], vms[k], -35.0) + spike_times.extend(bspk) + bins = np.arange(100, 250, 0.1) + (hist, binedges) = np.histogram(spike_times, bins) + curve7 = p7.plot( + binedges, + hist, + stepMode=True, + fillBrush=(0, 0, 0, 255), + brush=pg.mkBrush("k"), + fillLevel=0, + ) + return p7 diff --git a/project/hoc_trial_run_cartwheel.py b/project/hoc_trial_run_cartwheel.py new file mode 100644 index 0000000..cbf27a5 --- /dev/null +++ b/project/hoc_trial_run_cartwheel.py @@ -0,0 +1,160 @@ +from multiprocessing import Pool +from random import randint + +from neuron import h + +from cnmodel import cells + + +def run(run_input, processes): + results = [] + if processes == 1: + for r_input in run_input: + results.append(_run_trial(r_input)) + else: + p = Pool(processes) + for res in p.imap_unordered(_run_trial, run_input): + results.append(res) + return results + + +def add_pyramidal_cell(): + pyramidal = cells.Pyramidal.create(species="rat") + pyramidal.add_dendrites() + apical = pyramidal.maindend[0] + basal = pyramidal.maindend[1] + return pyramidal + + +def add_tuberculoventral_cell(): + tuberculoventral_1 = cells.Tuberculoventral.create() + tuberculoventral_2 = cells.Tuberculoventral.create() + return tuberculoventral_1, tuberculoventral_2 + + +def add_dstellate_cell(): + dstel1ate = cells.DStellateEager.create() + return dstel1ate + + +def add_cartwheel_cell(): + cartwheel = cells.Cartwheel.create() + return cartwheel + + +def _run_trial(run_input): + seed, info, run_number = run_input + """ + info is a dict + """ + pyramidal = add_pyramidal_cell() + tuberculoventral_1, tuberculoventral_2 = add_tuberculoventral_cell() + dstellate = add_dstellate_cell() + cartwheel = add_cartwheel_cell() + auditory_nerve_cells = [] + synapses = [] + inhib_synapses = [] + # auditory nerve attachments + # attach to pyramidal cell + for nsgc in range(48): + auditory_nerve_cells.append(cells.DummySGC(cf=info["cf"], sr=info["sr"])) + synapses.append(auditory_nerve_cells[-1].connect(pyramidal, type="multisite")) + auditory_nerve_cells[-1].set_sound_stim( + info["stim"], + seed=seed + nsgc + randint(0, 80000), + simulator=info["simulator"], + ) + # attach to tuberculoventral 1 + for nsgc in range(18): + # attach to tb cell + auditory_nerve_cells.append(cells.DummySGC(cf=info["cf"], sr=info["sr"])) + synapses.append(auditory_nerve_cells[-1].connect(tuberculoventral_1, type=info["synapse_type"])) + auditory_nerve_cells[-1].set_sound_stim( + info["stim"], + seed=seed + nsgc + randint(0, 80000), + simulator=info["simulator"], + ) + # attach to tuberculoventral 2 + for nsgc in range(18): + # attach to tb cell + auditory_nerve_cells.append(cells.DummySGC(cf=info["cf"], sr=info["sr"])) + synapses.append(auditory_nerve_cells[-1].connect(tuberculoventral_2, type="multisite")) + auditory_nerve_cells[-1].set_sound_stim( + info["stim"], + seed=seed + nsgc + randint(0, 80000), + simulator=info["simulator"], + ) + for nsgc in range(24): + # attach to dstellate cell + auditory_nerve_cells.append(cells.DummySGC(cf=info["cf"], sr=info["sr"])) + synapses.append(auditory_nerve_cells[-1].connect(dstellate, type="multisite")) + auditory_nerve_cells[-1].set_sound_stim( + info["stim"], + seed=seed + nsgc + randint(0, 80000), + simulator=info["simulator"], + ) + # Connections between network cells + for _ in range(5): + inhib_synapses.append(cartwheel.connect(pyramidal, type='simple')) + for _ in range(21): + inhib_synapses.append(tuberculoventral_1.connect(pyramidal, type="simple")) + inhib_synapses.append(tuberculoventral_2.connect(pyramidal, type="simple")) + for _ in range(15): + inhib_synapses.append(dstellate.connect(pyramidal, type="simple")) + inhib_synapses.append(dstellate.connect(tuberculoventral_1, type='simple')) + inhib_synapses.append(dstellate.connect(tuberculoventral_2, type='simple')) + for _ in range(3): + inhib_synapses.append(dstellate.connect(dstellate, type="simple")) + stim = insert_current_clamp(cartwheel.soma) + + # set up our recording vectors for each cell + Vm = h.Vector() + Vm.record(pyramidal.soma(0.5)._ref_v) + Vmtb = h.Vector() + Vmtb.record(tuberculoventral_1.soma(0.5)._ref_v) + Vmds = h.Vector() + Vmds.record(dstellate.soma(0.5)._ref_v) + Vmcar = h.Vector() + Vmcar.record(cartwheel.soma(0.5)._ref_v) + rtime = h.Vector() + rtime.record(h._ref_t) + # initialize + init_cells([pyramidal, cartwheel, tuberculoventral_1, tuberculoventral_2, dstellate]) + info["init"]() + # hoc trial run + h.tstop = 1e3 * info["run_duration"] # duration of a run + h.celsius = info["temp"] + h.dt = info["dt"] + h.t = 0.0 + h.run() + # dtime = time.time() - start + # print(f"Trial {run_number} completed after {dtime} secs") + + return { + "time": list(rtime), + "vm": list(Vm), + "auditory_nerve_cells": [x._spiketrain.tolist() for x in auditory_nerve_cells], + "vmtb": list(Vmtb), + "vmds": list(Vmds), + "vmcar": list(Vmcar), + } + + +def insert_current_clamp(sec): + """ + :param sec: to attach too + dur: ms + amp: nA + delay: ms + :return: stim needs to be put in a variable to stay alive + """ + stim = h.IClamp(0.5, sec=sec) + stim.dur = 1 + stim.amp = 0.5 + stim.delay = 100 + return stim + + +def init_cells(cells: list): + for x in cells: + x.cell_initialize() diff --git a/project/hoc_trial_run_dendrites.py b/project/hoc_trial_run_dendrites.py new file mode 100644 index 0000000..8522cfc --- /dev/null +++ b/project/hoc_trial_run_dendrites.py @@ -0,0 +1,150 @@ +from multiprocessing import Pool +from random import randint +from cnmodel import cells +from neuron import h +from tqdm import tqdm + + +def run(run_input, processes): + results = [] + if processes == 1: + for input in run_input: + results.append(_run_trial(input)) + else: + p = Pool(processes) + for res in tqdm(p.imap_unordered(_run_trial, run_input)): + results.append(res) + return results + + +def add_pyramidal_cell(): + pyramidal = cells.Pyramidal.create(species="rat") + pyramidal.add_dendrites() + apical_dend = pyramidal.maindend[0] + basal_dend = pyramidal.maindend[1] + return pyramidal + + +def add_tuberculoventral_cell(): + tuberculoventral_1 = cells.Tuberculoventral.create() + tuberculoventral_2 = cells.Tuberculoventral.create() + return tuberculoventral_1, tuberculoventral_2 + + +def add_dstellate_cell(): + dstel1ate = cells.DStellateEager.create() + return dstel1ate + + +def _run_trial(run_input): + seed, info, run_number = run_input + """ + info is a dict + """ + pyramidal = add_pyramidal_cell() + tuberculoventral_1, tuberculoventral_2 = add_tuberculoventral_cell() + dstellate = add_dstellate_cell() + + auditory_nerve_cells = [] + synapses = [] + inhib_synapses = [] + # auditory nerve attachments + # attach to pyramidal cell + for nsgc in range(48): + auditory_nerve_cells.append(cells.DummySGC(cf=info["cf"], sr=info["sr"])) + synapses.append(auditory_nerve_cells[-1].connect(pyramidal, type="multisite")) + auditory_nerve_cells[-1].set_sound_stim( + info["stim"], + seed=seed + nsgc + randint(0, 80000), + simulator=info["simulator"], + ) + # attach to tuberculoventral 1 + for nsgc in range(18): + # attach to tb cell + auditory_nerve_cells.append(cells.DummySGC(cf=info["cf"], sr=info["sr"])) + synapses.append(auditory_nerve_cells[-1].connect(tuberculoventral_1, type=info["synapse_type"])) + auditory_nerve_cells[-1].set_sound_stim( + info["stim"], + seed=seed + nsgc + randint(0, 80000), + simulator=info["simulator"], + ) + # attach to tuberculoventral 2 + for nsgc in range(18): + # attach to tb cell + auditory_nerve_cells.append(cells.DummySGC(cf=info["cf"], sr=info["sr"])) + synapses.append(auditory_nerve_cells[-1].connect(tuberculoventral_2, type="multisite")) + auditory_nerve_cells[-1].set_sound_stim( + info["stim"], + seed=seed + nsgc + randint(0, 80000), + simulator=info["simulator"], + ) + for nsgc in range(24): + # attach to dstellate cell + auditory_nerve_cells.append(cells.DummySGC(cf=info["cf"], sr=info["sr"])) + synapses.append(auditory_nerve_cells[-1].connect(dstellate, type="multisite")) + auditory_nerve_cells[-1].set_sound_stim( + info["stim"], + seed=seed + nsgc + randint(0, 80000), + simulator=info["simulator"], + ) + # Connections between network cells + # for _ in range(5): + # inhib_synapses.append(cartwheel.connect(pyramidal, type="simple")) + for _ in range(21): + inhib_synapses.append(tuberculoventral_1.connect(pyramidal, type="simple")) + inhib_synapses.append(tuberculoventral_2.connect(pyramidal, type="simple")) + for _ in range(15): + inhib_synapses.append(dstellate.connect(pyramidal, type="simple")) + inhib_synapses.append(dstellate.connect(tuberculoventral_1, type='simple')) + inhib_synapses.append(dstellate.connect(tuberculoventral_2, type='simple')) + for _ in range(3): + inhib_synapses.append(dstellate.connect(dstellate, type="simple")) + stim = insert_current_clamp(pyramidal.soma) + + # set up our recording vectors for each cell + Vm = h.Vector() + Vm.record(pyramidal.soma(0.5)._ref_v) + Vmtb = h.Vector() + Vmtb.record(tuberculoventral_1.soma(0.5)._ref_v) + Vmds = h.Vector() + Vmds.record(dstellate.soma(0.5)._ref_v) + rtime = h.Vector() + rtime.record(h._ref_t) + # hoc trial run + h.tstop = 1e3 * info["run_duration"] # duration of a run + h.celsius = info["temp"] + h.dt = info["dt"] + init_cells([pyramidal, tuberculoventral_1, tuberculoventral_2, dstellate]) + info["init"]() + h.t = 0.0 + h.run() + # dtime = time.time() - start + # print(f"Trial {run_number} completed after {dtime} secs") + + return { + "time": list(rtime), + "vm": list(Vm), + "auditory_nerve_cells": [x._spiketrain.tolist() for x in auditory_nerve_cells], + "vmtb": list(Vmtb), + "vmds": list(Vmds), + } + + +def insert_current_clamp(sec): + """ + :param sec: to attach too + dur: ms + amp: nA + delay: ms + :return: stim needs to be put in a variable to stay alive + """ + stim = h.IClamp(0.5, sec=sec) + stim.dur = 30 + stim.amp = -0.2 + stim.delay = 120 + return stim + + +def init_cells(cell: list): + for x in cell: + x.cell_initialize() diff --git a/project/network_pauser_prototype_cartwheel.py b/project/network_pauser_prototype_cartwheel.py new file mode 100644 index 0000000..2103f44 --- /dev/null +++ b/project/network_pauser_prototype_cartwheel.py @@ -0,0 +1,311 @@ +""" +Layout: + + if __name__==__main__ handles cmd args, instantiates test, runs it, displays results + + run_trial(): defines a model and then runs the test using preset params in hoc and return the info to the class + SGCInputTest: + __init__ : defines many static variables + run(): calls delivers information to the run_trial() function and the recieved information of a single run + back and stores it as an extensible list in the class + show(): displays graphs depending on the graph options selected below it and displayed in a printout + +""" + +import argparse +import json +import os +import sys +import time +from random import randint + +import gooey + +from cnmodel.protocols import Protocol +from cnmodel.util import custom_init +from cnmodel.util import sound +from graphs import * +from hoc_trial_run_cartwheel import run + + +class NetworkSimulation(Protocol): + """ + Tests a Single cell with input recieved from the SGC + + __init__: almost all parameters can be modified + run(): simply loops over the run_trial() function and stores the results just + show(): constructs the graphs using other functions + + """ + + def __init__( + self, + temp=34.0, + seed=randint(2500, 400000), + nrep=10, + stimulus="tone", + simulator="cochlea", + debug=True, + dt=0.025 + ): + """ + :param temp: (float) must be at 34 for default pyramidal cells + :param dt: (float) determine hoc resolution + :param seed: (int) contributes to randomization, needs to be changed to see different results (reduce this + number if you keep getting a timeout error + :param nrep: (int) number of presentations !!must be changed in the __name__ function if not calling from cmd line!! + :param stimulus: (str) must be 'tone' + :param simulator: (str) currently using cochlea instead of matlab + :param n_sgc:(int) This is the number of SGC fibers that connect to the post synaptic cell + :param debug: (bool) controls most of the terminal printouts is on by default + :param cell: (str) cell type !!must be changed in the __name__ function if not calling from cmd line!! + """ + super().__init__() + # + self.debug = debug + self.nrep = nrep + self.stimulus = stimulus + self.run_duration = 0.3 # in seconds + # stim parameters + self.pip_duration = 0.05 # in seconds + self.pip_start = [0.14] # in seconds + self.Fs = 100e3 # in Hz + self.f0 = 14013.0 # stimulus in Hz + self.cf = 14013.0 # SGCs in Hz + self.fMod = 100.0 # mod freq, Hz + self.dMod = 0.0 # % mod depth, Hz + self.dbspl = 55.0 + # usually cochlea + self.simulator = simulator + self.sr = 2 # set SR group + self.seed = seed + # physiological parameters + self.temp = temp + self.dt = dt + self.synapse_type = "multisite" + self.species = "rat" + + if self.stimulus == "tone": + self.stim = sound.TonePip( + rate=self.Fs, + duration=self.run_duration, + f0=self.f0, + dbspl=self.dbspl, + ramp_duration=5e-3, + pip_duration=self.pip_duration, + pip_start=self.pip_start, + ) + # result containers + self.vms = [] + self.vmtbs = [] + self.vmdss = [] + self.vmcar = [] + self.synapses = [] + self.auditory_nerve_cells = [] + self.time = [] + # debug function reports a print out of various information about the run + if self.debug: + print("Small Network Test Created") + print("#" * 70) + print(f"Running Test of Network with Simulated SGC fibers") + print() + print(f"Run Conditions: Run Time: {self.run_duration}s,") + print(f" Run Temp: {self.temp} ") + print(f" Number of Presentations: {nrep}") + print() + print(f"Stimulus Conditions: Type: {stimulus}") + print(f" Stim Duration: {self.pip_duration}s") + print(f" Characteristic F: {self.cf}hz") + print(f" Stim Start:{str(self.pip_start)}s") + + def run(self, processes=1, **kwargs): + """ + Runs the trials with the number of nreps set for the trial, calls a multiprocess run of however many trials + are needed. + If processes set to one then the it will run without the multiprocessing library(more reliable) + """ + super().run() + info = { + "stim": self.stim, + "simulator": self.simulator, + "cf": self.cf, + "sr": self.sr, + "run_duration": self.run_duration, + "synapse_type": self.synapse_type, + "temp": self.temp, + "dt": self.dt, + "init": custom_init, + } + # Generate inputs + b = [(self.seed + randint(0, 80000)) for _ in range(self.nrep)] + c = [info for _ in range(self.nrep)] + d = range(1, self.nrep+1) + + run_input = zip(b, c, d) + self.all_results = run(run_input, processes=processes) + self.unpack_data(self.all_results) + + def unpack_data(self, run_data): + len_of_data = 0 + for nr, res in enumerate(run_data): + try: + len_of_data += 1 + # res contains: {'time': time, 'vm': list(Vm), 'auditory_nerve_cells': auditory_nerve_cells._spiketrain,'vmtb': list(Vmtb)} + self.auditory_nerve_cells.append(res["auditory_nerve_cells"]) + self.time.append(res["time"]) + self.vms.append(res["vm"]) + self.vmtbs.append(res["vmtb"]) + self.vmdss.append(res["vmds"]) + self.vmcar.append(res["vmcar"]) + except(KeyError): + continue + self.nrep = len_of_data + + def show(self): + """ + Creates a single page graph that contains all of the graphs based on the graphical functions in the class + """ + self.win = pg.GraphicsWindow() + self.win.setBackground("w") + p2 = an_spike_graph(self.win, self.auditory_nerve_cells, 0, 0) + p3 = spike_graph(self.win, self.time, self.vms, 1, 0, title="Pyramidal") + p5 = spike_graph( + self.win, self.time, self.vmtbs, 2, 0, title="Tuberculoventral" + ) + p6 = spike_graph(self.win, self.time, self.vmdss, 3, 0, title="D-Stellate") + p9 = spike_graph(self.win, self.time, self.vmcar, 4, 0, title="Cartwheel") + p1 = stimulus_graph(self.win, self.stim, 0, 1) + p4 = voltage_graph(self.win, self.time, self.vms, 1, 1) + p7 = an_psth_graph( + self.win, self.auditory_nerve_cells, 2, 1 + ) + p8 = cell_psth_graph( + self.win, self.time, self.vms, 3, 1, title="Pyramidal" + ) + + # links x axis + p1.setXLink(p1) + p2.setXLink(p1) + p3.setXLink(p1) + p4.setXLink(p1) + p5.setXLink(p1) + p6.setXLink(p1) + p7.setXLink(p1) + p8.setXLink(p1) + p9.setXLink(p1) + + self.win.show() + if self.debug: + print("finished") + + def export(self): + if self.debug: + print("Exporting File Binary") + t = time.gmtime() + destination_name = f"{os.path.basename(__file__).strip('.py')}_{t.tm_mday}-{t.tm_mon}-{t.tm_year}_{t.tm_hour}_{t.tm_min}.json" + os.scandir() + dirname = os.path.join(os.path.dirname(__file__), "run_data") + if not os.path.isdir(dirname): + os.mkdir(dirname) + filepath = os.path.join(dirname, destination_name) + with open(filepath, "w") as f: + json.dump(self.all_results, f) + if self.debug: + print(f"Run saved to {filepath}") + + def load(self, load_file=None): + with open(load_file, "r") as file_in: + data_list = json.load(file_in) + self.unpack_data(data_list) + +@gooey.Gooey +def interface(): + parser = argparse.ArgumentParser( + description="Compute Neuron response for small network of DCN" + ) + # parser.add_argument(type=str, dest='cell', default='pyramidal', + # choices=['bushy', 'tstellate', 'dstellate', 'octopus', + # 'tuberculoventral', 'pyramidal'], + # help='Select target cell') + parser.add_argument( + "-n", + "--nrep", + type=int, + dest="nrep", + default=4, + help="Set number of repetitions", + ) + parser.add_argument( + "-l", + "--load", + type=str, + dest="load_file", + default=None, + help="Load data from a previous run json", + ) + parser.add_argument( + "-s", + "--save", + type=str, + dest="save_flag", + default=True, + help="If you do not want to export file set flag to False", + ) + parser.add_argument( + "-d", + "--debug", + type=str, + dest="debug_flag", + default=True, + help="If you do not want to see debug text or GUI set to False", + ) + parser.add_argument( + "-p", + "--process", + type=int, + dest="processes", + default=1, + help="Set the number of processes that the run will be run across", + ) + args = parser.parse_args() + start = time.time() + nrep = args.nrep + processes = args.processes + load_file = args.load_file + + # manages how options affect the class that is created to manage the trial run + if args.save_flag == "False": + save = False + else: + save = True + if args.debug_flag == "False": + debug_flag = False + else: + debug_flag = True + + if load_file: + if os.path.exists(load_file): + test = NetworkSimulation(nrep=nrep, debug=False) + test.load(load_file) + test.show() + else: + raise FileNotFoundError(f"{load_file} does not exist") + else: + test = NetworkSimulation(nrep=nrep, debug=debug_flag) + test.run(processes=processes) + if debug_flag: + test.show() + if save: + test.export() + + dtime = time.time() - start + print("#" * 70) + print(f"Total Elapsed Time {dtime/60} mins") + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() + + + +if __name__ == "__main__": + interface() + diff --git a/project/network_pauser_prototype_dendrites.py b/project/network_pauser_prototype_dendrites.py new file mode 100644 index 0000000..09b5a6b --- /dev/null +++ b/project/network_pauser_prototype_dendrites.py @@ -0,0 +1,298 @@ +""" +Layout: + + if __name__==__main__ handles cmd args, instantiates test, runs it, displays results + + run_trial(): defines a model and then runs the test using preset params in hoc and return the info to the class + SGCInputTest: + __init__ : defines many static variables + run(): calls delivers information to the run_trial() function and the recieved information of a single run + back and stores it as an extensible list in the class + show(): displays graphs depending on the graph options selected below it and displayed in a printout + +""" +import os +import argparse +import time +import json +import sys +from random import randint +from cnmodel.protocols import Protocol +from cnmodel.util import sound +from cnmodel.util import custom_init +from graphs import * +from hoc_trial_run_dendrites import run + + +class NetworkSimulation(Protocol): + """ + Tests a Single cell with input recieved from the SGC + + __init__: almost all parameters can be modified + run(): simply loops over the run_trial() function and stores the results just + show(): constructs the graphs using other functions + + """ + + def __init__( + self, + temp=34.0, + seed=randint(2500, 400000), + nrep=10, + stimulus="tone", + simulator="cochlea", + debug=True, + dt=0.025 + ): + """ + :param temp: (float) must be at 34 for default pyramidal cells + :param dt: (float) determine hoc resolution + :param seed: (int) contributes to randomization, needs to be changed to see different results (reduce this + number if you keep getting a timeout error + :param nrep: (int) number of presentations !!must be changed in the __name__ function if not calling from cmd line!! + :param stimulus: (str) must be 'tone' + :param simulator: (str) currently using cochlea instead of matlab + :param n_sgc:(int) This is the number of SGC fibers that connect to the post synaptic cell + :param debug: (bool) controls most of the terminal printouts is on by default + :param cell: (str) cell type !!must be changed in the __name__ function if not calling from cmd line!! + """ + super().__init__() + # + self.debug = debug + self.nrep = nrep + self.stimulus = stimulus + self.run_duration = 0.3 # in seconds + # stim parameters + self.pip_duration = 0.05 # in seconds + self.pip_start = [0.14] # in seconds + self.Fs = 100e3 # in Hz + self.f0 = 14013.0 # stimulus in Hz + self.cf = 14013.0 # SGCs in Hz + self.fMod = 100.0 # mod freq, Hz + self.dMod = 0.0 # % mod depth, Hz + self.dbspl = 55.0 + # usually cochlea + self.simulator = simulator + self.sr = 2 # set SR group + self.seed = seed + # physiological parameters + self.temp = temp + self.dt = dt + self.synapse_type = "multisite" + self.species = "rat" + + if self.stimulus == "tone": + self.stim = sound.TonePip( + rate=self.Fs, + duration=self.run_duration, + f0=self.f0, + dbspl=self.dbspl, + ramp_duration=5e-3, + pip_duration=self.pip_duration, + pip_start=self.pip_start, + ) + # result containers + self.vms = [] + self.vmtbs = [] + self.vmdss = [] + self.vmcar = [] + self.synapses = [] + self.auditory_nerve_cells = [] + self.time = [] + # debug function reports a print out of various information about the run + if self.debug: + print("Small Network Test Created") + print("#" * 70) + print(f"Running Test of Network with Simulated SGC fibers") + print() + print(f"Run Conditions: Run Time: {self.run_duration}s,") + print(f" Run Temp: {self.temp} ") + print(f" Number of Presentations: {nrep}") + print() + print(f"Stimulus Conditions: Type: {stimulus}") + print(f" Stim Duration: {self.pip_duration}s") + print(f" Characteristic F: {self.cf}hz") + print(f" Stim Start:{str(self.pip_start)}s") + + def run(self, processes=1, **kwargs): + """ + Runs the trials with the number of nreps set for the trial, calls a multiprocess run of however many trials + are needed. + If processes set to one then the it will run without the multiprocessing library(more reliable) + """ + super().run() + info = { + "stim": self.stim, + "simulator": self.simulator, + "cf": self.cf, + "sr": self.sr, + "run_duration": self.run_duration, + "synapse_type": self.synapse_type, + "temp": self.temp, + "dt": self.dt, + "init": custom_init, + } + # Generate inputs + b = [(self.seed + randint(0, 80000)) for _ in range(self.nrep)] + c = [info for _ in range(self.nrep)] + d = range(1, self.nrep+1) + + run_input = zip(b, c, d) + self.all_results = run(run_input, processes=processes) + self.unpack_data(self.all_results) + + def unpack_data(self, run_data): + len_of_data = 0 + for nr, res in enumerate(run_data): + try: + len_of_data += 1 + # res contains: {'time': time, 'vm': list(Vm), 'auditory_nerve_cells': auditory_nerve_cells._spiketrain,'vmtb': list(Vmtb)} + self.auditory_nerve_cells.append(res["auditory_nerve_cells"]) + self.time.append(res["time"]) + self.vms.append(res["vm"]) + self.vmtbs.append(res["vmtb"]) + self.vmdss.append(res["vmds"]) + self.vmcar.append(res["vmcar"]) + except(KeyError): + continue + self.nrep = len_of_data + + def show(self): + """ + Creates a single page graph that contains all of the graphs based on the graphical functions in the class + """ + self.win = pg.GraphicsWindow() + self.win.setBackground("w") + p2 = an_spike_graph(self.win, self.auditory_nerve_cells, 0, 0) + p3 = spike_graph(self.win, self.time, self.vms, 1, 0, title="Pyramidal") + p5 = spike_graph( + self.win, self.time, self.vmtbs, 2, 0, title="Tuberculoventral" + ) + p6 = spike_graph(self.win, self.time, self.vmdss, 3, 0, title="D-Stellate") + p1 = stimulus_graph(self.win, self.stim, 0, 1) + p4 = voltage_graph(self.win, self.time, self.vms, 1, 1) + p7 = an_psth_graph( + self.win, self.auditory_nerve_cells, 2, 1 + ) + p8 = cell_psth_graph( + self.win, self.time, self.vms, 3, 1, title="Pyramidal" + ) + + # links x axis + p1.setXLink(p1) + p2.setXLink(p1) + p3.setXLink(p1) + p4.setXLink(p1) + p5.setXLink(p1) + p6.setXLink(p1) + p7.setXLink(p1) + p8.setXLink(p1) + + self.win.show() + if self.debug: + print("finished") + + def export(self): + if self.debug: + print("Exporting File Binary") + t = time.gmtime() + destination_name = f"{os.path.basename(__file__).strip('.py')}_{t.tm_mday}-{t.tm_mon}-{t.tm_year}_{t.tm_hour}_{t.tm_min}.json" + os.scandir() + dirname = os.path.join(os.path.dirname(__file__), "run_data") + if not os.path.isdir(dirname): + os.mkdir(dirname) + filepath = os.path.join(dirname, destination_name) + with open(filepath, "w") as f: + json.dump(self.all_results, f) + if self.debug: + print(f"Run saved to {filepath}") + + def load(self, load_file=None): + with open(load_file, "r") as file_in: + data_list = json.load(file_in) + self.unpack_data(data_list) + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Compute Neuron response for small network of DCN" + ) + # parser.add_argument(type=str, dest='cell', default='pyramidal', + # choices=['bushy', 'tstellate', 'dstellate', 'octopus', + # 'tuberculoventral', 'pyramidal'], + # help='Select target cell') + parser.add_argument( + "-n", + "--nrep", + type=int, + dest="nrep", + default=4, + help="Set number of repetitions", + ) + parser.add_argument( + "-l", + "--load", + type=str, + dest="load_file", + default=None, + help="Load data from a previous run pickle", + ) + parser.add_argument( + "-s", + "--save", + type=str, + dest="save_flag", + default=True, + help="If you do not want to export file set flag to False", + ) + parser.add_argument( + "-d", + "--debug", + type=str, + dest="debug_flag", + default=True, + help="If you do not want to see debug text or GUI set to False", + ) + parser.add_argument( + "-p", + "--process", + type=int, + dest="processes", + default=1, + help="Set the number of processes that the run will be run across", + ) + args = parser.parse_args() + start = time.time() + nrep = args.nrep + processes = args.processes + load_file = args.load_file + + # manages how options affect the class that is created to manage the trial run + if args.save_flag == "False": + save = False + else: + save = True + if args.debug_flag == "False": + debug_flag = False + else: + debug_flag = True + + if not load_file: + test = NetworkSimulation(nrep=nrep, debug=debug_flag) + test.run(processes=processes) + if debug_flag: + test.show() + if save: + test.export() + else: + if os.path.exists(load_file): + test = NetworkSimulation(nrep=nrep, debug=False) + test.load(load_file) + test.show() + else: + raise FileNotFoundError(f"{load_file} does not exist") + dtime = time.time() - start + print("#" * 70) + print(f"Total Elapsed Time {dtime/60} mins") + + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() diff --git a/project/previous_version/Ad041599_062_Buildup_psth.txt b/project/previous_version/Ad041599_062_Buildup_psth.txt new file mode 100644 index 0000000..8fb58d8 --- /dev/null +++ b/project/previous_version/Ad041599_062_Buildup_psth.txt @@ -0,0 +1,2107 @@ +0 +316 +17354 +24673 +24937 +35490 +42614 +45361 +50019 +54607 +58369 +162871 +186891 +197586 +0 +23921 +26970 +36409 +50506 +56071 +137945 +158010 +189398 +0 +24260 +34341 +41425 +47368 +52041 +55868 +57008 +166449 +170316 +190255 +196830 +0 +19064 +25623 +28980 +36193 +45750 +54414 +56731 +58102 +171252 +184789 +189973 +0 +5744 +12518 +19551 +25934 +36306 +39450 +41602 +49968 +55025 +143639 +172529 +0 +877 +18033 +24231 +30434 +39337 +46196 +52451 +56359 +58745 +161196 +192589 +0 +15550 +22777 +30249 +37309 +40367 +45911 +53628 +57859 +167936 +0 +11800 +18027 +28231 +31038 +34109 +41507 +45491 +51369 +54672 +55205 +60045 +141871 +173310 +194310 +198683 +0 +18413 +29235 +37152 +39313 +42422 +49612 +56413 +147726 +168101 +183216 +0 +11614 +15788 +27985 +34316 +43063 +48885 +51619 +54287 +55138 +83662 +149746 +171225 +179907 +0 +14115 +24775 +32023 +36098 +38570 +45091 +47539 +56106 +63756 +157765 +171647 +176995 +186151 +0 +21849 +31876 +39169 +45818 +53919 +58139 +101834 +155215 +156729 +185581 +193191 +0 +25232 +28380 +31706 +38412 +41741 +46647 +54186 +58067 +169788 +0 +3421 +20999 +27180 +34030 +42133 +47772 +53403 +58848 +139727 +182482 +196192 +0 +5551 +14039 +24914 +34737 +41194 +48521 +55078 +154631 +176259 +194829 +0 +365 +17151 +25538 +36507 +46748 +50955 +55465 +58057 +145291 +180075 +0 +16316 +25983 +30319 +37057 +42781 +49424 +57250 +151356 +199540 +0 +12721 +18885 +19522 +25779 +33150 +38071 +41348 +48095 +51168 +52281 +52741 +55000 +57713 +85450 +0 +13036 +15799 +20656 +24515 +27258 +31888 +35896 +38398 +42811 +43582 +47856 +48795 +54726 +56640 +57748 +122547 +163639 +0 +447 +12561 +13496 +25838 +30506 +34632 +39159 +42597 +43679 +47775 +48715 +56767 +56960 +58706 +64267 +122941 +135237 +166980 +186635 +192382 +197849 +0 +368 +4683 +11161 +13602 +14626 +18789 +22019 +25381 +26132 +29200 +30761 +32161 +35314 +38267 +39387 +42108 +46020 +47163 +48953 +52967 +54108 +56619 +59917 +70151 +94919 +99960 +130476 +135156 +137469 +139041 +142244 +145449 +149470 +150287 +155453 +157607 +158815 +170122 +174207 +182983 +184399 +188019 +198504 +199645 +0 +3283 +4363 +5904 +19439 +20035 +21118 +26432 +28812 +30835 +33289 +33914 +35261 +36871 +40056 +44939 +47666 +49867 +53289 +55416 +56456 +59649 +62490 +64601 +70428 +73386 +79873 +88019 +91608 +92459 +96072 +97793 +100190 +105415 +106866 +108322 +130351 +133097 +134188 +134868 +137184 +141141 +141873 +142379 +146449 +147316 +152449 +154042 +155352 +157773 +161903 +163524 +169550 +175015 +179307 +187476 +190910 +192562 +196203 +198494 +0 +2292 +4017 +4640 +5403 +11779 +12375 +17682 +21458 +24335 +28004 +29852 +30346 +31956 +36872 +38906 +41332 +43960 +45155 +47024 +49692 +51135 +52255 +54239 +55191 +55881 +58964 +64913 +68912 +76792 +81745 +83075 +91160 +93674 +94121 +97656 +100813 +102977 +104369 +105958 +107436 +108255 +108662 +110115 +117137 +118342 +124261 +126854 +138385 +141021 +142050 +152018 +154007 +155785 +157341 +174275 +189149 +193864 +0 +13946 +16363 +19569 +27665 +31635 +35451 +43426 +47616 +48091 +54094 +57195 +171624 +0 +17232 +28687 +34597 +45360 +51671 +58377 +120482 +172065 +194023 +0 +18028 +25635 +30367 +32079 +40546 +46742 +54365 +57223 +58758 +170718 +0 +3416 +18754 +34797 +39342 +42212 +51245 +55807 +174232 +189032 +0 +22897 +30709 +37382 +43127 +51656 +56634 +58220 +190972 +0 +16558 +21853 +31338 +39885 +45284 +55987 +183635 +192575 +0 +15639 +30723 +38934 +46194 +51243 +55601 +149393 +170158 +188337 +0 +1396 +14558 +26871 +35563 +45425 +49458 +54293 +170050 +0 +23838 +31122 +37171 +44937 +48954 +54530 +58574 +168894 +191481 +0 +15580 +27702 +33259 +44747 +48887 +54641 +147305 +182009 +196671 +0 +26806 +33832 +48722 +55015 +59004 +176816 +0 +19616 +29250 +38850 +43347 +47754 +53226 +181183 +0 +5790 +22918 +30060 +40337 +44489 +50312 +54786 +180608 +0 +18640 +30040 +37915 +43894 +48843 +55579 +172571 +199446 +0 +25199 +38338 +44428 +52780 +58524 +150523 +165961 +190346 +0 +2690 +28434 +34058 +39366 +47200 +52636 +57634 +156276 +177823 +0 +28480 +35001 +39848 +47376 +54159 +59125 +148299 +174459 +195818 +0 +15038 +30675 +38027 +44266 +48100 +54945 +153234 +169923 +191086 +0 +15277 +23969 +29702 +38978 +51092 +54999 +59929 +174737 +199497 +0 +18318 +27279 +31902 +40733 +51272 +57342 +142384 +168866 +194210 +0 +13044 +23620 +32868 +42924 +49680 +56786 +151622 +168423 +183219 +0 +1753 +20221 +26678 +36348 +43262 +49214 +55099 +59223 +138843 +168785 +188882 +199847 +0 +22028 +28608 +35151 +43587 +50045 +55151 +176076 +193930 +0 +12776 +16975 +28600 +34612 +42063 +48660 +53705 +154438 +181122 +0 +1804 +19969 +26813 +37839 +45203 +51842 +57603 +159605 +186697 +0 +22275 +30594 +37708 +46590 +52132 +56565 +168228 +193096 +0 +15259 +28192 +34267 +41953 +48051 +53174 +58347 +163489 +198935 +0 +17974 +24456 +29898 +38491 +47154 +51180 +56322 +165784 +190804 +0 +15041 +22484 +31144 +38783 +44788 +55094 +171701 +186582 +0 +17817 +34665 +42034 +47975 +54862 +58265 +157693 +183854 +198208 +0 +19561 +26275 +33212 +40155 +48727 +56793 +187208 +0 +23583 +29046 +36817 +47244 +53274 +57862 +142380 +189729 +0 +2615 +25424 +35720 +45090 +53373 +57665 +58410 +121827 +152172 +180851 +0 +2087 +18244 +27663 +39101 +46353 +50763 +55978 +160511 +193729 +0 +16477 +24818 +30083 +36983 +43575 +53383 +56979 +148281 +159346 +172086 +190855 +0 +13684 +32463 +38789 +42986 +49353 +54303 +58219 +164845 +184447 +0 +3441 +13681 +15267 +24093 +31374 +38001 +43623 +49295 +55814 +172774 +0 +3240 +18365 +26099 +32369 +38982 +46662 +54948 +59595 +150360 +174242 +0 +3730 +24800 +30266 +37331 +42059 +49692 +57989 +158079 +192326 +0 +19375 +30597 +37253 +42820 +49751 +54462 +149421 +180762 +0 +24651 +31784 +37787 +45245 +49907 +55483 +196471 +0 +13051 +20810 +33639 +43025 +50720 +56087 +146887 +168654 +196893 +0 +15374 +28326 +36940 +41629 +49754 +55664 +152511 +174691 +194825 +0 +16302 +28527 +34866 +41655 +49753 +55810 +139154 +168554 +190879 +0 +14861 +21304 +30319 +42692 +48043 +51984 +55997 +153069 +178025 +199384 +0 +21081 +27385 +34566 +41396 +49139 +54636 +149472 +168482 +196992 +0 +16169 +25474 +33587 +39426 +43699 +54596 +58784 +193773 +0 +20413 +30494 +35821 +41768 +47934 +54976 +58568 +174838 +199111 +0 +16746 +31491 +39281 +44522 +53005 +56592 +175812 +194817 +0 +14056 +19807 +29052 +37238 +44690 +53487 +57818 +177616 +191038 +0 +16211 +25002 +41884 +46864 +53682 +58395 +149947 +180011 +194905 +0 +17062 +27432 +38360 +43250 +50998 +57016 +165634 +186925 +0 +3773 +20649 +28092 +35334 +40863 +46204 +53645 +58313 +149732 +176009 +190357 +0 +16093 +25375 +30220 +35727 +42432 +46942 +54035 +154447 +183937 +0 +24790 +35308 +40552 +48417 +53667 +57986 +164856 +189616 +0 +3205 +19789 +34792 +41293 +48438 +53278 +57536 +157955 +0 +14045 +25169 +30843 +43234 +50196 +56013 +158631 +198813 +0 +25225 +31299 +41249 +47001 +52427 +59162 +153776 +180490 +199382 +0 +17683 +27674 +37143 +42958 +50967 +56347 +172235 +199289 +0 +18188 +24845 +33279 +42339 +54008 +56871 +60081 +165121 +192083 +0 +15232 +22432 +27211 +36006 +41429 +46205 +51443 +58132 +174274 +0 +1548 +13832 +23780 +32814 +38509 +43987 +51414 +57918 +161346 +182512 +0 +5851 +15333 +22651 +30917 +39557 +44911 +55631 +157265 +181771 +191295 +0 +14584 +33227 +42152 +47607 +55023 +58188 +146056 +173970 +193301 +0 +22914 +31831 +37567 +43552 +52980 +57507 +164777 +0 +804 +26307 +36048 +40610 +53780 +163689 +0 +14412 +26633 +34868 +41729 +47340 +51648 +57975 +179433 +194133 +0 +26735 +35961 +45091 +53002 +58310 +190115 +0 +13838 +25907 +32901 +40194 +47086 +53222 +57646 +159684 +179869 +0 +14599 +20214 +27440 +34655 +44146 +47853 +55466 +150314 +188159 +0 +20410 +26682 +34223 +40562 +47419 +53657 +59305 +171434 +195155 +0 +20638 +30305 +36073 +43518 +49795 +54945 +161340 +180163 +0 +1743 +15130 +28392 +36888 +45571 +50536 +56455 +156700 +183047 +0 +24144 +29837 +36239 +45661 +52598 +56112 +192297 +0 +24005 +33658 +41623 +50538 +56817 +188162 +0 +1342 +21296 +29008 +39875 +54094 +180862 +0 +2806 +18316 +31045 +37485 +49902 +159108 +182757 +0 +14748 +25619 +32021 +36266 +45751 +50621 +55773 +176300 +192147 +0 +26162 +34273 +43136 +49426 +55349 +168956 +192792 +0 +13599 +19576 +29497 +35209 +40656 +51290 +56179 +169713 +187379 +0 +25152 +32045 +43425 +47686 +51940 +56094 +160547 +183970 +199742 +0 +15378 +26142 +32686 +37182 +41479 +50979 +57432 +184048 +0 +14051 +25582 +32246 +38652 +46265 +57219 +159970 +191527 +0 +17341 +24341 +29364 +35964 +40350 +47383 +56739 +0 +656 +26625 +33562 +38950 +48176 +52044 +58958 +169323 +0 +1104 +22028 +30400 +34051 +36208 +42836 +53074 +56984 +142579 +184785 +0 +4282 +25398 +35243 +42666 +50064 +56165 +160846 +198316 +0 +21697 +30823 +38198 +44132 +51302 +56587 +164547 +0 +2645 +14564 +25405 +32648 +41364 +46909 +53767 +58830 +179341 +0 +5642 +14539 +25327 +31227 +43216 +48378 +51211 +54570 +58697 +159848 +174614 +197497 +0 +27877 +36926 +45072 +51260 +55964 +161078 +183733 +0 +6052 +16571 +24120 +29338 +37289 +44517 +50342 +57435 +151997 +175473 +0 +13820 +24083 +28577 +35672 +39802 +46037 +53128 +60257 +131217 +164356 +178766 +0 +5709 +25880 +32169 +39787 +46586 +51972 +56217 +169577 +193913 +0 +26969 +34355 +40308 +45681 +50136 +55628 +170401 +183676 +0 +5478 +23891 +33304 +39262 +45564 +54611 +62618 +185831 +0 +18682 +34896 +44669 +51242 +154007 +186577 +0 +21799 +34779 +37945 +42896 +49322 +54783 +152315 +189107 +0 +24636 +33071 +37812 +45972 +51766 +57737 +0 +5390 +27574 +34411 +41561 +48337 +52735 +56920 +153444 +174519 +0 +316 +23633 +33439 +38727 +44872 +52480 +57910 +160788 +193750 +0 +15453 +25015 +38952 +45027 +51701 +56353 +156966 +187165 +0 +1396 +19299 +24993 +33872 +40035 +44292 +50198 +55790 +189908 +0 +13325 +20270 +36115 +44373 +50646 +57070 +182963 +0 +14926 +25648 +32116 +39353 +44988 +52071 +57861 +146462 +177558 +0 +5184 +17869 +25689 +37156 +43698 +49286 +54800 +151671 +192860 +0 +15718 +27109 +34738 +44498 +53346 +58430 +144599 +193424 +0 +14741 +25336 +31700 +37500 +46317 +50846 +57057 +164500 +182244 +0 +6077 +25471 +30712 +40771 +45341 +51461 +55396 +171170 +189222 +0 +13905 +26411 +33453 +39032 +44291 +49021 +55722 +161639 +0 +3014 +16563 +31543 +36785 +45557 +51820 +55860 +172442 +191023 +0 +14464 +21557 +30993 +37248 +46755 +53005 +57396 +177348 +196104 +0 +16584 +26899 +33647 +38743 +44852 +50467 +55754 +151705 +186369 +0 +4468 +17024 +28052 +36963 +43973 +49306 +54891 +154970 +175774 +199676 +0 +26052 +34964 +41727 +46324 +55777 +149873 +181829 +0 +19841 +30368 +40293 +51152 +55612 +171298 +0 +15800 +22882 +29912 +41300 +50796 +56727 +181114 +0 +5596 +21677 +30472 +39987 +49585 +54485 +165650 +187845 +0 +112 +18133 +26585 +36026 +43216 +51150 +57235 +124416 +145993 +183496 +194896 +0 +16234 +29348 +34602 +39834 +45875 +53021 +58736 +166666 +186898 +0 +15567 +26426 +33938 +41536 +47367 +54146 +164889 +180880 +199218 +0 +27185 +35051 +44856 +50319 +55789 +174767 +198720 +0 +16261 +25055 +31004 +37044 +44477 +50983 +55662 +126646 +172819 +194229 +0 +20906 +28647 +38935 +45877 +50955 +56777 +160642 +0 +4982 +25609 +33407 +37809 +44723 +53071 +58363 +163739 +0 +296 +21976 +27447 +37297 +45285 +53382 +59367 +170248 +199266 +0 +15307 +27715 +37618 +44323 +51584 +57037 +185421 +0 +5912 +21087 +30496 +39376 +45177 +52531 +57421 +151460 +165331 +185339 +199436 +0 +20490 +28300 +34380 +45423 +50908 +55682 +161030 +183848 +0 +2256 +16089 +28326 +36906 +43166 +50392 +57050 +151124 +181005 +0 +16449 +25017 +35664 +41580 +47376 +55021 +59048 +169635 +190956 +0 +22313 +29068 +34975 +41529 +46304 +51662 +160894 +190772 +0 +24996 +32905 +39566 +44135 +51970 +56692 +143088 +177988 +198831 +0 +26070 +33429 +40968 +46994 +55760 +154997 +176295 +0 +4718 +16039 +28374 +34655 +42838 +51128 +56515 +160778 +191144 +0 +26250 +32775 +39950 +47593 +56685 +149190 +187114 +0 +17867 +34084 +40231 +45079 +50594 +57719 +151386 +162817 +197811 +0 +26307 +33259 +39656 +48089 +53594 +57384 +148018 +182171 +0 +14806 +27422 +42112 +48238 +53910 +58368 +162917 +180470 +193595 +0 +16222 +25838 +37780 +41897 +46398 +53784 +180969 +0 +5361 +17057 +25015 +33550 +41044 +47188 +53818 +174463 +193118 +0 +15835 +27086 +35251 +41591 +47953 +54812 +164357 +186965 +0 +5216 +14189 +26441 +33151 +41144 +49331 +57417 +148847 +179031 +0 +23825 +33217 +41851 +46816 +51098 +57995 +151638 +186609 +0 +13035 +22905 +33371 +41126 +47732 +53201 +59442 +160507 +175075 +0 +3186 +20717 +28902 +34190 +38837 +46245 +53624 +58061 +148590 +176374 +0 +14819 +24679 +36240 +42641 +46985 +52735 +58789 +152858 +184846 +0 +16735 +26655 +33015 +40614 +46612 +55166 +167912 +190735 +0 +25960 +36818 +44478 +52372 +58164 +166741 +0 +3703 +20383 +28758 +35292 +41839 +50632 +56539 +148528 +172988 +198825 +0 +13886 +31183 +38187 +43209 +53009 +188431 +0 +2339 +17439 +28495 +33083 +47062 +52561 +58240 +176683 +199771 +0 +22212 +29056 +34532 +46904 +51239 +56997 +180194 +0 +4865 +25486 +32018 +42172 +48059 +52187 +59861 +164346 +0 +14758 +26901 +34773 +46353 +53227 +57708 +169975 +186061 +0 +4265 +16550 +28024 +36675 +42582 +48874 +55848 +158896 +190259 +0 +2660 +24784 +32416 +39467 +48524 +53230 +142473 +161846 +191619 +0 +16661 +22012 +28342 +33051 +39040 +46120 +53251 +57843 +163027 +186098 +0 +16698 +29606 +34313 +41189 +50915 +55018 +178936 +199484 +0 +15844 +23682 +32143 +40698 +50409 +55831 +140749 +173455 +0 +4595 +20743 +26634 +32667 +49482 +55418 +144467 +180160 +194810 +0 +28683 +35033 +39841 +51166 +56968 +189475 +0 +15619 +29048 +35958 +50410 +54533 +146286 +175277 +194331 +0 +24140 +33397 +39275 +43524 +49664 +55542 +146512 +167761 +189419 +0 +4379 +25959 +35897 +48760 +54646 +153301 +173174 +191421 +0 +24982 +34688 +42346 +49464 +55865 +150760 +171131 +187996 +0 +14611 +26574 +34542 +40266 +45379 +51399 +56076 +144330 +166285 +188811 +199627 +0 +17499 +28710 +34420 +39083 +48816 +51451 +57710 +177148 +0 +4867 +21832 +27718 +36801 +41464 +51456 +57863 +141311 +160698 +174741 +196197 +0 +20332 +26379 +31878 +37758 +43228 +55907 +146818 +178139 +197747 +0 +1497 +13106 +28772 +35558 +40636 +53882 +57671 +140253 +162919 +185948 +0 +18079 +33973 +41787 +46187 +51808 +182959 +199057 +0 +20960 +27091 +35121 +41733 +48040 +49415 +55286 +59574 +167392 +0 +3441 +31642 +38493 +49404 +54055 +159318 +180068 +0 +1162 +18511 +27913 +35038 +42999 +48156 +55006 +61242 +174833 +0 +3122 +20814 +30369 +36059 +43378 +49705 +56168 +133191 +163852 +192749 +0 +16243 +33487 +39113 +45881 +50297 +55956 +160909 +194420 +0 diff --git a/project/previous_version/Ad081098_065_PauserBuildup_psth.txt b/project/previous_version/Ad081098_065_PauserBuildup_psth.txt new file mode 100644 index 0000000..4e55cd1 --- /dev/null +++ b/project/previous_version/Ad081098_065_PauserBuildup_psth.txt @@ -0,0 +1,1810 @@ +0 +6860 +9579 +23476 +35612 +44797 +50129 +56359 +59533 +196488 +0 +8142 +24717 +31341 +54424 +57340 +0 +6713 +20229 +28539 +36478 +44111 +48031 +53183 +56483 +0 +7735 +18829 +27932 +31472 +41760 +49541 +58044 +198141 +0 +8049 +29782 +37773 +44974 +54619 +57981 +0 +8887 +16896 +23712 +30131 +38160 +52927 +58574 +63117 +171730 +0 +7258 +20306 +28040 +35964 +45434 +54629 +57911 +0 +7683 +18695 +22989 +30100 +51679 +55146 +58538 +0 +7373 +26311 +30359 +37092 +43450 +53576 +57237 +0 +7846 +16873 +23830 +27160 +42087 +46741 +54819 +59374 +0 +8281 +19767 +23176 +30977 +40819 +47052 +56092 +59130 +0 +8039 +20037 +23590 +29470 +33139 +44605 +49252 +55888 +185689 +0 +8255 +23430 +28587 +32681 +37627 +43988 +49025 +57572 +196351 +0 +7614 +23214 +27464 +35737 +40894 +47889 +53604 +56386 +0 +2574 +8049 +16616 +25509 +32553 +37384 +44949 +51784 +55663 +58250 +0 +8223 +17090 +29771 +39088 +45030 +54353 +57788 +0 +7931 +19593 +26073 +37623 +46321 +50819 +56008 +59053 +0 +8628 +15936 +20502 +31802 +41890 +49229 +56296 +61879 +0 +3063 +7973 +19289 +31701 +36270 +49672 +55156 +57923 +0 +8900 +17913 +25790 +30057 +38128 +45798 +51492 +57256 +177345 +0 +6870 +15451 +21206 +27541 +32558 +42778 +54808 +58312 +0 +7373 +15159 +23352 +35400 +39321 +42744 +55157 +58807 +0 +7955 +17650 +21264 +27527 +31573 +45424 +49435 +56405 +184942 +0 +7932 +20051 +26385 +34872 +38671 +49247 +54583 +58111 +0 +8083 +17113 +23115 +32421 +36544 +41340 +52893 +56176 +59208 +0 +6986 +22592 +25789 +30400 +36874 +49257 +54926 +57778 +0 +9036 +23537 +28486 +34589 +38746 +53561 +56856 +0 +2618 +8206 +17845 +26230 +31938 +44760 +52454 +55286 +58693 +0 +7314 +16558 +29045 +41930 +53564 +56637 +59440 +0 +8317 +16320 +26816 +32798 +39668 +46871 +51524 +55766 +58698 +0 +8214 +20591 +28755 +41594 +47450 +51653 +55837 +198102 +0 +6692 +24069 +30503 +36062 +40163 +47505 +55257 +60392 +0 +8821 +17177 +23165 +28328 +40220 +55320 +58020 +0 +7581 +15409 +26124 +30373 +36307 +42383 +53488 +56079 +0 +8301 +16654 +24264 +32935 +40100 +47578 +52879 +61070 +0 +8314 +17349 +25755 +31799 +39248 +45738 +54413 +57143 +0 +7981 +15900 +20388 +26297 +31735 +40611 +45480 +53819 +57350 +0 +8334 +18695 +33047 +37512 +49699 +54238 +0 +9315 +16569 +21466 +27220 +30937 +37320 +45175 +56547 +59276 +0 +8326 +22994 +26524 +35542 +45826 +54864 +58928 +0 +8649 +16870 +24666 +32378 +35682 +46587 +50441 +54782 +61123 +188714 +0 +8785 +22981 +26187 +31726 +47831 +55506 +58690 +0 +7901 +16304 +20543 +27261 +41660 +50413 +55431 +58470 +0 +8368 +17630 +21182 +33087 +39225 +48088 +54961 +58896 +0 +8237 +19755 +23300 +27875 +34807 +39389 +56783 +0 +8179 +20551 +26448 +31395 +38484 +45100 +55852 +58561 +0 +8379 +16106 +20943 +27284 +37475 +50961 +54498 +57271 +0 +8067 +16963 +20539 +32507 +40392 +49950 +53002 +59602 +62975 +0 +7964 +16724 +29175 +38673 +46599 +52854 +56626 +0 +8198 +17419 +30427 +35374 +41876 +48962 +53673 +57112 +0 +8506 +16494 +22764 +26569 +40457 +50498 +53783 +58110 +0 +7375 +20636 +24184 +31136 +41255 +44325 +54760 +60890 +189099 +0 +7651 +18648 +24591 +32631 +45486 +49439 +53412 +58467 +61607 +0 +8718 +16073 +23051 +29601 +36655 +43912 +50283 +56940 +59594 +0 +8155 +16891 +26707 +30693 +45390 +49300 +53738 +58450 +0 +8687 +17758 +22650 +33610 +40096 +44677 +57404 +0 +8380 +25691 +32080 +39916 +50022 +56310 +59616 +0 +8254 +16638 +29201 +36697 +49325 +53265 +60594 +0 +7869 +18748 +27547 +30555 +34406 +41400 +49693 +57363 +60465 +0 +8372 +17933 +26722 +31525 +41862 +49943 +56877 +60839 +0 +7712 +17930 +27082 +31740 +35598 +44824 +49494 +53373 +57093 +0 +8390 +21504 +27742 +37150 +45037 +48277 +57164 +59942 +0 +8474 +22727 +30522 +35200 +41001 +50151 +54354 +57940 +0 +15713 +21875 +27484 +39447 +43514 +51511 +55849 +0 +8557 +17351 +28276 +32214 +39277 +45477 +54961 +60858 +0 +8722 +16203 +22702 +27591 +31427 +35111 +42973 +50035 +56340 +0 +8935 +16922 +21140 +24786 +32261 +39876 +46845 +55439 +59061 +0 +8136 +23450 +26769 +36367 +40325 +46964 +54345 +58217 +0 +8290 +17954 +26547 +37935 +43969 +55568 +63466 +0 +9601 +19950 +27295 +31815 +41175 +45394 +56855 +0 +8438 +21668 +27360 +31107 +35009 +39567 +48377 +55158 +58512 +0 +8685 +21341 +30095 +37136 +43976 +53050 +55890 +0 +7459 +16537 +26746 +31343 +37703 +41355 +56595 +59282 +0 +8651 +16472 +21816 +29084 +36478 +46416 +55548 +58484 +0 +8830 +17807 +21958 +28101 +32325 +38200 +47667 +50997 +0 +8983 +23303 +27790 +36329 +42088 +48140 +52653 +56746 +0 +8221 +18086 +28500 +33472 +42320 +50042 +55745 +0 +8399 +17177 +23690 +29052 +33963 +42650 +46185 +51353 +56709 +0 +8616 +16767 +23287 +29085 +36915 +45585 +49402 +56633 +0 +8765 +15383 +26950 +35250 +38989 +46940 +53786 +57200 +0 +8720 +17402 +26542 +30289 +42888 +56438 +59051 +0 +8338 +17400 +30127 +37519 +40797 +51578 +56371 +59105 +0 +9285 +17514 +25297 +31826 +35471 +48944 +56472 +59270 +0 +8964 +15337 +30683 +42105 +46397 +53246 +56703 +60139 +0 +9066 +16898 +23194 +33426 +39604 +43796 +56421 +59101 +0 +8584 +18100 +21870 +32483 +36294 +44231 +51661 +56817 +0 +7563 +18633 +25541 +29847 +42548 +46538 +55043 +57648 +0 +8436 +20297 +23368 +30641 +42150 +50904 +55973 +0 +9022 +23143 +29177 +35407 +45481 +51852 +57209 +0 +8684 +15082 +26156 +31250 +46331 +55516 +58096 +0 +7733 +15785 +21242 +32288 +40200 +47357 +51915 +56273 +59148 +0 +8263 +15754 +24319 +28446 +41032 +50990 +55777 +0 +8669 +16903 +25447 +31193 +40359 +48391 +53987 +57625 +0 +8554 +17201 +21942 +28115 +32779 +41621 +46391 +52671 +57734 +0 +8229 +17282 +25110 +30238 +35913 +40205 +49695 +53770 +56477 +0 +8605 +20608 +27351 +39984 +43305 +50230 +55338 +58335 +0 +7788 +17195 +22299 +37933 +49333 +53284 +56809 +0 +8275 +23207 +29721 +38021 +47128 +52349 +56291 +0 +8693 +16694 +20621 +28137 +32460 +41061 +50921 +55648 +58639 +0 +8030 +17512 +28649 +32395 +38178 +47271 +53202 +56406 +59997 +0 +9006 +20590 +26062 +35229 +39331 +46020 +54717 +57513 +0 +7942 +16810 +24125 +30315 +44566 +50863 +57519 +60055 +0 +8306 +23446 +32355 +46032 +51135 +53915 +58283 +0 +8935 +22454 +29033 +39960 +45846 +53497 +56570 +0 +7261 +17046 +21056 +28987 +37542 +45069 +51108 +57490 +62186 +0 +8151 +20782 +27128 +38035 +42195 +48234 +51966 +57983 +0 +9028 +15814 +20413 +24811 +30084 +36718 +42472 +54549 +58059 +0 +8936 +16799 +23251 +27568 +39171 +47205 +54087 +58781 +0 +7975 +17445 +27620 +31019 +37179 +41273 +49893 +53980 +58405 +0 +7941 +16721 +21999 +30214 +39343 +47792 +51382 +55390 +0 +7616 +16431 +27951 +37866 +47578 +52697 +56609 +60136 +0 +8235 +20207 +25486 +34153 +43645 +52540 +55561 +58614 +0 +8386 +20567 +28279 +33197 +38291 +42509 +48787 +56064 +58590 +0 +7947 +17535 +22411 +26719 +34049 +39580 +47634 +51116 +54927 +58260 +0 +7915 +18719 +23884 +27128 +35267 +41311 +44629 +52589 +58218 +0 +7729 +16500 +26052 +32075 +43573 +52077 +57814 +61121 +0 +7334 +21317 +35379 +40613 +45499 +55071 +58598 +0 +7581 +16953 +24308 +29182 +35299 +45995 +49575 +57536 +0 +503 +8372 +16177 +25665 +34995 +41302 +55812 +58258 +0 +8292 +16828 +24946 +30200 +34465 +46619 +50136 +55388 +59099 +0 +8673 +17467 +27177 +30346 +40639 +46557 +55162 +57854 +0 +8741 +20402 +27496 +34986 +45230 +52058 +55375 +58343 +0 +8260 +17849 +24834 +33037 +43284 +47522 +54044 +57446 +0 +9433 +17275 +23785 +32822 +41779 +47691 +53292 +57403 +0 +8324 +17520 +20719 +24945 +32169 +38912 +44061 +50748 +57312 +0 +8176 +17852 +26871 +31412 +36762 +47118 +51587 +56115 +59355 +0 +8351 +15726 +28216 +31771 +39913 +44423 +52105 +58494 +0 +8141 +16216 +24331 +29459 +36653 +41384 +48141 +56108 +58885 +0 +7965 +23297 +26747 +37817 +46512 +50450 +55516 +0 +9278 +24178 +31106 +37225 +44512 +50675 +56077 +59250 +0 +8647 +17024 +23417 +27586 +40984 +45903 +54612 +57073 +0 +8856 +19513 +22807 +27798 +40274 +46414 +53266 +57433 +0 +8859 +17543 +27998 +33296 +38968 +46442 +54721 +57485 +0 +3122 +8409 +22554 +26388 +32432 +47294 +52130 +57589 +0 +8612 +21610 +28872 +35431 +42969 +51450 +56446 +59308 +0 +7967 +19068 +33122 +39218 +45502 +54049 +58475 +0 +7909 +17061 +23652 +29666 +42303 +48116 +57004 +59679 +0 +8608 +16996 +29321 +37125 +42390 +55486 +58215 +0 +8132 +21266 +26671 +30998 +40314 +47057 +55259 +58784 +0 +8582 +17393 +24365 +36856 +40585 +51820 +56863 +0 +7588 +18304 +27448 +39232 +44247 +51912 +55468 +58678 +0 +8813 +17711 +22289 +34643 +40621 +50442 +55675 +58498 +0 +8923 +16993 +24029 +29942 +35775 +45678 +54558 +57206 +0 +8251 +21105 +24529 +31790 +39205 +47224 +54331 +57061 +195353 +0 +8257 +25854 +30406 +40398 +49017 +52786 +56330 +59427 +0 +8651 +18334 +28107 +32524 +38146 +49607 +55083 +57906 +0 +8982 +17558 +27675 +37098 +49251 +53286 +57184 +0 +7816 +20886 +27556 +32925 +37850 +43364 +53279 +56391 +59631 +0 +8230 +16309 +20482 +26375 +30164 +35701 +44440 +53908 +57709 +61647 +0 +8902 +19558 +27710 +35691 +47215 +51897 +56579 +59781 +0 +8220 +16420 +23378 +28430 +44737 +49067 +56022 +58814 +0 +8937 +18795 +26572 +36873 +42459 +53277 +57387 +0 +8092 +15836 +24966 +28771 +38015 +52334 +55661 +59781 +0 +8880 +26335 +35187 +46767 +55454 +58250 +0 +8412 +15944 +22209 +30241 +36585 +43753 +52036 +55556 +58454 +0 +8765 +19895 +26822 +31119 +36242 +45022 +53285 +56230 +0 +7602 +16954 +27092 +39982 +43274 +49260 +55688 +0 +8704 +17446 +24867 +35306 +42059 +45157 +52978 +57607 +0 +8006 +16466 +23803 +34197 +39633 +52283 +55984 +59673 +0 +9812 +17393 +25333 +29863 +35122 +47275 +52459 +55964 +60124 +0 +8540 +16202 +28980 +38752 +47194 +50941 +54426 +57376 +0 +7866 +17396 +21020 +30779 +40925 +46596 +55960 +58899 +0 +8846 +16513 +26637 +32155 +45387 +49917 +56387 +0 +8952 +17333 +21667 +31218 +34928 +43643 +47519 +52181 +56125 +0 +8139 +22117 +26011 +39450 +53387 +57632 +0 +8772 +16280 +26894 +33997 +40036 +44553 +52221 +57336 +60393 +0 +8432 +20795 +30076 +34940 +39256 +53274 +58507 +0 +8410 +17294 +22351 +27324 +32394 +38684 +45086 +50449 +55758 +58504 +0 +17450 +27537 +32102 +38813 +50652 +53716 +57405 +0 +8418 +17720 +29121 +33879 +37632 +45350 +49763 +54377 +57856 +0 +7975 +16528 +24275 +29740 +34934 +42131 +51205 +55094 +58278 +0 +7702 +17295 +27102 +32444 +36975 +41562 +53969 +57944 +0 +8044 +17107 +20655 +27354 +36997 +40874 +49444 +56487 +0 +8657 +20390 +24958 +31460 +37020 +41527 +52903 +55748 +0 +7762 +17129 +26752 +30872 +36321 +42420 +48069 +52887 +56017 +60302 +0 +8788 +17246 +23896 +30574 +41121 +47696 +54162 +57335 +60861 +0 +7968 +17684 +21664 +29922 +37176 +42023 +54979 +57934 +0 +9751 +17503 +24563 +29547 +33569 +45574 +48700 +54140 +59582 +0 +7953 +17144 +22030 +29933 +37190 +46000 +50327 +54841 +58332 +0 +8210 +17263 +24273 +31352 +41686 +45991 +53308 +58000 +0 +8047 +22785 +28627 +33531 +42576 +54148 +57444 +60380 +0 +7825 +20381 +26886 +33772 +38175 +54810 +57331 +0 +8557 +17166 +27394 +33489 +37380 +46695 +50489 +55261 +58558 +0 +7939 +18479 +26085 +38040 +47163 +53445 +57185 +0 +7882 +19570 +23724 +32141 +37233 +50331 +57857 +61315 +0 +8148 +17962 +23330 +27280 +36254 +41578 +45530 +50038 +56036 +0 +8607 +18551 +22818 +32010 +40599 +44144 +53853 +57014 +0 +8194 +17696 +22733 +27527 +34757 +42987 +56097 +59120 +0 +8756 +17643 +27758 +32782 +39212 +50996 +56051 +58627 +0 +7991 +16747 +24547 +32418 +47891 +56164 +60348 +0 +8770 +17464 +21750 +31458 +39552 +49558 +56435 +0 +8726 +20137 +24035 +31382 +36786 +40759 +48610 +52296 +56629 +59269 +0 +8537 +16813 +23268 +31124 +39475 +43360 +56394 +59155 +0 +7381 +25447 +30975 +34993 +38524 +54206 +57870 +0 +8058 +17359 +22383 +25915 +34642 +38471 +45686 +55152 +57404 +0 +8888 +16040 +23154 +28042 +40078 +43787 +51117 +55593 +59617 +0 +9185 +22785 +27445 +34065 +42570 +48932 +55411 +63636 +0 +8583 +17610 +25538 +32546 +40167 +44287 +54133 +57870 +0 +8994 +25939 +32018 +38867 +42830 +51600 +55524 +60408 +0 +8969 +16757 +24143 +27709 +35838 +41775 +52624 +56263 +0 diff --git a/project/previous_version/Ad081998_199_WideChopper_psth.txt b/project/previous_version/Ad081998_199_WideChopper_psth.txt new file mode 100644 index 0000000..067dad9 --- /dev/null +++ b/project/previous_version/Ad081998_199_WideChopper_psth.txt @@ -0,0 +1,1392 @@ +0 +11357 +17494 +24137 +30135 +36265 +43783 +49168 +0 +11557 +18522 +26267 +32527 +39541 +46701 +52353 +0 +11035 +19292 +26906 +33080 +39379 +48711 +0 +10344 +19099 +26135 +32604 +40261 +48825 +0 +12672 +20790 +28128 +35671 +42167 +50489 +0 +11721 +19182 +26396 +35512 +44323 +51207 +0 +11617 +19463 +25808 +32472 +40526 +47455 +0 +11495 +18685 +26657 +35143 +41961 +51589 +0 +12765 +20813 +29803 +39294 +47704 +56361 +0 +12261 +20261 +27853 +35546 +42904 +50776 +0 +13111 +20919 +29150 +36280 +43882 +50949 +0 +10022 +17908 +25241 +32060 +39596 +46368 +52966 +0 +13165 +20951 +28519 +35982 +44014 +55462 +0 +12103 +19213 +26908 +34039 +41594 +48407 +58302 +0 +12320 +19676 +29581 +37926 +44876 +53122 +0 +12006 +19479 +28269 +36074 +43610 +51916 +0 +12670 +21992 +29518 +36851 +45615 +54356 +0 +13416 +21453 +29308 +36724 +43478 +53118 +0 +13296 +21221 +28857 +37531 +46702 +55056 +0 +12273 +19923 +27770 +36717 +42983 +50613 +0 +12775 +21302 +28353 +37076 +43796 +53855 +0 +13580 +21557 +29876 +39478 +47145 +54814 +0 +12551 +19722 +27688 +35380 +43562 +52747 +0 +11942 +19271 +27183 +35966 +45935 +54076 +0 +13326 +21325 +28453 +36120 +42557 +53644 +0 +12932 +20618 +28133 +37703 +45106 +52842 +0 +11888 +19484 +26766 +34300 +41937 +50409 +0 +12999 +20926 +28826 +36282 +46296 +0 +13357 +24478 +31665 +39987 +48944 +0 +13288 +21575 +28383 +36159 +45087 +52043 +0 +12493 +20394 +27797 +35398 +46716 +53921 +0 +11947 +21219 +30175 +36880 +47029 +54860 +0 +13614 +23242 +30128 +38641 +46658 +56043 +0 +12022 +19928 +27540 +34275 +45059 +54404 +0 +13554 +22857 +30676 +39458 +47717 +54361 +0 +13118 +21376 +28161 +36167 +44368 +52487 +0 +13510 +21423 +31232 +40615 +47877 +55510 +0 +13513 +21393 +29243 +38755 +46807 +55664 +0 +12913 +20993 +28164 +37619 +44095 +54991 +0 +14176 +21228 +28865 +37207 +44766 +53915 +0 +12637 +20393 +28551 +37696 +48360 +0 +11683 +19555 +26765 +35169 +42350 +54508 +0 +11412 +19588 +26635 +33910 +41142 +49834 +0 +13149 +20735 +27807 +39537 +46080 +0 +11377 +20557 +28225 +34617 +43459 +52026 +0 +12998 +21461 +30856 +38998 +47143 +58026 +0 +12001 +19650 +26968 +34492 +42781 +49495 +0 +11321 +18289 +25462 +35749 +43461 +53603 +0 +11695 +18652 +26881 +35833 +43377 +52097 +0 +12895 +21051 +27173 +35106 +45627 +53097 +0 +9849 +17703 +24783 +33674 +41990 +48771 +0 +11562 +18579 +26343 +34645 +41863 +47789 +0 +12367 +21423 +28534 +35365 +46833 +0 +12971 +22652 +30019 +36988 +45402 +55157 +0 +11431 +18541 +25609 +32824 +39185 +47799 +0 +12651 +20889 +28286 +36361 +44724 +54153 +0 +13360 +22220 +29221 +37090 +44031 +0 +11690 +19473 +27472 +35665 +44108 +51142 +0 +10738 +17783 +26004 +33037 +40683 +49125 +0 +12087 +19553 +26566 +35890 +43738 +56136 +0 +13046 +20850 +28915 +36844 +47424 +55867 +0 +12280 +19963 +27585 +35781 +45689 +54049 +0 +11947 +19556 +27693 +34381 +42550 +51702 +0 +11794 +21435 +28156 +36090 +43281 +53070 +0 +13483 +21465 +28165 +37087 +47494 +54936 +0 +10926 +17736 +24543 +33391 +41556 +50632 +0 +12760 +19664 +26342 +34640 +44285 +51818 +0 +11875 +19002 +26558 +37703 +44683 +52634 +0 +12507 +20230 +26975 +35509 +43792 +51761 +0 +13980 +22630 +32886 +41843 +48742 +0 +12358 +20134 +26794 +34575 +42054 +52507 +0 +13791 +23222 +32056 +41114 +50170 +0 +13578 +22035 +30723 +39155 +47673 +54548 +0 +11692 +18900 +26488 +33950 +42776 +51879 +0 +11461 +19006 +25928 +34694 +43538 +56126 +0 +12570 +21593 +28661 +37003 +46992 +54728 +0 +11192 +20041 +26904 +35799 +45748 +52990 +0 +12525 +20979 +29578 +35997 +44342 +53093 +0 +12741 +20451 +28553 +40466 +50406 +0 +11403 +19051 +26705 +36342 +44305 +53893 +0 +12119 +19720 +28035 +36141 +44188 +53710 +0 +12263 +22319 +31422 +39421 +48093 +0 +11727 +19262 +26137 +33722 +41378 +49686 +0 +12242 +20265 +27349 +34952 +42330 +51148 +0 +13094 +20996 +28831 +37081 +44732 +53625 +0 +10062 +17326 +24944 +33169 +42760 +50357 +0 +13929 +22614 +30748 +37959 +46534 +53893 +0 +10656 +17958 +25138 +32566 +42583 +50193 +0 +14551 +22028 +29027 +38238 +47072 +56590 +0 +9830 +16828 +24480 +30732 +38935 +46619 +56043 +0 +12221 +21384 +28189 +34872 +44580 +53395 +0 +10997 +19339 +27601 +34495 +42349 +51731 +0 +13122 +21387 +30215 +38750 +46790 +57677 +0 +10953 +18575 +26375 +33108 +41262 +50850 +0 +12927 +21311 +28496 +35800 +45299 +0 +11233 +19087 +28364 +35284 +42695 +50647 +0 +12932 +21369 +29720 +37015 +42963 +53571 +0 +13099 +21207 +28774 +37389 +43933 +53939 +0 +11866 +19655 +25979 +32734 +39342 +46408 +53731 +0 +11876 +20715 +27337 +35503 +41532 +49478 +0 +11601 +20027 +27538 +35891 +42830 +54275 +0 +11505 +19660 +26570 +33554 +42338 +49683 +0 +13209 +20618 +28898 +35745 +43289 +51504 +0 +12331 +20062 +27098 +34661 +44310 +51360 +0 +12543 +19692 +28065 +35370 +43753 +52498 +0 +10625 +18852 +27105 +34237 +42112 +50662 +0 +11792 +19555 +26965 +35900 +43890 +52785 +0 +12526 +20255 +27899 +35075 +42715 +49730 +0 +11074 +19259 +26367 +34437 +40801 +48978 +0 +12547 +19924 +26363 +34124 +45018 +51768 +0 +12540 +21034 +28014 +35509 +42169 +51854 +0 +11381 +18663 +27604 +35463 +45397 +54266 +0 +11151 +18818 +26320 +34028 +41619 +50841 +0 +11951 +19678 +26912 +33645 +42423 +50510 +0 +10955 +18526 +25609 +33549 +43683 +55399 +0 +12882 +21342 +28373 +36695 +44563 +52378 +0 +12571 +20504 +28859 +36734 +45217 +52742 +0 +12289 +19576 +27834 +35277 +42689 +49320 +0 +12432 +21774 +28787 +37916 +46918 +0 +10593 +18560 +25928 +36097 +42764 +50149 +0 +12666 +20449 +27256 +34428 +43483 +51843 +0 +13424 +20960 +29008 +36833 +45225 +52513 +0 +12000 +19343 +28483 +38651 +44899 +53632 +0 +11020 +18831 +26776 +34336 +40937 +50163 +0 +12060 +19014 +26598 +36364 +45196 +0 +12336 +20306 +27731 +34993 +43310 +51930 +0 +11428 +19433 +26115 +34760 +42675 +50631 +0 +9856 +18195 +25270 +33698 +40672 +47023 +54653 +0 +12355 +19828 +27058 +37100 +44454 +54744 +0 +12173 +20018 +27843 +35117 +43500 +50558 +0 +12005 +19823 +27013 +34430 +42844 +51344 +0 +11850 +21051 +28564 +36079 +42147 +52961 +0 +11195 +20412 +29146 +36073 +43651 +51823 +0 +11641 +19772 +26780 +34139 +42809 +50716 +0 +10792 +18071 +25980 +33400 +40877 +50676 +0 +10880 +17659 +24619 +32623 +41509 +49806 +0 +12459 +21186 +28289 +35969 +46862 +54142 +0 +11003 +18244 +26411 +35604 +44897 +52931 +0 +12566 +21339 +29256 +38353 +46735 +53689 +0 +11430 +19194 +29117 +37116 +46740 +54604 +0 +12102 +19672 +26420 +36892 +45111 +52557 +0 +11604 +19476 +26790 +37738 +47407 +57368 +0 +10859 +17931 +25978 +35213 +43642 +50823 +0 +11908 +19826 +28385 +35691 +43774 +51844 +0 +10341 +18327 +25710 +34369 +43106 +50355 +0 +9674 +17027 +24009 +31883 +40622 +47975 +0 +11133 +19101 +26925 +33955 +43021 +50384 +0 +12775 +22833 +29544 +37424 +46412 +53805 +0 +12104 +19934 +27007 +34748 +42967 +0 +11337 +18225 +26546 +34556 +43760 +50511 +0 +12926 +19878 +26826 +35001 +43578 +53542 +0 +11218 +18269 +26578 +34043 +42875 +50825 +0 +10882 +18478 +25598 +32941 +40755 +47314 +0 +13373 +21668 +28113 +36972 +46667 +54321 +0 +10666 +18394 +25944 +35413 +42697 +48934 +0 +11741 +18560 +26937 +34409 +43216 +50403 +0 +10426 +17884 +25664 +33524 +43379 +52053 +0 +11400 +18528 +25453 +33245 +42044 +49855 +0 +11131 +18735 +26254 +32858 +45474 +53535 +0 +10924 +18027 +26354 +34212 +40776 +47961 +0 +11325 +19210 +26980 +34904 +44840 +52053 +0 +11068 +20844 +27187 +36192 +44009 +54244 +0 +12135 +20595 +27931 +35167 +41780 +51230 +0 +12623 +20657 +28733 +35980 +43981 +51962 +0 +12236 +19370 +28274 +35391 +41800 +51373 +0 +11764 +19740 +28369 +36237 +44372 +50678 +0 +11538 +19176 +26723 +35214 +43892 +52925 +0 +11964 +20351 +26348 +34365 +42872 +50230 +0 +10385 +17768 +26220 +34370 +42049 +50729 +0 +11801 +18279 +25698 +33417 +41393 +48798 +0 +11244 +19056 +26933 +34714 +42653 +49495 +0 +11999 +20364 +27976 +35164 +43801 +53080 +0 +12018 +20529 +27212 +34153 +41183 +49101 +0 +11888 +21685 +28963 +35811 +42485 +52995 +0 +11128 +18699 +26662 +34341 +45277 +53201 +0 +12337 +21046 +28089 +36343 +47782 +54711 +0 +11610 +18506 +29387 +36476 +45051 +0 +12153 +20093 +28096 +34384 +40972 +50511 +0 +11481 +19675 +27218 +35265 +41953 +50355 +0 +13025 +20698 +29213 +36097 +45889 +52850 +0 +11466 +19201 +26364 +36929 +46212 +54186 +0 +13611 +21908 +29923 +40018 +47951 +0 +12267 +20930 +28632 +36884 +49476 +0 +11931 +20196 +28307 +37447 +44769 +53125 +0 +11022 +18102 +24568 +30757 +38061 +46737 +53625 +0 +11641 +20692 +27868 +35116 +44433 +52890 +0 +11744 +20046 +27153 +34450 +42217 +48697 +0 +9637 +17380 +25405 +33274 +41364 +47810 +0 +10343 +18416 +25818 +32883 +40037 +51732 +0 +9899 +17554 +23620 +30358 +38004 +47837 +53619 +0 +11735 +19329 +27802 +35144 +42641 +50684 +0 +12892 +20236 +28478 +36441 +44333 +51170 +0 +11738 +19748 +27782 +35353 +44494 +52140 +0 +12490 +21405 +28990 +37491 +47080 +55268 +0 +11782 +20080 +27422 +36561 +45447 +53287 +0 +12635 +21098 +30133 +39174 +47828 +55953 +0 +12334 +19636 +27894 +34812 +44545 +52583 +0 +11288 +20065 +27109 +34629 +42454 +52779 +0 +13323 +24855 +33551 +42334 +49586 +0 +10842 +18996 +26626 +33784 +42577 +50864 +0 diff --git a/project/previous_version/histgen.py b/project/previous_version/histgen.py new file mode 100644 index 0000000..fe120db --- /dev/null +++ b/project/previous_version/histgen.py @@ -0,0 +1,96 @@ +# coding: utf-8 + +# In[1]: + + +import os +import sys +import pyqtgraph as pg +import numpy as np + + +# In[7]: + + +dir_path = os.path.abspath("") + +win = pg.GraphicsWindow() +win.setBackground("w") +p1 = win.addPlot( + title="Pauser PSTH", + row=0, + col=0, + labels={"bottom": "T (ms)", "left": "# of spikes"}, +) +p2 = win.addPlot( + title="Buildup PSTH", + row=1, + col=0, + labels={"bottom": "T (ms)", "left": "# of spikes"}, +) +p3 = win.addPlot( + title="Wide Chopper PSTH", + row=2, + col=0, + labels={"bottom": "T (ms)", "left": "# of spikes"}, +) + +# In[ ]: + +bins = np.arange(0, 80, 0.5) + +PB_spike_data = [] +with open("Ad081098_065_PauserBuildup_psth.txt", "r+") as df: + for x in df: + x = x.strip("\n").strip() + x = float(x) * 1e-3 + if x: + PB_spike_data.append(x) +histogram, binedges = np.histogram(PB_spike_data, bins) +p1.plot( + binedges, + histogram, + stepMode=True, + fillBrush=(0, 0, 0, 255), + brush=pg.mkBrush("k"), + fillLevel=0, +) +B_spike_data = [] +with open("Ad041599_062_Buildup_psth.txt", "r+") as df: + for x in df: + x = x.strip("\n").strip() + x = float(x) * 1e-3 + if x: + B_spike_data.append(x) +histogram, binedges = np.histogram(B_spike_data, bins) +p2.plot( + binedges, + histogram, + stepMode=True, + fillBrush=(0, 0, 0, 255), + brush=pg.mkBrush("k"), + fillLevel=0, +) +C_spike_data = [] +with open("Ad081998_199_WideChopper_psth.txt", "r+") as df: + for x in df: + x = x.strip("\n").strip() + x = float(x) * 1e-3 + if x: + C_spike_data.append(x) +histogram, binedges = np.histogram(C_spike_data, bins) +p3.plot( + binedges, + histogram, + stepMode=True, + fillBrush=(0, 0, 0, 255), + brush=pg.mkBrush("k"), + fillLevel=0, +) +# In[ ]: + + +win.show() +print("finished") +if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() diff --git a/project/previous_version/test_network_PSTH.py b/project/previous_version/test_network_PSTH.py new file mode 100644 index 0000000..073df27 --- /dev/null +++ b/project/previous_version/test_network_PSTH.py @@ -0,0 +1,451 @@ +""" +Layout: + + if __name__==__main__ handles cmd args, instantiates test, runs it, displays results + + run_trial(): defines a model and then runs the test using preset params in hoc and return the info to the class + SGCInputTest: + __init__ : defines many static variables + run(): calls delivers information to the run_trial() function and the recieved information of a single run + back and stores it as an exstensible list in the class + show(): displays graphs depending on the graph options selected below it and displayed in a printout + +""" +import argparse +import numpy as np +import pyqtgraph as pg +from neuron import h +from cnmodel.protocols import Protocol +from cnmodel import cells +from cnmodel.util import sound +from cnmodel.util import custom_init +import cnmodel.util.pynrnutilities as PU +from cnmodel import data + +try: + from tqdm import trange +except ImportError: + raise ImportError("Please 'pip install tqdm' to allow for progress bar") + +species = "rat" # tables for other species do not yet exist + + +def run_trial(cell, info): + """ + info is a dict + """ + assert cell == "pyramidal" + post_cell = cells.Pyramidal.create(species=species) + inhib_cell = cells.Tuberculoventral.create() + inhib_cell2 = cells.Tuberculoventral.create() + # dstell = cells.DStellate.create() + pre_cells = [] + synapses = [] + inhib_synapses = [] + for nsgc in range(48): + # attach to pyramidal cell + pre_cells.append(cells.DummySGC(cf=info["cf"], sr=info["sr"])) + synapses.append(pre_cells[-1].connect(post_cell, type=info["synapse_type"])) + pre_cells[-1].set_sound_stim( + info["stim"], seed=info["seed"] + nsgc, simulator=info["simulator"] + ) + synapses[ + -1 + ].terminal.relsite.Dep_Flag = False # no depression in these simulations + for nsgc in range(16): + pre_cells.append(cells.DummySGC(cf=info["cf"], sr=info["sr"])) + inhib_synapses.append( + pre_cells[-1].connect(inhib_cell, type=info["synapse_type"]) + ) + inhib_synapses.append( + pre_cells[-1].connect(inhib_cell2, type=info["synapse_type"]) + ) + pre_cells[-1].set_sound_stim( + info["stim"], seed=info["seed"] + nsgc + 48, simulator=info["simulator"] + ) + synapses[ + -1 + ].terminal.relsite.Dep_Flag = False # no depression in these simulations + # for nsgc in range(20): + # pre_cells.append(cells.DummySGC(cf=info['cf'], sr=info['sr'])) + # inhib_synapses.append(pre_cells[-1].connect(dstell, type=info['synapse_type'])) + # pre_cells[-1].set_sound_stim(info['stim'], seed=info['seed'] + nsgc + 16 + 48, simulator=info['simulator']) + # synapses[-1].terminal.relsite.Dep_Flag = False # no depression in these simulations + for _ in range(21): + inhib_synapses.append(inhib_cell.connect(post_cell, type="simple")) + inhib_synapses.append(inhib_cell2.connect(post_cell, type="simple")) + # for _ in range(15): + # inhib_synapses.append(inhib_cell.connect(dstell, type='simple')) + + Vm = h.Vector() + Vm.record(post_cell.soma(0.5)._ref_v) + Vmtb = h.Vector() + Vmtb.record(inhib_cell.soma(0.5)._ref_v) + rtime = h.Vector() + rtime.record(h._ref_t) + h.tstop = 1e3 * info["run_duration"] # duration of a run + h.celsius = info["temp"] + h.dt = info["dt"] + post_cell.cell_initialize() + info["init"]() + h.t = 0.0 + h.run() + # package data + pre_cells_data = [x._spiketrain for x in pre_cells] + Vm_list = np.array(Vm) + Vmtb_list = np.array(Vmtb) + time_list = np.array(rtime) + # clean up + del ( + pre_cells, + synapses, + inhib_cell, + inhib_synapses, + Vm, + Vmtb, + post_cell, + inhib_cell2, + info, + ) + + return { + "time": time_list, + "vm": Vm_list, + "pre_cells": pre_cells_data, + "vmtb": Vmtb_list, + } + + +class SGCTestPSTH(Protocol): + """ + Tests a Single cell with input recieved from the SGC + + __init__: almost all parameters can be modified + run(): simply loops over the run_trial() function and stores the results just + show(): constructs the graphs using other functions + + """ + + def __init__( + self, + temp=34.0, + seed=2918, + nrep=10, + stimulus="tone", + simulator="cochlea", + n_sgc=12, + debug=True, + cell="pyramidal", + ): + """ + :param temp: (float) must be at 34 for default pyramidal cells + :param dt: (float) determine hoc resolution + :param seed: (int) contributes to randomization, needs to be changed to see different results (reduce this + number if you keep getting a timeout error + :param nrep: (int) number of presentations !!must be changed in the __name__ function if not calling from cmd line!! + :param stimulus: (str) must be 'tone' + :param simulator: (str) currently using cochlea instead of matlab + :param n_sgc:(int) This is the number of SGC fibers that connect to the post synaptic cell + :param debug: (bool) controls most of the terminal printouts is on by default + :param cell: (str) cell type !!must be changed in the __name__ function if not calling from cmd line!! + """ + super().__init__() + assert stimulus == "tone" + assert cell in [ + "bushy", + "tstellate", + "octopus", + "dstellate", + "tuberculoventral", + "pyramidal", + ] + self.debug = debug + self.nrep = nrep + self.stimulus = stimulus + self.run_duration = 0.30 # in seconds + self.pip_duration = 0.05 # in seconds + self.pip_start = [0.1] # in seconds + self.Fs = 100e3 # in Hz + self.f0 = 13000.0 # stimulus in Hz + self.cf = 13000.0 # SGCs in Hz + self.fMod = 100.0 # mod freq, Hz + self.dMod = 0.0 # % mod depth, Hz + self.dbspl = 40.0 + self.simulator = simulator + self.sr = 2 # set SR group + self.seed = seed + self.temp = temp + self.dt = 0.025 + self.cell = cell + self.synapse_type = "multisite" + + if self.stimulus == "tone": + self.stim = sound.TonePip( + rate=self.Fs, + duration=self.run_duration, + f0=self.f0, + dbspl=self.dbspl, + ramp_duration=5e-3, + pip_duration=self.pip_duration, + pip_start=self.pip_start, + ) + + if not n_sgc: + n_sgc = data.get( + "convergence", species="mouse", post_type=self.cell, pre_type="sgc" + )[0] + self.n_sgc = int(np.round(n_sgc)) + # convert nS to uS for NEURON + + self.vms = [None for n in range(self.nrep)] + self.vmtbs = [None for n in range(self.nrep)] + self.synapses = [None for n in range(self.nrep)] + self.pre_cells = [None for n in range(self.nrep)] + self.time = [None for n in range(self.nrep)] + # debug function reports a print out of various information about the run + if self.debug: + print("SGCInputTest Created") + print() + print("Test parameters") + print("#" * 70) + print(f"Running test of {cell} cell synapse with Simulated SGC fibers") + print() + print(f"Run Conditions: Run Time: {self.run_duration}s,") + print(f" Run Temp: {self.temp} ") + print(f" Sgc Connections {n_sgc}") + print(f" Number of Presentations: {nrep}") + print() + print(f"Stimulus Conditions: Type: {stimulus}") + print(f" Stim Duration: {self.pip_duration}s") + print(f" Characteristic F: {self.cf}hz") + print(f" Stim Start:{str(self.pip_start)}s") + + def run(self): + super().run() + info = { + "n_sgc": self.n_sgc, + "stim": self.stim, + "simulator": self.simulator, + "cf": self.cf, + "sr": self.sr, + "seed": self.seed, + "run_duration": self.run_duration, + "synapse_type": self.synapse_type, + "temp": self.temp, + "dt": self.dt, + "init": custom_init, + } + for nr in trange(self.nrep): + info["seed"] = self.seed + self.n_sgc + (nr * (48 + 16 + 20)) + res = run_trial(self.cell, info) + # res contains: {'time': time, 'vm': list(Vm), 'pre_cells': pre_cells._spiketrain,'vmtb': list(Vmtb)} + self.pre_cells[nr] = res["pre_cells"] + self.time[nr] = res["time"] + self.vms[nr] = res["vm"] + self.vmtbs[nr] = res["vmtb"] + + def show(self): + """ + Creates a single page graph that contains all of the graphs based on the graphical functions in the class + + """ + self.win = pg.GraphicsWindow() + self.win.setBackground("w") + p1 = self.stimulus_graph() + p2 = self.an_spike_graph() + p3 = self.pyram_spike_graph() + p4 = self.voltage_graph() + p5 = self.tb_cell_spike_graph() + p6 = ( + self.an_psth_graph() + ) # requires that an_spikes_graph() has been called before + p7 = ( + self.cell_psth_graph() + ) # requires that cell_spikes_graph() has been called before + + # links x axis + p1.setXLink(p1) + p2.setXLink(p1) + p3.setXLink(p1) + p4.setXLink(p1) + p5.setXLink(p1) + p6.setXLink(p1) + p7.setXLink(p1) + self.win.show() + if self.debug: + print("finished") + + ############# Graph options to be included in the show() method ################### + def stimulus_graph(self): + p1 = self.win.addPlot( + title="Stimulus", row=0, col=0, labels={"bottom": "T (ms)", "left": "V"} + ) + p1.plot(self.stim.time * 1000, self.stim.sound, pen=pg.mkPen("k", width=0.75)) + return p1 + + def an_spike_graph(self): + p2 = self.win.addPlot( + title="AN spikes", + row=1, + col=0, + labels={"bottom": "T (ms)", "left": "AN spikes (first trial)"}, + ) + self.all_xan = [] + for nr in range(self.nrep): + xan = [] + yan = [] + for k in range(len(self.pre_cells[nr])): + r = self.pre_cells[nr][k] + xan.extend(r) + self.all_xan.extend(r) + yr = k + np.zeros_like(r) + 0.2 + yan.extend(yr) + c = pg.PlotCurveItem() + xp = np.repeat(np.array(xan), 2) + yp = np.repeat(np.array(yan), 2) + yp[1::2] = yp[::2] + 0.6 + c.setData( + xp.flatten(), + yp.flatten(), + connect="pairs", + width=1.0, + pen=pg.mkPen("k", width=1.5), + ) + p2.addItem(c) + + return p2 + + def pyram_spike_graph(self): + p3 = self.win.addPlot( + title="Pyramidal Spikes", + row=2, + col=0, + labels={"bottom": "T (ms)", "left": "Trial #"}, + ) + xcn = [] + ycn = [] + for k in range(self.nrep): + bspk = PU.findspikes(self.time[k], self.vms[k], -35.0) + xcn.extend(bspk) + yr = k + np.zeros_like(bspk) + 0.2 + ycn.extend(yr) + d = pg.PlotCurveItem() + xp = np.repeat(np.array(xcn), 2) + yp = np.repeat(np.array(ycn), 2) + yp[1::2] = yp[::2] + 0.6 + d.setData( + xp.flatten(), yp.flatten(), connect="pairs", pen=pg.mkPen("k", width=1.5) + ) + self.xcn = xcn + self.ycn = ycn + p3.addItem(d) + + return p3 + + def voltage_graph(self): + p4 = self.win.addPlot( + title="%s Vm" % self.cell, + row=0, + col=1, + labels={"bottom": "T (ms)", "left": "Vm (mV)"}, + ) + if self.nrep > 3: + display = 3 + else: + display = self.nrep + for nr in range(display): + p4.plot( + self.time[nr], + self.vms[nr], + pen=pg.mkPen(pg.intColor(nr, self.nrep), hues=self.nrep, width=1.0), + ) + return p4 + + def tb_cell_spike_graph(self): + p5 = self.win.addPlot( + title="Tuberculoventral Spikes", + row=3, + col=0, + labels={"bottom": "T (ms)", "left": "Trial #"}, + ) + xtcn = [] + ytcn = [] + for k in range(self.nrep): + bspk = PU.findspikes(self.time[k], self.vmtbs[k], -35.0) + xtcn.extend(bspk) + yr = k + np.zeros_like(bspk) + 0.2 + ytcn.extend(yr) + d = pg.PlotCurveItem() + xp = np.repeat(np.array(xtcn), 2) + yp = np.repeat(np.array(ytcn), 2) + yp[1::2] = yp[::2] + 0.6 + d.setData( + xp.flatten(), yp.flatten(), connect="pairs", pen=pg.mkPen("k", width=1.5) + ) + p5.addItem(d) + + return p5 + + def an_psth_graph(self): + p6 = self.win.addPlot( + title="AN PSTH", + row=1, + col=1, + labels={"bottom": "T (ms)", "left": "Sp/ms/trial"}, + ) + bins = np.arange(50, 200, 1) + (hist, binedges) = np.histogram(self.all_xan, bins) + curve6 = p6.plot( + binedges, + hist, + stepMode=True, + fillBrush=(0, 0, 0, 255), + brush=pg.mkBrush("k"), + fillLevel=0, + ) + return p6 + + def cell_psth_graph(self): + p7 = self.win.addPlot( + title="Pyramidal PSTH", + row=2, + col=1, + labels={"bottom": "T (ms)", "left": "Sp/ms/trial"}, + ) + bins = np.arange(50, 200, 1) + (hist, binedges) = np.histogram(self.xcn, bins) + curve7 = p7.plot( + binedges, + hist, + stepMode=True, + fillBrush=(0, 0, 0, 255), + brush=pg.mkBrush("k"), + fillLevel=0, + ) + return p7 + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Compute AN only PSTH in postsynaptic cell" + ) + parser.add_argument( + "-n", + "--nrep", + type=int, + dest="nrep", + default=10, + help="Set number of repetitions", + ) + + args = parser.parse_args() + + nrep = args.nrep + prot = SGCTestPSTH(nrep=50) + prot.run() + prot.show() + + import sys + + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() diff --git a/project/previous_version/test_single_cell_psth.py b/project/previous_version/test_single_cell_psth.py new file mode 100644 index 0000000..4bf60f4 --- /dev/null +++ b/project/previous_version/test_single_cell_psth.py @@ -0,0 +1,412 @@ +""" +Layout: + + if __name__==__main__ handles cmd args, instantiates test, runs it, displays results + + run_trial(): defines a model and then runs the test using preset params in hoc and return the info to the class + SGCInputTest: + __init__ : defines many static variables + run(): calls delivers information to the run_trial() function and the recieved information of a single run + back and stores it as an exstensible list in the class + show(): displays graphs depending on the graph options selected below it and displayed in a printout + +""" +import argparse +import numpy as np +import pyqtgraph as pg +from neuron import h +from cnmodel.protocols import Protocol +from cnmodel import cells +from cnmodel.util import sound +from cnmodel.util import custom_init +import cnmodel.util.pynrnutilities as PU +from cnmodel import data + +try: + from tqdm import trange +except ImportError as err: + raise ImportError("Please 'pip install tqdm' to allow for progress bar") + +species = "rat" # tables for other species do not yet exist + + +def run_trial(cell, info): + """ + info is a dict + """ + if cell == "bushy": + post_cell = cells.Bushy.create(species=species) + elif cell == "tstellate": + post_cell = cells.TStellate.create(species=species) + elif cell == "octopus": + post_cell = cells.Octopus.create(species=species) + elif cell == "dstellate": + post_cell = cells.DStellate.create(species=species) + elif cell == "tuberculoventral": + post_cell = cells.DStellate.create(species=species) + elif cell == "pyramidal": + post_cell = cells.Pyramidal.create(species=species) + else: + raise ValueError("cell %s is not yet implemented for PSTH testing" % cell) + pre_cells = [] + synapses = [] + for nsgc, sgc in enumerate(range(info["n_sgc"])): + pre_cells.append(cells.DummySGC(cf=info["cf"], sr=info["sr"])) + synapses.append(pre_cells[-1].connect(post_cell, type=info["synapse_type"])) + synapses[ + -1 + ].terminal.relsite.Dep_Flag = False # no depression in these simulations + pre_cells[-1].set_sound_stim( + info["stim"], seed=info["seed"] + nsgc, simulator=info["simulator"] + ) + + # stim = insert_current_clamp(post_cell.soma) + Vm = h.Vector() + Vm.record(post_cell.soma(0.5)._ref_v) + rtime = h.Vector() + rtime.record(h._ref_t) + h.tstop = 1e3 * info["run_duration"] # duration of a run + h.celsius = info["temp"] + h.dt = info["dt"] + post_cell.cell_initialize() + info["init"](v_init=-60) + h.t = 0.0 + h.run() + pre_cells_data = [x._spiketrain for x in pre_cells] + + return {"time": np.array(rtime), "vm": list(Vm), "pre_cells": pre_cells_data} + + +# stim = insert_current_clamp(post_cell.soma) +def insert_current_clamp(sec): + """ + :param sec: to attach too + dur: ms + amp: nA + delay: ms + :return: stim needs to be put in a variable to stay alive + """ + stim = h.IClamp(0.5, sec=sec) + stim.dur = 90 + stim.amp = -0.2 + stim.delay = 2 + return stim + + +class SGCTestPSTH(Protocol): + """ + Tests a Single cell with input recieved from the SGC + + __init__: almost all parameters can be modified + run(): simply loops over the run_trial() function and stores the results just + show(): constructs the graphs using other functions + + """ + + def __init__( + self, + temp=34.0, + seed=5908035, + nrep=10, + stimulus="tone", + simulator="cochlea", + n_sgc=12, + debug=True, + cell="bushy", + ): + """ + :param temp: (float) must be at 34 for default pyramidal cells + :param dt: (float) determine hoc resolution + :param seed: (int) contributes to randomization, needs to be changed to see different results (reduce this + number if you keep getting a timeout error + :param nrep: (int) number of presentations !!must be changed in the __name__ function if not calling from cmd line!! + :param stimulus: (str) must be 'tone' + :param simulator: (str) currently using cochlea instead of matlab + :param n_sgc:(int) This is the number of SGC fibers that connect to the post synaptic cell + :param debug: (bool) controls most of the terminal printouts is on by default + :param cell: (str) cell type !!must be changed in the __name__ function if not calling from cmd line!! + """ + super().__init__() + assert stimulus == "tone" + assert cell in [ + "bushy", + "tstellate", + "octopus", + "dstellate", + "tuberculoventral", + "pyramidal", + ] + self.debug = debug + self.nrep = nrep + self.stimulus = stimulus + self.run_duration = 0.30 # in seconds + self.pip_duration = 0.05 # in seconds + self.pip_start = [0.1] # in seconds + self.Fs = 100e3 # in Hz + self.f0 = 13000.0 # stimulus in Hz + self.cf = 13000.0 # SGCs in Hz + self.fMod = 100.0 # mod freq, Hz + self.dMod = 0.0 # % mod depth, Hz + self.dbspl = 55.0 + self.simulator = simulator + self.sr = 2 # set SR group + self.seed = seed + self.temp = temp + self.dt = 0.025 + self.cell = cell + self.synapse_type = "multisite" + + if self.stimulus == "tone": + self.stim = sound.TonePip( + rate=self.Fs, + duration=self.run_duration, + f0=self.f0, + dbspl=self.dbspl, + ramp_duration=2.5e-3, + pip_duration=self.pip_duration, + pip_start=self.pip_start, + ) + + if not n_sgc: + n_sgc = data.get( + "convergence", species="mouse", post_type=self.cell, pre_type="sgc" + )[0] + self.n_sgc = int(np.round(n_sgc)) + # convert nS to uS for NEURON + + self.vms = [None for n in range(self.nrep)] + self.synapses = [None for n in range(self.nrep)] + self.pre_cells = [None for n in range(self.nrep)] + self.time = [None for n in range(self.nrep)] + # debug function reports a print out of various information about the run + if self.debug: + print("SGCInputTest Created") + print() + print("Test parameters") + print("#" * 70) + print(f"Running test of {cell} cell synapse with Simulated SGC fibers") + print() + print(f"Run Conditions: Run Time: {self.run_duration}s,") + print(f" Run Temp: {self.temp} ") + print(f" Sgc Connections {n_sgc}") + print(f" Number of Presentations: {nrep}") + print() + print(f"Stimulus Conditions: Type: {stimulus}") + print(f" Stim Duration: {self.pip_duration}s") + print(f" Characteristic F: {self.cf}hz") + print(f" Stim Start:{str(self.pip_start)}s") + + def run(self): + super().run() + info = { + "n_sgc": self.n_sgc, + "stim": self.stim, + "simulator": self.simulator, + "cf": self.cf, + "sr": self.sr, + "seed": self.seed, + "run_duration": self.run_duration, + "synapse_type": self.synapse_type, + "temp": self.temp, + "dt": self.dt, + "init": custom_init, + } + for nr in trange(self.nrep): + info["seed"] = self.seed + self.n_sgc + nr + 3 + res = run_trial(self.cell, info) + # res contains: {'time': time, 'vm': list(Vm), 'pre_cells': pre_cells._spiketrain,} + self.pre_cells[nr] = res["pre_cells"] + self.time[nr] = res["time"] + self.vms[nr] = res["vm"] + + def show(self): + """ + Creates a single page graph that contains all of the graphs based on the graphical functions in the class + + """ + self.win = pg.GraphicsWindow() + self.win.setBackground("w") + p1 = self.stimulus_graph() + p2 = self.an_spikes_graph() + p3 = self.cell_spikes_graph() + p4 = self.voltage_graph() + p6 = ( + self.an_psth_graph() + ) # requires that an_spikes_graph() has been called before + p7 = ( + self.cell_psth_graph() + ) # requires that cell_spikes_graph() has been called before + + # links x axis + p1.setXLink(p1) + p2.setXLink(p1) + p3.setXLink(p1) + p4.setXLink(p1) + self.win.show() + if self.debug: + print("finished") + + ############# Graph options to be included in the show() method ################### + def stimulus_graph(self): + p1 = self.win.addPlot( + title="Single Tone Stimulus", row=0, col=0, labels={"bottom": "T (ms)"} + ) + p1.plot(self.stim.time * 1000, self.stim.sound, pen=pg.mkPen("k", width=0.75)) + return p1 + + def an_spikes_graph(self): + p2 = self.win.addPlot( + title="AN spikes", + row=1, + col=0, + labels={"bottom": "T (ms)", "left": "AN spikes (first trial)"}, + ) + self.all_xan = [] + for nr in range(self.nrep): + xan = [] + yan = [] + for k in range(len(self.pre_cells[nr])): + r = self.pre_cells[nr][k] + xan.extend(r) + self.all_xan.extend(r) + yr = k + np.zeros_like(r) + 0.2 + yan.extend(yr) + c = pg.PlotCurveItem() + xp = np.repeat(np.array(xan), 2) + yp = np.repeat(np.array(yan), 2) + yp[1::2] = yp[::2] + 0.6 + c.setData( + xp.flatten(), + yp.flatten(), + connect="pairs", + width=1.0, + pen=pg.mkPen("k", width=1.5), + ) + p2.addItem(c) + + return p2 + + def cell_spikes_graph(self): + p3 = self.win.addPlot( + title="Pyramidal Cell Spikes", + row=2, + col=0, + labels={"bottom": "T (ms)", "left": "Trial #"}, + ) + xcn = [] + ycn = [] + for k in range(self.nrep): + bspk = PU.findspikes(self.time[k], self.vms[k], -35.0) + xcn.extend(bspk) + yr = k + np.zeros_like(bspk) + 0.2 + ycn.extend(yr) + d = pg.PlotCurveItem() + xp = np.repeat(np.array(xcn), 2) + yp = np.repeat(np.array(ycn), 2) + yp[1::2] = yp[::2] + 0.6 + d.setData( + xp.flatten(), yp.flatten(), connect="pairs", pen=pg.mkPen("k", width=1.5) + ) + self.xcn = xcn + self.ycn = ycn + p3.addItem(d) + + return p3 + + def voltage_graph(self): + p4 = self.win.addPlot( + title="Pyramidal Vm", + row=0, + col=1, + labels={"bottom": "T (ms)", "left": "Vm (mV)"}, + ) + if self.nrep > 5: + display = 3 + else: + display = self.nrep + for nr in range(display): + p4.plot( + self.time[nr], + self.vms[nr], + pen=pg.mkPen(pg.intColor(nr, self.nrep), hues=self.nrep, width=1.0), + ) + return p4 + + def an_psth_graph(self): + p6 = self.win.addPlot( + title="AN PSTH", + row=1, + col=1, + labels={"bottom": "T (ms)", "left": "# of Spikes(0.75ms"}, + ) + bins = np.arange(60, 200, 0.5) + (hist, binedges) = np.histogram(self.all_xan, bins) + curve6 = p6.plot( + binedges, + hist, + stepMode=True, + fillBrush=(0, 0, 0, 255), + brush=pg.mkBrush("k"), + fillLevel=0, + ) + return p6 + + def cell_psth_graph(self): + p7 = self.win.addPlot( + title="Pyramidal PSTH", + row=2, + col=1, + labels={"bottom": "T (ms)", "left": "# of Spikes(0.75ms)"}, + ) + bins = np.arange(60, 200, 0.5) + (hist, binedges) = np.histogram(self.xcn, bins) + curve7 = p7.plot( + binedges, + hist, + stepMode=True, + fillBrush=(0, 0, 0, 255), + brush=pg.mkBrush("k"), + fillLevel=0, + ) + return p7 + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description="Compute AN only PSTH in postsynaptic cell" + ) + parser.add_argument( + type=str, + dest="cell", + default="pyramidal", + choices=[ + "bushy", + "tstellate", + "dstellate", + "octopus", + "tuberculoventral", + "pyramidal", + ], + help="Select target cell", + ) + parser.add_argument( + "-n", + "--nrep", + type=int, + dest="nrep", + default=1, + help="Set number of repetitions", + ) + + args = parser.parse_args() + + cell = args.cell + nrep = args.nrep + prot = SGCTestPSTH(nrep=100, cell=cell) + prot.run() + prot.show() + + import sys + + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() diff --git a/project/previous_version/tone_pyram_sgc_input_PSTH2.7.py b/project/previous_version/tone_pyram_sgc_input_PSTH2.7.py new file mode 100644 index 0000000..1b15768 --- /dev/null +++ b/project/previous_version/tone_pyram_sgc_input_PSTH2.7.py @@ -0,0 +1,397 @@ +""" +The Assumptions of this cell are modified to the test_sgc_input_PSTH.py but should be identical in function + +synapse type = simple +synapse type = single +species = mouse +sgc = dummy SGC lacks cell body +cell connection = pyramidal + + + +""" + +import sys +import numpy as np +import pyqtgraph as pg +from neuron import h +from cnmodel.protocols import Protocol +from cnmodel import cells +from cnmodel.util import sound +from cnmodel.util import custom_init +import cnmodel.util.pynrnutilities as PU +from cnmodel import data + +synapseType = "simple" # no other options exist +species = "mouse" # tables for other species do not yet exist + + +def main(): + prot = SGCInputTestPSTH(seed=1233451898) + prot.run() + prot.show() + if sys.flags.interactive == 0: + pg.QtGui.QApplication.exec_() + + +class SGCInputTestPSTH(Protocol): + def __init__(self, temp=34.0, dt=0.025, seed=575982035): + """ + :param temp: Celcius + :param dt: resolution in ms + :param seed: seed should be generated randomly + + Pre-determined variables that can be changed by editing the value next to them + + AMPA_gmax and n_sgc = loaded from data that is kept in cnmodel/data dir + + Defines a single tone parameters with which to test the neuron complex + """ + # super only defines reset function + super(SGCInputTestPSTH, self).__init__() + # + self.temp = temp + self.dt = dt + self.seed = seed + self.simulator = "cochlea" + # predetermined variables + self.cell = "pyramidal" + self.nrep = 50 # number of repetitions + self.stimulus = "tone" + self.Fs = 100e3 # in Hz + self.f0 = 4000.0 # stimulus in Hz + self.cf = 4000.0 # SGCs in Hz + self.fMod = 100.0 # mod freq, Hz + self.dMod = 0.0 # % mod depth, Hz + self.dbspl = 50.0 + self.sr = 2 # set SR group + + # variables loaded from data + AMPA_gmax, n_sgc = self.load_variables_from_data() + self.n_sgc = int(np.round(n_sgc)) + + # value needed for simple synapses + self.AMPA_gmax = AMPA_gmax + + # the stimulation delivered is a Tone + self.run_duration = 0.20 # in seconds + self.pip_duration = 0.05 # in seconds + self.pip_start = [0.1] # in seconds + self.f0 = 4000.0 + self.cf = 4000.0 + self.stim = sound.TonePip( + rate=self.Fs, + duration=self.run_duration, + f0=self.f0, + dbspl=self.dbspl, + ramp_duration=2.5e-3, + pip_duration=self.pip_duration, + pip_start=self.pip_start, + ) + + # creates empty lists that will contain the results of each rep + self.vms = [None for n in range(self.nrep)] + self.synapses = [None for n in range(self.nrep)] + self.xmtrs = [None for n in range(self.nrep)] + self.pre_cells = [None for n in range(self.nrep)] + self.time = [None for n in range(self.nrep)] + + def load_variables_from_data(self): + AMPA_gmax = ( + data.get( + "sgc_synapse", species=species, post_type=self.cell, field="AMPA_gmax" + )[0] + / 1e3 + ) + n_sgc = data.get( + "convergence", species=species, post_type=self.cell, pre_type="sgc" + )[0] + print(n_sgc) + return AMPA_gmax, n_sgc + + def check_assertations(self): + assert self.cell in [ + "bushy", + "tstellate", + "octopus", + "dstellate", + "tuberculoventral", + "pyramidal", + ] + assert self.stimulus == "tone" # cases available + assert synapseType == "simple" + + def run(self): + self.check_assertations() + # info based on the parameters set in the __init__ statement + info = { + "n_sgc": self.n_sgc, + "gmax": self.AMPA_gmax, + "stim": self.stim, + "simulator": self.simulator, + "cf": self.cf, + "sr": self.sr, + "seed": self.seed, + "run_duration": self.run_duration, + "temp": self.temp, + "dt": self.dt, + "init": custom_init, + } + + # run number of trials based on nrep defined in __init__ statement + for nr in range(self.nrep): + info["seed"] = self.seed + 3 * self.n_sgc * nr + res = run_trial(info) + # res contains: {'time': time, 'vm': Vm, 'xmtr': xmtr, 'pre_cells': pre_cells, 'post_cell': post_cell} + + # unpacks the res dict returned from the run_trial() into refrenceable variables + self.pre_cells[nr] = res["pre_cells"] + self.time[nr] = res["time"] + self.xmtr = {k: v.to_python() for k, v in res["xmtr"].items()} + self.vms[nr] = res["vm"] + self.synapses[nr] = res["synapses"] + self.xmtrs[nr] = self.xmtr + + def show(self): + """ + Creates a single page graph that contains all of the graphs based on the graphical functions in the class + + """ + self.win = pg.GraphicsWindow() + self.win.setBackground("w") + p1 = self.stimulus_graph() + p2 = self.an_spikes_graph() + p3 = self.cell_spikes_graph() + p4 = self.voltage_graph() + p5 = self.xmtr_graph() + p6 = ( + self.an_psth_graph() + ) # requires that an_spikes_graph() has been called before + p7 = ( + self.cell_psth_graph() + ) # requires that cell_spikes_graph() has been called before + + # links x axis + p1.setXLink(p1) + p2.setXLink(p1) + p3.setXLink(p1) + p4.setXLink(p1) + p5.setXLink(p1) + self.win.show() + + ############# Graph options to be included in the show() method ################### + def stimulus_graph(self): + p1 = self.win.addPlot( + title="Stimulus", row=0, col=0, labels={"bottom": "T (ms)", "left": "V"} + ) + p1.plot( + self.stim.time * 1000, self.stim.sound, pen=pg.mkPen("k", width=0.75) + ) + return p1 + + def an_spikes_graph(self): + p2 = self.win.addPlot( + title="AN spikes", + row=1, + col=0, + labels={"bottom": "T (ms)", "left": "AN spikes (first trial)"}, + ) + for nr in range(self.nrep): + xan = [] + yan = [] + for k in range(len(self.pre_cells[nr])): + r = self.pre_cells[nr][k]._spiketrain + xan.extend(r) + yr = k + np.zeros_like(r) + 0.2 + yan.extend(yr) + c = pg.PlotCurveItem() + xp = np.repeat(np.array(xan), 2) + yp = np.repeat(np.array(yan), 2) + yp[1::2] = yp[::2] + 0.6 + c.setData( + xp.flatten(), + yp.flatten(), + connect="pairs", + pen=pg.mkPen(pg.intColor(nr, self.nrep), hues=self.nrep, width=1.0), + ) + self.xan = xan + self.yan = yan + p2.addItem(c) + return p2 + + def cell_spikes_graph(self): + p3 = self.win.addPlot( + title="%s Spikes" % self.cell, + row=2, + col=0, + labels={"bottom": "T (ms)", "left": "Trial #"}, + ) + xcn = [] + ycn = [] + xspks = [] + for k in range(self.nrep): + bspk = PU.findspikes(self.time[k], self.vms[k], -35.0) + xcn.extend(bspk) + yr = k + np.zeros_like(bspk) + 0.2 + ycn.extend(yr) + d = pg.PlotCurveItem() + xp = np.repeat(np.array(xcn), 2) + yp = np.repeat(np.array(ycn), 2) + yp[1::2] = yp[::2] + 0.6 + d.setData( + xp.flatten(), + yp.flatten(), + connect="pairs", + pen=pg.mkPen("k", width=1.5), + ) + self.xcn = xcn + self.ycn = ycn + p3.addItem(d) + + return p3 + + def voltage_graph(self): + p4 = self.win.addPlot( + title="%s Vm" % self.cell, + row=3, + col=0, + labels={"bottom": "T (ms)", "left": "Vm (mV)"}, + ) + for nr in range(self.nrep): + p4.plot( + self.time[nr], + self.vms[nr], + pen=pg.mkPen(pg.intColor(nr, self.nrep), hues=self.nrep, width=1.0), + ) + return p4 + + def xmtr_graph(self): + p5 = self.win.addPlot( + title="xmtr", row=0, col=1, labels={"bottom": "T (ms)", "left": "gSyn"} + ) + if synapseType == "multisite": + for nr in [0]: + syn = self.synapses[nr] + j = 0 + for k in range(self.n_sgc): + synapse = syn[k] + for i in range(synapse.terminal.n_rzones): + p5.plot( + self.time[nr], + self.xmtrs[nr]["xmtr%04d" % j], + pen=pg.mkPen( + pg.intColor(nr, self.nrep), + hues=self.nrep, + width=1.0, + ), + ) + j = j + 1 + return p5 + + def an_psth_graph(self): + p6 = self.win.addPlot( + title="AN PSTH", + row=1, + col=1, + labels={"bottom": "T (ms)", "left": "Sp/ms/trial"}, + ) + bins = np.arange(0, 200, 1) + (hist, binedges) = np.histogram(self.xan, bins) + curve6 = p6.plot( + binedges, + hist, + stepMode=True, + fillBrush=(0, 0, 0, 255), + brush=pg.mkBrush("k"), + fillLevel=0, + ) + return p6 + + def cell_psth_graph(self): + p7 = self.win.addPlot( + title="%s PSTH" % self.cell, + row=2, + col=1, + labels={"bottom": "T (ms)", "left": "Sp/ms/trial"}, + ) + bins = np.arange(0, 200, 1) + (hist, binedges) = np.histogram(self.xcn, bins) + curve7 = p7.plot( + binedges, + hist, + stepMode=True, + fillBrush=(0, 0, 0, 255), + brush=pg.mkBrush("k"), + fillLevel=0, + ) + return p7 + + +def run_trial(info): + """ + This function is really the bread + and butter of the run and determines the layout + of the model and the stimulus is + created and delivered by the SGC. + + Runs a single trial and returns it + into another dictionary that is stored + before the next trial is run. + + :param info: dict containing :'n_sgc': self.n_sgc, + 'gmax': self.AMPA_gmax, + 'stim': self.stim, + 'simulator': self.simulator, + 'cf': self.cf, 'sr': self.sr, + 'seed': self.seed, + 'run_duration': self.run_duration, + 'temp': self.temp, + 'dt': self.dt, + 'init': custom_init + + post cell allowed to use defaults in the case of things like pyramidal cells are guinea pigs instead of a mouse + """ + # for the model to change the post_cell needs to be changed here otherwise the model will not be changed. + # special consideration needs to be taken because not all cell parameters are universal + # ex: Pyramidal does not have a species='mouse', nothing just assumes a default and not all defaults are the same + post_cell = cells.Pyramidal.create() + pre_cells = [] + synapses = [] + xmtr = {} + + # connects all of the SGC fibers to the post_cell using simple synapses and then generates a sound stim based on a + # seed the number of repetitions desired + for nsgc, sgc in enumerate(range(info["n_sgc"])): + pre_cells.append(cells.DummySGC(cf=info["cf"], sr=info["sr"])) + synapses.append(pre_cells[-1].connect(post_cell, type="simple")) + synapses[-1].terminal.netcon.weight[0] = info["gmax"] + + # sets sounds stim for each of the SGC fibers independently + pre_cells[-1].set_sound_stim( + info["stim"], seed=info["seed"] + nsgc, simulator=info["simulator"] + ) + + # Recording each trial and returning it as a dictionary + Vm = h.Vector() + Vm.record(post_cell.soma(0.5)._ref_v) + rtime = h.Vector() + rtime.record(h._ref_t) + h.tstop = 1e3 * info["run_duration"] # duration of a run + h.celsius = info["temp"] + h.dt = info["dt"] + post_cell.cell_initialize() + info["init"]() + h.t = 0.0 + h.run() + return { + "time": np.array(rtime), + "vm": Vm.to_python(), + "xmtr": xmtr, + "pre_cells": pre_cells, + "post_cell": post_cell, + "synapses": synapses, + } + + +if __name__ == "__main__": + main() diff --git a/project/util/__init__.py b/project/util/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/project/util/tools.py b/project/util/tools.py new file mode 100644 index 0000000..146c4b4 --- /dev/null +++ b/project/util/tools.py @@ -0,0 +1,35 @@ +import functools +import time + + +class Clock(object): + """ + This is a decorator for the purpose of timing + functions and classes, it can be added to any function + and during runtime will spit out a formatted str + that displays function(arguments) and results with + a time delta. Uses pref_counter() not time() + """ + + def __init__(self, func): + self.func = func + functools.update_wrapper(self, func) + + def __call__(self, *args, **kwargs): + t0 = time.perf_counter() + result = self.func(*args, **kwargs) + elapsed = time.perf_counter() - t0 + name = self.func.__name__ + arg_lst = [] + if args: + arg_lst.extend(repr(arg) for arg in args) + if kwargs: + arg_lst.extend("{}={}".format(k, w) for k, w in kwargs.items()) + arg_str = ", ".join(arg_lst) + print( + "TIME TRIAL: {:s}({:.30s}~) -> {!r:.30}~ dt=[{:.8}]".format( + name, arg_str, result, elapsed + ) + ) + print() + return result diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..ca44e8d --- /dev/null +++ b/setup.py @@ -0,0 +1,25 @@ +from setuptools import setup, find_packages +import os + +path = os.path.join(os.path.dirname(__file__), "cnmodel") +version = None +for line in open(os.path.join(path, "__init__.py"), "r").readlines(): + if line.startswith("__version__"): + version = line.partition("=")[2].strip("\"' \n") + break +if version is None: + raise Exception("Could not read __version__ from cnmodel/__init__.py") + + +setup( + name="cnmodel", + version=version, + description="A biophysically realistic model of the cochlear nucleus", + url="http://github.com/pbmanis/cnmodel", + author="Paul B. Manis and Luke Campagnola", + author_email="pmanis@med.unc.edu", + license="MIT", + packages=find_packages(include=["cnmodel*"]), + zip_safe=False, + install_requires=['cochlea', 'lmfit', 'tqdm', 'resampy'] +) diff --git a/test.py b/test.py new file mode 100644 index 0000000..a87bb4a --- /dev/null +++ b/test.py @@ -0,0 +1,48 @@ +from __future__ import print_function + +""" +Run unit tests for cnmodel +""" + +import os, sys +import pytest + + +def runtests(): + # Make sure we look for cnmodel here first. + path = os.path.dirname(__file__) + sys.path.insert(0, path) + + # Allow user to audit tests with --audit flag + import cnmodel + + if "--audit" in sys.argv: + sys.argv.remove("--audit") + sys.argv.append("-s") # needed for cli-based user interaction + cnmodel.AUDIT_TESTS = True + + # generate test flags + flags = sys.argv[1:] + flags.append("-v") + tb = [flag for flag in flags if flag.startswith("--tb")] + if len(tb) == 0: + flags.append("--tb=short") + + add_path = True + for flag in flags: + if os.path.isdir(flag) or os.path.isfile(flag): + add_path = False + break + if add_path: + flags.append("cnmodel/") + + # ignore the an cache + flags.append("--ignore=cnmodel/an_model/cache/") + + # Start tests. + print("Testing with flags: %s" % " ".join(flags)) + pytest.main(flags) + + +if __name__ == "__main__": + runtests() diff --git a/todo.rst b/todo.rst new file mode 100644 index 0000000..48acb70 --- /dev/null +++ b/todo.rst @@ -0,0 +1,44 @@ +Things tested and to do: + +ccstim: called by test_stim, but does ot appear to exist. +stim does not provide all the protocols tested in test_stim + +test_circuit.py: + File "test_circuit.py", line 42, in + bushy.resolve_inputs(depth=2) + File "/Users/pbmanis/Desktop/Python/cnmodel/cnmodel/populations/population.py", line 133, in resolve_inputs + pre_cells = self.connect_pop_to_cell(pop, i) + File "/Users/pbmanis/Desktop/Python/cnmodel/cnmodel/populations/population.py", line 166, in connect_pop_to_cell + pre_cell.connect(cell) + File "/Users/pbmanis/Desktop/Python/cnmodel/cnmodel/cells/cell.py", line 217, in connect + synapse = synapses.Synapse(self, pre_opts, post_cell, post_opts, **kwds) + File "/Users/pbmanis/Desktop/Python/cnmodel/cnmodel/synapses/synapse.py", line 13, in __init__ + self.terminal = pre_cell.make_terminal(post_cell, **pre_opts) + File "/Users/pbmanis/Desktop/Python/cnmodel/cnmodel/cells/cell.py", line 246, in make_terminal + post_cell.__class__.__name__)) + NotImplementedError: Cannot make Terminal connecting TStellateRothman => BushyRothman + +test_mechanisms: + some mechanisms do not make sense to be tested in this routine; need to exclude (done) + + +test_physiology: ok + +test_populations : not sure what this is supposed to do. + +test_sgc_input.py : works. + +test_sgc_input_phaselocking: no bushy cell spikes. Is inputs strength scaled correctly? + +test_simple_synapses works. + +test_sound_stim works + +test_synapses (more detailed test) works + +toy_model : works. + + + + +