diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b82bd79..df06999 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,25 +13,26 @@ jobs: strategy: fail-fast: false matrix: - python-version: [ 3.8, 3.9, "3.10" ] + python-version: [ 3.9, "3.10", "3.11", "3.12" ] engine: [ jNeuroML, jNeuroML_NEURON, jNeuroML_NetPyNE, jNeuroML_validate, jNeuroML_PyNN_NEURON ] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v3 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} + - name: Install OMV run: | pip install git+https://github.com/OpenSourceBrain/osb-model-validation pip install scipy sympy matplotlib cython pandas tables - pip install 'numpy<=1.23.0' # see https://github.com/OpenSourceBrain/osb-model-validation/issues/91 - - name: Run OMV tests on engine ${{ matrix.engine }} run: | omv all -V --engine=${{ matrix.engine }} + - name: OMV final version info run: | omv list -V # list installed engines diff --git a/.github/workflows/non_omv.yml b/.github/workflows/non_omv.yml index ec62919..4254e60 100644 --- a/.github/workflows/non_omv.yml +++ b/.github/workflows/non_omv.yml @@ -11,18 +11,23 @@ jobs: runs-on: ubuntu-latest strategy: + fail-fast: false matrix: - python-version: [ 3.8, 3.9 ] + python-version: [ 3.9, "3.11", "3.12" , "3.13" ] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v3 + uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} + - name: Install OpenCortex run: | pip install . + pip install ruff + - name: Run some examples run: | echo "Running non OMV tests..." diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 96f0105..0000000 --- a/.travis.yml +++ /dev/null @@ -1,56 +0,0 @@ -# Framework for running automated tests on OSB using Travis-CI, see https://github.com/OpenSourceBrain/osb-model-validation - -dist: xenial -sudo: false - -addons: - apt: - packages: - #- python-matplotlib - #- python-numpy - #- python-scipy - - python-tk - - python-lxml - - python-tornado - - python-tables - -language: python -python: - - 2.7 - #- 3.6 - -env: - - OMV_ENGINE=jNeuroML - - OMV_ENGINE=jNeuroML_NEURON - - OMV_ENGINE=jNeuroML_NetPyNE - - OMV_ENGINE=jNeuroML_PyNN_NEURON - - OMV_ENGINE=jNeuroML_validate - - OMV_ENGINE=NON_OMV_TESTS - -install: - - git clone https://github.com/OpenSourceBrain/osb-model-validation - - cd osb-model-validation - - python setup.py install - - cd .. - - - pip install matplotlib>=2.2.5 # This is more because Matplotlib v2.x is required... - - pip install future pandas matplotlib-scalebar bokeh scipy # For NetPyNE... - - pip install tables # Ditto - - - pip install . - -script: - - omv all -V; export OMV_SUCCESS=$?; echo $OMV_SUCCESS - - echo "Finished all OMV tests" - - omv list-engines -V - - if [[ ${OMV_ENGINE} == "NON_OMV_TESTS" ]]; then echo "Continuing with tests not under OMV..."; else exit $OMV_SUCCESS; fi - - echo "Running non OMV tests..." - - cd examples - - ./regenerateAll.sh - - ls -alt - - cd ../opencortex/test - - nosetests -vs - - - - diff --git a/doc/conf.py b/doc/conf.py index 04a4073..9c4f2fe 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -10,207 +10,211 @@ # All configuration values have a default; values that are commented out # serve to show the default. -import sys, os +import sys +import os import opencortex # 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. -#sys.path.insert(0, os.path.abspath('.')) +# sys.path.insert(0, os.path.abspath('.')) -sys.path.insert(0, os.path.abspath('../opencortex')) -sys.path.insert(0, os.path.abspath('..')) +sys.path.insert(0, os.path.abspath("../opencortex")) +sys.path.insert(0, os.path.abspath("..")) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' +# 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.doctest'] +extensions = ["sphinx.ext.autodoc", "sphinx.ext.doctest"] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix of source filenames. -source_suffix = '.txt' +source_suffix = ".txt" # The encoding of source files. -#source_encoding = 'utf-8-sig' +# source_encoding = 'utf-8-sig' # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'OpenCortex' -copyright = u'2017, OpenCortex authors and contributors' +project = "OpenCortex" +copyright = "2017, OpenCortex authors and contributors" # 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. -for l in open('../opencortex/__init__.py'): - if '__version__' in l: +for l in open("../opencortex/__init__.py"): + if "__version__" in l: version = l.split("'")[1] # The full version, including alpha/beta/rc tags. release = opencortex.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. -#language = None +# language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: -#today = '' +# today = '' # Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' +# today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['_build'] +exclude_patterns = ["_build"] # The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None +# default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True +# add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). -#add_module_names = True +# add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. -#show_authors = False +# show_authors = False # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] +# modindex_common_prefix = [] # -- 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 = 'nature' +html_theme = "nature" # 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 = {} +# html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] +# html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". -#html_title = None +# html_title = None # A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None +# html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. -html_logo = 'logo.png' +html_logo = "logo.png" # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. -#html_favicon = None +# html_favicon = None # 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'] +html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' +# html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. -#html_use_smartypants = True +# html_use_smartypants = True # Custom sidebar templates, maps document names to template names. -#html_sidebars = {} +# html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. -#html_additional_pages = {} +# html_additional_pages = {} # If false, no module index is generated. -#html_domain_indices = True +# html_domain_indices = True # If false, no index is generated. -#html_use_index = True +# html_use_index = True # If true, the index is split into individual pages for each letter. -#html_split_index = False +# html_split_index = False # If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True +# html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True +# html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True +# html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. -#html_use_opensearch = '' +# html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None +# html_file_suffix = None # Output file base name for HTML help builder. -htmlhelp_basename = 'OpenCortexdoc' +htmlhelp_basename = "OpenCortexdoc" # -- 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': '', + # The paper size ('letterpaper' or 'a4paper'). + #'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + #'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ - ('index', 'OpenCortex.tex', u'OpenCortex Documentation', - u'OpenCortex authors and contributors', 'manual'), + ( + "index", + "OpenCortex.tex", + "OpenCortex Documentation", + "OpenCortex authors and contributors", + "manual", + ), ] # The name of an image file (relative to this directory) to place at the top of # the title page. -#latex_logo = None +# latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. -#latex_use_parts = False +# latex_use_parts = False # If true, show page references after internal links. -#latex_show_pagerefs = False +# latex_show_pagerefs = False # If true, show URL addresses after external links. -#latex_show_urls = False +# latex_show_urls = False # Documents to append as an appendix to all manuals. -#latex_appendices = [] +# latex_appendices = [] # If false, no module index is generated. -#latex_domain_indices = True +# latex_domain_indices = True # -- Options for manual page output -------------------------------------------- @@ -218,12 +222,17 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - ('index', 'libneuroml', u'OpenCortex Documentation', - [u'OpenCortex authors and contributors'], 1) + ( + "index", + "libneuroml", + "OpenCortex Documentation", + ["OpenCortex authors and contributors"], + 1, + ) ] # If true, show URL addresses after external links. -#man_show_urls = False +# man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ @@ -232,16 +241,22 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - ('index', 'OpenCortex', u'OpenCortex Documentation', - u'OpenCortex authors and contributors', 'OpenCortex', 'One line description of project.', - 'Miscellaneous'), + ( + "index", + "OpenCortex", + "OpenCortex Documentation", + "OpenCortex authors and contributors", + "OpenCortex", + "One line description of project.", + "Miscellaneous", + ), ] # Documents to append as an appendix to all manuals. -#texinfo_appendices = [] +# texinfo_appendices = [] # If false, no module index is generated. -#texinfo_domain_indices = True +# texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. -#texinfo_show_urls = 'footnote' +# texinfo_show_urls = 'footnote' diff --git a/examples/ACNet.net.nml b/examples/ACNet.net.nml index 9357a3c..ca4cf4d 100644 --- a/examples/ACNet.net.nml +++ b/examples/ACNet.net.nml @@ -2,8 +2,8 @@ This NeuroML 2 file was generated by OpenCortex v0.1.18 using: - libNeuroML v0.6.3 - pyNeuroML v1.3.7 + libNeuroML v0.6.8 + pyNeuroML v1.3.22 diff --git a/examples/ACNet.py b/examples/ACNet.py index fe89270..e9da1cc 100644 --- a/examples/ACNet.py +++ b/examples/ACNet.py @@ -1,200 +1,250 @@ import opencortex.core as oc import sys -''' +""" Simple network using cells from ACNet model -''' - - -def generate(reference = "ACNet", - num_pyr = 48, - num_bask = 12, - scalex=1, - scaley=1, - scalez=1, - connections=True, - global_delay = 0, - duration = 250, - segments_to_plot_record = {'pop_pyr':[0],'pop_bask':[0]}, - format='xml'): - - +""" + + +def generate( + reference="ACNet", + num_pyr=48, + num_bask=12, + scalex=1, + scaley=1, + scalez=1, + connections=True, + global_delay=0, + duration=250, + segments_to_plot_record={"pop_pyr": [0], "pop_bask": [0]}, + format="xml", +): nml_doc, network = oc.generate_network(reference) - oc.include_opencortex_cell(nml_doc, 'acnet2/pyr_4_sym.cell.nml') - oc.include_opencortex_cell(nml_doc, 'acnet2/bask.cell.nml') - - xDim = 500*scalex - yDim = 50*scaley - zDim = 500*scalez - - pop_pyr = oc.add_population_in_rectangular_region(network, 'pop_pyr', - 'pyr_4_sym', num_pyr, - 0,0,0, xDim,yDim,zDim, - color='.8 0 0') - - pop_bask = oc.add_population_in_rectangular_region(network, 'pop_bask', - 'bask', num_bask, - 0,yDim,0, xDim,yDim+yDim,zDim, - color='0 0 .8') - - ampa_syn = oc.add_exp_two_syn(nml_doc, id="AMPA_syn", - gbase="30e-9S", erev="0mV", - tau_rise="0.003s", tau_decay="0.0031s") - - ampa_syn_inh = oc.add_exp_two_syn(nml_doc, id="AMPA_syn_inh", - gbase="0.15e-9S", erev="0mV", - tau_rise="0.003s", tau_decay="0.0031s") - - gaba_syn = oc.add_exp_two_syn(nml_doc, id="GABA_syn", - gbase="0.6e-9S", erev="-0.080V", - tau_rise="0.005s", tau_decay="0.012s") - - gaba_syn_inh = oc.add_exp_two_syn(nml_doc, id="GABA_syn_inh", - gbase="0S", erev="-0.080V", - tau_rise="0.003s", tau_decay="0.008s") - - pfs = oc.add_poisson_firing_synapse(nml_doc, id="poissonFiringSyn", - average_rate="30 Hz", synapse_id=ampa_syn.id) - + oc.include_opencortex_cell(nml_doc, "acnet2/pyr_4_sym.cell.nml") + oc.include_opencortex_cell(nml_doc, "acnet2/bask.cell.nml") + + xDim = 500 * scalex + yDim = 50 * scaley + zDim = 500 * scalez + + pop_pyr = oc.add_population_in_rectangular_region( + network, + "pop_pyr", + "pyr_4_sym", + num_pyr, + 0, + 0, + 0, + xDim, + yDim, + zDim, + color=".8 0 0", + ) + + pop_bask = oc.add_population_in_rectangular_region( + network, + "pop_bask", + "bask", + num_bask, + 0, + yDim, + 0, + xDim, + yDim + yDim, + zDim, + color="0 0 .8", + ) + + ampa_syn = oc.add_exp_two_syn( + nml_doc, + id="AMPA_syn", + gbase="30e-9S", + erev="0mV", + tau_rise="0.003s", + tau_decay="0.0031s", + ) + + ampa_syn_inh = oc.add_exp_two_syn( + nml_doc, + id="AMPA_syn_inh", + gbase="0.15e-9S", + erev="0mV", + tau_rise="0.003s", + tau_decay="0.0031s", + ) + + gaba_syn = oc.add_exp_two_syn( + nml_doc, + id="GABA_syn", + gbase="0.6e-9S", + erev="-0.080V", + tau_rise="0.005s", + tau_decay="0.012s", + ) + + gaba_syn_inh = oc.add_exp_two_syn( + nml_doc, + id="GABA_syn_inh", + gbase="0S", + erev="-0.080V", + tau_rise="0.003s", + tau_decay="0.008s", + ) + + pfs = oc.add_poisson_firing_synapse( + nml_doc, id="poissonFiringSyn", average_rate="30 Hz", synapse_id=ampa_syn.id + ) total_conns = 0 if connections: - - this_syn=ampa_syn.id - proj = oc.add_targeted_projection(network, - "Proj_pyr_pyr", - pop_pyr, - pop_pyr, - targeting_mode='convergent', - synapse_list=[this_syn], - pre_segment_group = 'soma_group', - post_segment_group = 'dendrite_group', - number_conns_per_cell=7, - delays_dict = {this_syn:global_delay}) + this_syn = ampa_syn.id + proj = oc.add_targeted_projection( + network, + "Proj_pyr_pyr", + pop_pyr, + pop_pyr, + targeting_mode="convergent", + synapse_list=[this_syn], + pre_segment_group="soma_group", + post_segment_group="dendrite_group", + number_conns_per_cell=7, + delays_dict={this_syn: global_delay}, + ) if proj: total_conns += len(proj[0].connection_wds) - this_syn=ampa_syn_inh.id - proj = oc.add_targeted_projection(network, - "Proj_pyr_bask", - pop_pyr, - pop_bask, - targeting_mode='convergent', - synapse_list=[this_syn], - pre_segment_group = 'soma_group', - post_segment_group = 'all', - number_conns_per_cell=21, - delays_dict = {this_syn:global_delay}) + this_syn = ampa_syn_inh.id + proj = oc.add_targeted_projection( + network, + "Proj_pyr_bask", + pop_pyr, + pop_bask, + targeting_mode="convergent", + synapse_list=[this_syn], + pre_segment_group="soma_group", + post_segment_group="all", + number_conns_per_cell=21, + delays_dict={this_syn: global_delay}, + ) if proj: total_conns += len(proj[0].connection_wds) - this_syn=gaba_syn.id - proj = oc.add_targeted_projection(network, - "Proj_bask_pyr", - pop_bask, - pop_pyr, - targeting_mode='convergent', - synapse_list=[this_syn], - pre_segment_group = 'soma_group', - post_segment_group = 'all', - number_conns_per_cell=21, - delays_dict = {this_syn:global_delay}) + this_syn = gaba_syn.id + proj = oc.add_targeted_projection( + network, + "Proj_bask_pyr", + pop_bask, + pop_pyr, + targeting_mode="convergent", + synapse_list=[this_syn], + pre_segment_group="soma_group", + post_segment_group="all", + number_conns_per_cell=21, + delays_dict={this_syn: global_delay}, + ) if proj: total_conns += len(proj[0].connection_wds) - this_syn=gaba_syn_inh.id - proj = oc.add_targeted_projection(network, - "Proj_bask_bask", - pop_bask, - pop_bask, - targeting_mode='convergent', - synapse_list=[this_syn], - pre_segment_group = 'soma_group', - post_segment_group = 'all', - number_conns_per_cell=5, - delays_dict = {this_syn:global_delay}) + this_syn = gaba_syn_inh.id + proj = oc.add_targeted_projection( + network, + "Proj_bask_bask", + pop_bask, + pop_bask, + targeting_mode="convergent", + synapse_list=[this_syn], + pre_segment_group="soma_group", + post_segment_group="all", + number_conns_per_cell=5, + delays_dict={this_syn: global_delay}, + ) if proj: total_conns += len(proj[0].connection_wds) - - oc.add_targeted_inputs_to_population(network, "Stim0", - pop_pyr, pfs.id, - segment_group='soma_group', - number_per_cell = 1, - all_cells=True) - - - if num_pyr != 48 or num_bask!=12: - new_reference = '%s_%scells_%sconns'%(nml_doc.id,num_pyr+num_bask,total_conns) + oc.add_targeted_inputs_to_population( + network, + "Stim0", + pop_pyr, + pfs.id, + segment_group="soma_group", + number_per_cell=1, + all_cells=True, + ) + + if num_pyr != 48 or num_bask != 12: + new_reference = "%s_%scells_%sconns" % ( + nml_doc.id, + num_pyr + num_bask, + total_conns, + ) network.id = new_reference nml_doc.id = new_reference - nml_file_name = '%s.net.%s'%(network.id,'nml.h5' if format == 'hdf5' else 'nml') - target_dir = 'HDF5/' if format == 'hdf5' else './' - - oc.save_network(nml_doc, - nml_file_name, - validate=(format=='xml'), - format = format, - target_dir=target_dir) + nml_file_name = "%s.net.%s" % (network.id, "nml.h5" if format == "hdf5" else "nml") + target_dir = "HDF5/" if format == "hdf5" else "./" + oc.save_network( + nml_doc, + nml_file_name, + validate=(format == "xml"), + format=format, + target_dir=target_dir, + ) - gen_plots_for_quantities = {} # Dict with displays vs lists of quantity paths - gen_saves_for_quantities = {} # Dict with file names vs lists of quantity paths + gen_plots_for_quantities = {} # Dict with displays vs lists of quantity paths + gen_saves_for_quantities = {} # Dict with file names vs lists of quantity paths for pop in segments_to_plot_record.keys(): pop_nml = network.get_by_id(pop) - if pop_nml is not None and pop_nml.size>0: - + if pop_nml is not None and pop_nml.size > 0: group = len(segments_to_plot_record[pop]) == 1 if group: - display = 'Display_%s_v'%(pop) - file_ = 'Sim_%s.%s.v.dat'%(nml_doc.id,pop) + display = "Display_%s_v" % (pop) + file_ = "Sim_%s.%s.v.dat" % (nml_doc.id, pop) gen_plots_for_quantities[display] = [] gen_saves_for_quantities[file_] = [] for i in range(int(pop_nml.size)): if not group: - display = 'Display_%s_%i_v'%(pop,i) - file_ = 'Sim_%s.%s.%i.v.dat'%(nml_doc.id,pop,i) + display = "Display_%s_%i_v" % (pop, i) + file_ = "Sim_%s.%s.%i.v.dat" % (nml_doc.id, pop, i) gen_plots_for_quantities[display] = [] gen_saves_for_quantities[file_] = [] for seg in segments_to_plot_record[pop]: - quantity = '%s/%i/%s/%i/v'%(pop,i,pop_nml.component,seg) + quantity = "%s/%i/%s/%i/v" % (pop, i, pop_nml.component, seg) gen_plots_for_quantities[display].append(quantity) gen_saves_for_quantities[file_].append(quantity) - lems_file_name = oc.generate_lems_simulation(nml_doc, - network, - target_dir+nml_file_name, - duration = duration, - dt = 0.025, - gen_plots_for_all_v = False, - gen_plots_for_quantities = gen_plots_for_quantities, - gen_saves_for_all_v = False, - gen_saves_for_quantities = gen_saves_for_quantities, - target_dir=target_dir, - report_file_name='report.acnet.txt') + lems_file_name = oc.generate_lems_simulation( + nml_doc, + network, + target_dir + nml_file_name, + duration=duration, + dt=0.025, + gen_plots_for_all_v=False, + gen_plots_for_quantities=gen_plots_for_quantities, + gen_saves_for_all_v=False, + gen_saves_for_quantities=gen_saves_for_quantities, + target_dir=target_dir, + report_file_name="report.acnet.txt", + ) return nml_doc, nml_file_name, lems_file_name -if __name__ == '__main__': - - if '-test' in sys.argv: - - generate(num_pyr = 2, - num_bask=2, - duration = 500, - global_delay = 2) +if __name__ == "__main__": + if "-test" in sys.argv: + generate(num_pyr=2, num_bask=2, duration=500, global_delay=2) - generate(num_pyr = 1, - num_bask=0, - duration = 500, - segments_to_plot_record = {'pop_pyr':range(9)}) + generate( + num_pyr=1, + num_bask=0, + duration=500, + segments_to_plot_record={"pop_pyr": range(9)}, + ) else: - generate(global_delay = 1) - generate(global_delay = 1, format='hdf5') + generate(global_delay=1) + generate(global_delay=1, format="hdf5") diff --git a/examples/Balanced.net.nml b/examples/Balanced.net.nml index b9e2311..65ee2ac 100644 --- a/examples/Balanced.net.nml +++ b/examples/Balanced.net.nml @@ -2,8 +2,8 @@ This NeuroML 2 file was generated by OpenCortex v0.1.18 using: - libNeuroML v0.6.3 - pyNeuroML v1.3.7 + libNeuroML v0.6.8 + pyNeuroML v1.3.22 diff --git a/examples/Balanced.py b/examples/Balanced.py index 6826c8e..a855118 100644 --- a/examples/Balanced.py +++ b/examples/Balanced.py @@ -1,8 +1,7 @@ -''' +""" Generates a NeuroML 2 file with many types of cells, populations and inputs for testing purposes -''' - +""" import opencortex.core as oc import sys @@ -10,38 +9,46 @@ min_pop_size = 3 + def scale_pop_size(baseline, scale): - return max(min_pop_size, int(baseline*scale)) - - -def generate(reference = "Balanced", - num_bbp =1, - scalePops = 1, - scalex=1, - scaley=1, - scalez=1, - connections=True, - duration = 1000, - input_rate = 150, - global_delay = 0, - max_in_pop_to_plot_and_save = 5, - gen_spike_saves_for_all_somas = True, - format='xml'): - - num_exc = scale_pop_size(80,scalePops) - num_inh = scale_pop_size(40,scalePops) - + return max(min_pop_size, int(baseline * scale)) + + +def generate( + reference="Balanced", + num_bbp=1, + scalePops=1, + scalex=1, + scaley=1, + scalez=1, + connections=True, + duration=1000, + input_rate=150, + global_delay=0, + max_in_pop_to_plot_and_save=5, + gen_spike_saves_for_all_somas=True, + format="xml", +): + num_exc = scale_pop_size(80, scalePops) + num_inh = scale_pop_size(40, scalePops) + nml_doc, network = oc.generate_network(reference) - oc.include_opencortex_cell(nml_doc, 'AllenInstituteCellTypesDB_HH/HH_477127614.cell.nml') - oc.include_opencortex_cell(nml_doc, 'AllenInstituteCellTypesDB_HH/HH_476686112.cell.nml') - - if num_bbp>0: - oc.include_opencortex_cell(nml_doc, 'BlueBrainProject_NMC/cADpyr229_L23_PC_5ecbf9b163_0_0.cell.nml') + oc.include_opencortex_cell( + nml_doc, "AllenInstituteCellTypesDB_HH/HH_477127614.cell.nml" + ) + oc.include_opencortex_cell( + nml_doc, "AllenInstituteCellTypesDB_HH/HH_476686112.cell.nml" + ) + + if num_bbp > 0: + oc.include_opencortex_cell( + nml_doc, "BlueBrainProject_NMC/cADpyr229_L23_PC_5ecbf9b163_0_0.cell.nml" + ) - xDim = 400*scalex - yDim = 500*scaley - zDim = 300*scalez + xDim = 400 * scalex + yDim = 500 * scaley + zDim = 300 * scalez xs = -200 ys = -150 @@ -49,180 +56,192 @@ def generate(reference = "Balanced", ##### Synapses - synAmpa1 = oc.add_exp_two_syn(nml_doc, id="synAmpa1", gbase="1nS", - erev="0mV", tau_rise="0.5ms", tau_decay="5ms") - - synGaba1 = oc.add_exp_two_syn(nml_doc, id="synGaba1", gbase="2nS", - erev="-80mV", tau_rise="1ms", tau_decay="20ms") + synAmpa1 = oc.add_exp_two_syn( + nml_doc, + id="synAmpa1", + gbase="1nS", + erev="0mV", + tau_rise="0.5ms", + tau_decay="5ms", + ) + + synGaba1 = oc.add_exp_two_syn( + nml_doc, + id="synGaba1", + gbase="2nS", + erev="-80mV", + tau_rise="1ms", + tau_decay="20ms", + ) ##### Input types - - pfs1 = oc.add_poisson_firing_synapse(nml_doc, - id="psf1", - average_rate="%s Hz"%input_rate, - synapse_id=synAmpa1.id) - + pfs1 = oc.add_poisson_firing_synapse( + nml_doc, id="psf1", average_rate="%s Hz" % input_rate, synapse_id=synAmpa1.id + ) ##### Populations - popExc = oc.add_population_in_rectangular_region(network, - 'popExc', - 'HH_477127614', - num_exc, - xs,ys,zs, - xDim,yDim,zDim, - color='.8 0 0') - - popInh = oc.add_population_in_rectangular_region(network, - 'popInh', - 'HH_476686112', - num_inh, - xs,ys,zs, - xDim,yDim,zDim, - color='0 0 .8') + popExc = oc.add_population_in_rectangular_region( + network, + "popExc", + "HH_477127614", + num_exc, + xs, + ys, + zs, + xDim, + yDim, + zDim, + color=".8 0 0", + ) + + popInh = oc.add_population_in_rectangular_region( + network, + "popInh", + "HH_476686112", + num_inh, + xs, + ys, + zs, + xDim, + yDim, + zDim, + color="0 0 .8", + ) if num_bbp == 1: - popBBP = oc.add_single_cell_population(network, - 'popBBP', - 'cADpyr229_L23_PC_5ecbf9b163_0_0', - z=200, - color='0 .8 0') + popBBP = oc.add_single_cell_population( + network, "popBBP", "cADpyr229_L23_PC_5ecbf9b163_0_0", z=200, color="0 .8 0" + ) elif num_bbp > 1: - - popBBP = oc.add_population_in_rectangular_region(network, - 'popBBP', - 'cADpyr229_L23_PC_5ecbf9b163_0_0', - num_bbp, - xs,ys,zs, - xDim,yDim,zDim, - color='0 .8 0') - + popBBP = oc.add_population_in_rectangular_region( + network, + "popBBP", + "cADpyr229_L23_PC_5ecbf9b163_0_0", + num_bbp, + xs, + ys, + zs, + xDim, + yDim, + zDim, + color="0 .8 0", + ) ##### Projections total_conns = 0 if connections: - - proj = oc.add_probabilistic_projection(network, "proj0", - popExc, popExc, - synAmpa1.id, 0.5, delay = global_delay) + proj = oc.add_probabilistic_projection( + network, "proj0", popExc, popExc, synAmpa1.id, 0.5, delay=global_delay + ) total_conns += len(proj.connection_wds) - proj = oc.add_probabilistic_projection(network, "proj1", - popExc, popInh, - synAmpa1.id, 0.7, delay = global_delay) + proj = oc.add_probabilistic_projection( + network, "proj1", popExc, popInh, synAmpa1.id, 0.7, delay=global_delay + ) total_conns += len(proj.connection_wds) - proj = oc.add_probabilistic_projection(network, "proj3", - popInh, popExc, - synGaba1.id, 0.7, delay = global_delay) + proj = oc.add_probabilistic_projection( + network, "proj3", popInh, popExc, synGaba1.id, 0.7, delay=global_delay + ) total_conns += len(proj.connection_wds) - proj = oc.add_probabilistic_projection(network, "proj4", - popInh, popInh, - synGaba1.id, 0.5, delay = global_delay) + proj = oc.add_probabilistic_projection( + network, "proj4", popInh, popInh, synGaba1.id, 0.5, delay=global_delay + ) total_conns += len(proj.connection_wds) + if num_bbp > 0: + proj = oc.add_probabilistic_projection( + network, "proj5", popExc, popBBP, synAmpa1.id, 0.5, delay=global_delay + ) - - if num_bbp>0: - proj = oc.add_probabilistic_projection(network, "proj5", - popExc, popBBP, - synAmpa1.id, 0.5, delay = global_delay) - total_conns += len(proj.connection_wds) ##### Inputs - oc.add_inputs_to_population(network, "Stim0", - popExc, pfs1.id, - all_cells=True) - + oc.add_inputs_to_population(network, "Stim0", popExc, pfs1.id, all_cells=True) + ##### Save NeuroML and LEMS Simulation files - ##### Save NeuroML and LEMS Simulation files - if num_bbp != 1: - new_reference = 'Balanced_%scells_%sconns'%(num_bbp+num_exc+num_inh,total_conns) + new_reference = "Balanced_%scells_%sconns" % ( + num_bbp + num_exc + num_inh, + total_conns, + ) network.id = new_reference nml_doc.id = new_reference - nml_file_name = '%s.net.%s'%(network.id,'nml.h5' if format == 'hdf5' else 'nml') - oc.save_network(nml_doc, - nml_file_name, - validate=(format=='xml'), - format = format) - - if format=='xml': - - plot_v = {popExc.id:[],popInh.id:[]} - save_v = {'%s_v.dat'%popExc.id:[],'%s_v.dat'%popInh.id:[]} - - if num_bbp>0: - plot_v[popBBP.id]=[] - save_v['%s_v.dat'%popBBP.id]=[] - - for i in range(min(max_in_pop_to_plot_and_save,num_exc)): - plot_v[popExc.id].append("%s/%i/%s/v"%(popExc.id,i,popExc.component)) - save_v['%s_v.dat'%popExc.id].append("%s/%i/%s/v"%(popExc.id,i,popExc.component)) - - for i in range(min(max_in_pop_to_plot_and_save,num_inh)): - plot_v[popInh.id].append("%s/%i/%s/v"%(popInh.id,i,popInh.component)) - save_v['%s_v.dat'%popInh.id].append("%s/%i/%s/v"%(popInh.id,i,popInh.component)) - - for i in range(min(max_in_pop_to_plot_and_save,num_bbp)): - plot_v[popBBP.id].append("%s/%i/%s/v"%(popBBP.id,i,popBBP.component)) - save_v['%s_v.dat'%popBBP.id].append("%s/%i/%s/v"%(popBBP.id,i,popBBP.component)) - - lems_file_name = oc.generate_lems_simulation(nml_doc, network, - nml_file_name, - duration = duration, - dt = 0.025, - gen_plots_for_all_v = False, - gen_plots_for_quantities = plot_v, - gen_saves_for_all_v = False, - gen_saves_for_quantities = save_v, - gen_spike_saves_for_all_somas = gen_spike_saves_for_all_somas) + nml_file_name = "%s.net.%s" % (network.id, "nml.h5" if format == "hdf5" else "nml") + oc.save_network(nml_doc, nml_file_name, validate=(format == "xml"), format=format) + + if format == "xml": + plot_v = {popExc.id: [], popInh.id: []} + save_v = {"%s_v.dat" % popExc.id: [], "%s_v.dat" % popInh.id: []} + + if num_bbp > 0: + plot_v[popBBP.id] = [] + save_v["%s_v.dat" % popBBP.id] = [] + + for i in range(min(max_in_pop_to_plot_and_save, num_exc)): + plot_v[popExc.id].append("%s/%i/%s/v" % (popExc.id, i, popExc.component)) + save_v["%s_v.dat" % popExc.id].append( + "%s/%i/%s/v" % (popExc.id, i, popExc.component) + ) + + for i in range(min(max_in_pop_to_plot_and_save, num_inh)): + plot_v[popInh.id].append("%s/%i/%s/v" % (popInh.id, i, popInh.component)) + save_v["%s_v.dat" % popInh.id].append( + "%s/%i/%s/v" % (popInh.id, i, popInh.component) + ) + + for i in range(min(max_in_pop_to_plot_and_save, num_bbp)): + plot_v[popBBP.id].append("%s/%i/%s/v" % (popBBP.id, i, popBBP.component)) + save_v["%s_v.dat" % popBBP.id].append( + "%s/%i/%s/v" % (popBBP.id, i, popBBP.component) + ) + + lems_file_name = oc.generate_lems_simulation( + nml_doc, + network, + nml_file_name, + duration=duration, + dt=0.025, + gen_plots_for_all_v=False, + gen_plots_for_quantities=plot_v, + gen_saves_for_all_v=False, + gen_saves_for_quantities=save_v, + gen_spike_saves_for_all_somas=gen_spike_saves_for_all_somas, + ) else: lems_file_name = None - + return nml_doc, nml_file_name, lems_file_name - -if __name__ == '__main__': - - if '-all' in sys.argv: + +if __name__ == "__main__": + if "-all" in sys.argv: generate() - - generate(num_bbp =10, - scalePops = 5, - scalex=2, - scalez=2, - connections=False) - - generate(num_bbp =10, - scalePops = 5, - scalex=2, - scalez=2, - global_delay = 2) - - generate(num_bbp =0, - scalePops = 2, - scalex=2, - scalez=2, - duration = 2000, - global_delay = 2) - - elif '-test' in sys.argv: - - generate(num_bbp =0, - scalePops = 0.2, - scalex=2, - scalez=2, - duration = 1000, - max_in_pop_to_plot_and_save = 5, - global_delay = 2, - input_rate=250) + + generate(num_bbp=10, scalePops=5, scalex=2, scalez=2, connections=False) + + generate(num_bbp=10, scalePops=5, scalex=2, scalez=2, global_delay=2) + + generate( + num_bbp=0, scalePops=2, scalex=2, scalez=2, duration=2000, global_delay=2 + ) + + elif "-test" in sys.argv: + generate( + num_bbp=0, + scalePops=0.2, + scalex=2, + scalez=2, + duration=1000, + max_in_pop_to_plot_and_save=5, + global_delay=2, + input_rate=250, + ) else: - generate(gen_spike_saves_for_all_somas = True, - global_delay = 2) + generate(gen_spike_saves_for_all_somas=True, global_delay=2) diff --git a/examples/Balanced_240cells_36926conns.net.nml b/examples/Balanced_240cells_36926conns.net.nml index 3d6ffa6..627af62 100644 --- a/examples/Balanced_240cells_36926conns.net.nml +++ b/examples/Balanced_240cells_36926conns.net.nml @@ -2,8 +2,8 @@ This NeuroML 2 file was generated by OpenCortex v0.1.18 using: - libNeuroML v0.6.3 - pyNeuroML v1.3.7 + libNeuroML v0.6.8 + pyNeuroML v1.3.22 diff --git a/examples/Balanced_610cells_0conns.net.nml b/examples/Balanced_610cells_0conns.net.nml index 7353554..6661478 100644 --- a/examples/Balanced_610cells_0conns.net.nml +++ b/examples/Balanced_610cells_0conns.net.nml @@ -2,8 +2,8 @@ This NeuroML 2 file was generated by OpenCortex v0.1.18 using: - libNeuroML v0.6.3 - pyNeuroML v1.3.7 + libNeuroML v0.6.8 + pyNeuroML v1.3.22 diff --git a/examples/Balanced_610cells_213550conns.net.nml b/examples/Balanced_610cells_213550conns.net.nml index fa3b6ff..4f88664 100644 --- a/examples/Balanced_610cells_213550conns.net.nml +++ b/examples/Balanced_610cells_213550conns.net.nml @@ -2,8 +2,8 @@ This NeuroML 2 file was generated by OpenCortex v0.1.18 using: - libNeuroML v0.6.3 - pyNeuroML v1.3.7 + libNeuroML v0.6.8 + pyNeuroML v1.3.22 diff --git a/examples/Complex.net.nml b/examples/Complex.net.nml index 31ef86a..e4ceb53 100644 --- a/examples/Complex.net.nml +++ b/examples/Complex.net.nml @@ -2,8 +2,8 @@ This NeuroML 2 file was generated by OpenCortex v0.1.18 using: - libNeuroML v0.6.3 - pyNeuroML v1.3.7 + libNeuroML v0.6.8 + pyNeuroML v1.3.22 diff --git a/examples/Complex.py b/examples/Complex.py index a9f366f..858c289 100644 --- a/examples/Complex.py +++ b/examples/Complex.py @@ -1,7 +1,7 @@ -''' +""" Generates a complex NeuroML 2 file with many types of cells, populations and inputs for testing purposes -''' +""" import opencortex.core as oc @@ -9,11 +9,13 @@ nml_doc, network = oc.generate_network("Complex") -scale = .1 +scale = 0.1 min_pop_size = 3 + def scale_pop_size(baseline): - return max(min_pop_size, int(baseline*scale)) + return max(min_pop_size, int(baseline * scale)) + xDim = 500 yDim = 100 @@ -22,177 +24,199 @@ def scale_pop_size(baseline): ##### Cells -#oc.add_cell_prototype(nml_doc, 'izhikevich/Izh_471141261.cell.nml') -oc.include_opencortex_cell(nml_doc, 'izhikevich/RS.cell.nml') -oc.include_opencortex_cell(nml_doc, 'iaf/iaf.cell.nml') -oc.include_opencortex_cell(nml_doc, 'iaf/iafRef.cell.nml') -oc.include_opencortex_cell(nml_doc, 'acnet2/pyr_4_sym_soma.cell.nml') -oc.include_opencortex_cell(nml_doc, 'acnet2/pyr_4_sym.cell.nml') +# oc.add_cell_prototype(nml_doc, 'izhikevich/Izh_471141261.cell.nml') +oc.include_opencortex_cell(nml_doc, "izhikevich/RS.cell.nml") +oc.include_opencortex_cell(nml_doc, "iaf/iaf.cell.nml") +oc.include_opencortex_cell(nml_doc, "iaf/iafRef.cell.nml") +oc.include_opencortex_cell(nml_doc, "acnet2/pyr_4_sym_soma.cell.nml") +oc.include_opencortex_cell(nml_doc, "acnet2/pyr_4_sym.cell.nml") # TODO: add method oc.add_spike_generator_poisson(...) -spike_gen = neuroml.SpikeGeneratorPoisson(id="poissonInput", - average_rate="50Hz") - -nml_doc.spike_generator_poissons.append(spike_gen) +spike_gen = neuroml.SpikeGeneratorPoisson(id="poissonInput", average_rate="50Hz") +nml_doc.spike_generator_poissons.append(spike_gen) ##### Synapses -synAmpa1 = oc.add_exp_two_syn(nml_doc, id="synAmpa1", gbase="1nS", - erev="0mV", tau_rise="0.5ms", tau_decay="5ms") - -synAmpa2 = oc.add_exp_two_syn(nml_doc, id="synAmpa2", gbase="2nS", - erev="0mV", tau_rise="0.5ms", tau_decay="8ms") +synAmpa1 = oc.add_exp_two_syn( + nml_doc, id="synAmpa1", gbase="1nS", erev="0mV", tau_rise="0.5ms", tau_decay="5ms" +) -synGaba1 = oc.add_exp_two_syn(nml_doc, id="synGaba1", gbase="1nS", - erev="-70mV", tau_rise="2ms", tau_decay="20ms") +synAmpa2 = oc.add_exp_two_syn( + nml_doc, id="synAmpa2", gbase="2nS", erev="0mV", tau_rise="0.5ms", tau_decay="8ms" +) + +synGaba1 = oc.add_exp_two_syn( + nml_doc, id="synGaba1", gbase="1nS", erev="-70mV", tau_rise="2ms", tau_decay="20ms" +) ##### Input types - -pfs100 = oc.add_poisson_firing_synapse(nml_doc, - id="poissonFiringSyn100", - average_rate="100 Hz", - synapse_id=synAmpa1.id) - -pfs200 = oc.add_poisson_firing_synapse(nml_doc, - id="poissonFiringSyn200", - average_rate="200 Hz", - synapse_id=synAmpa1.id) - -pfsStrong = oc.add_poisson_firing_synapse(nml_doc, - id="poissonFiringSynStrong", - average_rate="200 Hz", - synapse_id=synAmpa2.id) - + +pfs100 = oc.add_poisson_firing_synapse( + nml_doc, id="poissonFiringSyn100", average_rate="100 Hz", synapse_id=synAmpa1.id +) + +pfs200 = oc.add_poisson_firing_synapse( + nml_doc, id="poissonFiringSyn200", average_rate="200 Hz", synapse_id=synAmpa1.id +) + +pfsStrong = oc.add_poisson_firing_synapse( + nml_doc, id="poissonFiringSynStrong", average_rate="200 Hz", synapse_id=synAmpa2.id +) + ##### Populations -popIaf = oc.add_population_in_rectangular_region(network, - 'popIaf', - 'iaf', - scale_pop_size(20), - 0,offset,0, - xDim,yDim,zDim, - color='.8 0 0') +popIaf = oc.add_population_in_rectangular_region( + network, + "popIaf", + "iaf", + scale_pop_size(20), + 0, + offset, + 0, + xDim, + yDim, + zDim, + color=".8 0 0", +) import neuroml -popIaf.properties.append(neuroml.Property('radius',5)) -offset+=yDim - -popIafRef = oc.add_population_in_rectangular_region(network, - 'popIafRef', - 'iafRef', - scale_pop_size(20), - 0,offset,0, - xDim,yDim,zDim, - color='0 0 .8') -popIafRef.properties.append(neuroml.Property('radius',5)) -offset+=yDim - -popIzh = oc.add_population_in_rectangular_region(network, - 'popIzh', - 'RS', - scale_pop_size(20), - 0,offset,0, - xDim,yDim,zDim, - color='0 .8 0') -popIzh.properties.append(neuroml.Property('radius',5)) -offset+=yDim - -popPyrS = oc.add_population_in_rectangular_region(network, - 'popPyrS', - 'pyr_4_sym_soma', - scale_pop_size(20), - 0,offset,0, - xDim,yDim,zDim, - color='0.8 .8 0') -offset+=yDim - -popPyr = oc.add_population_in_rectangular_region(network, - 'popPyr', - 'pyr_4_sym', - scale_pop_size(20), - 0,offset,0, - xDim,yDim,zDim, - color='0 .8 0.8') -offset+=yDim - - -popStim = oc.add_population_in_rectangular_region(network, - "popPoisson", - spike_gen.id, - scale_pop_size(100), - 0,offset,0, - xDim,yDim,zDim, - color='.8 0 .8') -popStim.properties.append(neuroml.Property('radius',3)) -offset+=yDim + +popIaf.properties.append(neuroml.Property("radius", 5)) +offset += yDim + +popIafRef = oc.add_population_in_rectangular_region( + network, + "popIafRef", + "iafRef", + scale_pop_size(20), + 0, + offset, + 0, + xDim, + yDim, + zDim, + color="0 0 .8", +) +popIafRef.properties.append(neuroml.Property("radius", 5)) +offset += yDim + +popIzh = oc.add_population_in_rectangular_region( + network, + "popIzh", + "RS", + scale_pop_size(20), + 0, + offset, + 0, + xDim, + yDim, + zDim, + color="0 .8 0", +) +popIzh.properties.append(neuroml.Property("radius", 5)) +offset += yDim + +popPyrS = oc.add_population_in_rectangular_region( + network, + "popPyrS", + "pyr_4_sym_soma", + scale_pop_size(20), + 0, + offset, + 0, + xDim, + yDim, + zDim, + color="0.8 .8 0", +) +offset += yDim + +popPyr = oc.add_population_in_rectangular_region( + network, + "popPyr", + "pyr_4_sym", + scale_pop_size(20), + 0, + offset, + 0, + xDim, + yDim, + zDim, + color="0 .8 0.8", +) +offset += yDim + + +popStim = oc.add_population_in_rectangular_region( + network, + "popPoisson", + spike_gen.id, + scale_pop_size(100), + 0, + offset, + 0, + xDim, + yDim, + zDim, + color=".8 0 .8", +) +popStim.properties.append(neuroml.Property("radius", 3)) +offset += yDim ##### Projections - -proj0 = oc.add_targeted_projection(network, - prefix="proj0", - presynaptic_population=popStim, - postsynaptic_population=popPyr, - targeting_mode="convergent", - synapse_list=[synAmpa1.id], - number_conns_per_cell=2, - pre_segment_group=None, - post_segment_group="dendrite_group", - delays_dict={synAmpa1.id:3}, - weights_dict={synAmpa1.id:1}) - - -proj1 = oc.add_probabilistic_projection(network, - "proj1", - popIaf, - popIzh, - synAmpa1.id, - 0.5) - - -proj2 = oc.add_targeted_projection(network, - prefix="proj2", - presynaptic_population=popPyr, - postsynaptic_population=popPyrS, - targeting_mode="convergent", - synapse_list=[synAmpa1.id], - number_conns_per_cell=2, - pre_segment_group="soma_group", - post_segment_group="soma_group", - delays_dict={synAmpa1.id:3}, - weights_dict={synAmpa1.id:'3*random()'}) - -##### Inputs -oc.add_inputs_to_population(network, "Stim0", - popIzh, pfsStrong.id, - all_cells=True) +proj0 = oc.add_targeted_projection( + network, + prefix="proj0", + presynaptic_population=popStim, + postsynaptic_population=popPyr, + targeting_mode="convergent", + synapse_list=[synAmpa1.id], + number_conns_per_cell=2, + pre_segment_group=None, + post_segment_group="dendrite_group", + delays_dict={synAmpa1.id: 3}, + weights_dict={synAmpa1.id: 1}, +) + + +proj1 = oc.add_probabilistic_projection( + network, "proj1", popIaf, popIzh, synAmpa1.id, 0.5 +) + + +proj2 = oc.add_targeted_projection( + network, + prefix="proj2", + presynaptic_population=popPyr, + postsynaptic_population=popPyrS, + targeting_mode="convergent", + synapse_list=[synAmpa1.id], + number_conns_per_cell=2, + pre_segment_group="soma_group", + post_segment_group="soma_group", + delays_dict={synAmpa1.id: 3}, + weights_dict={synAmpa1.id: "3*random()"}, +) + +##### Inputs -oc.add_inputs_to_population(network, "Stim1", - popIaf, pfs200.id, - all_cells=True) +oc.add_inputs_to_population(network, "Stim0", popIzh, pfsStrong.id, all_cells=True) -oc.add_inputs_to_population(network, "Stim2", - popIafRef, pfs200.id, - all_cells=True) +oc.add_inputs_to_population(network, "Stim1", popIaf, pfs200.id, all_cells=True) -oc.add_inputs_to_population(network, "Stim3", - popPyrS, pfs100.id, - all_cells=True) +oc.add_inputs_to_population(network, "Stim2", popIafRef, pfs200.id, all_cells=True) +oc.add_inputs_to_population(network, "Stim3", popPyrS, pfs100.id, all_cells=True) ##### Save NeuroML and LEMS Simulation files -nml_file_name = '%s.net.nml'%network.id +nml_file_name = "%s.net.nml" % network.id oc.save_network(nml_doc, nml_file_name, validate=True) -oc.generate_lems_simulation(nml_doc, - network, - nml_file_name, - duration = 500, - dt = 0.025) - +oc.generate_lems_simulation(nml_doc, network, nml_file_name, duration=500, dt=0.025) diff --git a/examples/Deterministic.net.nml b/examples/Deterministic.net.nml index 0461797..ef3d266 100644 --- a/examples/Deterministic.net.nml +++ b/examples/Deterministic.net.nml @@ -2,8 +2,8 @@ This NeuroML 2 file was generated by OpenCortex v0.1.18 using: - libNeuroML v0.6.3 - pyNeuroML v1.3.7 + libNeuroML v0.6.8 + pyNeuroML v1.3.22 diff --git a/examples/Deterministic.py b/examples/Deterministic.py index db44ea0..db10994 100644 --- a/examples/Deterministic.py +++ b/examples/Deterministic.py @@ -1,8 +1,8 @@ -''' -Generates a deterministic NeuroML 2 file (not stochastic elements )with many -types of cells, populations and inputs for testing exact spike times across +""" +Generates a deterministic NeuroML 2 file (not stochastic elements )with many +types of cells, populations and inputs for testing exact spike times across simulations -''' +""" import opencortex.core as oc @@ -12,8 +12,8 @@ ##### Cells -oc.include_opencortex_cell(nml_doc, 'izhikevich/RS.cell.nml') -oc.include_opencortex_cell(nml_doc, 'iaf/iaf.cell.nml') +oc.include_opencortex_cell(nml_doc, "izhikevich/RS.cell.nml") +oc.include_opencortex_cell(nml_doc, "iaf/iaf.cell.nml") xDim = 500 yDim = 100 @@ -23,77 +23,65 @@ ##### Synapses -synAmpa1 = oc.add_exp_two_syn(nml_doc, id="synAmpa1", gbase="1nS", - erev="0mV", tau_rise="0.5ms", tau_decay="10ms") +synAmpa1 = oc.add_exp_two_syn( + nml_doc, id="synAmpa1", gbase="1nS", erev="0mV", tau_rise="0.5ms", tau_decay="10ms" +) -synGaba1 = oc.add_exp_two_syn(nml_doc, id="synGaba1", gbase="1nS", - erev="-70mV", tau_rise="2ms", tau_decay="20ms") +synGaba1 = oc.add_exp_two_syn( + nml_doc, id="synGaba1", gbase="1nS", erev="-70mV", tau_rise="2ms", tau_decay="20ms" +) ##### Input types -pg0 = oc.add_pulse_generator(nml_doc, - id="pg0", - delay="50ms", - duration="400ms", - amplitude="0.6nA") - -pg1 = oc.add_pulse_generator(nml_doc, - id="pg1", - delay="50ms", - duration="400ms", - amplitude="0.5nA") - +pg0 = oc.add_pulse_generator( + nml_doc, id="pg0", delay="50ms", duration="400ms", amplitude="0.6nA" +) + +pg1 = oc.add_pulse_generator( + nml_doc, id="pg1", delay="50ms", duration="400ms", amplitude="0.5nA" +) + ##### Populations -pop_iaf = oc.add_population_in_rectangular_region(network, - 'pop_iaf', - 'iaf', - 5, - 0,offset,0, - xDim,yDim,zDim, - color='.8 0 0') +pop_iaf = oc.add_population_in_rectangular_region( + network, "pop_iaf", "iaf", 5, 0, offset, 0, xDim, yDim, zDim, color=".8 0 0" +) import neuroml -pop_iaf.properties.append(neuroml.Property('radius',5)) -offset+=yDim -pop_rs = oc.add_population_in_rectangular_region(network, - 'pop_rs', - 'RS', - 5, - 0,offset,0, - xDim,yDim,zDim, - color='0 .8 0') -pop_rs.properties.append(neuroml.Property('radius',5)) +pop_iaf.properties.append(neuroml.Property("radius", 5)) +offset += yDim + +pop_rs = oc.add_population_in_rectangular_region( + network, "pop_rs", "RS", 5, 0, offset, 0, xDim, yDim, zDim, color="0 .8 0" +) +pop_rs.properties.append(neuroml.Property("radius", 5)) ##### Projections -oc.add_probabilistic_projection(network, - "proj0", - pop_iaf, - pop_rs, - synAmpa1.id, - 0.5) - +oc.add_probabilistic_projection(network, "proj0", pop_iaf, pop_rs, synAmpa1.id, 0.5) + ##### Inputs -oc.add_inputs_to_population(network, "Stim0", - pop_iaf, pg0.id, - only_cells=[i for i in [0,2] if i This NeuroML 2 file was generated by OpenCortex v0.1.18 using: - libNeuroML v0.6.3 - pyNeuroML v1.3.7 + libNeuroML v0.6.8 + pyNeuroML v1.3.22 diff --git a/examples/GapJunctions.py b/examples/GapJunctions.py index 07f99c5..2e398c4 100644 --- a/examples/GapJunctions.py +++ b/examples/GapJunctions.py @@ -1,129 +1,143 @@ import opencortex.core as oc import sys -''' +""" Simple network using electrical connections (gap junctions) -''' - - -def generate(reference = "GapJunctions", - num_pre = 5, - num_post = 2, - connections=True, - duration = 1000, - segments_to_plot_record = {'pop_pre':[0],'pop_post':[0]}, - format='xml'): +""" +def generate( + reference="GapJunctions", + num_pre=5, + num_post=2, + connections=True, + duration=1000, + segments_to_plot_record={"pop_pre": [0], "pop_post": [0]}, + format="xml", +): nml_doc, network = oc.generate_network(reference) - oc.include_opencortex_cell(nml_doc, 'acnet2/pyr_4_sym.cell.nml') + oc.include_opencortex_cell(nml_doc, "acnet2/pyr_4_sym.cell.nml") xDim = 500 yDim = 50 zDim = 500 - pop_pre = oc.add_population_in_rectangular_region(network, 'pop_pre', - 'pyr_4_sym', num_pre, - 0,0,0, xDim,yDim,zDim, - color='0 .8 0') - - pop_post = oc.add_population_in_rectangular_region(network, 'pop_post', - 'pyr_4_sym', num_post, - 0,yDim,0, xDim,yDim+yDim,zDim, - color='0 .8 0.8') - - ampa_syn = oc.add_exp_two_syn(nml_doc, id="AMPA_syn", - gbase="30e-9S", erev="0mV", - tau_rise="0.003s", tau_decay="0.0031s") - - gj_syn = oc.add_gap_junction_synapse(nml_doc, id="gj0", - conductance="5nS") - - - pfs = oc.add_poisson_firing_synapse(nml_doc, id="poissonFiringSyn", - average_rate="30 Hz", synapse_id=ampa_syn.id) - - oc.add_inputs_to_population(network, "Stim0", - pop_pre, pfs.id, all_cells=True) - + pop_pre = oc.add_population_in_rectangular_region( + network, + "pop_pre", + "pyr_4_sym", + num_pre, + 0, + 0, + 0, + xDim, + yDim, + zDim, + color="0 .8 0", + ) + + pop_post = oc.add_population_in_rectangular_region( + network, + "pop_post", + "pyr_4_sym", + num_post, + 0, + yDim, + 0, + xDim, + yDim + yDim, + zDim, + color="0 .8 0.8", + ) + + ampa_syn = oc.add_exp_two_syn( + nml_doc, + id="AMPA_syn", + gbase="30e-9S", + erev="0mV", + tau_rise="0.003s", + tau_decay="0.0031s", + ) + + gj_syn = oc.add_gap_junction_synapse(nml_doc, id="gj0", conductance="5nS") + + pfs = oc.add_poisson_firing_synapse( + nml_doc, id="poissonFiringSyn", average_rate="30 Hz", synapse_id=ampa_syn.id + ) + + oc.add_inputs_to_population(network, "Stim0", pop_pre, pfs.id, all_cells=True) total_conns = 0 if connections: - - this_syn=gj_syn.id - proj = oc.add_targeted_electrical_projection(nml_doc, - network, - "Proj0", - pop_pre, - pop_post, - targeting_mode='convergent', - synapse_list=[this_syn], - pre_segment_group = 'soma_group', - post_segment_group = 'dendrite_group', - number_conns_per_cell=3) - if proj: - total_conns += len(proj[0].electrical_connections)+len(proj[0].electrical_connection_instances) - - - - - nml_file_name = '%s.net.%s'%(network.id,'nml.h5' if format == 'hdf5' else 'nml') - oc.save_network(nml_doc, - nml_file_name, - validate=(format=='xml'), - format = format) - - if format=='xml': - - gen_plots_for_quantities = {} # Dict with displays vs lists of quantity paths - gen_saves_for_quantities = {} # Dict with file names vs lists of quantity paths + this_syn = gj_syn.id + proj = oc.add_targeted_electrical_projection( + nml_doc, + network, + "Proj0", + pop_pre, + pop_post, + targeting_mode="convergent", + synapse_list=[this_syn], + pre_segment_group="soma_group", + post_segment_group="dendrite_group", + number_conns_per_cell=3, + ) + if proj: + total_conns += len(proj[0].electrical_connections) + len( + proj[0].electrical_connection_instances + ) + + nml_file_name = "%s.net.%s" % (network.id, "nml.h5" if format == "hdf5" else "nml") + oc.save_network(nml_doc, nml_file_name, validate=(format == "xml"), format=format) + + if format == "xml": + gen_plots_for_quantities = {} # Dict with displays vs lists of quantity paths + gen_saves_for_quantities = {} # Dict with file names vs lists of quantity paths for pop in segments_to_plot_record.keys(): pop_nml = network.get_by_id(pop) - if pop_nml is not None and pop_nml.size>0: - + if pop_nml is not None and pop_nml.size > 0: group = len(segments_to_plot_record[pop]) == 1 if group: - display = 'Display_%s_v'%(pop) - file_ = 'Sim_%s.%s.v.dat'%(nml_doc.id,pop) + display = "Display_%s_v" % (pop) + file_ = "Sim_%s.%s.v.dat" % (nml_doc.id, pop) gen_plots_for_quantities[display] = [] gen_saves_for_quantities[file_] = [] for i in range(int(pop_nml.size)): if not group: - display = 'Display_%s_%i_v'%(pop,i) - file_ = 'Sim_%s.%s.%i.v.dat'%(nml_doc.id,pop,i) + display = "Display_%s_%i_v" % (pop, i) + file_ = "Sim_%s.%s.%i.v.dat" % (nml_doc.id, pop, i) gen_plots_for_quantities[display] = [] gen_saves_for_quantities[file_] = [] for seg in segments_to_plot_record[pop]: - quantity = '%s/%i/%s/%i/v'%(pop,i,pop_nml.component,seg) + quantity = "%s/%i/%s/%i/v" % (pop, i, pop_nml.component, seg) gen_plots_for_quantities[display].append(quantity) gen_saves_for_quantities[file_].append(quantity) - lems_file_name = oc.generate_lems_simulation(nml_doc, network, - nml_file_name, - duration = duration, - dt = 0.025, - gen_plots_for_all_v = False, - gen_plots_for_quantities = gen_plots_for_quantities, - gen_saves_for_all_v = False, - gen_saves_for_quantities = gen_saves_for_quantities) + lems_file_name = oc.generate_lems_simulation( + nml_doc, + network, + nml_file_name, + duration=duration, + dt=0.025, + gen_plots_for_all_v=False, + gen_plots_for_quantities=gen_plots_for_quantities, + gen_saves_for_all_v=False, + gen_saves_for_quantities=gen_saves_for_quantities, + ) else: lems_file_name = None return nml_doc, nml_file_name, lems_file_name -if __name__ == '__main__': - - if '-test' in sys.argv: - - generate(num_pre = 1, - num_post=1, - duration = 1000) +if __name__ == "__main__": + if "-test" in sys.argv: + generate(num_pre=1, num_post=1, duration=1000) else: generate() diff --git a/examples/HDF5/ACNet.net.nml.h5 b/examples/HDF5/ACNet.net.nml.h5 index 9a30ab1..2fc3f0e 100644 Binary files a/examples/HDF5/ACNet.net.nml.h5 and b/examples/HDF5/ACNet.net.nml.h5 differ diff --git a/examples/HDF5/IClamps.net.nml.h5 b/examples/HDF5/IClamps.net.nml.h5 index e834d75..e635baa 100644 Binary files a/examples/HDF5/IClamps.net.nml.h5 and b/examples/HDF5/IClamps.net.nml.h5 differ diff --git a/examples/HDF5/LEMS_ACNet.xml b/examples/HDF5/LEMS_ACNet.xml index 66e22ac..1d98c75 100644 --- a/examples/HDF5/LEMS_ACNet.xml +++ b/examples/HDF5/LEMS_ACNet.xml @@ -2,7 +2,7 @@ diff --git a/examples/HDF5/LEMS_IClamps.xml b/examples/HDF5/LEMS_IClamps.xml index 4137101..988c4b6 100644 --- a/examples/HDF5/LEMS_IClamps.xml +++ b/examples/HDF5/LEMS_IClamps.xml @@ -2,7 +2,7 @@ diff --git a/examples/HDF5/LEMS_SpikingNet.xml b/examples/HDF5/LEMS_SpikingNet.xml index db5aedb..ad6e1e9 100644 --- a/examples/HDF5/LEMS_SpikingNet.xml +++ b/examples/HDF5/LEMS_SpikingNet.xml @@ -2,7 +2,7 @@ diff --git a/examples/HDF5/SpikingNet.net.nml.h5 b/examples/HDF5/SpikingNet.net.nml.h5 index 14f2d2e..6e4efdc 100644 Binary files a/examples/HDF5/SpikingNet.net.nml.h5 and b/examples/HDF5/SpikingNet.net.nml.h5 differ diff --git a/examples/HDF5/Weights.net.nml.h5 b/examples/HDF5/Weights.net.nml.h5 index 7e2566e..7709fae 100644 Binary files a/examples/HDF5/Weights.net.nml.h5 and b/examples/HDF5/Weights.net.nml.h5 differ diff --git a/examples/IClamps.net.nml b/examples/IClamps.net.nml index b4e7b94..2b788f1 100644 --- a/examples/IClamps.net.nml +++ b/examples/IClamps.net.nml @@ -2,8 +2,8 @@ This NeuroML 2 file was generated by OpenCortex v0.1.18 using: - libNeuroML v0.6.3 - pyNeuroML v1.3.7 + libNeuroML v0.6.8 + pyNeuroML v1.3.22 diff --git a/examples/IClamps.py b/examples/IClamps.py index 27572c0..1b12ffd 100644 --- a/examples/IClamps.py +++ b/examples/IClamps.py @@ -1,89 +1,72 @@ - import opencortex.core as oc nml_doc, network = oc.generate_network("IClamps") -oc.include_opencortex_cell(nml_doc, 'izhikevich/RS.cell.nml') -oc.include_opencortex_cell(nml_doc, 'acnet2/pyr_4_sym_soma.cell.nml') -#oc.include_opencortex_cell(nml_doc, '../NeuroML2/prototypes/BlueBrainProject_NMC/cADpyr229_L23_PC_5ecbf9b163_0_0.cell.nml') +oc.include_opencortex_cell(nml_doc, "izhikevich/RS.cell.nml") +oc.include_opencortex_cell(nml_doc, "acnet2/pyr_4_sym_soma.cell.nml") +# oc.include_opencortex_cell(nml_doc, '../NeuroML2/prototypes/BlueBrainProject_NMC/cADpyr229_L23_PC_5ecbf9b163_0_0.cell.nml') -popIzh = oc.add_single_cell_population(network, - 'popIzh', - 'RS', - color='.8 0 0') +popIzh = oc.add_single_cell_population(network, "popIzh", "RS", color=".8 0 0") import neuroml -popIzh.properties.append(neuroml.Property('radius',5)) -popHH = oc.add_single_cell_population(network, - 'popHH', - 'pyr_4_sym_soma', - z=100, - color='0 .8 0') -''' +popIzh.properties.append(neuroml.Property("radius", 5)) + +popHH = oc.add_single_cell_population( + network, "popHH", "pyr_4_sym_soma", z=100, color="0 .8 0" +) +""" popBBP = oc.add_single_cell_population(network, 'popBBP', 'cADpyr229_L23_PC_5ecbf9b163_0_0', - z=200)''' - -pgIzh = oc.add_pulse_generator(nml_doc, - id="pgIzh", - delay="100ms", - duration="300ms", - amplitude="0.5nA") - -pgHH = oc.add_pulse_generator(nml_doc, - id="pgHH", - delay="100ms", - duration="300ms", - amplitude="0.7nA") -''' + z=200)""" + +pgIzh = oc.add_pulse_generator( + nml_doc, id="pgIzh", delay="100ms", duration="300ms", amplitude="0.5nA" +) + +pgHH = oc.add_pulse_generator( + nml_doc, id="pgHH", delay="100ms", duration="300ms", amplitude="0.7nA" +) +""" pgBBP = oc.add_pulse_generator(nml_doc, id="pgBBP", delay="100ms", duration="300ms", - amplitude="0.7nA")''' - - -oc.add_inputs_to_population(network, - "Stim0", - popIzh, - pgIzh.id, - all_cells=True) - -oc.add_inputs_to_population(network, - "Stim1", - popHH, - pgHH.id, - all_cells=True) -''' + amplitude="0.7nA")""" + + +oc.add_inputs_to_population(network, "Stim0", popIzh, pgIzh.id, all_cells=True) + +oc.add_inputs_to_population(network, "Stim1", popHH, pgHH.id, all_cells=True) +""" oc.add_inputs_to_population(network, "Stim2", popBBP, pgBBP.id, - all_cells=True)''' + all_cells=True)""" -duration = 500 -dt = 0.005 -nml_file_name = '%s.net.nml'%network.id +duration = 500 +dt = 0.005 +nml_file_name = "%s.net.nml" % network.id oc.save_network(nml_doc, nml_file_name, validate=True) -oc.generate_lems_simulation(nml_doc, - network, - nml_file_name, - duration, - dt, - report_file_name='report.iclamp.txt') - -nml_file_name = '%s.net.nml.h5'%network.id -target_dir='HDF5/' -oc.save_network(nml_doc, nml_file_name, validate=False, target_dir=target_dir, format='hdf5') +oc.generate_lems_simulation( + nml_doc, network, nml_file_name, duration, dt, report_file_name="report.iclamp.txt" +) + +nml_file_name = "%s.net.nml.h5" % network.id +target_dir = "HDF5/" +oc.save_network( + nml_doc, nml_file_name, validate=False, target_dir=target_dir, format="hdf5" +) -oc.generate_lems_simulation(nml_doc, - network, - target_dir+nml_file_name, - duration, - dt, - target_dir=target_dir, - report_file_name='report.iclamp.h5.txt') - +oc.generate_lems_simulation( + nml_doc, + network, + target_dir + nml_file_name, + duration, + dt, + target_dir=target_dir, + report_file_name="report.iclamp.h5.txt", +) diff --git a/examples/L23TraubDemo.net.nml b/examples/L23TraubDemo.net.nml index dc8ee08..51855f4 100644 --- a/examples/L23TraubDemo.net.nml +++ b/examples/L23TraubDemo.net.nml @@ -2,8 +2,8 @@ This NeuroML 2 file was generated by OpenCortex v0.1.18 using: - libNeuroML v0.6.3 - pyNeuroML v1.3.7 + libNeuroML v0.6.8 + pyNeuroML v1.3.22 diff --git a/examples/L23TraubDemo.py b/examples/L23TraubDemo.py index 9f4b902..a7f2c91 100644 --- a/examples/L23TraubDemo.py +++ b/examples/L23TraubDemo.py @@ -1,4 +1,3 @@ - import opencortex.core as oc import sys @@ -6,130 +5,120 @@ DEFAULT_RS_POP_SIZE = 1 DEFAULT_BASK_POP_SIZE = 1 -def generate(reference = "L23TraubDemo", - num_rs = DEFAULT_RS_POP_SIZE, - num_bask = DEFAULT_BASK_POP_SIZE, - scalex=1, - scaley=1, - scalez=1, - connections=False, - poisson_inputs=True, - offset_curent_range_pA=None, - prob_conn_ei = 1, - global_delay = 0, - duration = 300, - segments_to_plot_record = {'pop_rs':[0],'pop_bask':[0]}, - format='xml'): - +def generate( + reference="L23TraubDemo", + num_rs=DEFAULT_RS_POP_SIZE, + num_bask=DEFAULT_BASK_POP_SIZE, + scalex=1, + scaley=1, + scalez=1, + connections=False, + poisson_inputs=True, + offset_curent_range_pA=None, + prob_conn_ei=1, + global_delay=0, + duration=300, + segments_to_plot_record={"pop_rs": [0], "pop_bask": [0]}, + format="xml", +): nml_doc, network = oc.generate_network(reference) - #oc.add_cell_and_channels(nml_doc, 'acnet2/pyr_4_sym.cell.nml','pyr_4_sym') - oc.include_opencortex_cell(nml_doc, 'Thalamocortical/L23PyrRS.cell.nml') - oc.include_opencortex_cell(nml_doc, 'Thalamocortical/SupBasket.cell.nml') - - xDim = 500*scalex - yDim = 200*scaley - zDim = 500*scalez - - pop_rs = oc.add_population_in_rectangular_region(network, - 'pop_rs', - 'L23PyrRS', - num_rs, - 0,0,0, - xDim,yDim,zDim, - color='.8 0 0') - - pop_bask = oc.add_population_in_rectangular_region(network, - 'pop_bask', - 'SupBasket', - num_bask, - 0,0,0, - xDim,yDim,zDim, - color='0 0 .8') - - syn0 = oc.add_exp_two_syn(nml_doc, - id="syn0", - gbase="1nS", - erev="0mV", - tau_rise="0.5ms", - tau_decay="10ms") - - syn1 = oc.add_exp_two_syn(nml_doc, - id="syn1", - gbase="2nS", - erev="0mV", - tau_rise="1ms", - tau_decay="15ms") - - - if poisson_inputs: + # oc.add_cell_and_channels(nml_doc, 'acnet2/pyr_4_sym.cell.nml','pyr_4_sym') + oc.include_opencortex_cell(nml_doc, "Thalamocortical/L23PyrRS.cell.nml") + oc.include_opencortex_cell(nml_doc, "Thalamocortical/SupBasket.cell.nml") + + xDim = 500 * scalex + yDim = 200 * scaley + zDim = 500 * scalez + + pop_rs = oc.add_population_in_rectangular_region( + network, "pop_rs", "L23PyrRS", num_rs, 0, 0, 0, xDim, yDim, zDim, color=".8 0 0" + ) + + pop_bask = oc.add_population_in_rectangular_region( + network, + "pop_bask", + "SupBasket", + num_bask, + 0, + 0, + 0, + xDim, + yDim, + zDim, + color="0 0 .8", + ) + + syn0 = oc.add_exp_two_syn( + nml_doc, id="syn0", gbase="1nS", erev="0mV", tau_rise="0.5ms", tau_decay="10ms" + ) + + syn1 = oc.add_exp_two_syn( + nml_doc, id="syn1", gbase="2nS", erev="0mV", tau_rise="1ms", tau_decay="15ms" + ) - pfs = oc.add_poisson_firing_synapse(nml_doc, - id="poissonFiringSyn", - average_rate="150 Hz", - synapse_id=syn0.id) + if poisson_inputs: + pfs = oc.add_poisson_firing_synapse( + nml_doc, id="poissonFiringSyn", average_rate="150 Hz", synapse_id=syn0.id + ) - oc.add_inputs_to_population(network, - "Stim0", - pop_rs, - pfs.id, - all_cells=True) - ''' + oc.add_inputs_to_population(network, "Stim0", pop_rs, pfs.id, all_cells=True) + """ oc.add_inputs_to_population(network, "Stim1", pop_bask, pfs.id, - all_cells=True)''' + all_cells=True)""" if offset_curent_range_pA: - - for pop_id in offset_curent_range_pA: + pop = next(p for p in network.populations if p.id == pop_id) - pop = next(p for p in network.populations if p.id==pop_id) - - pg0 = oc.add_pulse_generator(nml_doc, - id="offset_current_%s"%pop.id, - delay="0ms", - duration="%sms"%duration, - amplitude="1pA") + pg0 = oc.add_pulse_generator( + nml_doc, + id="offset_current_%s" % pop.id, + delay="0ms", + duration="%sms" % duration, + amplitude="1pA", + ) import neuroml import random - - input_list = neuroml.InputList(id="inputs_offset_current_%s"%pop.id, - component=pg0.id, - populations=pop.id) - + + input_list = neuroml.InputList( + id="inputs_offset_current_%s" % pop.id, + component=pg0.id, + populations=pop.id, + ) + network.input_lists.append(input_list) - + min_, max_ = offset_curent_range_pA[pop_id] - + for i in range(pop.get_size()): - - input = neuroml.InputW(id=i, - target="../%s/%i/%s" % (pop.id, i, pop.component), - destination="synapses", - weight=(min_ + (max_-min_)*random.random())) - + input = neuroml.InputW( + id=i, + target="../%s/%i/%s" % (pop.id, i, pop.component), + destination="synapses", + weight=(min_ + (max_ - min_) * random.random()), + ) + input_list.input_ws.append(input) - - - + total_conns = 0 if connections: - - proj = oc.add_probabilistic_projection(network, - "proj0", - pop_rs, - pop_bask, - syn1.id, - prob_conn_ei, - weight=1, - delay=global_delay) - - - ''' + proj = oc.add_probabilistic_projection( + network, + "proj0", + pop_rs, + pop_bask, + syn1.id, + prob_conn_ei, + weight=1, + delay=global_delay, + ) + + """ proj = oc.add_targeted_projection(nml_doc, network, "proj0", @@ -141,91 +130,92 @@ def generate(reference = "L23TraubDemo", pre_segment_group = 'axon_group', post_segment_group = 'dendrite_group', delays_dict = {syn1.id:2}, - weights_dict = {syn1.id:1})''' - - if proj: + weights_dict = {syn1.id:1})""" + + if proj: total_conns += len(proj.connection_wds) - - - if num_rs != DEFAULT_RS_POP_SIZE or num_bask!=DEFAULT_BASK_POP_SIZE: - new_reference = '%s_%scells_%sconns'%(nml_doc.id,num_rs+num_bask,total_conns) + + if num_rs != DEFAULT_RS_POP_SIZE or num_bask != DEFAULT_BASK_POP_SIZE: + new_reference = "%s_%scells_%sconns" % ( + nml_doc.id, + num_rs + num_bask, + total_conns, + ) network.id = new_reference nml_doc.id = new_reference - nml_file_name = '%s.net.%s'%(network.id,'nml.h5' if format == 'hdf5' else 'nml') - oc.save_network(nml_doc, - nml_file_name, - validate=(format=='xml'), - format = format) + nml_file_name = "%s.net.%s" % (network.id, "nml.h5" if format == "hdf5" else "nml") + oc.save_network(nml_doc, nml_file_name, validate=(format == "xml"), format=format) + + if format == "xml": + gen_plots_for_quantities = {} # Dict with displays vs lists of quantity paths + gen_saves_for_quantities = {} # Dict with file names vs lists of quantity paths - if format=='xml': - gen_plots_for_quantities = {} # Dict with displays vs lists of quantity paths - gen_saves_for_quantities = {} # Dict with file names vs lists of quantity paths - for pop in segments_to_plot_record.keys(): pop_nml = network.get_by_id(pop) - if pop_nml is not None and pop_nml.size>0: + if pop_nml is not None and pop_nml.size > 0: for i in range(int(pop_nml.size)): - gen_plots_for_quantities['Display_%s_%i_v'%(pop,i)] = [] - gen_saves_for_quantities['Sim_%s.%s.%i.v.dat'%(nml_doc.id,pop,i)] = [] + gen_plots_for_quantities["Display_%s_%i_v" % (pop, i)] = [] + gen_saves_for_quantities[ + "Sim_%s.%s.%i.v.dat" % (nml_doc.id, pop, i) + ] = [] for seg in segments_to_plot_record[pop]: - quantity = '%s/%i/%s/%i/v'%(pop,i,pop_nml.component,seg) - gen_plots_for_quantities['Display_%s_%i_v'%(pop,i)].append(quantity) - gen_saves_for_quantities['Sim_%s.%s.%i.v.dat'%(nml_doc.id,pop,i)].append(quantity) - - - - lems_file_name = oc.generate_lems_simulation(nml_doc, network, - nml_file_name, - duration = duration, - dt = 0.025, - gen_plots_for_all_v = False, - gen_plots_for_quantities = gen_plots_for_quantities, - gen_saves_for_all_v = False, - gen_saves_for_quantities = gen_saves_for_quantities) + quantity = "%s/%i/%s/%i/v" % (pop, i, pop_nml.component, seg) + gen_plots_for_quantities["Display_%s_%i_v" % (pop, i)].append( + quantity + ) + gen_saves_for_quantities[ + "Sim_%s.%s.%i.v.dat" % (nml_doc.id, pop, i) + ].append(quantity) + + lems_file_name = oc.generate_lems_simulation( + nml_doc, + network, + nml_file_name, + duration=duration, + dt=0.025, + gen_plots_for_all_v=False, + gen_plots_for_quantities=gen_plots_for_quantities, + gen_saves_for_all_v=False, + gen_saves_for_quantities=gen_saves_for_quantities, + ) else: lems_file_name = None - + return nml_doc, nml_file_name, lems_file_name -if __name__ == '__main__': - - if '-test' in sys.argv: - - generate(num_rs = 2, - num_bask=0, - duration = 50, - global_delay = 2) - - generate(num_rs = 0, - num_bask=4, - duration = 10, - offset_curent_range_pA = { 'pop_bask': [-50,50] }, - poisson_inputs=False ) - - #segments_to_plot_record = {'pop_bask':[0,117,104,55]}) - - - - generate(num_rs = 8, - num_bask=4, - duration = 200, - connections = True, - global_delay = 2) - - generate(num_rs = 32, - num_bask=16, - duration = 200, - offset_curent_range_pA = { 'pop_rs': [-50,50] }, - connections = True, - global_delay = 2, - prob_conn_ei = 0.2) - +if __name__ == "__main__": + if "-test" in sys.argv: + generate(num_rs=2, num_bask=0, duration=50, global_delay=2) + + generate( + num_rs=0, + num_bask=4, + duration=10, + offset_curent_range_pA={"pop_bask": [-50, 50]}, + poisson_inputs=False, + ) + + # segments_to_plot_record = {'pop_bask':[0,117,104,55]}) + + generate(num_rs=8, num_bask=4, duration=200, connections=True, global_delay=2) + + generate( + num_rs=32, + num_bask=16, + duration=200, + offset_curent_range_pA={"pop_rs": [-50, 50]}, + connections=True, + global_delay=2, + prob_conn_ei=0.2, + ) + else: - - generate(global_delay = 5, - connections = True, - offset_curent_range_pA = { 'pop_rs': [-50,50] }, - duration = 300) + generate( + global_delay=5, + connections=True, + offset_curent_range_pA={"pop_rs": [-50, 50]}, + duration=300, + ) diff --git a/examples/LEMS_ACNet.xml b/examples/LEMS_ACNet.xml index a30b45d..e574490 100644 --- a/examples/LEMS_ACNet.xml +++ b/examples/LEMS_ACNet.xml @@ -2,7 +2,7 @@ diff --git a/examples/LEMS_Balanced.xml b/examples/LEMS_Balanced.xml index 81916c1..d155ebc 100644 --- a/examples/LEMS_Balanced.xml +++ b/examples/LEMS_Balanced.xml @@ -2,7 +2,7 @@ diff --git a/examples/LEMS_Balanced_610cells_0conns.xml b/examples/LEMS_Balanced_610cells_0conns.xml index 467e61d..a3f7fbd 100644 --- a/examples/LEMS_Balanced_610cells_0conns.xml +++ b/examples/LEMS_Balanced_610cells_0conns.xml @@ -2,7 +2,7 @@ diff --git a/examples/LEMS_Complex.xml b/examples/LEMS_Complex.xml index c814402..a111610 100644 --- a/examples/LEMS_Complex.xml +++ b/examples/LEMS_Complex.xml @@ -2,7 +2,7 @@ diff --git a/examples/LEMS_Deterministic.xml b/examples/LEMS_Deterministic.xml index 28b7d5d..40e9d3b 100644 --- a/examples/LEMS_Deterministic.xml +++ b/examples/LEMS_Deterministic.xml @@ -2,7 +2,7 @@ diff --git a/examples/LEMS_GapJunctions.xml b/examples/LEMS_GapJunctions.xml index 2aa6ee0..40eca90 100644 --- a/examples/LEMS_GapJunctions.xml +++ b/examples/LEMS_GapJunctions.xml @@ -2,7 +2,7 @@ diff --git a/examples/LEMS_IClamps.xml b/examples/LEMS_IClamps.xml index 78e44f1..7eed990 100644 --- a/examples/LEMS_IClamps.xml +++ b/examples/LEMS_IClamps.xml @@ -2,7 +2,7 @@ diff --git a/examples/LEMS_L23TraubDemo.xml b/examples/LEMS_L23TraubDemo.xml index 9655567..3605b84 100644 --- a/examples/LEMS_L23TraubDemo.xml +++ b/examples/LEMS_L23TraubDemo.xml @@ -2,7 +2,7 @@ diff --git a/examples/LEMS_Recording.xml b/examples/LEMS_Recording.xml index f94fd48..797a15f 100644 --- a/examples/LEMS_Recording.xml +++ b/examples/LEMS_Recording.xml @@ -2,7 +2,7 @@ diff --git a/examples/LEMS_SimpleNet.xml b/examples/LEMS_SimpleNet.xml index 55c400c..b882cbd 100644 --- a/examples/LEMS_SimpleNet.xml +++ b/examples/LEMS_SimpleNet.xml @@ -2,7 +2,7 @@ diff --git a/examples/LEMS_SpikingNet.xml b/examples/LEMS_SpikingNet.xml index a4d605a..214f79d 100644 --- a/examples/LEMS_SpikingNet.xml +++ b/examples/LEMS_SpikingNet.xml @@ -2,7 +2,7 @@ diff --git a/examples/LEMS_VClamp.xml b/examples/LEMS_VClamp.xml index efca50d..eb96bb9 100644 --- a/examples/LEMS_VClamp.xml +++ b/examples/LEMS_VClamp.xml @@ -2,7 +2,7 @@ diff --git a/examples/LEMS_Weights.xml b/examples/LEMS_Weights.xml index 0c22fcd..6fa23c9 100644 --- a/examples/LEMS_Weights.xml +++ b/examples/LEMS_Weights.xml @@ -2,7 +2,7 @@ diff --git a/examples/Multiscale.py b/examples/Multiscale.py index 186f7a6..74f80ac 100644 --- a/examples/Multiscale.py +++ b/examples/Multiscale.py @@ -1,7 +1,7 @@ -''' +""" Generates a NeuroML 2 file with many types of cells, populations and inputs for testing purposes -''' +""" import opencortex.core as oc import sys @@ -18,382 +18,422 @@ def scale_pop_size(baseline, scale): - return max(min_pop_size, int(baseline*scale)) - - -def generate(scalePops = 1, - percentage_exc_detailed=0, - scalex=1, - scaley=1, - scalez=1, - ratio_inh_exc=2, - connections=True, - duration = 1000, - input_rate = 150, - global_delay = 2, - max_in_pop_to_plot_and_save = 5, - format='xml', - run_in_simulator=None): - - reference = ("Multiscale__g%s__i%s"%(ratio_inh_exc,input_rate)).replace('.','_') - - - num_exc = scale_pop_size(80,scalePops) - num_exc2 = int(0.5 + num_exc*percentage_exc_detailed/100.0) + return max(min_pop_size, int(baseline * scale)) + + +def generate( + scalePops=1, + percentage_exc_detailed=0, + scalex=1, + scaley=1, + scalez=1, + ratio_inh_exc=2, + connections=True, + duration=1000, + input_rate=150, + global_delay=2, + max_in_pop_to_plot_and_save=5, + format="xml", + run_in_simulator=None, +): + reference = ("Multiscale__g%s__i%s" % (ratio_inh_exc, input_rate)).replace(".", "_") + + num_exc = scale_pop_size(80, scalePops) + num_exc2 = int(0.5 + num_exc * percentage_exc_detailed / 100.0) num_exc -= num_exc2 - num_inh = scale_pop_size(40,scalePops) - + num_inh = scale_pop_size(40, scalePops) + nml_doc, network = oc.generate_network(reference) - oc.include_opencortex_cell(nml_doc, 'AllenInstituteCellTypesDB_HH/HH_477127614.cell.nml') - oc.include_opencortex_cell(nml_doc, 'AllenInstituteCellTypesDB_HH/HH_476686112.cell.nml') - oc.include_opencortex_cell(nml_doc, 'L23Pyr_SmithEtAl2013/L23_NoHotSpot.cell.nml') - + oc.include_opencortex_cell( + nml_doc, "AllenInstituteCellTypesDB_HH/HH_477127614.cell.nml" + ) + oc.include_opencortex_cell( + nml_doc, "AllenInstituteCellTypesDB_HH/HH_476686112.cell.nml" + ) + oc.include_opencortex_cell(nml_doc, "L23Pyr_SmithEtAl2013/L23_NoHotSpot.cell.nml") - xDim = 1000*scalex - yDim = 300*scaley - zDim = 1000*scalez + xDim = 1000 * scalex + yDim = 300 * scaley + zDim = 1000 * scalez xs = -200 ys = -150 zs = 100 ##### Synapses - - exc_syn_nS = 1. - - synAmpa1 = oc.add_exp_two_syn(nml_doc, id="synAmpa1", gbase="%snS"%exc_syn_nS, - erev="0mV", tau_rise="0.5ms", tau_decay="5ms") - synGaba1 = oc.add_exp_two_syn(nml_doc, id="synGaba1", gbase="%snS"%(exc_syn_nS*ratio_inh_exc), - erev="-80mV", tau_rise="1ms", tau_decay="20ms") + exc_syn_nS = 1.0 + + synAmpa1 = oc.add_exp_two_syn( + nml_doc, + id="synAmpa1", + gbase="%snS" % exc_syn_nS, + erev="0mV", + tau_rise="0.5ms", + tau_decay="5ms", + ) + + synGaba1 = oc.add_exp_two_syn( + nml_doc, + id="synGaba1", + gbase="%snS" % (exc_syn_nS * ratio_inh_exc), + erev="-80mV", + tau_rise="1ms", + tau_decay="20ms", + ) ##### Input types - - pfs1 = oc.add_poisson_firing_synapse(nml_doc, - id="psf1", - average_rate="%s Hz"%input_rate, - synapse_id=synAmpa1.id) - + pfs1 = oc.add_poisson_firing_synapse( + nml_doc, id="psf1", average_rate="%s Hz" % input_rate, synapse_id=synAmpa1.id + ) ##### Populations - popExc = oc.add_population_in_rectangular_region(network, - 'popExc', - 'HH_477127614', - num_exc, - xs,ys,zs, - xDim,yDim,zDim, - color='0 0 1') - - popExc2 = oc.add_population_in_rectangular_region(network, - 'popExc2', - 'L23_NoHotSpot', - num_exc2, - xs,ys,zs, - xDim,yDim,zDim, - color='0 1 0') - - allExc = [popExc,popExc2] - - popInh = oc.add_population_in_rectangular_region(network, - 'popInh', - 'HH_476686112', - num_inh, - xs,ys,zs, - xDim,yDim,zDim, - color='1 0 0') - + popExc = oc.add_population_in_rectangular_region( + network, + "popExc", + "HH_477127614", + num_exc, + xs, + ys, + zs, + xDim, + yDim, + zDim, + color="0 0 1", + ) + + popExc2 = oc.add_population_in_rectangular_region( + network, + "popExc2", + "L23_NoHotSpot", + num_exc2, + xs, + ys, + zs, + xDim, + yDim, + zDim, + color="0 1 0", + ) + + allExc = [popExc, popExc2] + + popInh = oc.add_population_in_rectangular_region( + network, + "popInh", + "HH_476686112", + num_inh, + xs, + ys, + zs, + xDim, + yDim, + zDim, + color="1 0 0", + ) ##### Projections if connections: - for pop1 in allExc: - for pop2 in allExc: - proj = oc.add_probabilistic_projection(network, "proj0", - pop1, pop2, - synAmpa1.id, 0.5, delay = global_delay) - - proj = oc.add_probabilistic_projection(network, "proj1", - pop1, popInh, - synAmpa1.id, 0.7, delay = global_delay) + proj = oc.add_probabilistic_projection( + network, "proj0", pop1, pop2, synAmpa1.id, 0.5, delay=global_delay + ) - proj = oc.add_probabilistic_projection(network, "proj2", - popInh, pop1, - synGaba1.id, 0.7, delay = global_delay) + proj = oc.add_probabilistic_projection( + network, "proj1", pop1, popInh, synAmpa1.id, 0.7, delay=global_delay + ) - proj = oc.add_probabilistic_projection(network, "proj3", - popInh, popInh, - synGaba1.id, 0.5, delay = global_delay) + proj = oc.add_probabilistic_projection( + network, "proj2", popInh, pop1, synGaba1.id, 0.7, delay=global_delay + ) - + proj = oc.add_probabilistic_projection( + network, "proj3", popInh, popInh, synGaba1.id, 0.5, delay=global_delay + ) ##### Inputs for pop in allExc: - oc.add_inputs_to_population(network, "Stim_%s"%pop.id, - pop, pfs1.id, - all_cells=True) - - - - ##### Save NeuroML and LEMS Simulation files - - target_dir='./temp/' - - nml_file_name = '%s.net.%s'%(network.id,'nml.h5' if format == 'hdf5' else 'nml') - oc.save_network(nml_doc, - nml_file_name, - validate=(format=='xml'), - format = format, - target_dir=target_dir) - - if format=='xml': - - plot_v = {popExc.id:[],popExc2.id:[],popInh.id:[]} - exc_traces = '%s_%s_v.dat'%(network.id,popExc.id) - exc2_traces = '%s_%s_v.dat'%(network.id,popExc2.id) - inh_traces = '%s_%s_v.dat'%(network.id,popInh.id) - save_v = {exc_traces:[], inh_traces:[], exc2_traces:[]} - - - for i in range(min(max_in_pop_to_plot_and_save,num_exc)): - plot_v[popExc.id].append("%s/%i/%s/v"%(popExc.id,i,popExc.component)) - save_v[exc_traces].append("%s/%i/%s/v"%(popExc.id,i,popExc.component)) - - for i in range(min(max_in_pop_to_plot_and_save,num_exc2)): - plot_v[popExc2.id].append("%s/%i/%s/v"%(popExc2.id,i,popExc2.component)) - save_v[exc2_traces].append("%s/%i/%s/v"%(popExc2.id,i,popExc2.component)) - - for i in range(min(max_in_pop_to_plot_and_save,num_inh)): - plot_v[popInh.id].append("%s/%i/%s/v"%(popInh.id,i,popInh.component)) - save_v[inh_traces].append("%s/%i/%s/v"%(popInh.id,i,popInh.component)) - - gen_spike_saves_for_all_somas = run_in_simulator!='jNeuroML_NetPyNE' - - lems_file_name = oc.generate_lems_simulation(nml_doc, network, - target_dir+nml_file_name, - duration = duration, - dt = 0.025, - gen_plots_for_all_v = False, - gen_plots_for_quantities = plot_v, - gen_saves_for_all_v = False, - gen_saves_for_quantities = save_v, - gen_spike_saves_for_all_somas = gen_spike_saves_for_all_somas, - target_dir=target_dir) - - + oc.add_inputs_to_population( + network, "Stim_%s" % pop.id, pop, pfs1.id, all_cells=True + ) + + ##### Save NeuroML and LEMS Simulation files + + target_dir = "./temp/" + + nml_file_name = "%s.net.%s" % (network.id, "nml.h5" if format == "hdf5" else "nml") + oc.save_network( + nml_doc, + nml_file_name, + validate=(format == "xml"), + format=format, + target_dir=target_dir, + ) + + if format == "xml": + plot_v = {popExc.id: [], popExc2.id: [], popInh.id: []} + exc_traces = "%s_%s_v.dat" % (network.id, popExc.id) + exc2_traces = "%s_%s_v.dat" % (network.id, popExc2.id) + inh_traces = "%s_%s_v.dat" % (network.id, popInh.id) + save_v = {exc_traces: [], inh_traces: [], exc2_traces: []} + + for i in range(min(max_in_pop_to_plot_and_save, num_exc)): + plot_v[popExc.id].append("%s/%i/%s/v" % (popExc.id, i, popExc.component)) + save_v[exc_traces].append("%s/%i/%s/v" % (popExc.id, i, popExc.component)) + + for i in range(min(max_in_pop_to_plot_and_save, num_exc2)): + plot_v[popExc2.id].append("%s/%i/%s/v" % (popExc2.id, i, popExc2.component)) + save_v[exc2_traces].append( + "%s/%i/%s/v" % (popExc2.id, i, popExc2.component) + ) + + for i in range(min(max_in_pop_to_plot_and_save, num_inh)): + plot_v[popInh.id].append("%s/%i/%s/v" % (popInh.id, i, popInh.component)) + save_v[inh_traces].append("%s/%i/%s/v" % (popInh.id, i, popInh.component)) + + gen_spike_saves_for_all_somas = run_in_simulator != "jNeuroML_NetPyNE" + + lems_file_name = oc.generate_lems_simulation( + nml_doc, + network, + target_dir + nml_file_name, + duration=duration, + dt=0.025, + gen_plots_for_all_v=False, + gen_plots_for_quantities=plot_v, + gen_saves_for_all_v=False, + gen_saves_for_quantities=save_v, + gen_spike_saves_for_all_somas=gen_spike_saves_for_all_somas, + target_dir=target_dir, + ) + if run_in_simulator: - - print("Running %s in %s"%(lems_file_name, run_in_simulator)) - - traces, events = oc.simulate_network(lems_file_name, - run_in_simulator, - max_memory='4000M', - nogui=True, - load_saved_data=True, - reload_events=True, - plot=False, - verbose=False) - - - print("Reloaded traces: %s"%traces.keys()) - #print("Reloaded events: %s"%events.keys()) - + print("Running %s in %s" % (lems_file_name, run_in_simulator)) + + traces, events = oc.simulate_network( + lems_file_name, + run_in_simulator, + max_memory="4000M", + nogui=True, + load_saved_data=True, + reload_events=True, + plot=False, + verbose=False, + ) + + print("Reloaded traces: %s" % traces.keys()) + # print("Reloaded events: %s"%events.keys()) + use_events_for_rates = False - + exc_rate = 0 inh_rate = 0 - + if use_events_for_rates: - if (run_in_simulator=='jNeuroML_NetPyNE'): - raise('Saving of spikes (and so calculation of rates) not yet supported in jNeuroML_NetPyNE') + if run_in_simulator == "jNeuroML_NetPyNE": + raise ( + "Saving of spikes (and so calculation of rates) not yet supported in jNeuroML_NetPyNE" + ) for ek in events.keys(): - rate = 1000 * len(events[ek])/float(duration) - print("Cell %s has rate %s Hz"%(ek,rate)) - if 'popExc' in ek: - exc_rate += rate/num_exc - if 'popInh' in ek: - inh_rate += rate/num_inh - + rate = 1000 * len(events[ek]) / float(duration) + print("Cell %s has rate %s Hz" % (ek, rate)) + if "popExc" in ek: + exc_rate += rate / num_exc + if "popInh" in ek: + inh_rate += rate / num_inh + else: - tot_exc_rate = 0 + tot_exc_rate = 0 exc_cells = 0 - tot_inh_rate = 0 + tot_inh_rate = 0 inh_cells = 0 - tt = [t*1000 for t in traces['t']] + tt = [t * 1000 for t in traces["t"]] for tk in traces.keys(): - if tk!='t': - rate = get_rate_from_trace(tt,[v*1000 for v in traces[tk]]) - print("Cell %s has rate %s Hz"%(tk,rate)) - if 'popExc' in tk: + if tk != "t": + rate = get_rate_from_trace(tt, [v * 1000 for v in traces[tk]]) + print("Cell %s has rate %s Hz" % (tk, rate)) + if "popExc" in tk: tot_exc_rate += rate - exc_cells+=1 - if 'popInh' in tk: + exc_cells += 1 + if "popInh" in tk: tot_inh_rate += rate - inh_cells+=1 - - exc_rate = tot_exc_rate/exc_cells - inh_rate = tot_inh_rate/inh_cells - - - - print("Run %s: Exc rate: %s Hz; Inh rate %s Hz"%(reference,exc_rate, inh_rate)) - + inh_cells += 1 + + exc_rate = tot_exc_rate / exc_cells + inh_rate = tot_inh_rate / inh_cells + + print( + "Run %s: Exc rate: %s Hz; Inh rate %s Hz" + % (reference, exc_rate, inh_rate) + ) + return exc_rate, inh_rate, traces - + else: lems_file_name = None - + return nml_doc, nml_file_name, lems_file_name - - -def get_rate_from_trace(times, volts): - analysis_var={'peak_delta':0,'baseline':0,'dvdt_threshold':0, 'peak_threshold':0} + +def get_rate_from_trace(times, volts): + analysis_var = { + "peak_delta": 0, + "baseline": 0, + "dvdt_threshold": 0, + "peak_threshold": 0, + } try: - analysis_data=analysis.IClampAnalysis(volts, - times, - analysis_var, - start_analysis=0, - end_analysis=times[-1], - smooth_data=False, - show_smoothed_data=False) + analysis_data = analysis.IClampAnalysis( + volts, + times, + analysis_var, + start_analysis=0, + end_analysis=times[-1], + smooth_data=False, + show_smoothed_data=False, + ) analysed = analysis_data.analyse() pp.pprint(analysed) - return analysed['mean_spike_frequency'] - + return analysed["mean_spike_frequency"] + except: return 0 - + def _plot_(X, g_rng, i_rng, sbplt=111, ttl=[]): ax = pl.subplot(sbplt) pl.title(ttl) - pl.imshow(X, origin='lower', interpolation='none') - pl.xlabel('Ratio inh/exc') - pl.ylabel('Input (Hz)') - ax.set_xticks(range(0,len(g_rng))); ax.set_xticklabels(g_rng) - ax.set_yticks(range(0,len(i_rng))); ax.set_yticklabels(i_rng) + pl.imshow(X, origin="lower", interpolation="none") + pl.xlabel("Ratio inh/exc") + pl.ylabel("Input (Hz)") + ax.set_xticks(range(0, len(g_rng))) + ax.set_xticklabels(g_rng) + ax.set_yticks(range(0, len(i_rng))) + ax.set_yticklabels(i_rng) pl.colorbar() -if __name__ == '__main__': - - if '-all' in sys.argv: +if __name__ == "__main__": + if "-all" in sys.argv: generate() - - generate(scalePops = 5, - scalex=2, - scalez=2, - connections=False) - - - elif '-paramSweep' in sys.argv: - + + generate(scalePops=5, scalex=2, scalez=2, connections=False) + + elif "-paramSweep" in sys.argv: duration = 600 - run_in_simulator='jNeuroML_NEURON' - #run_in_simulator='jNeuroML_NetPyNE' + run_in_simulator = "jNeuroML_NEURON" + # run_in_simulator='jNeuroML_NetPyNE' scalePops = 1 - + quick = False quick = True - - g_rng = np.arange(.5, 4.5, .5) + + g_rng = np.arange(0.5, 4.5, 0.5) i_rng = np.arange(50, 400, 50) - trace_highlight = [(1.5,150)] - + trace_highlight = [(1.5, 150)] + if quick: - g_rng = [2,3,4] + g_rng = [2, 3, 4] g_rng = [1.5] - i_rng = [100,150,200] + i_rng = [100, 150, 200] i_rng = [150] duration = 1000 - scalePops = .3 - + scalePops = 0.3 Rexc = np.zeros((len(g_rng), len(i_rng))) Rinh = np.zeros((len(g_rng), len(i_rng))) - - count=1 + + count = 1 for i1, g in enumerate(g_rng): for i2, i in enumerate(i_rng): print("====================================") highlight = False for h in trace_highlight: - if h[0]==g and h[1]==i: + if h[0] == g and h[1] == i: highlight = True - print(" Run %s of %s: g = %s; i=%s (highlighting: %s)"%(count, len(g_rng)*len(i_rng), g, i, highlight)) - info = generate(scalePops = scalePops, + print( + " Run %s of %s: g = %s; i=%s (highlighting: %s)" + % (count, len(g_rng) * len(i_rng), g, i, highlight) + ) + info = generate( + scalePops=scalePops, scalex=2, scalez=2, - duration = duration, - max_in_pop_to_plot_and_save = 5, - global_delay = 2, - ratio_inh_exc = g, + duration=duration, + max_in_pop_to_plot_and_save=5, + global_delay=2, + ratio_inh_exc=g, input_rate=i, - run_in_simulator=run_in_simulator) - - Rexc[i1,i2] = info[0] - Rinh[i1,i2] = info[1] + run_in_simulator=run_in_simulator, + ) + + Rexc[i1, i2] = info[0] + Rinh[i1, i2] = info[1] if highlight: traces = info[2] all_t = [] all_v = [] colours = [] - tr_shade_e=1 - tr_shade_e2=1 - tr_shade_i=1 + tr_shade_e = 1 + tr_shade_e2 = 1 + tr_shade_i = 1 for vs in traces.keys(): - if vs!='t': + if vs != "t": all_v.append(traces[vs]) - all_t.append(traces['t']) - if 'Exc2' in vs: - colours.append((1-tr_shade_e2,1,1-tr_shade_e2)) - tr_shade_e2*=0.8 - elif 'Exc' in vs: - colours.append((1-tr_shade_e,1-tr_shade_e,1)) - tr_shade_e*=0.8 + all_t.append(traces["t"]) + if "Exc2" in vs: + colours.append((1 - tr_shade_e2, 1, 1 - tr_shade_e2)) + tr_shade_e2 *= 0.8 + elif "Exc" in vs: + colours.append((1 - tr_shade_e, 1 - tr_shade_e, 1)) + tr_shade_e *= 0.8 else: - colours.append((1,1-tr_shade_i,1-tr_shade_i)) - tr_shade_i*=0.8 - - - pynml.generate_plot(all_t,all_v,"Sim g=%s, i=%s"%(g,i),colors=colours,show_plot_already=False) - count+=1 - - - - fig = pl.figure(figsize=(16,8)) - info = "%s: scale %s, %s ms"%(run_in_simulator,scalePops, duration) + colours.append((1, 1 - tr_shade_i, 1 - tr_shade_i)) + tr_shade_i *= 0.8 + + pynml.generate_plot( + all_t, + all_v, + "Sim g=%s, i=%s" % (g, i), + colors=colours, + show_plot_already=False, + ) + count += 1 + + fig = pl.figure(figsize=(16, 8)) + info = "%s: scale %s, %s ms" % (run_in_simulator, scalePops, duration) fig.canvas.set_window_title(info) pl.suptitle(info) - _plot_(Rexc.T, g_rng, i_rng, 221, 'Rates Exc (Hz)') - _plot_(Rinh.T, g_rng, i_rng, 222, 'Rates Inh (Hz)') - - - - pl.subplots_adjust(wspace=.3, hspace=.3) + _plot_(Rexc.T, g_rng, i_rng, 221, "Rates Exc (Hz)") + _plot_(Rinh.T, g_rng, i_rng, 222, "Rates Inh (Hz)") + pl.subplots_adjust(wspace=0.3, hspace=0.3) - pl.savefig('%s_%s_%sms.png'%(run_in_simulator,scalePops, duration), bbox_inches='tight') - print("Finished: "+info) + pl.savefig( + "%s_%s_%sms.png" % (run_in_simulator, scalePops, duration), + bbox_inches="tight", + ) + print("Finished: " + info) pl.show() - else: - generate(ratio_inh_exc=1.5, - duration = 500, - input_rate = 250, - scalePops=.2, - percentage_exc_detailed=50) \ No newline at end of file + generate( + ratio_inh_exc=1.5, + duration=500, + input_rate=250, + scalePops=0.2, + percentage_exc_detailed=50, + ) diff --git a/examples/Recording.net.nml b/examples/Recording.net.nml index 6343239..17ae2f6 100644 --- a/examples/Recording.net.nml +++ b/examples/Recording.net.nml @@ -2,8 +2,8 @@ This NeuroML 2 file was generated by OpenCortex v0.1.18 using: - libNeuroML v0.6.3 - pyNeuroML v1.3.7 + libNeuroML v0.6.8 + pyNeuroML v1.3.22 diff --git a/examples/Recording.py b/examples/Recording.py index 5126209..a98235b 100644 --- a/examples/Recording.py +++ b/examples/Recording.py @@ -1,6 +1,6 @@ -''' +""" Generates a NeuroML 2 file with a LEMS file recording many details of the network -''' +""" import opencortex.core as oc @@ -10,7 +10,7 @@ ##### Cells -oc.include_opencortex_cell(nml_doc, 'acnet2/pyr_4_sym.cell.nml') +oc.include_opencortex_cell(nml_doc, "acnet2/pyr_4_sym.cell.nml") xDim = 500 yDim = 100 @@ -20,78 +20,61 @@ ##### Synapses -synAmpa1 = oc.add_exp_two_syn(nml_doc, id="synAmpa1", gbase="1nS", - erev="0mV", tau_rise="0.5ms", tau_decay="10ms") - -synAmpa2 = oc.add_exp_two_syn(nml_doc, id="synAmpa2", gbase="0.5nS", - erev="0mV", tau_rise="0.5ms", tau_decay="5ms") +synAmpa1 = oc.add_exp_two_syn( + nml_doc, id="synAmpa1", gbase="1nS", erev="0mV", tau_rise="0.5ms", tau_decay="10ms" +) + +synAmpa2 = oc.add_exp_two_syn( + nml_doc, id="synAmpa2", gbase="0.5nS", erev="0mV", tau_rise="0.5ms", tau_decay="5ms" +) ##### Input types -pg0 = oc.add_pulse_generator(nml_doc, - id="pg0", - delay="10ms", - duration="300ms", - amplitude="0.3nA") - -pg1 = oc.add_pulse_generator(nml_doc, - id="pg1", - delay="50ms", - duration="400ms", - amplitude="0.35nA") - -pfs = oc.add_poisson_firing_synapse(nml_doc, - id="poissonFiringSyn", - average_rate="150 Hz", - synapse_id=synAmpa2.id) - +pg0 = oc.add_pulse_generator( + nml_doc, id="pg0", delay="10ms", duration="300ms", amplitude="0.3nA" +) + +pg1 = oc.add_pulse_generator( + nml_doc, id="pg1", delay="50ms", duration="400ms", amplitude="0.35nA" +) + +pfs = oc.add_poisson_firing_synapse( + nml_doc, id="poissonFiringSyn", average_rate="150 Hz", synapse_id=synAmpa2.id +) + ##### Populations -pop0 = oc.add_population_in_rectangular_region(network, - 'pop0', - 'pyr_4_sym', - 5, - 0,offset,0, - xDim,yDim,zDim, - color='0 .8 0') +pop0 = oc.add_population_in_rectangular_region( + network, "pop0", "pyr_4_sym", 5, 0, offset, 0, xDim, yDim, zDim, color="0 .8 0" +) -offset+=yDim +offset += yDim ##### Projections -oc.add_probabilistic_projection(network, - "proj0", - pop0, - pop0, - synAmpa1.id, - 0.5) - +oc.add_probabilistic_projection(network, "proj0", pop0, pop0, synAmpa1.id, 0.5) + ##### Inputs -oc.add_inputs_to_population(network, "Stim0", - pop0, pg0.id, - only_cells=[0]) - -oc.add_inputs_to_population(network, "Stim1", - pop0, pg1.id, - only_cells=[1]) +oc.add_inputs_to_population(network, "Stim0", pop0, pg0.id, only_cells=[0]) + +oc.add_inputs_to_population(network, "Stim1", pop0, pg1.id, only_cells=[1]) + - -oc.add_inputs_to_population(network, "Stim2", - pop0, pfs.id, - all_cells=True) +oc.add_inputs_to_population(network, "Stim2", pop0, pfs.id, all_cells=True) -nml_file_name = '%s.net.nml'%network.id +nml_file_name = "%s.net.nml" % network.id oc.save_network(nml_doc, nml_file_name, validate=True) -oc.generate_lems_simulation(nml_doc, - network, - nml_file_name, - duration = 500, - dt = 0.005, - plot_all_segments = True, - save_all_segments = True) - +oc.generate_lems_simulation( + nml_doc, + network, + nml_file_name, + duration=500, + dt=0.005, + plot_all_segments=True, + save_all_segments=True, +) diff --git a/examples/SimpleNet.net.nml b/examples/SimpleNet.net.nml index 432c298..c33bd7e 100644 --- a/examples/SimpleNet.net.nml +++ b/examples/SimpleNet.net.nml @@ -2,8 +2,8 @@ This NeuroML 2 file was generated by OpenCortex v0.1.18 using: - libNeuroML v0.6.3 - pyNeuroML v1.3.7 + libNeuroML v0.6.8 + pyNeuroML v1.3.22 diff --git a/examples/SimpleNet.py b/examples/SimpleNet.py index 1c1da25..cd26147 100644 --- a/examples/SimpleNet.py +++ b/examples/SimpleNet.py @@ -1,72 +1,55 @@ - import opencortex.core as oc min_pop_size = 3 -def scale_pop_size(baseline, scale): - return max(min_pop_size, int(baseline*scale)) - +def scale_pop_size(baseline, scale): + return max(min_pop_size, int(baseline * scale)) -def generate(reference = "SimpleNet", - scale=1, - format='xml'): - population_size = scale_pop_size(3,scale) +def generate(reference="SimpleNet", scale=1, format="xml"): + population_size = scale_pop_size(3, scale) nml_doc, network = oc.generate_network(reference) - oc.include_opencortex_cell(nml_doc, 'izhikevich/RS.cell.nml') + oc.include_opencortex_cell(nml_doc, "izhikevich/RS.cell.nml") - pop = oc.add_population_in_rectangular_region(network, - 'RS_pop', - 'RS', - population_size, - 0,0,0, - 100,100,100, - color='0 .8 0') + pop = oc.add_population_in_rectangular_region( + network, "RS_pop", "RS", population_size, 0, 0, 0, 100, 100, 100, color="0 .8 0" + ) import neuroml - pop.properties.append(neuroml.Property('radius',10)) - - syn = oc.add_exp_two_syn(nml_doc, - id="syn0", - gbase="2nS", - erev="0mV", - tau_rise="0.5ms", - tau_decay="10ms") - - pfs = oc.add_poisson_firing_synapse(nml_doc, - id="poissonFiringSyn", - average_rate="50 Hz", - synapse_id=syn.id) - - oc.add_inputs_to_population(network, - "Stim0", - pop, - pfs.id, - all_cells=True) - - nml_file_name = '%s.net.nml'%network.id - oc.save_network(nml_doc, - nml_file_name, - validate=(format=='xml'), - format = format) - - if format=='xml': - oc.generate_lems_simulation(nml_doc, - network, - nml_file_name, - duration = 500, - dt = 0.025, - report_file_name='report.simple.txt') - - -if __name__ == '__main__': - - import sys - - if len(sys.argv)==2: + + pop.properties.append(neuroml.Property("radius", 10)) + + syn = oc.add_exp_two_syn( + nml_doc, id="syn0", gbase="2nS", erev="0mV", tau_rise="0.5ms", tau_decay="10ms" + ) + + pfs = oc.add_poisson_firing_synapse( + nml_doc, id="poissonFiringSyn", average_rate="50 Hz", synapse_id=syn.id + ) + + oc.add_inputs_to_population(network, "Stim0", pop, pfs.id, all_cells=True) + + nml_file_name = "%s.net.nml" % network.id + oc.save_network(nml_doc, nml_file_name, validate=(format == "xml"), format=format) + + if format == "xml": + oc.generate_lems_simulation( + nml_doc, + network, + nml_file_name, + duration=500, + dt=0.025, + report_file_name="report.simple.txt", + ) + + +if __name__ == "__main__": + import sys + + if len(sys.argv) == 2: generate(scale=int(sys.argv[1])) else: - generate() \ No newline at end of file + generate() diff --git a/examples/SpikingNet.net.nml b/examples/SpikingNet.net.nml index 6ff73c5..dfaf4c2 100644 --- a/examples/SpikingNet.net.nml +++ b/examples/SpikingNet.net.nml @@ -2,8 +2,8 @@ This NeuroML 2 file was generated by OpenCortex v0.1.18 using: - libNeuroML v0.6.3 - pyNeuroML v1.3.7 + libNeuroML v0.6.8 + pyNeuroML v1.3.22 diff --git a/examples/SpikingNet.py b/examples/SpikingNet.py index 67ae2ed..cbbf05a 100644 --- a/examples/SpikingNet.py +++ b/examples/SpikingNet.py @@ -1,4 +1,3 @@ - import opencortex.core as oc population_size0 = 10 @@ -6,83 +5,76 @@ nml_doc, network = oc.generate_network("SpikingNet") -oc.include_opencortex_cell(nml_doc, 'izhikevich/RS.cell.nml') +oc.include_opencortex_cell(nml_doc, "izhikevich/RS.cell.nml") -pop_pre = oc.add_population_in_rectangular_region(network, - 'pop_pre', - 'RS', - population_size0, - 0,0,0, - 100,100,100, - color='.8 0 0') +pop_pre = oc.add_population_in_rectangular_region( + network, "pop_pre", "RS", population_size0, 0, 0, 0, 100, 100, 100, color=".8 0 0" +) import neuroml -pop_pre.properties.append(neuroml.Property('radius',10)) - -pop_post = oc.add_population_in_rectangular_region(network, - 'pop_post', - 'RS', - population_size1, - 0,100,0, - 100,200,100, - color='0 0 .8') - -pop_post.properties.append(neuroml.Property('radius',10)) - -syn0 = oc.add_exp_two_syn(nml_doc, - id="syn0", - gbase="1nS", - erev="0mV", - tau_rise="0.5ms", - tau_decay="10ms") - -syn1 = oc.add_exp_two_syn(nml_doc, - id="syn1", - gbase="2nS", - erev="0mV", - tau_rise="1ms", - tau_decay="15ms") - -pfs = oc.add_poisson_firing_synapse(nml_doc, - id="poissonFiringSyn", - average_rate="150 Hz", - synapse_id=syn0.id) - -oc.add_inputs_to_population(network, - "Stim0", - pop_pre, - pfs.id, - all_cells=True) - -oc.add_probabilistic_projection(network, - "proj0", - pop_pre, - pop_post, - syn1.id, - 0.3, - weight=0.05, - delay=5) - -duration = 1000 -dt = 0.01 -nml_file_name = '%s.net.nml'%network.id + +pop_pre.properties.append(neuroml.Property("radius", 10)) + +pop_post = oc.add_population_in_rectangular_region( + network, + "pop_post", + "RS", + population_size1, + 0, + 100, + 0, + 100, + 200, + 100, + color="0 0 .8", +) + +pop_post.properties.append(neuroml.Property("radius", 10)) + +syn0 = oc.add_exp_two_syn( + nml_doc, id="syn0", gbase="1nS", erev="0mV", tau_rise="0.5ms", tau_decay="10ms" +) + +syn1 = oc.add_exp_two_syn( + nml_doc, id="syn1", gbase="2nS", erev="0mV", tau_rise="1ms", tau_decay="15ms" +) + +pfs = oc.add_poisson_firing_synapse( + nml_doc, id="poissonFiringSyn", average_rate="150 Hz", synapse_id=syn0.id +) + +oc.add_inputs_to_population(network, "Stim0", pop_pre, pfs.id, all_cells=True) + +oc.add_probabilistic_projection( + network, "proj0", pop_pre, pop_post, syn1.id, 0.3, weight=0.05, delay=5 +) + +duration = 1000 +dt = 0.01 +nml_file_name = "%s.net.nml" % network.id oc.save_network(nml_doc, nml_file_name, validate=True) -oc.generate_lems_simulation(nml_doc, - network, - nml_file_name, - duration = duration, - dt = dt, - report_file_name='report.spiking.txt') - -nml_file_name = '%s.net.nml.h5'%network.id -target_dir='HDF5/' -oc.save_network(nml_doc, nml_file_name, validate=False, target_dir=target_dir, format='hdf5') - -oc.generate_lems_simulation(nml_doc, - network, - target_dir+nml_file_name, - duration, - dt, - target_dir=target_dir, - report_file_name='report.spiking.h5.txt') +oc.generate_lems_simulation( + nml_doc, + network, + nml_file_name, + duration=duration, + dt=dt, + report_file_name="report.spiking.txt", +) + +nml_file_name = "%s.net.nml.h5" % network.id +target_dir = "HDF5/" +oc.save_network( + nml_doc, nml_file_name, validate=False, target_dir=target_dir, format="hdf5" +) + +oc.generate_lems_simulation( + nml_doc, + network, + target_dir + nml_file_name, + duration, + dt, + target_dir=target_dir, + report_file_name="report.spiking.h5.txt", +) diff --git a/examples/VClamp.net.nml b/examples/VClamp.net.nml index b76c067..43f0e7b 100644 --- a/examples/VClamp.net.nml +++ b/examples/VClamp.net.nml @@ -2,8 +2,8 @@ This NeuroML 2 file was generated by OpenCortex v0.1.18 using: - libNeuroML v0.6.3 - pyNeuroML v1.3.7 + libNeuroML v0.6.8 + pyNeuroML v1.3.22 diff --git a/examples/VClamp.py b/examples/VClamp.py index 4979870..da43f17 100644 --- a/examples/VClamp.py +++ b/examples/VClamp.py @@ -1,142 +1,144 @@ -''' +""" Generates a NeuroML 2 network with a number of cells with voltage clamps -''' +""" import opencortex.core as oc import sys -def generate(reference = "VClamp", - poisson_inputs=True, - use_vclamp=False, - duration = 500, - format='xml'): - - +def generate( + reference="VClamp", + poisson_inputs=True, + use_vclamp=False, + duration=500, + format="xml", +): nml_doc, network = oc.generate_network(reference) - oc.include_opencortex_cell(nml_doc, 'Thalamocortical/L23PyrRS.cell.nml') - + oc.include_opencortex_cell(nml_doc, "Thalamocortical/L23PyrRS.cell.nml") + num_cells = 4 - pop_rs = oc.add_population_in_rectangular_region(network, - 'popRS', - 'L23PyrRS', - num_cells, - 0,0,0, - 1000,20,20, - color='.8 0 0') - - syn0 = oc.add_exp_two_syn(nml_doc, - id="syn0", - gbase="1nS", - erev="0mV", - tau_rise="0.5ms", - tau_decay="10ms") - - - if poisson_inputs: + pop_rs = oc.add_population_in_rectangular_region( + network, "popRS", "L23PyrRS", num_cells, 0, 0, 0, 1000, 20, 20, color=".8 0 0" + ) - pfs = oc.add_transient_poisson_firing_synapse(nml_doc, - id="poissonFiringSyn", - average_rate="20 Hz", - delay="50 ms", - duration="400 ms", - synapse_id=syn0.id) - - oc.add_targeted_inputs_to_population(network, - "pfs_noise", - pop_rs, - pfs.id, - segment_group='dendrite_group', - number_per_cell = 100, - all_cells=True) + syn0 = oc.add_exp_two_syn( + nml_doc, id="syn0", gbase="1nS", erev="0mV", tau_rise="0.5ms", tau_decay="10ms" + ) + + if poisson_inputs: + pfs = oc.add_transient_poisson_firing_synapse( + nml_doc, + id="poissonFiringSyn", + average_rate="20 Hz", + delay="50 ms", + duration="400 ms", + synapse_id=syn0.id, + ) + + oc.add_targeted_inputs_to_population( + network, + "pfs_noise", + pop_rs, + pfs.id, + segment_group="dendrite_group", + number_per_cell=100, + all_cells=True, + ) all_vclamp_segs = [0, 142, 87] - vclamp_segs = {0:[],1:[0],2:[0, 142], 3:all_vclamp_segs} - - gen_plots_for_quantities = {} # Dict with displays vs lists of quantity paths - gen_saves_for_quantities = {} # Dict with file names vs lists of quantity paths - - if use_vclamp: - - v_clamped = '-70mV' - - for cell_id in vclamp_segs: + vclamp_segs = {0: [], 1: [0], 2: [0, 142], 3: all_vclamp_segs} + gen_plots_for_quantities = {} # Dict with displays vs lists of quantity paths + gen_saves_for_quantities = {} # Dict with file names vs lists of quantity paths + if use_vclamp: + v_clamped = "-70mV" + + for cell_id in vclamp_segs: for seg_id in vclamp_segs[cell_id]: + vc = oc.add_voltage_clamp_triple( + nml_doc, + id="vclamp_cell%i_seg%i" % (cell_id, seg_id), + delay="0ms", + duration="%sms" % duration, + conditioning_voltage=v_clamped, + testing_voltage=v_clamped, + return_voltage=v_clamped, + simple_series_resistance="1e1ohm", + active="1", + ) + + vc_dat_file = "v_clamps_i_cell%s_seg%s.dat" % (cell_id, seg_id) - vc = oc.add_voltage_clamp_triple(nml_doc, id='vclamp_cell%i_seg%i'%(cell_id,seg_id), - delay='0ms', - duration='%sms'%duration, - conditioning_voltage=v_clamped, - testing_voltage=v_clamped, - return_voltage=v_clamped, - simple_series_resistance="1e1ohm", - active = "1") + gen_saves_for_quantities[vc_dat_file] = [] - vc_dat_file = 'v_clamps_i_cell%s_seg%s.dat'%(cell_id,seg_id) + oc.add_inputs_to_population( + network, + "input_vClamp_cell%i_seg%i" % (cell_id, seg_id), + pop_rs, + vc.id, + all_cells=False, + only_cells=[cell_id], + segment_ids=[seg_id], + ) + + q = "%s/%s/%s/%s/%s/i" % ( + pop_rs.id, + cell_id, + pop_rs.component, + seg_id, + vc.id, + ) - gen_saves_for_quantities[vc_dat_file] = [] + gen_saves_for_quantities[vc_dat_file].append(q) - oc.add_inputs_to_population(network, "input_vClamp_cell%i_seg%i"%(cell_id,seg_id), - pop_rs, vc.id, - all_cells=False, - only_cells=[cell_id], - segment_ids=[seg_id]) + nml_file_name = "%s.net.%s" % (network.id, "nml.h5" if format == "hdf5" else "nml") + oc.save_network(nml_doc, nml_file_name, validate=(format == "xml"), format=format) - q = '%s/%s/%s/%s/%s/i'%(pop_rs.id, cell_id,pop_rs.component,seg_id,vc.id) + segments_to_plot_record = {pop_rs.id: all_vclamp_segs + [20, 50, 99, 139]} - gen_saves_for_quantities[vc_dat_file].append(q) - - - nml_file_name = '%s.net.%s'%(network.id,'nml.h5' if format == 'hdf5' else 'nml') - oc.save_network(nml_doc, - nml_file_name, - validate=(format=='xml'), - format = format) - - - segments_to_plot_record = {pop_rs.id:all_vclamp_segs+[20,50,99,139]} - - if format=='xml': - + if format == "xml": for pop in segments_to_plot_record.keys(): pop_nml = network.get_by_id(pop) - if pop_nml is not None and pop_nml.size>0: + if pop_nml is not None and pop_nml.size > 0: for i in range(int(pop_nml.size)): - gen_plots_for_quantities['Display_%s_%i_v'%(pop,i)] = [] - gen_saves_for_quantities['Sim_%s.%s.%i.v.dat'%(nml_doc.id,pop,i)] = [] + gen_plots_for_quantities["Display_%s_%i_v" % (pop, i)] = [] + gen_saves_for_quantities[ + "Sim_%s.%s.%i.v.dat" % (nml_doc.id, pop, i) + ] = [] for seg in segments_to_plot_record[pop]: - quantity = '%s/%i/%s/%i/v'%(pop,i,pop_nml.component,seg) - gen_plots_for_quantities['Display_%s_%i_v'%(pop,i)].append(quantity) - gen_saves_for_quantities['Sim_%s.%s.%i.v.dat'%(nml_doc.id,pop,i)].append(quantity) - - - - lems_file_name = oc.generate_lems_simulation(nml_doc, network, - nml_file_name, - duration = duration, - dt = 0.025, - gen_plots_for_all_v = False, - gen_plots_for_quantities = gen_plots_for_quantities, - gen_saves_for_all_v = False, - gen_saves_for_quantities = gen_saves_for_quantities) + quantity = "%s/%i/%s/%i/v" % (pop, i, pop_nml.component, seg) + gen_plots_for_quantities["Display_%s_%i_v" % (pop, i)].append( + quantity + ) + gen_saves_for_quantities[ + "Sim_%s.%s.%i.v.dat" % (nml_doc.id, pop, i) + ].append(quantity) + + lems_file_name = oc.generate_lems_simulation( + nml_doc, + network, + nml_file_name, + duration=duration, + dt=0.025, + gen_plots_for_all_v=False, + gen_plots_for_quantities=gen_plots_for_quantities, + gen_saves_for_all_v=False, + gen_saves_for_quantities=gen_saves_for_quantities, + ) else: lems_file_name = None - + return nml_doc, nml_file_name, lems_file_name -if __name__ == '__main__': - - if '-test' in sys.argv: - +if __name__ == "__main__": + if "-test" in sys.argv: generate() - + else: - generate(use_vclamp=True) diff --git a/examples/Weights.net.nml b/examples/Weights.net.nml index 77a2b0b..ca21088 100644 --- a/examples/Weights.net.nml +++ b/examples/Weights.net.nml @@ -2,8 +2,8 @@ This NeuroML 2 file was generated by OpenCortex v0.1.18 using: - libNeuroML v0.6.3 - pyNeuroML v1.3.7 + libNeuroML v0.6.8 + pyNeuroML v1.3.22 diff --git a/examples/Weights.py b/examples/Weights.py index 7c92af5..a0b6e73 100644 --- a/examples/Weights.py +++ b/examples/Weights.py @@ -6,173 +6,213 @@ from neuroml import ContinuousProjection from neuroml import ContinuousConnectionInstanceW -info = ''' +info = """ Simple network having multiple connections (chemical/gap junction/analog) with variable weights -''' +""" -def generate(reference = "Weights", - num_each = 6, - connections=True, - duration = 1000, - format='xml'): - +def generate( + reference="Weights", num_each=6, connections=True, duration=1000, format="xml" +): nml_doc, network = oc.generate_network(reference) - cell_id = 'HH_477127614' - cell = oc.include_opencortex_cell(nml_doc, 'AllenInstituteCellTypesDB_HH/%s.cell.nml'%cell_id) + cell_id = "HH_477127614" + cell = oc.include_opencortex_cell( + nml_doc, "AllenInstituteCellTypesDB_HH/%s.cell.nml" % cell_id + ) xDim = 500 yDim = 500 zDim = 30 - pop_pre = oc.add_population_in_rectangular_region(network, 'pop_pre', - cell_id, num_each, - 0,0,0, xDim,yDim,zDim, - color='.8 0 0') - - pop_post_chem_exc = oc.add_population_in_rectangular_region(network, 'pop_post_chem_exc', - cell_id, num_each+1, - 0,yDim,0, xDim,yDim,zDim, - color='0 0 .8') - - pop_post_chem_inh = oc.add_population_in_rectangular_region(network, 'pop_post_chem_inh', - cell_id, num_each+2, - xDim,yDim,0, xDim,yDim,zDim, - color='0 .8 .8') - - pop_post_cont = oc.add_population_in_rectangular_region(network, 'pop_post_cont', - cell_id, num_each+3, - xDim,0,0, xDim,yDim,zDim, - color='0 .8 0') - - ampa_syn = oc.add_exp_two_syn(nml_doc, id="AMPA_syn", - gbase="10nS", erev="0mV", - tau_rise="2ms", tau_decay="10ms") - - gaba_syn = oc.add_exp_two_syn(nml_doc, id="GABA_syn", - gbase="10nS", erev="-80mV", - tau_rise="3ms", tau_decay="30ms") - - gj_syn = oc.add_gap_junction_synapse(nml_doc, id="gj0", - conductance=".05nS") - - - analog_syn = GradedSynapse(id='analog_syn', - conductance="10nS", - delta="5mV", - Vth="-35mV", - k="0.025per_ms", - erev="0mV") + pop_pre = oc.add_population_in_rectangular_region( + network, "pop_pre", cell_id, num_each, 0, 0, 0, xDim, yDim, zDim, color=".8 0 0" + ) + + pop_post_chem_exc = oc.add_population_in_rectangular_region( + network, + "pop_post_chem_exc", + cell_id, + num_each + 1, + 0, + yDim, + 0, + xDim, + yDim, + zDim, + color="0 0 .8", + ) + + pop_post_chem_inh = oc.add_population_in_rectangular_region( + network, + "pop_post_chem_inh", + cell_id, + num_each + 2, + xDim, + yDim, + 0, + xDim, + yDim, + zDim, + color="0 .8 .8", + ) + + pop_post_cont = oc.add_population_in_rectangular_region( + network, + "pop_post_cont", + cell_id, + num_each + 3, + xDim, + 0, + 0, + xDim, + yDim, + zDim, + color="0 .8 0", + ) + + ampa_syn = oc.add_exp_two_syn( + nml_doc, + id="AMPA_syn", + gbase="10nS", + erev="0mV", + tau_rise="2ms", + tau_decay="10ms", + ) + + gaba_syn = oc.add_exp_two_syn( + nml_doc, + id="GABA_syn", + gbase="10nS", + erev="-80mV", + tau_rise="3ms", + tau_decay="30ms", + ) + + gj_syn = oc.add_gap_junction_synapse(nml_doc, id="gj0", conductance=".05nS") + + analog_syn = GradedSynapse( + id="analog_syn", + conductance="10nS", + delta="5mV", + Vth="-35mV", + k="0.025per_ms", + erev="0mV", + ) silent_syn = SilentSynapse(id="silent1") - + nml_doc.graded_synapses.append(analog_syn) nml_doc.silent_synapses.append(silent_syn) + pfs = oc.add_poisson_firing_synapse( + nml_doc, id="poissonFiringSyn", average_rate="10 Hz", synapse_id=ampa_syn.id + ) - pfs = oc.add_poisson_firing_synapse(nml_doc, id="poissonFiringSyn", - average_rate="10 Hz", synapse_id=ampa_syn.id) - - oc.add_inputs_to_population(network, "Stim0", - pop_pre, pfs.id, all_cells=True) - + oc.add_inputs_to_population(network, "Stim0", pop_pre, pfs.id, all_cells=True) if connections: - - proj_chem_exc = oc.add_probabilistic_projection(network, - "proj_chem_exc", - pop_pre, - pop_post_chem_exc, - ampa_syn.id, - 0.7, - weight=1, - delay=5) - + proj_chem_exc = oc.add_probabilistic_projection( + network, + "proj_chem_exc", + pop_pre, + pop_post_chem_exc, + ampa_syn.id, + 0.7, + weight=1, + delay=5, + ) + for conn in proj_chem_exc.connection_wds: if conn.get_pre_cell_id() < 3 and conn.get_post_cell_id() < 3: conn.weight = 0.5 - - proj_chem_inh = oc.add_probabilistic_projection(network, - "proj_chem_inh", - pop_pre, - pop_post_chem_inh, - gaba_syn.id, - 0.7, - weight=1, - delay=5) - + + proj_chem_inh = oc.add_probabilistic_projection( + network, + "proj_chem_inh", + pop_pre, + pop_post_chem_inh, + gaba_syn.id, + 0.7, + weight=1, + delay=5, + ) + for conn in proj_chem_inh.connection_wds: if conn.get_pre_cell_id() < 3 and conn.get_post_cell_id() < 3: conn.weight = 2 - - - proj_cont = ContinuousProjection(id='proj_cont', \ - presynaptic_population=pop_pre.id, - postsynaptic_population=pop_post_cont.id) + + proj_cont = ContinuousProjection( + id="proj_cont", + presynaptic_population=pop_pre.id, + postsynaptic_population=pop_post_cont.id, + ) network.continuous_projections.append(proj_cont) - + for i in range(pop_pre.get_size()): for j in range(pop_post_cont.get_size()): - conn0 = ContinuousConnectionInstanceW(id='%s'%(j+i*pop_pre.get_size()), \ - pre_cell='../%s/%s/%s'%(pop_pre.id,i,cell_id), - post_cell='../%s/%s/%s'%(pop_post_cont.id,j,cell_id), - pre_component=silent_syn.id, - post_component=analog_syn.id, - weight=(i+j)/10.0) + conn0 = ContinuousConnectionInstanceW( + id="%s" % (j + i * pop_pre.get_size()), + pre_cell="../%s/%s/%s" % (pop_pre.id, i, cell_id), + post_cell="../%s/%s/%s" % (pop_post_cont.id, j, cell_id), + pre_component=silent_syn.id, + post_component=analog_syn.id, + weight=(i + j) / 10.0, + ) proj_cont.continuous_connection_instance_ws.append(conn0) - - - + gj_pops = [pop_pre, pop_post_chem_exc, pop_post_chem_inh, pop_post_cont] - + for pre in gj_pops: for post in gj_pops: - - proj_gap = oc.add_targeted_electrical_projection(nml_doc, - network, - "proj_", - pre, - post, - targeting_mode='convergent', - synapse_list=[gj_syn.id], - pre_segment_group = 'soma_group', - post_segment_group = 'soma_group', - number_conns_per_cell=3) - - for conn in network.electrical_projections[-1].electrical_connection_instance_ws: + proj_gap = oc.add_targeted_electrical_projection( + nml_doc, + network, + "proj_", + pre, + post, + targeting_mode="convergent", + synapse_list=[gj_syn.id], + pre_segment_group="soma_group", + post_segment_group="soma_group", + number_conns_per_cell=3, + ) + + for conn in network.electrical_projections[ + -1 + ].electrical_connection_instance_ws: conn.weight = conn.get_pre_cell_id() + conn.get_post_cell_id() - - nml_file_name = '%s.net.%s'%(network.id,'nml.h5' if format == 'hdf5' else 'nml') - target_dir = 'HDF5/' if format == 'hdf5' else './' - - oc.save_network(nml_doc, - nml_file_name, - validate=(format=='xml'), - format = format, - target_dir=target_dir) - - if format=='xml': - - lems_file_name = oc.generate_lems_simulation(nml_doc, network, - nml_file_name, - duration = duration, - dt = 0.025, - gen_plots_for_all_v = True, - gen_saves_for_all_v = True) + nml_file_name = "%s.net.%s" % (network.id, "nml.h5" if format == "hdf5" else "nml") + target_dir = "HDF5/" if format == "hdf5" else "./" + + oc.save_network( + nml_doc, + nml_file_name, + validate=(format == "xml"), + format=format, + target_dir=target_dir, + ) + + if format == "xml": + lems_file_name = oc.generate_lems_simulation( + nml_doc, + network, + nml_file_name, + duration=duration, + dt=0.025, + gen_plots_for_all_v=True, + gen_saves_for_all_v=True, + ) else: lems_file_name = None return nml_doc, nml_file_name, lems_file_name -if __name__ == '__main__': - - if '-test' in sys.argv: - - generate(num_pre = 1, - duration = 1000) +if __name__ == "__main__": + if "-test" in sys.argv: + generate(num_pre=1, duration=1000) else: generate() - generate(format='hdf5') + generate(format="hdf5") diff --git a/examples/netpyneLoad.py b/examples/netpyneLoad.py index 90335e9..72fc46a 100644 --- a/examples/netpyneLoad.py +++ b/examples/netpyneLoad.py @@ -1,4 +1,4 @@ -''' +""" NetPyNE simulator compliant export for: Components: @@ -17,13 +17,11 @@ org.neuroml.model v1.4.5 jLEMS v0.9.8.5 -''' +""" # Main NetPyNE script for: SimpleNet # See https://github.com/Neurosim-lab/netpyne -from netpyne import init # import netpyne init module - ############################################################################### # NETWORK PARAMETERS @@ -32,24 +30,40 @@ netParams = {} # dictionary to store sets of network parameters # Cell properties list -netParams['cellParams'] = [] +netParams["cellParams"] = [] next_gid = 0 -gids = {} # Require these in this file for plotting etc. +gids = {} # Require these in this file for plotting etc. + - # cell params for cell RS in population RS_pop -cellRule = {'label': 'RS_pop', 'conditions': {'cellType': 'RS'}, 'sections': {}} -RS_pop_soma = {'geom': {}, 'topol': {}, 'mechs': {}, 'pointps':{}, 'syns': {}} # soma -RS_pop_soma['pointps']['RS'] = { '_type':'RS', 'v0':-60.0, 'k':7.0E-4, 'vr':-60.0, 'vt':-40.0, 'vpeak':35.0, 'a':0.030000001, 'b':-0.0019999999, 'c':-50.0, 'd':0.1, 'C':1.00000005E-4, } +cellRule = {"label": "RS_pop", "conditions": {"cellType": "RS"}, "sections": {}} +RS_pop_soma = {"geom": {}, "topol": {}, "mechs": {}, "pointps": {}, "syns": {}} # soma +RS_pop_soma["pointps"]["RS"] = { + "_type": "RS", + "v0": -60.0, + "k": 7.0e-4, + "vr": -60.0, + "vt": -40.0, + "vpeak": 35.0, + "a": 0.030000001, + "b": -0.0019999999, + "c": -50.0, + "d": 0.1, + "C": 1.00000005e-4, +} # Todo: work this out here from area etc. -cm = (318309 * RS_pop_soma['pointps']['RS']['C'] if RS_pop_soma['pointps']['RS'].has_key('C') else 318.31927 ) +cm = ( + 318309 * RS_pop_soma["pointps"]["RS"]["C"] + if RS_pop_soma["pointps"]["RS"].has_key("C") + else 318.31927 +) -RS_pop_soma['geom'] = {'diam': 10, 'L': 10, 'Ra': 1, 'cm': cm} +RS_pop_soma["geom"] = {"diam": 10, "L": 10, "Ra": 1, "cm": cm} -cellRule['sections'] = {'soma': RS_pop_soma} # add sections to dict -netParams['cellParams'].append(cellRule) # add dict to list of cell properties +cellRule["sections"] = {"soma": RS_pop_soma} # add sections to dict +netParams["cellParams"].append(cellRule) # add dict to list of cell properties # SIMULATION PARAMETERS @@ -57,62 +71,66 @@ simConfig = {} # dictionary to store simConfig # Simulation parameters -simConfig['duration'] = simConfig['tstop'] = 500.0 # Duration of the simulation, in ms -simConfig['dt'] = 0.024999999 # Internal integration timestep to use -simConfig['randseed'] = 1 # Random seed to use -simConfig['createNEURONObj'] = 1 # create HOC objects when instantiating network -simConfig['createPyStruct'] = 1 # create Python structure (simulator-independent) when instantiating network -simConfig['verbose'] = True # show detailed messages - -# Recording -simConfig['recordCells'] = ['all'] -simConfig['recordTraces'] = {'Vsoma':{'sec':'soma','loc':0.5,'var':'v'}} - -simConfig['plotCells'] = ['all'] +simConfig["duration"] = simConfig["tstop"] = 500.0 # Duration of the simulation, in ms +simConfig["dt"] = 0.024999999 # Internal integration timestep to use +simConfig["randseed"] = 1 # Random seed to use +simConfig["createNEURONObj"] = 1 # create HOC objects when instantiating network +simConfig["createPyStruct"] = ( + 1 # create Python structure (simulator-independent) when instantiating network +) +simConfig["verbose"] = True # show detailed messages + +# Recording +simConfig["recordCells"] = ["all"] +simConfig["recordTraces"] = {"Vsoma": {"sec": "soma", "loc": 0.5, "var": "v"}} + +simConfig["plotCells"] = ["all"] # Display id: DispPop__RS_pop # Line id: RS_pop[0]: v; displaying v on cell: 0 in population: RS_pop; -simConfig['recordStim'] = True # record spikes of cell stims -simConfig['recordStep'] = simConfig['dt'] # Step size in ms to save data (eg. V traces, LFP, etc) - +simConfig["recordStim"] = True # record spikes of cell stims +simConfig["recordStep"] = simConfig[ + "dt" +] # Step size in ms to save data (eg. V traces, LFP, etc) -# Analysis and plotting -simConfig['plotRaster'] = True # Whether or not to plot a raster -simConfig['plotLFPSpectrum'] = False # plot power spectral density -simConfig['maxspikestoplot'] = 3e8 # Maximum number of spikes to plot -simConfig['plotConn'] = False # whether to plot conn matrix -simConfig['plotWeightChanges'] = False # whether to plot weight changes (shown in conn matrix) -#simConfig['plot3dArch'] = True # plot 3d architecture +# Analysis and plotting +simConfig["plotRaster"] = True # Whether or not to plot a raster +simConfig["plotLFPSpectrum"] = False # plot power spectral density +simConfig["maxspikestoplot"] = 3e8 # Maximum number of spikes to plot +simConfig["plotConn"] = False # whether to plot conn matrix +simConfig["plotWeightChanges"] = ( + False # whether to plot weight changes (shown in conn matrix) +) +# simConfig['plot3dArch'] = True # plot 3d architecture # Saving -simConfig['filename'] = 'SimpleNet.txt' # Set file output name -simConfig['saveFileStep'] = simConfig['dt'] # step size in ms to save data to disk -simConfig['saveDat'] = True # save to dat file - - +simConfig["filename"] = "SimpleNet.txt" # Set file output name +simConfig["saveFileStep"] = simConfig["dt"] # step size in ms to save data to disk +simConfig["saveDat"] = True # save to dat file import netpyne.framework as f import netpyne.utils as npUtils -npUtils.importNeuroML2Network('SimpleNet.net.nml', netParams, simConfig) +npUtils.importNeuroML2Network("SimpleNet.net.nml", netParams, simConfig) -f.net.connectCells() # create connections between cells based on params +f.net.connectCells() # create connections between cells based on params -f.net.addStims() # add external stimulation to cells (IClamps etc) -f.sim.setupRecording() # setup variables to record for each cell (spikes, V traces, etc) -f.sim.runSim() # run parallel Neuron simulation -f.sim.gatherData() # gather spiking data and cell info from each node -f.sim.saveData() # save params, cell info and sim output to file (pickle,mat,txt,etc) -f.analysis.plotData() # plot spike raster +f.net.addStims() # add external stimulation to cells (IClamps etc) +f.sim.setupRecording() # setup variables to record for each cell (spikes, V traces, etc) +f.sim.runSim() # run parallel Neuron simulation +f.sim.gatherData() # gather spiking data and cell info from each node +f.sim.saveData() # save params, cell info and sim output to file (pickle,mat,txt,etc) +f.analysis.plotData() # plot spike raster -#f.sim.exportNeuroML2("Test",lems=False) # export cells and connectivity to NeuroML 2 format +# f.sim.exportNeuroML2("Test",lems=False) # export cells and connectivity to NeuroML 2 format from neuron import h -h('forall psection()') -print("Finished...") \ No newline at end of file +h("forall psection()") + +print("Finished...") diff --git a/examples/neuromllite/SimpleNet.py b/examples/neuromllite/SimpleNet.py index 8a02791..dd20add 100644 --- a/examples/neuromllite/SimpleNet.py +++ b/examples/neuromllite/SimpleNet.py @@ -1,59 +1,78 @@ -from neuromllite import Network, Cell, InputSource, Population, Synapse, RectangularRegion, RandomLayout -from neuromllite import Projection, RandomConnectivity, Input, Simulation -from neuromllite.NetworkGenerator import generate_and_run +from neuromllite import ( + Network, + Cell, + InputSource, + Population, + Synapse, + RectangularRegion, + RandomLayout, +) +from neuromllite import Input, Simulation import sys ################################################################################ ### Build new network -net = Network(id='SimpleNet') -net.notes = 'Simple network with single population' +net = Network(id="SimpleNet") +net.notes = "Simple network with single population" net.temperature = 32.0 -cell = Cell(id='RS', neuroml2_source_file='../../NeuroML2/prototypes/izhikevich/RS.cell.nml') +cell = Cell( + id="RS", neuroml2_source_file="../../NeuroML2/prototypes/izhikevich/RS.cell.nml" +) net.cells.append(cell) -syn = Synapse(id='ampa', neuroml2_source_file='../../NeuroML2/prototypes/synapses/ampa.synapse.nml') +syn = Synapse( + id="ampa", + neuroml2_source_file="../../NeuroML2/prototypes/synapses/ampa.synapse.nml", +) net.synapses.append(syn) -input_source = InputSource(id='poissonFiringSyn', - neuroml2_input='poissonFiringSynapse', - parameters={'average_rate':"50Hz", 'synapse':syn.id, 'spike_target':"./ampa"}) +input_source = InputSource( + id="poissonFiringSyn", + neuroml2_input="poissonFiringSynapse", + parameters={"average_rate": "50Hz", "synapse": syn.id, "spike_target": "./ampa"}, +) net.input_sources.append(input_source) -r1 = RectangularRegion(id='region1', x=0,y=0,z=0,width=100,height=100,depth=100) +r1 = RectangularRegion(id="region1", x=0, y=0, z=0, width=100, height=100, depth=100) net.regions.append(r1) -p0 = Population(id='RS_pop', size=3, component=cell.id, properties={'color':'0 .8 0'},random_layout = RandomLayout(region=r1.id)) +p0 = Population( + id="RS_pop", + size=3, + component=cell.id, + properties={"color": "0 .8 0"}, + random_layout=RandomLayout(region=r1.id), +) net.populations.append(p0) -net.inputs.append(Input(id='Stim0', - input_source=input_source.id, - population=p0.id, - percentage=100)) +net.inputs.append( + Input(id="Stim0", input_source=input_source.id, population=p0.id, percentage=100) +) print(net.to_json()) -new_file = net.to_json_file('%s.json'%net.id) +new_file = net.to_json_file("%s.json" % net.id) ################################################################################ ### Build Simulation object & save as JSON -sim = Simulation(id='SimSimpleNet', - network=new_file, - duration='1000', - dt='0.025', - record_traces={'all':'*'}) +sim = Simulation( + id="SimSimpleNet", + network=new_file, + duration="1000", + dt="0.025", + record_traces={"all": "*"}, +) sim.to_json_file() - ################################################################################ ### Run in some simulators from neuromllite.NetworkGenerator import check_to_generate_or_run -import sys check_to_generate_or_run(sys.argv, sim) diff --git a/examples/test_scaling.py b/examples/test_scaling.py index 61d87fc..6f3b5b7 100644 --- a/examples/test_scaling.py +++ b/examples/test_scaling.py @@ -1,18 +1,14 @@ from Balanced import generate -nml_doc, nml_file_name, lems_file_name = generate(num_bbp =10, - scalePops = 20, - scalex=2, - scalez=2, - connections=True, - format='hdf5') - +nml_doc, nml_file_name, lems_file_name = generate( + num_bbp=10, scalePops=20, scalex=2, scalez=2, connections=True, format="hdf5" +) + from neuroml.loaders import NeuroMLHdf5Loader nml_doc2 = NeuroMLHdf5Loader.load(nml_file_name) -for doc in [nml_doc,nml_doc2]: +for doc in [nml_doc, nml_doc2]: doc.summary() - \ No newline at end of file diff --git a/opencortex/__init__.py b/opencortex/__init__.py index 64d2c4f..efe128e 100644 --- a/opencortex/__init__.py +++ b/opencortex/__init__.py @@ -9,16 +9,21 @@ ### ############################################################## -print("\n*********************************************************************************************") -print(" Please note that OpenCortex is in a preliminary state "); +print( + "\n*********************************************************************************************" +) +print(" Please note that OpenCortex is in a preliminary state ") print(" and the API is subject to change without notice! ") -print("*********************************************************************************************\n") +print( + "*********************************************************************************************\n" +) -__version__ = '0.1.18' +__version__ = "0.1.18" verbose = False + def print_comment_v(text): """ Always print the comment @@ -31,10 +36,11 @@ def print_comment(text, print_it=verbose): Print a comment only if print_it == True """ prefix = "OpenCortex >>> " - if not isinstance(text, str): text = text.decode('ascii') + if not isinstance(text, str): + text = text.decode("ascii") if print_it: + print("%s%s" % (prefix, text.replace("\n", "\n" + prefix))) - print("%s%s"%(prefix, text.replace("\n", "\n"+prefix))) def set_verbose(value=True): global verbose diff --git a/opencortex/build/__init__.py b/opencortex/build/__init__.py index c2dccc9..b5cf368 100644 --- a/opencortex/build/__init__.py +++ b/opencortex/build/__init__.py @@ -1,10 +1,10 @@ ############################################################### -### +### ### Note: OpenCortex is under active development, the API is subject to change without notice!! -### +### ### Authors: Padraig Gleeson, Rokas Stanislovas ### -### This software has been funded by the Wellcome Trust, as well as a GSoC 2016 project +### This software has been funded by the Wellcome Trust, as well as a GSoC 2016 project ### on Cortical Network develoment ### ############################################################## @@ -35,98 +35,135 @@ ############################################################################################## -def _add_connection(projection, - id, - presynaptic_population, - pre_cell_id, - pre_seg_id, - postsynaptic_population, - post_cell_id, - post_seg_id, - delay, - weight, - pre_fraction=0.5, - post_fraction=0.5): +def _add_connection( + projection, + id, + presynaptic_population, + pre_cell_id, + pre_seg_id, + postsynaptic_population, + post_cell_id, + post_seg_id, + delay, + weight, + pre_fraction=0.5, + post_fraction=0.5, +): """ Add a single connection to a projection between `presynaptic_population` and `postsynaptic_population` """ - - opencortex.print_comment("Adding single conn %s in proj %s: %s(%s:%s:%s) -> %s(%s:%s:%s), delay: %sms, weight: %s" % (id, projection.id, \ - presynaptic_population.id, pre_cell_id, pre_seg_id, pre_fraction, \ - postsynaptic_population.id, post_cell_id, post_seg_id, post_fraction, - delay, weight)) - - connection = neuroml.ConnectionWD(id=id, \ - pre_cell_id="../%s/%i/%s" % (presynaptic_population.id, pre_cell_id, presynaptic_population.component), \ - pre_segment_id=pre_seg_id, \ - pre_fraction_along=pre_fraction, - post_cell_id="../%s/%i/%s" % (postsynaptic_population.id, post_cell_id, postsynaptic_population.component), \ - post_segment_id=post_seg_id, - post_fraction_along=post_fraction, - delay='%s ms' % delay, - weight=weight) + opencortex.print_comment( + "Adding single conn %s in proj %s: %s(%s:%s:%s) -> %s(%s:%s:%s), delay: %sms, weight: %s" + % ( + id, + projection.id, + presynaptic_population.id, + pre_cell_id, + pre_seg_id, + pre_fraction, + postsynaptic_population.id, + post_cell_id, + post_seg_id, + post_fraction, + delay, + weight, + ) + ) + + connection = neuroml.ConnectionWD( + id=id, + pre_cell_id="../%s/%i/%s" + % (presynaptic_population.id, pre_cell_id, presynaptic_population.component), + pre_segment_id=pre_seg_id, + pre_fraction_along=pre_fraction, + post_cell_id="../%s/%i/%s" + % (postsynaptic_population.id, post_cell_id, postsynaptic_population.component), + post_segment_id=post_seg_id, + post_fraction_along=post_fraction, + delay="%s ms" % delay, + weight=weight, + ) projection.connection_wds.append(connection) ############################################################################################## -def add_elect_connection(projection, - id, - presynaptic_population, - pre_cell_id, - pre_seg_id, - postsynaptic_population, - post_cell_id, - post_seg_id, - gap_junction_id, - pre_fraction=0.5, - post_fraction=0.5): +def add_elect_connection( + projection, + id, + presynaptic_population, + pre_cell_id, + pre_seg_id, + postsynaptic_population, + post_cell_id, + post_seg_id, + gap_junction_id, + pre_fraction=0.5, + post_fraction=0.5, +): """ Add a single electrical connection (via a gap junction) to a projection between `presynaptic_population` and `postsynaptic_population` """ - opencortex.print_comment("Adding single electrical conn %s in proj %s: %s(%s:%s:%s) -> %s(%s:%s:%s)" % (id, projection.id, \ - presynaptic_population.id, pre_cell_id, pre_seg_id, pre_fraction, \ - postsynaptic_population.id, post_cell_id, post_seg_id, post_fraction)) - - connection = neuroml.ElectricalConnectionInstanceW(id=id, \ - pre_cell="../%s/%i/%s" % (presynaptic_population.id, pre_cell_id, presynaptic_population.component), \ - post_cell="../%s/%i/%s" % (postsynaptic_population.id, post_cell_id, postsynaptic_population.component), \ - synapse=gap_junction_id, \ - pre_segment=pre_seg_id, \ - post_segment=post_seg_id, \ - pre_fraction_along=pre_fraction, \ - post_fraction_along=post_fraction, - weight=1) + opencortex.print_comment( + "Adding single electrical conn %s in proj %s: %s(%s:%s:%s) -> %s(%s:%s:%s)" + % ( + id, + projection.id, + presynaptic_population.id, + pre_cell_id, + pre_seg_id, + pre_fraction, + postsynaptic_population.id, + post_cell_id, + post_seg_id, + post_fraction, + ) + ) + + connection = neuroml.ElectricalConnectionInstanceW( + id=id, + pre_cell="../%s/%i/%s" + % (presynaptic_population.id, pre_cell_id, presynaptic_population.component), + post_cell="../%s/%i/%s" + % (postsynaptic_population.id, post_cell_id, postsynaptic_population.component), + synapse=gap_junction_id, + pre_segment=pre_seg_id, + post_segment=post_seg_id, + pre_fraction_along=pre_fraction, + post_fraction_along=post_fraction, + weight=1, + ) projection.electrical_connection_instance_ws.append(connection) - ############################################################################################## -def add_probabilistic_projection_list(net, - presynaptic_population, - postsynaptic_population, - synapse_list, - connection_probability, - delay=0, - weight=1, - presynaptic_population_list=True, - postsynaptic_population_list=True, - clipped_distributions=True, - std_delay=None, - std_weight=None): - - ''' + +def add_probabilistic_projection_list( + net, + presynaptic_population, + postsynaptic_population, + synapse_list, + connection_probability, + delay=0, + weight=1, + presynaptic_population_list=True, + postsynaptic_population_list=True, + clipped_distributions=True, + std_delay=None, + std_weight=None, +): + """ Modification of the method `add_probabilistic_projection()` to allow multiple synaptic components per physical projection; specifically works for networks containing single-compartment neuronal models. This method also allows gaussian variation in synaptic weight and delay; it also accepts populations that do not necessarily have the type attribute in set to `populationList` . - ''' + """ if presynaptic_population.size == 0 or postsynaptic_population.size == 0: return None @@ -134,11 +171,13 @@ def add_probabilistic_projection_list(net, proj_components = {} for synapse_id in synapse_list: - - proj = neuroml.Projection(id="%s_%s_%s" % (synapse_id, presynaptic_population.id, postsynaptic_population.id), - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id, - synapse=synapse_id) + proj = neuroml.Projection( + id="%s_%s_%s" + % (synapse_id, presynaptic_population.id, postsynaptic_population.id), + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + synapse=synapse_id, + ) proj_components[synapse_id] = proj @@ -147,47 +186,46 @@ def add_probabilistic_projection_list(net, ######### check whether delay and weight varies with a synaptic component if isinstance(delay, list): - if not len(delay) == len(synapse_list): - - opencortex.print_comment_v("Error in method opencortex.build.add_probabilistic_projection_list() : argument delay is a list but not of the same length as" - " argument synapse_list; execution will terminate.") + opencortex.print_comment_v( + "Error in method opencortex.build.add_probabilistic_projection_list() : argument delay is a list but not of the same length as" + " argument synapse_list; execution will terminate." + ) quit() if isinstance(weight, list): - if not len(weight) == len(synapse_list): - - opencortex.print_comment_v("Error in method opencortex.build.add_probabilistic_projection_list() : argument weight is a list but not of the same length as" - " argument synapse_list; execution will terminate.") + opencortex.print_comment_v( + "Error in method opencortex.build.add_probabilistic_projection_list() : argument weight is a list but not of the same length as" + " argument synapse_list; execution will terminate." + ) quit() if std_delay != None: - if isinstance(std_delay, list): - if not len(std_delay) == len(synapse_list): - - opencortex.print_comment_v("Error in method opencortex.build.add_probabilistic_projection_list() : argument std_delay is a list but not of the same length as" - " argument synapse_list; execution will terminate.") + opencortex.print_comment_v( + "Error in method opencortex.build.add_probabilistic_projection_list() : argument std_delay is a list but not of the same length as" + " argument synapse_list; execution will terminate." + ) quit() if std_weight != None: - if isinstance(std_weight, list): - if not len(std_weight) == len(synapse_list): - - opencortex.print_comment_v("Error in method opencortex.build.add_probabilistic_projection_list() : argument std_weight is a list but not of the same length as" - " argument synapse_list; execution will terminate.") + opencortex.print_comment_v( + "Error in method opencortex.build.add_probabilistic_projection_list() : argument std_weight is a list but not of the same length as" + " argument synapse_list; execution will terminate." + ) quit() for i in range(0, presynaptic_population.size): for j in range(0, postsynaptic_population.size): if i != j or presynaptic_population.id != postsynaptic_population.id: - - if connection_probability >= 1 or random.random() < connection_probability: - + if ( + connection_probability >= 1 + or random.random() < connection_probability + ): if not isinstance(delay, list): if std_delay != None: if clipped_distributions: @@ -228,45 +266,52 @@ def add_probabilistic_projection_list(net, syn_counter = 0 for synapse_id in synapse_list: - if isinstance(delay, list): - if std_delay != None: if isinstance(std_delay, list): if clipped_distributions: found_positive_delay = False while not found_positive_delay: - del_val = random.gauss(delay[syn_counter], std_delay[syn_counter]) + del_val = random.gauss( + delay[syn_counter], + std_delay[syn_counter], + ) if del_val >= 0: found_positive_delay = True else: - del_val = random.gauss(delay[syn_counter], std_delay[syn_counter]) + del_val = random.gauss( + delay[syn_counter], std_delay[syn_counter] + ) else: - if clipped_distributions: found_positive_delay = False while not found_positive_delay: - del_val = random.gauss(delay[syn_counter], std_delay) + del_val = random.gauss( + delay[syn_counter], std_delay + ) if del_val >= 0: found_positive_delay = True else: - del_val = random.gauss(delay[syn_counter], std_delay) + del_val = random.gauss( + delay[syn_counter], std_delay + ) else: - del_val = delay[syn_counter] if isinstance(weight, list): - if std_weight != None: if isinstance(std_weight, list): if clipped_distributions: found_signed_weight = False while not found_signed_weight: - w_val = random.gauss(weight[syn_counter], std_weight[syn_counter]) + w_val = random.gauss( + weight[syn_counter], + std_weight[syn_counter], + ) if weight[syn_counter] > 0: if w_val >= 0: @@ -279,14 +324,17 @@ def add_probabilistic_projection_list(net, else: found_signed_weight = True else: - w_val = random.gauss(weight[syn_counter], std_weight[syn_counter]) + w_val = random.gauss( + weight[syn_counter], std_weight[syn_counter] + ) else: - if clipped_distributions: found_signed_weight = False while not found_signed_weight: - w_val = random.gauss(weight[syn_counter], std_weight) + w_val = random.gauss( + weight[syn_counter], std_weight + ) if weight[syn_counter] > 0: if w_val >= 0: @@ -300,35 +348,52 @@ def add_probabilistic_projection_list(net, found_signed_weight = True else: - w_val = random.gauss(weight[syn_counter], std_weight) + w_val = random.gauss( + weight[syn_counter], std_weight + ) else: - w_val = weight[syn_counter] if presynaptic_population_list: - pre_cell_string = "../%s/%i/%s" % (presynaptic_population.id, i, presynaptic_population.component) + pre_cell_string = "../%s/%i/%s" % ( + presynaptic_population.id, + i, + presynaptic_population.component, + ) else: - pre_cell_string = "../%s[%i]" % (presynaptic_population.id, i) + pre_cell_string = "../%s[%i]" % ( + presynaptic_population.id, + i, + ) if postsynaptic_population_list: - post_cell_string = "../%s/%i/%s" % (postsynaptic_population.id, j, postsynaptic_population.component) + post_cell_string = "../%s/%i/%s" % ( + postsynaptic_population.id, + j, + postsynaptic_population.component, + ) else: - post_cell_string = "../%s[%i]" % (postsynaptic_population.id, j) - - connection = neuroml.ConnectionWD(id=count, \ - pre_cell_id=pre_cell_string, \ - pre_segment_id=0, \ - pre_fraction_along=0.5, - post_cell_id=post_cell_string, \ - post_segment_id=0, - post_fraction_along=0.5, - delay='%f ms' % del_val, - weight=w_val) - - proj_components[synapse_id].connection_wds.append(connection) + post_cell_string = "../%s[%i]" % ( + postsynaptic_population.id, + j, + ) + + connection = neuroml.ConnectionWD( + id=count, + pre_cell_id=pre_cell_string, + pre_segment_id=0, + pre_fraction_along=0.5, + post_cell_id=post_cell_string, + post_segment_id=0, + post_fraction_along=0.5, + delay="%f ms" % del_val, + weight=w_val, + ) + + proj_components[synapse_id].connection_wds.append(connection) syn_counter += 1 @@ -337,7 +402,6 @@ def add_probabilistic_projection_list(net, return_proj_components = [] if count != 0: - for synapse_id in synapse_list: net.projections.append(proj_components[synapse_id]) return_proj_components.append(proj_components[synapse_id]) @@ -345,38 +409,43 @@ def add_probabilistic_projection_list(net, return return_proj_components else: - return None -############################################################################################## +############################################################################################## + def _evaluate_expression(expr): - ''' + """ For example for string expression for weights, e.g. '3*random()' - ''' - expr2 = str(expr).replace('random','random.random').replace('normal','np.random.normal') + """ + expr2 = ( + str(expr) + .replace("random", "random.random") + .replace("normal", "np.random.normal") + ) val = eval(expr2) - opencortex.print_comment('Evaluated %s as %s'%(expr, val)) + opencortex.print_comment("Evaluated %s as %s" % (expr, val)) return val - -############################################################################################## -def add_targeted_projection_by_dicts(net, - proj_array, - presynaptic_population, - postsynaptic_population, - targeting_mode, - synapse_list, - pre_seg_target_dict, - post_seg_target_dict, - subset_dict, - delays_dict=None, - weights_dict=None): +############################################################################################## - '''This method adds the divergent or convergent chemical projection depending on the input argument targeting_mode. The input arguments are as follows: +def add_targeted_projection_by_dicts( + net, + proj_array, + presynaptic_population, + postsynaptic_population, + targeting_mode, + synapse_list, + pre_seg_target_dict, + post_seg_target_dict, + subset_dict, + delays_dict=None, + weights_dict=None, +): + """This method adds the divergent or convergent chemical projection depending on the input argument targeting_mode. The input arguments are as follows: net - the network object created using libNeuroML API ( neuroml.Network() ); @@ -406,12 +475,21 @@ def add_targeted_projection_by_dicts(net, delays_dict - optional dictionary that specifies the delays (in ms) for individual synapse components, e.g. {'NMDA':5.0} or {'AMPA':3.0,'NMDA':5}; - weights_dict - optional dictionary that specifies the weights for individual synapse components, e.g. {'NMDA':1} or {'NMDA':1,'AMPA':2}.''' - - opencortex.print_comment_v("Adding %s projection with %s conns: %s: %s -> %s, %s" % (targeting_mode, subset_dict, proj_array, presynaptic_population.id, postsynaptic_population.id, synapse_list)) - - if targeting_mode == 'divergent': - + weights_dict - optional dictionary that specifies the weights for individual synapse components, e.g. {'NMDA':1} or {'NMDA':1,'AMPA':2}.""" + + opencortex.print_comment_v( + "Adding %s projection with %s conns: %s: %s -> %s, %s" + % ( + targeting_mode, + subset_dict, + proj_array, + presynaptic_population.id, + postsynaptic_population.id, + synapse_list, + ) + ) + + if targeting_mode == "divergent": pop1_size = presynaptic_population.size pop1_id = presynaptic_population.id @@ -420,8 +498,7 @@ def add_targeted_projection_by_dicts(net, pop2_id = postsynaptic_population.size - if targeting_mode == 'convergent': - + if targeting_mode == "convergent": pop1_size = postsynaptic_population.size pop1_id = postsynaptic_population.id @@ -431,86 +508,69 @@ def add_targeted_projection_by_dicts(net, pop2_id = presynaptic_population.id if isinstance(subset_dict, dict): - numberConnections = {} for subset in subset_dict.keys(): - numberConnections[subset] = int(subset_dict[subset]) if isinstance(subset_dict, int) or isinstance(subset_dict, float): - numberConnections = int(subset_dict) count = 0 for i in range(0, pop1_size): - total_conns = 0 if isinstance(subset_dict, dict): - conn_subsets = {} for subset in subset_dict.keys(): - if subset_dict[subset] != numberConnections[subset]: - - if random.random() < subset_dict[subset] - numberConnections[subset]: - + if ( + random.random() + < subset_dict[subset] - numberConnections[subset] + ): conn_subsets[subset] = numberConnections[subset] + 1 else: - conn_subsets[subset] = numberConnections[subset] else: - conn_subsets[subset] = numberConnections[subset] total_conns = total_conns + conn_subsets[subset] if isinstance(subset_dict, float) or isinstance(subset_dict, int): - conn_subsets = 0 if subset_dict != numberConnections: - if random.random() < subset_dict - numberConnections: - conn_subsets = numberConnections + 1 else: - conn_subsets = numberConnections else: - conn_subsets = numberConnections total_conns = total_conns + conn_subsets - if total_conns != 0: - + if total_conns != 0: ##### allows only one pre segment group per presynaptic population e.g. distal_axon if pre_seg_target_dict != None and len(pre_seg_target_dict.keys()) == 1: - pre_subset_dict = {} pre_subset_dict[list(pre_seg_target_dict.keys())[0]] = total_conns else: - pre_subset_dict = None pop2_cell_ids = list(range(0, pop2_size)) if pop1_id == pop2_id: - pop2_cell_ids.remove(i) if pop2_cell_ids != []: - if len(pop2_cell_ids) >= total_conns: ##### get unique set of cells pop2_cells = random.sample(pop2_cell_ids, total_conns) @@ -520,35 +580,34 @@ def add_targeted_projection_by_dicts(net, pop2_cells = [] for value in range(0, total_conns): - cell_id = random.sample(pop2_cell_ids, 1) pop2_cells.extend(cell_id) - post_target_seg_array, post_target_fractions = get_target_segments(post_seg_target_dict, conn_subsets) + post_target_seg_array, post_target_fractions = get_target_segments( + post_seg_target_dict, conn_subsets + ) if pre_subset_dict != None: - - pre_target_seg_array, pre_target_fractions = get_target_segments(pre_seg_target_dict, pre_subset_dict) + pre_target_seg_array, pre_target_fractions = get_target_segments( + pre_seg_target_dict, pre_subset_dict + ) else: - pre_target_seg_array = None - pre_target_fractions = None + pre_target_fractions = None for j in pop2_cells: - post_seg_id = post_target_seg_array[0] del post_target_seg_array[0] post_fraction_along = post_target_fractions[0] - del post_target_fractions[0] + del post_target_fractions[0] if pre_target_seg_array != None and pre_target_fractions != None: - pre_seg_id = pre_target_seg_array[0] del pre_target_seg_array[0] @@ -558,27 +617,23 @@ def add_targeted_projection_by_dicts(net, del pre_target_fractions[0] else: - pre_seg_id = 0 pre_fraction_along = 0.5 - if targeting_mode == 'divergent': - + if targeting_mode == "divergent": pre_cell_id = i post_cell_id = j - if targeting_mode == 'convergent': - + if targeting_mode == "convergent": pre_cell_id = j - post_cell_id = i + post_cell_id = i syn_counter = 0 for synapse_id in synapse_list: - delay = 0 weight = 1 @@ -586,55 +641,58 @@ def add_targeted_projection_by_dicts(net, if delays_dict != None: for synapseComp in delays_dict.keys(): if synapseComp in synapse_id: - delay = _evaluate_expression(delays_dict[synapseComp]) + delay = _evaluate_expression( + delays_dict[synapseComp] + ) if weights_dict != None: for synapseComp in weights_dict.keys(): if synapseComp in synapse_id: - weight = _evaluate_expression(weights_dict[synapseComp]) + weight = _evaluate_expression( + weights_dict[synapseComp] + ) + + _add_connection( + proj_array[syn_counter], + count, + presynaptic_population, + pre_cell_id, + pre_seg_id, + postsynaptic_population, + post_cell_id, + post_seg_id, + delay=delay, + weight=weight, + pre_fraction=pre_fraction_along, + post_fraction=post_fraction_along, + ) - _add_connection(proj_array[syn_counter], - count, - presynaptic_population, - pre_cell_id, - pre_seg_id, - postsynaptic_population, - post_cell_id, - post_seg_id, - delay=delay, - weight=weight, - pre_fraction=pre_fraction_along, - post_fraction=post_fraction_along) - - - syn_counter += 1 + syn_counter += 1 count += 1 - - if count != 0: - + if count != 0: for synapse_ind in range(0, len(synapse_list)): - net.projections.append(proj_array[synapse_ind]) - return proj_array - + return proj_array ############################################################################################## -def _add_elect_projection(net, - proj_array, - presynaptic_population, - postsynaptic_population, - targeting_mode, - synapse_list, - pre_seg_target_dict, - post_seg_target_dict, - subset_dict): - '''This method adds the divergent or convergent electrical projection depending on the input argument targeting_mode. The input arguments are as follows: +def _add_elect_projection( + net, + proj_array, + presynaptic_population, + postsynaptic_population, + targeting_mode, + synapse_list, + pre_seg_target_dict, + post_seg_target_dict, + subset_dict, +): + """This method adds the divergent or convergent electrical projection depending on the input argument targeting_mode. The input arguments are as follows: net - the network object created using libNeuroML API ( neuroml.Network() ); @@ -660,10 +718,9 @@ def _add_elect_projection(net, Case II, targeting mode = 'convergent' - the number of synaptic connections per target segment group per each postsynaptic cell; - alternatively, subset_dict can be a number that specifies the total number of synaptic connections (either divergent or convergent) irrespective of target segment groups.''' - - if targeting_mode == 'divergent': + alternatively, subset_dict can be a number that specifies the total number of synaptic connections (either divergent or convergent) irrespective of target segment groups.""" + if targeting_mode == "divergent": pop1_size = presynaptic_population.size pop1_id = presynaptic_population.id @@ -672,8 +729,7 @@ def _add_elect_projection(net, pop2_id = postsynaptic_population.size - if targeting_mode == 'convergent': - + if targeting_mode == "convergent": pop1_size = postsynaptic_population.size pop1_id = postsynaptic_population.id @@ -685,121 +741,101 @@ def _add_elect_projection(net, count = 0 if isinstance(subset_dict, dict): - numberConnections = {} for subset in subset_dict.keys(): - numberConnections[subset] = int(subset_dict[subset]) if isinstance(subset_dict, int) or isinstance(subset_dict, float): - numberConnections = int(subset_dict) for i in range(0, pop1_size): - total_conns = 0 if isinstance(subset_dict, dict): - conn_subsets = {} for subset in subset_dict.keys(): - if subset_dict[subset] != numberConnections[subset]: - - if random.random() < subset_dict[subset] - numberConnections[subset]: - + if ( + random.random() + < subset_dict[subset] - numberConnections[subset] + ): conn_subsets[subset] = numberConnections[subset] + 1 else: - conn_subsets[subset] = numberConnections[subset] else: - conn_subsets[subset] = numberConnections[subset] total_conns = total_conns + conn_subsets[subset] if isinstance(subset_dict, float) or isinstance(subset_dict, int): - conn_subsets = 0 if subset_dict != numberConnections: - if random.random() < subset_dict - numberConnections: - conn_subsets = numberConnections + 1 else: - conn_subsets = numberConnections else: - conn_subsets = numberConnections total_conns = total_conns + conn_subsets - if total_conns != 0: - + if total_conns != 0: if pre_seg_target_dict != None and len(pre_seg_target_dict.keys()) == 1: - pre_subset_dict = {} pre_subset_dict[list(pre_seg_target_dict.keys())[0]] = total_conns else: - pre_subset_dict = None pop2_cell_ids = list(range(0, pop2_size)) if pop1_id == pop2_id: - pop2_cell_ids.remove(i) if pop2_cell_ids != []: - if len(pop2_cell_ids) >= total_conns: - pop2_cells = random.sample(pop2_cell_ids, total_conns) else: - pop2_cells = [] for value in range(0, total_conns): - cell_id = random.sample(pop2_cell_ids, 1) pop2_cells.extend(cell_id) - post_target_seg_array, post_target_fractions = get_target_segments(post_seg_target_dict, conn_subsets) + post_target_seg_array, post_target_fractions = get_target_segments( + post_seg_target_dict, conn_subsets + ) if pre_subset_dict != None: - - pre_target_seg_array, pre_target_fractions = get_target_segments(pre_seg_target_dict, pre_subset_dict) + pre_target_seg_array, pre_target_fractions = get_target_segments( + pre_seg_target_dict, pre_subset_dict + ) else: - pre_target_seg_array = None - pre_target_fractions = None + pre_target_fractions = None for j in pop2_cells: - post_seg_id = post_target_seg_array[0] del post_target_seg_array[0] post_fraction_along = post_target_fractions[0] - del post_target_fractions[0] + del post_target_fractions[0] if pre_target_seg_array != None and pre_target_fractions != None: - pre_seg_id = pre_target_seg_array[0] del pre_target_seg_array[0] @@ -809,71 +845,68 @@ def _add_elect_projection(net, del pre_target_fractions[0] else: - pre_seg_id = 0 pre_fraction_along = 0.5 - if targeting_mode == 'divergent': - + if targeting_mode == "divergent": pre_cell_id = i post_cell_id = j - if targeting_mode == 'convergent': - + if targeting_mode == "convergent": pre_cell_id = j - post_cell_id = i + post_cell_id = i - syn_counter = 0 + syn_counter = 0 for synapse_id in synapse_list: + add_elect_connection( + proj_array[syn_counter], + count, + presynaptic_population, + pre_cell_id, + pre_seg_id, + postsynaptic_population, + post_cell_id, + post_seg_id, + synapse_id, + pre_fraction=pre_fraction_along, + post_fraction=post_fraction_along, + ) - add_elect_connection(proj_array[syn_counter], - count, - presynaptic_population, - pre_cell_id, - pre_seg_id, - postsynaptic_population, - post_cell_id, - post_seg_id, - synapse_id, - pre_fraction=pre_fraction_along, - post_fraction=post_fraction_along) - - syn_counter += 1 + syn_counter += 1 count += 1 if count != 0: - for synapse_ind in range(0, len(synapse_list)): - net.electrical_projections.append(proj_array[synapse_ind]) - return proj_array + return proj_array ############################################################################################## -def add_chem_spatial_projection(net, - proj_array, - presynaptic_population, - postsynaptic_population, - targeting_mode, - synapse_list, - pre_seg_target_dict, - post_seg_target_dict, - subset_dict, - distance_rule, - pre_cell_positions, - post_cell_positions, - delays_dict, - weights_dict): - - '''This method adds the divergent distance-dependent chemical projection. The input arguments are as follows: +def add_chem_spatial_projection( + net, + proj_array, + presynaptic_population, + postsynaptic_population, + targeting_mode, + synapse_list, + pre_seg_target_dict, + post_seg_target_dict, + subset_dict, + distance_rule, + pre_cell_positions, + post_cell_positions, + delays_dict, + weights_dict, +): + """This method adds the divergent distance-dependent chemical projection. The input arguments are as follows: net - the network object created using libNeuroML API ( neuroml.Network() ); @@ -904,7 +937,7 @@ def add_chem_spatial_projection(net, Note: the chemical connection is made only if distance-dependent probability is higher than some random number random.random(); thus, the actual numbers of connections made - according to the distance-dependent rule might be smaller than the numbers of connections specified by subset_dict; subset_dict defines the upper bound for the + according to the distance-dependent rule might be smaller than the numbers of connections specified by subset_dict; subset_dict defines the upper bound for the number of connections. @@ -916,10 +949,9 @@ def add_chem_spatial_projection(net, delays_dict - optional dictionary that specifies the delays (in ms) for individual synapse components, e.g. {'NMDA':5.0} or {'AMPA':3.0,'NMDA':5}; - weights_dict - optional dictionary that specifies the weights for individual synapse components, e.g. {'NMDA':1} or {'NMDA':1,'AMPA':2}.''' - - if targeting_mode == 'divergent': + weights_dict - optional dictionary that specifies the weights for individual synapse components, e.g. {'NMDA':1} or {'NMDA':1,'AMPA':2}.""" + if targeting_mode == "divergent": pop1_size = presynaptic_population.size pop1_id = presynaptic_population.id @@ -932,8 +964,7 @@ def add_chem_spatial_projection(net, pop2_cell_positions = post_cell_positions - if targeting_mode == 'convergent': - + if targeting_mode == "convergent": pop1_size = postsynaptic_population.size pop1_id = postsynaptic_population.id @@ -947,109 +978,101 @@ def add_chem_spatial_projection(net, pop2_cell_positions = pre_cell_positions if isinstance(subset_dict, dict): - numberConnections = {} for subset in subset_dict.keys(): - numberConnections[subset] = int(subset_dict[subset]) if isinstance(subset_dict, int) or isinstance(subset_dict, float): - numberConnections = int(subset_dict) count = 0 for i in range(0, pop1_size): - total_conns = 0 if isinstance(subset_dict, dict): - conn_subsets = {} for subset in subset_dict.keys(): - if subset_dict[subset] != numberConnections[subset]: - - if random.random() < subset_dict[subset] - numberConnections[subset]: - + if ( + random.random() + < subset_dict[subset] - numberConnections[subset] + ): conn_subsets[subset] = numberConnections[subset] + 1 else: - conn_subsets[subset] = numberConnections[subset] else: - conn_subsets[subset] = numberConnections[subset] total_conns = total_conns + conn_subsets[subset] if isinstance(subset_dict, float) or isinstance(subset_dict, int): - conn_subsets = 0 if subset_dict != numberConnections: - if random.random() < subset_dict - numberConnections: - conn_subsets = numberConnections + 1 else: - conn_subsets = numberConnections else: - conn_subsets = numberConnections total_conns = total_conns + conn_subsets - if total_conns != 0: - + if total_conns != 0: if pre_seg_target_dict != None and len(pre_seg_target_dict.keys()) == 1: - pre_subset_dict = {} pre_subset_dict[list(pre_seg_target_dict.keys())[0]] = total_conns else: - pre_subset_dict = None pop2_cell_ids = list(range(0, pop2_size)) if pop1_id == pop2_id: - pop2_cell_ids.remove(i) if pop2_cell_ids != []: - cell1_position = pop1_cell_positions[i] - post_target_seg_array, post_fractions_along = get_target_segments(post_seg_target_dict, conn_subsets) + post_target_seg_array, post_fractions_along = get_target_segments( + post_seg_target_dict, conn_subsets + ) if pre_subset_dict != None: - - pre_target_seg_array, pre_target_fractions = get_target_segments(pre_seg_target_dict, pre_subset_dict) + pre_target_seg_array, pre_target_fractions = get_target_segments( + pre_seg_target_dict, pre_subset_dict + ) else: - pre_target_seg_array = None - pre_target_fractions = None + pre_target_fractions = None conn_counter = 0 for j in pop2_cell_ids: - cell2_position = pop2_cell_positions[j] - r = math.sqrt(sum([(a - b) ** 2 for a, b in zip(cell1_position, cell2_position)])) - - if eval(distance_rule) >= 1 or random.random() < eval(distance_rule): - + r = math.sqrt( + sum( + [ + (a - b) ** 2 + for a, b in zip(cell1_position, cell2_position) + ] + ) + ) + + if eval(distance_rule) >= 1 or random.random() < eval( + distance_rule + ): conn_counter += 1 post_seg_id = post_target_seg_array[0] @@ -1060,8 +1083,10 @@ def add_chem_spatial_projection(net, del post_fractions_along[0] - if pre_target_seg_array != None and pre_target_fractions != None: - + if ( + pre_target_seg_array != None + and pre_target_fractions != None + ): pre_seg_id = pre_target_seg_array[0] del pre_target_seg_array[0] @@ -1071,19 +1096,16 @@ def add_chem_spatial_projection(net, del pre_target_fractions[0] else: - pre_seg_id = 0 pre_fraction_along = 0.5 - if targeting_mode == 'divergent': - + if targeting_mode == "divergent": pre_cell_id = i post_cell_id = j - if targeting_mode == 'convergent': - + if targeting_mode == "convergent": pre_cell_id = j post_cell_id = i @@ -1091,7 +1113,6 @@ def add_chem_spatial_projection(net, syn_counter = 0 for synapse_id in synapse_list: - delay = 0 weight = 1 @@ -1099,27 +1120,31 @@ def add_chem_spatial_projection(net, if delays_dict != None: for synapseComp in delays_dict.keys(): if synapseComp in synapse_id: - delay = _evaluate_expression(delays_dict[synapseComp]) + delay = _evaluate_expression( + delays_dict[synapseComp] + ) if weights_dict != None: for synapseComp in weights_dict.keys(): if synapseComp in synapse_id: - weight = _evaluate_expression(weights_dict[synapseComp]) - - - _add_connection(proj_array[syn_counter], - count, - presynaptic_population, - pre_cell_id, - pre_seg_id, - postsynaptic_population, - post_cell_id, - post_seg_id, - delay=delay, - weight=weight, - pre_fraction=pre_fraction_along, - post_fraction=post_fraction_along) + weight = _evaluate_expression( + weights_dict[synapseComp] + ) + _add_connection( + proj_array[syn_counter], + count, + presynaptic_population, + pre_cell_id, + pre_seg_id, + postsynaptic_population, + post_cell_id, + post_seg_id, + delay=delay, + weight=weight, + pre_fraction=pre_fraction_along, + post_fraction=post_fraction_along, + ) syn_counter += 1 @@ -1129,30 +1154,30 @@ def add_chem_spatial_projection(net, break if count != 0: - for synapse_ind in range(0, len(synapse_list)): - net.projections.append(proj_array[synapse_ind]) - return proj_array + return proj_array ############################################################################################## -def add_elect_spatial_projection(net, - proj_array, - presynaptic_population, - postsynaptic_population, - targeting_mode, - synapse_list, - pre_seg_target_dict, - post_seg_target_dict, - subset_dict, - distance_rule, - pre_cell_positions, - post_cell_positions): - - '''This method adds the divergent or convergent electrical projection depending on the input argument targeting_mode. The input arguments are as follows: + +def add_elect_spatial_projection( + net, + proj_array, + presynaptic_population, + postsynaptic_population, + targeting_mode, + synapse_list, + pre_seg_target_dict, + post_seg_target_dict, + subset_dict, + distance_rule, + pre_cell_positions, + post_cell_positions, +): + """This method adds the divergent or convergent electrical projection depending on the input argument targeting_mode. The input arguments are as follows: net - the network object created using libNeuroML API ( neuroml.Network() ); @@ -1182,7 +1207,7 @@ def add_elect_spatial_projection(net, Note: the electrical connection is made only if distance-dependent probability is higher than some random number random.random(); thus, the actual numbers of connections made - according to the distance-dependent rule might be smaller than the numbers of connections specified by subset_dict; subset_dict defines the upper bound for the + according to the distance-dependent rule might be smaller than the numbers of connections specified by subset_dict; subset_dict defines the upper bound for the number of connections. @@ -1190,10 +1215,9 @@ def add_elect_spatial_projection(net, pre_cell_positions- array specifying the cell positions for the presynaptic population; the format is an array of [ x coordinate, y coordinate, z coordinate]; - post_cell_positions- array specifying the cell positions for the postsynaptic population; the format is an array of [ x coordinate, y coordinate, z coordinate];''' - - if targeting_mode == 'divergent': + post_cell_positions- array specifying the cell positions for the postsynaptic population; the format is an array of [ x coordinate, y coordinate, z coordinate];""" + if targeting_mode == "divergent": pop1_size = presynaptic_population.size pop1_id = presynaptic_population.id @@ -1206,8 +1230,7 @@ def add_elect_spatial_projection(net, pop2_cell_positions = post_cell_positions - if targeting_mode == 'convergent': - + if targeting_mode == "convergent": pop1_size = postsynaptic_population.size pop1_id = postsynaptic_population.id @@ -1223,107 +1246,99 @@ def add_elect_spatial_projection(net, count = 0 if isinstance(subset_dict, dict): - numberConnections = {} for subset in subset_dict.keys(): - numberConnections[subset] = int(subset_dict[subset]) if isinstance(subset_dict, int) or isinstance(subset_dict, float): - numberConnections = int(subset_dict) for i in range(0, pop1_size): - total_conns = 0 if isinstance(subset_dict, dict): - conn_subsets = {} for subset in subset_dict.keys(): - if subset_dict[subset] != numberConnections[subset]: - - if random.random() < subset_dict[subset] - numberConnections[subset]: - + if ( + random.random() + < subset_dict[subset] - numberConnections[subset] + ): conn_subsets[subset] = numberConnections[subset] + 1 else: - conn_subsets[subset] = numberConnections[subset] else: - conn_subsets[subset] = numberConnections[subset] total_conns = total_conns + conn_subsets[subset] if isinstance(subset_dict, float) or isinstance(subset_dict, int): - conn_subsets = 0 if subset_dict != numberConnections: - if random.random() < subset_dict - numberConnections: - conn_subsets = numberConnections + 1 else: - conn_subsets = numberConnections else: - conn_subsets = numberConnections total_conns = total_conns + conn_subsets - if total_conns != 0: - + if total_conns != 0: if pre_seg_target_dict != None and len(pre_seg_target_dict.keys()) == 1: - pre_subset_dict = {} pre_subset_dict[list(pre_seg_target_dict.keys())[0]] = total_conns else: - - pre_subset_dict = None + pre_subset_dict = None pop2_cell_ids = list(range(0, pop2_size)) if pop1_id == pop2_id: - pop2_cell_ids.remove(i) if pop2_cell_ids != []: - cell1_position = pop1_cell_positions[i] - post_target_seg_array, post_target_fractions = get_target_segments(post_seg_target_dict, conn_subsets) + post_target_seg_array, post_target_fractions = get_target_segments( + post_seg_target_dict, conn_subsets + ) if pre_subset_dict != None: - - pre_target_seg_array, pre_target_fractions = get_target_segments(pre_seg_target_dict, pre_subset_dict) + pre_target_seg_array, pre_target_fractions = get_target_segments( + pre_seg_target_dict, pre_subset_dict + ) else: - pre_target_seg_array = None - pre_target_fractions = None + pre_target_fractions = None conn_counter = 0 for j in pop2_cell_ids: - cell2_position = pop2_cell_positions[j] - r = math.sqrt(sum([(a - b) ** 2 for a, b in zip(cell1_position, cell2_position)])) - - if eval(distance_rule) >= 1 or random.random() < eval(distance_rule): - + r = math.sqrt( + sum( + [ + (a - b) ** 2 + for a, b in zip(cell1_position, cell2_position) + ] + ) + ) + + if eval(distance_rule) >= 1 or random.random() < eval( + distance_rule + ): conn_counter += 1 post_seg_id = post_target_seg_array[0] @@ -1332,10 +1347,12 @@ def add_elect_spatial_projection(net, post_fraction_along = post_target_fractions[0] - del post_target_fractions[0] - - if pre_target_seg_array != None and pre_target_fractions != None: + del post_target_fractions[0] + if ( + pre_target_seg_array != None + and pre_target_fractions != None + ): pre_seg_id = pre_target_seg_array[0] del pre_target_seg_array[0] @@ -1345,40 +1362,38 @@ def add_elect_spatial_projection(net, del pre_target_fractions[0] else: - pre_seg_id = 0 pre_fraction_along = 0.5 - if targeting_mode == 'divergent': - + if targeting_mode == "divergent": pre_cell_id = i post_cell_id = j - if targeting_mode == 'convergent': - + if targeting_mode == "convergent": pre_cell_id = j - post_cell_id = i + post_cell_id = i - syn_counter = 0 + syn_counter = 0 for synapse_id in synapse_list: + add_elect_connection( + proj_array[syn_counter], + count, + presynaptic_population, + pre_cell_id, + pre_seg_id, + postsynaptic_population, + post_cell_id, + post_seg_id, + synapse_id, + pre_fraction=pre_fraction_along, + post_fraction=post_fraction_along, + ) - add_elect_connection(proj_array[syn_counter], - count, - presynaptic_population, - pre_cell_id, - pre_seg_id, - postsynaptic_population, - post_cell_id, - post_seg_id, - synapse_id, - pre_fraction=pre_fraction_along, - post_fraction=post_fraction_along) - - syn_counter += 1 + syn_counter += 1 count += 1 @@ -1386,92 +1401,94 @@ def add_elect_spatial_projection(net, break if count != 0: - for synapse_ind in range(0, len(synapse_list)): - net.electrical_projections.append(proj_array[synapse_ind]) - return proj_array + return proj_array ############################################################################################## -def make_target_dict(cell_object, - target_segs): - '''This method constructs the dictionary whose keys are the names of target segment groups or individual segments and the corresponding values are dictionaries + +def make_target_dict(cell_object, target_segs): + """This method constructs the dictionary whose keys are the names of target segment groups or individual segments and the corresponding values are dictionaries with keys 'LengthDist' and 'SegList', as returned by the get_seg_lengths. Input arguments are as follows: cell_object - object created using libNeuroML API which corresponds to the target cell; - target_segs - a dictionary in the format returned by the method extract_seg_ids(); the keys are the ids of target segment groups or names of individual segments and - the values are lists of corresponding target segment ids.''' + target_segs - a dictionary in the format returned by the method extract_seg_ids(); the keys are the ids of target segment groups or names of individual segments and + the values are lists of corresponding target segment ids.""" targetDict = {} for target in target_segs.keys(): targetDict[target] = {} lengths, segment_list = get_seg_lengths(cell_object, target_segs[target]) - targetDict[target]['LengthDist'] = lengths - targetDict[target]['SegList'] = segment_list + targetDict[target]["LengthDist"] = lengths + targetDict[target]["SegList"] = segment_list return targetDict ############################################################################################################################ -def get_target_cells(population, - fraction_to_target, - list_of_xvectors=None, - list_of_yvectors=None, - list_of_zvectors=None): - '''This method returns the list of target cells according to which fraction of randomly selected cells is targeted and whether these cells are localized in the specific +def get_target_cells( + population, + fraction_to_target, + list_of_xvectors=None, + list_of_yvectors=None, + list_of_zvectors=None, +): + """This method returns the list of target cells according to which fraction of randomly selected cells is targeted and whether these cells are localized in the specific rectangular regions of the network. These regions are specified by list_of_xvectors, list_of_yvectors and list_of_zvectors. These lists must have the same length. The input variable list_of_xvectors stores the lists whose elements define the left and right margins of the target rectangular regions along the x dimension. Similarly, the input variables list_of_yvectors and list_of_zvectors store the lists whose elements define the left and right margins of the target rectangular regions along - the y and z dimensions, respectively.''' + the y and z dimensions, respectively.""" if list_of_xvectors == None or list_of_yvectors == None or list_of_zvectors == None: - - target_cells = random.sample(range(population.size), int(round(fraction_to_target * population.size))) + target_cells = random.sample( + range(population.size), int(round(fraction_to_target * population.size)) + ) else: - cell_instances = population.instances region_specific_targets_per_cell_group = [] for region in range(0, len(list_of_xvectors)): - for cell in range(0, len(cell_instances)): - cell_inst = cell_instances[cell] location = cell_inst.location - if (list_of_xvectors[region][0] < location.x) and \ - (location.x < list_of_xvectors[region][1]): - ########## assumes that the surface of the cortical column starts at the zero level and deeper layers are found at increasingly negative values - if (list_of_yvectors[region][0] > location.y) and \ - (location.y > list_of_yvectors[region][1]): - - if (list_of_zvectors[region][0] < location.z) and \ - (location.z < list_of_zvectors[region][1]): - - region_specific_targets_per_cell_group.append(cell) - - target_cells = random.sample(region_specific_targets_per_cell_group, int(round(fraction_to_target * len(region_specific_targets_per_cell_group)))) - + if (list_of_xvectors[region][0] < location.x) and ( + location.x < list_of_xvectors[region][1] + ): + ########## assumes that the surface of the cortical column starts at the zero level and deeper layers are found at increasingly negative values + if (list_of_yvectors[region][0] > location.y) and ( + location.y > list_of_yvectors[region][1] + ): + if (list_of_zvectors[region][0] < location.z) and ( + location.z < list_of_zvectors[region][1] + ): + region_specific_targets_per_cell_group.append(cell) + + target_cells = random.sample( + region_specific_targets_per_cell_group, + int( + round(fraction_to_target * len(region_specific_targets_per_cell_group)) + ), + ) return target_cells ############################################################################################## -def get_seg_lengths(cell_object, - target_segments): - '''This method constructs the cumulative distribution of target segments and the corresponding list of target segment ids. - Input arguments: cell_object - object created using libNeuroML API which corresponds to the target cell; target_segments - the list of target segment ids. ''' +def get_seg_lengths(cell_object, target_segments): + """This method constructs the cumulative distribution of target segments and the corresponding list of target segment ids. + Input arguments: cell_object - object created using libNeuroML API which corresponds to the target cell; target_segments - the list of target segment ids.""" cumulative_length_dist = [] segment_list = [] @@ -1479,7 +1496,6 @@ def get_seg_lengths(cell_object, for seg in cell_object.morphology.segments: for target_seg in target_segments: if target_seg == seg.id: - if seg.distal != None: xd = seg.distal.x yd = seg.distal.y @@ -1499,8 +1515,8 @@ def get_seg_lengths(cell_object, yp = segment_parent.distal.y zp = segment_parent.distal.z dist = [xd, yd, zd] - prox = [xp, yp, zp] - length = math.sqrt(sum([(a - b) ** 2 for a, b in zip(dist, prox)])) + prox = [xp, yp, zp] + length = math.sqrt(sum([(a - b) ** 2 for a, b in zip(dist, prox)])) segment_list.append(target_seg) totalLength = totalLength + length @@ -1511,55 +1527,53 @@ def get_seg_lengths(cell_object, ############################################################################################## -def extract_seg_ids(cell_object, - target_compartment_array, - targeting_mode): - '''This method extracts the segment ids that map on the target segment groups or individual segments. - cell_object is the loaded cell object using neuroml.loaders.NeuroMLLoader, target_compartment_array is an array of target compartment names (e.g. segment group ids or individual segment names) and targeting_mode is one of the strings: "segments" or "segGroups". ''' +def extract_seg_ids(cell_object, target_compartment_array, targeting_mode): + """This method extracts the segment ids that map on the target segment groups or individual segments. + cell_object is the loaded cell object using neuroml.loaders.NeuroMLLoader, target_compartment_array is an array of target compartment names (e.g. segment group ids or individual segment names) and targeting_mode is one of the strings: "segments" or "segGroups".""" segment_id_array = [] segment_group_array = {} cell_segment_array = [] - + for segment in cell_object.morphology.segments: - segment_id_array.append(segment.id) + segment_id_array.append(segment.id) segment_name_and_id = [] segment_name_and_id.append(segment.name) segment_name_and_id.append(segment.id) cell_segment_array.append(segment_name_and_id) - + for segment_group in cell_object.morphology.segment_groups: pooled_segment_group_data = {} segment_list = [] segment_group_list = [] - + segment_list = cell_object.get_all_segments_in_group(segment_group) - + for included_segment_group in segment_group.includes: segment_group_list.append(included_segment_group.segment_groups) - pooled_segment_group_data["segments"] = segment_list pooled_segment_group_data["groups"] = segment_group_list - segment_group_array[segment_group.id] = pooled_segment_group_data - + segment_group_array[segment_group.id] = pooled_segment_group_data target_segment_array = {} found_target_groups = [] if targeting_mode == "segments": - for segment_counter in range(0, len(cell_segment_array)): for target_segment in range(0, len(target_compartment_array)): - if cell_segment_array[segment_counter][0] == target_compartment_array[target_segment]: - target_segment_array[target_compartment_array[target_segment]] = [cell_segment_array[segment_counter][1]] + if ( + cell_segment_array[segment_counter][0] + == target_compartment_array[target_segment] + ): + target_segment_array[target_compartment_array[target_segment]] = [ + cell_segment_array[segment_counter][1] + ] found_target_groups.append(target_compartment_array[target_segment]) - if targeting_mode == "segGroups": - for segment_group in segment_group_array.keys(): for target_group in range(0, len(target_compartment_array)): if target_compartment_array[target_group] == segment_group: @@ -1567,89 +1581,93 @@ def extract_seg_ids(cell_object, found_target_groups.append(target_compartment_array[target_group]) if segment_group_array[segment_group]["segments"] != []: for segment in segment_group_array[segment_group]["segments"]: - if not segment in segment_target_array: + if segment not in segment_target_array: segment_target_array.append(segment) - - target_segment_array[target_compartment_array[target_group]] = segment_target_array + target_segment_array[target_compartment_array[target_group]] = ( + segment_target_array + ) if len(found_target_groups) != len(target_compartment_array): + groups_not_found = list( + set(target_compartment_array) - set(found_target_groups) + ) - groups_not_found = list(set(target_compartment_array)- set(found_target_groups)) - - opencortex.print_comment_v("Error in method opencortex.build.extract_seg_ids(): target segments or segment groups in %s are not found in %s. Execution will terminate." - % (groups_not_found, cell_object.id)) + opencortex.print_comment_v( + "Error in method opencortex.build.extract_seg_ids(): target segments or segment groups in %s are not found in %s. Execution will terminate." + % (groups_not_found, cell_object.id) + ) quit() - - return target_segment_array + + return target_segment_array ###################################################################################### -def get_target_segments(seg_specifications, - subset_dict): - '''This method generates the list of target segments and target fractions per cell according to two types of input dictionaries: +def get_target_segments(seg_specifications, subset_dict): + """This method generates the list of target segments and target fractions per cell according to two types of input dictionaries: seg_specifications - a dictionary in the format returned by make_target_dict(); keys are target group names or individual segment names and the corresponding values are dictionaries with keys 'LengthDist' and 'SegList', as returned by the get_seg_lengths; - subset_dict - a dictionary whose keys are target group names or individual segment names; each key stores the corresponding number of connections per target group.''' + subset_dict - a dictionary whose keys are target group names or individual segment names; each key stores the corresponding number of connections per target group.""" - #opencortex.print_comment_v("get_target_segments(): %s; %s"%(seg_specifications.keys(), subset_dict)) + # opencortex.print_comment_v("get_target_segments(): %s; %s"%(seg_specifications.keys(), subset_dict)) target_segs_per_cell = [] target_fractions_along_per_cell = [] if isinstance(subset_dict, dict): - for target_group in subset_dict.keys(): - no_per_target_group = subset_dict[target_group] if target_group in seg_specifications.keys(): - target_segs_per_group = [] target_fractions_along_per_group = [] - cumulative_length_dist = seg_specifications[target_group]['LengthDist'] + cumulative_length_dist = seg_specifications[target_group]["LengthDist"] + + segment_list = seg_specifications[target_group]["SegList"] - segment_list = seg_specifications[target_group]['SegList'] - - #opencortex.print_comment_v("cumulative_length_dist: %s; segment_list: %s"%(cumulative_length_dist, segment_list)) + # opencortex.print_comment_v("cumulative_length_dist: %s; segment_list: %s"%(cumulative_length_dist, segment_list)) not_selected = True while not_selected: - p = random.random() loc = p * cumulative_length_dist[-1] if len(segment_list) == len(cumulative_length_dist): - for seg_index in range(0, len(segment_list)): - current_dist_value = cumulative_length_dist[seg_index] if seg_index == 0: - previous_dist_value = 0 else: + previous_dist_value = cumulative_length_dist[ + seg_index - 1 + ] - previous_dist_value = cumulative_length_dist[seg_index-1] - if loc >= previous_dist_value and loc <= current_dist_value: + segment_length = ( + current_dist_value - previous_dist_value + ) - segment_length = current_dist_value-previous_dist_value - - length_within_seg = loc-previous_dist_value + length_within_seg = loc - previous_dist_value - post_fraction_along = float(length_within_seg) / segment_length if segment_length>0 else 0.5 + post_fraction_along = ( + float(length_within_seg) / segment_length + if segment_length > 0 + else 0.5 + ) target_segs_per_group.append(segment_list[seg_index]) - target_fractions_along_per_group.append(post_fraction_along) + target_fractions_along_per_group.append( + post_fraction_along + ) break @@ -1661,44 +1679,38 @@ def get_target_segments(seg_specifications, target_fractions_along_per_cell.extend(target_fractions_along_per_group) - if isinstance(subset_dict, float) or isinstance(subset_dict, int): - total_num_per_target_groups = int(subset_dict) not_selected = True while not_selected: + random_target_group = random.sample(list(seg_specifications.keys()), 1)[0] - random_target_group = random.sample(seg_specifications.keys(), 1)[0] + cumulative_length_dist = seg_specifications[random_target_group][ + "LengthDist" + ] - cumulative_length_dist = seg_specifications[random_target_group]['LengthDist'] - - segment_list = seg_specifications[random_target_group]['SegList'] + segment_list = seg_specifications[random_target_group]["SegList"] p = random.random() loc = p * cumulative_length_dist[-1] if len(segment_list) == len(cumulative_length_dist): - for seg_index in range(0, len(segment_list)): - current_dist_value = cumulative_length_dist[seg_index] if seg_index == 0: - previous_dist_value = 0 else: - - previous_dist_value = cumulative_length_dist[seg_index-1] + previous_dist_value = cumulative_length_dist[seg_index - 1] if loc > previous_dist_value and loc < current_dist_value: + segment_length = current_dist_value - previous_dist_value - segment_length = current_dist_value-previous_dist_value - - length_within_seg = loc-previous_dist_value + length_within_seg = loc - previous_dist_value post_fraction_along = float(length_within_seg) / segment_length @@ -1709,7 +1721,6 @@ def get_target_segments(seg_specifications, break if len(target_segs_per_cell) == total_num_per_target_groups: - not_selected = False break @@ -1719,42 +1730,33 @@ def get_target_segments(seg_specifications, ########################################################################################################################### -def get_pre_and_post_segment_ids(proj): - '''This method extracts the lists of pre and post segment ids per given projection. Can be used when substituting the cell types from one NeuroML2 network to the other. +def get_pre_and_post_segment_ids(proj): + """This method extracts the lists of pre and post segment ids per given projection. Can be used when substituting the cell types from one NeuroML2 network to the other. - return pre_segment_ids, post_segment_ids''' + return pre_segment_ids, post_segment_ids""" pre_segment_ids = [] post_segment_ids = [] - if hasattr(proj, 'connection_wds'): - + if hasattr(proj, "connection_wds"): if proj.connection_wds != []: - connections = proj.connection_wds - elif hasattr(proj, 'connections'): - + elif hasattr(proj, "connections"): if proj.connections != []: - connections = proj.connections - elif hasattr(proj, 'electrical_connection_instances'): - + elif hasattr(proj, "electrical_connection_instances"): if proj.electrical_connection_instances != []: - connections = proj.electrical_connection_instances else: - if proj.electrical_connections != []: - connections = proj.electrical_connections for conn_counter in range(0, len(connections)): - connection = connections[conn_counter] pre_segment_ids.append(connection.pre_segment_id) @@ -1763,12 +1765,12 @@ def get_pre_and_post_segment_ids(proj): return pre_segment_ids, post_segment_ids + ################################################################################################################################## # Helper method which will be made redundant with a better generated Python API... def _get_cells_of_all_known_types(nml_doc): - all_cells_known = [] all_cells_known.extend(nml_doc.cells) all_cells_known.extend(nml_doc.izhikevich_cells) @@ -1778,9 +1780,9 @@ def _get_cells_of_all_known_types(nml_doc): return all_cells_known + # Helper method which will be made redundant with a better generated Python API... def _get_channels_of_all_known_types(nml_doc): - all_channels = [] all_channels.extend(nml_doc.ion_channel) all_channels.extend(nml_doc.ion_channel_hhs) @@ -1791,9 +1793,9 @@ def _get_channels_of_all_known_types(nml_doc): return all_channels + # Helper method which will be made redundant with a better generated Python API... def _add_to_neuroml_doc(nml_doc, element): - if isinstance(element, neuroml.Cell): nml_doc.cells.append(element) elif isinstance(element, neuroml.IzhikevichCell): @@ -1819,116 +1821,112 @@ def _add_to_neuroml_doc(nml_doc, element): # Add to list of files to be copied when the network is saved def _copy_to_dir_for_model(nml_doc, file_name): - to_be_copied_on_save.append(file_name) - - + + # Save included cell/channel files to specific dir when the network is saved -def _finalise_copy_to_dir_for_model(nml_doc, target_dir='./', use_subfolder=True): +def _finalise_copy_to_dir_for_model(nml_doc, target_dir="./", use_subfolder=True): for file_name in to_be_copied_on_save: + dir_for_model = target_dir + nml_doc.id if use_subfolder else target_dir - dir_for_model = target_dir+nml_doc.id if use_subfolder else target_dir - if not os.path.isdir(dir_for_model): os.mkdir(dir_for_model) - if not os.path.exists(dir_for_model+"/"+file_name): + if not os.path.exists(dir_for_model + "/" + file_name): shutil.copy(file_name, dir_for_model) -########################################################################################## +########################################################################################## -def copy_nml2_source(dir_to_project_nml2, - primary_nml2_dir, - electrical_synapse_tags, - chemical_synapse_tags, - extra_channel_tags=[]): - '''This method copies the individual NeuroML2 model components from the primary source dir to corresponding component folders in the target dir: "synapses", "gapJunctions", +def copy_nml2_source( + dir_to_project_nml2, + primary_nml2_dir, + electrical_synapse_tags, + chemical_synapse_tags, + extra_channel_tags=[], +): + """This method copies the individual NeuroML2 model components from the primary source dir to corresponding component folders in the target dir: "synapses", "gapJunctions", - "channels" and "cells" are created in the dir_to_project_nml2.''' + "channels" and "cells" are created in the dir_to_project_nml2.""" full_path_to_synapses = os.path.join(dir_to_project_nml2, "synapses") if not os.path.exists(full_path_to_synapses): - os.makedirs(full_path_to_synapses) full_path_to_gap_junctions = os.path.join(dir_to_project_nml2, "gapJunctions") if not os.path.exists(full_path_to_gap_junctions): - os.makedirs(full_path_to_gap_junctions) full_path_to_channels = os.path.join(dir_to_project_nml2, "channels") if not os.path.exists(full_path_to_channels): - os.makedirs(full_path_to_channels) full_path_to_cells = os.path.join(dir_to_project_nml2, "cells") if not os.path.exists(full_path_to_cells): - os.makedirs(full_path_to_cells) - opencortex.print_comment_v("Will be copying cell component files from %s to %s" % (primary_nml2_dir, full_path_to_cells)) + opencortex.print_comment_v( + "Will be copying cell component files from %s to %s" + % (primary_nml2_dir, full_path_to_cells) + ) - opencortex.print_comment_v("Will be copying channel component files from %s to %s" % (primary_nml2_dir, full_path_to_channels)) + opencortex.print_comment_v( + "Will be copying channel component files from %s to %s" + % (primary_nml2_dir, full_path_to_channels) + ) - opencortex.print_comment_v("Will be copying synapse component files from %s to %s" % (primary_nml2_dir, full_path_to_synapses)) + opencortex.print_comment_v( + "Will be copying synapse component files from %s to %s" + % (primary_nml2_dir, full_path_to_synapses) + ) - opencortex.print_comment_v("Will be copying gap junction component files from %s to %s" % (primary_nml2_dir, full_path_to_gap_junctions)) + opencortex.print_comment_v( + "Will be copying gap junction component files from %s to %s" + % (primary_nml2_dir, full_path_to_gap_junctions) + ) src_files = os.listdir(primary_nml2_dir) for file_name in src_files: - full_file_name = os.path.join(primary_nml2_dir, file_name) - if '.cell.nml' in file_name: - + if ".cell.nml" in file_name: shutil.copy(full_file_name, full_path_to_cells) continue for elect_tag in electrical_synapse_tags: - if elect_tag in file_name: - shutil.copy(full_file_name, full_path_to_gap_junctions) continue for chem_tag in chemical_synapse_tags: - if chem_tag in file_name: - shutil.copy(full_file_name, full_path_to_synapses) continue - if '.channel.nml' in file_name: - + if ".channel.nml" in file_name: shutil.copy(full_file_name, full_path_to_channels) continue - if extra_channel_tags != []: - + if extra_channel_tags != []: for channel_tag in extra_channel_tags: - if channel_tag in file_name: - shutil.copy(full_file_name, full_path_to_channels) - def _include_neuroml2_cell(nml_doc, cell_nml2_path, cell_id, channels_also=True): - - ''' + """ This could be called from opencortex.core - ''' + """ nml2_doc_cell = pynml.read_neuroml2_file(cell_nml2_path, include_includes=False) @@ -1937,41 +1935,48 @@ def _include_neuroml2_cell(nml_doc, cell_nml2_path, cell_id, channels_also=True) all_cells[cell_id] = cell _copy_to_dir_for_model(nml_doc, cell_nml2_path) - - new_file = '%s/%s' % (nml_doc.id, os.path.basename(cell_nml2_path)) - - if not new_file in all_included_files: - nml_doc.includes.append(neuroml.IncludeType(new_file)) + + new_file = "%s/%s" % (nml_doc.id, os.path.basename(cell_nml2_path)) + + if new_file not in all_included_files: + nml_doc.includes.append(neuroml.IncludeType(new_file)) all_included_files.append(new_file) if channels_also: - nml_file_dir = os.path.dirname(cell_nml2_path) if len(os.path.dirname(cell_nml2_path))>0 else '.' + nml_file_dir = ( + os.path.dirname(cell_nml2_path) + if len(os.path.dirname(cell_nml2_path)) > 0 + else "." + ) for included in nml2_doc_cell.includes: - - incl_file = '%s/%s'%(nml_file_dir,included.href) + incl_file = "%s/%s" % (nml_file_dir, included.href) _copy_to_dir_for_model(nml_doc, incl_file) - - new_file = '%s/%s' % (nml_doc.id, os.path.basename(included.href)) - - if not new_file in all_included_files: + + new_file = "%s/%s" % (nml_doc.id, os.path.basename(included.href)) + + if new_file not in all_included_files: nml_doc.includes.append(neuroml.IncludeType(new_file)) all_included_files.append(new_file) - + cell_ids_vs_nml_docs[cell_id] = nml2_doc_cell ######################################################################################### -def _add_cell_and_channels(nml_doc, cell_nml2_rel_path, cell_id, use_prototypes=True): +def _add_cell_and_channels(nml_doc, cell_nml2_rel_path, cell_id, use_prototypes=True): if use_prototypes: + cell_nml2_path = ( + os.path.dirname(__file__) + + "/../../NeuroML2/prototypes/" + + cell_nml2_rel_path + ) - cell_nml2_path = os.path.dirname(__file__) + "/../../NeuroML2/prototypes/" + cell_nml2_rel_path - - opencortex.print_comment_v("Translated %s to %s" % (cell_nml2_rel_path, cell_nml2_path)) + opencortex.print_comment_v( + "Translated %s to %s" % (cell_nml2_rel_path, cell_nml2_path) + ) else: - cell_nml2_path = cell_nml2_rel_path nml2_doc_cell = pynml.read_neuroml2_file(cell_nml2_path, include_includes=False) @@ -1981,284 +1986,278 @@ def _add_cell_and_channels(nml_doc, cell_nml2_rel_path, cell_id, use_prototypes= all_cells[cell_id] = cell _copy_to_dir_for_model(nml_doc, cell_nml2_path) - new_file = '%s/%s.cell.nml' % (nml_doc.id, cell_id) - if not new_file in all_included_files: - nml_doc.includes.append(neuroml.IncludeType(new_file)) + new_file = "%s/%s.cell.nml" % (nml_doc.id, cell_id) + if new_file not in all_included_files: + nml_doc.includes.append(neuroml.IncludeType(new_file)) all_included_files.append(new_file) for included in nml2_doc_cell.includes: - - if '../channels/' in included.href: - + if "../channels/" in included.href: path_included = included.href.split("/") channel_file = path_included[-1] - old_loc = '../../channels/%s' % channel_file + old_loc = "../../channels/%s" % channel_file - elif '..\channels\'' in included.href: - - path_included = included.href.split("\"") + elif "..\channels'" in included.href: + path_included = included.href.split('"') channel_file = path_included[-1] old_loc = "..\..\channels\%s'" % channel_file else: - channel_file = included.href - old_loc = '%s/%s' % (os.path.dirname(os.path.abspath(cell_nml2_path)), channel_file) + old_loc = "%s/%s" % ( + os.path.dirname(os.path.abspath(cell_nml2_path)), + channel_file, + ) _copy_to_dir_for_model(nml_doc, old_loc) - new_loc = '%s/%s' % (nml_doc.id, channel_file) - - if not new_loc in all_included_files: + new_loc = "%s/%s" % (nml_doc.id, channel_file) + + if new_loc not in all_included_files: nml_doc.includes.append(neuroml.IncludeType(new_loc)) all_included_files.append(new_loc) - nml2_doc_cell_full = pynml.read_neuroml2_file(cell_nml2_path, include_includes=True) cell_ids_vs_nml_docs[cell_id] = nml2_doc_cell_full -####################################################################################################################################### +####################################################################################################################################### -def remove_component_dirs(dir_to_project_nml2, - list_of_cell_ids, - extra_channel_tags=None): - '''This method removes the sufolder strings of NeuroML2 component types (if they exist) from the 'includes' of each NeuroML2 cell in the target dir. +def remove_component_dirs( + dir_to_project_nml2, list_of_cell_ids, extra_channel_tags=None +): + """This method removes the sufolder strings of NeuroML2 component types (if they exist) from the 'includes' of each NeuroML2 cell in the target dir. - Target directory is specified by the input argument dir_to_project_nml2.''' + Target directory is specified by the input argument dir_to_project_nml2.""" list_of_cell_file_names = [] for cell_id in list_of_cell_ids: - list_of_cell_file_names.append(cell_id + ".cell.nml") for cell_file_name in list_of_cell_file_names: - full_path_to_cell = os.path.join(dir_to_project_nml2, cell_file_name) - nml2_doc_cell = pynml.read_neuroml2_file(full_path_to_cell, include_includes=False) + nml2_doc_cell = pynml.read_neuroml2_file( + full_path_to_cell, include_includes=False + ) for included in nml2_doc_cell.includes: - - if '.channel.nml' in included.href: - - if '../channels/' in included.href: - + if ".channel.nml" in included.href: + if "../channels/" in included.href: split_href = included.href.split("/") included.href = split_href[-1] continue - if '..\channels\'' in included.href: - - split_href = included.href.split("\'") + if "..\channels'" in included.href: + split_href = included.href.split("'") included.href = split_href[-1] continue else: - if extra_channel_tags != None: - for channel_tag in included.href: - if channel_tag in included.href: - - if '../channels/' in included.href: - + if "../channels/" in included.href: split_href = included.href.split("/") included.href = split_href[-1] break - if '..\channels\'' in included.href: - - split_href = included.href.split("\'") + if "..\channels'" in included.href: + split_href = included.href.split("'") included.href = split_href[-1] break - pynml.write_neuroml2_file(nml2_doc_cell, full_path_to_cell) + pynml.write_neuroml2_file(nml2_doc_cell, full_path_to_cell) ############################################################################################## -def add_synapses(nml_doc, nml2_path, synapse_list, synapse_tag=True): - - for synapse in synapse_list: +def add_synapses(nml_doc, nml2_path, synapse_list, synapse_tag=True): + for synapse in synapse_list: if synapse_tag: + _copy_to_dir_for_model( + nml_doc, os.path.join(nml2_path, "%s.synapse.nml" % synapse) + ) - _copy_to_dir_for_model(nml_doc, os.path.join(nml2_path, "%s.synapse.nml" % synapse)) - - new_file = '%s/%s.synapse.nml' % (nml_doc.id, synapse) + new_file = "%s/%s.synapse.nml" % (nml_doc.id, synapse) else: - _copy_to_dir_for_model(nml_doc, os.path.join(nml2_path, "%s.nml" % synapse)) - new_file = '%s/%s.nml' % (nml_doc.id, synapse) - - nml_doc.includes.append(neuroml.IncludeType(new_file)) + new_file = "%s/%s.nml" % (nml_doc.id, synapse) + nml_doc.includes.append(neuroml.IncludeType(new_file)) +################################################################################ -################################################################################ def _add_pulse_generator(nml_doc, id, delay, duration, amplitude): - """ - Adds a element to the document. See the definition of the + Adds a element to the document. See the definition of the behaviour of this here: https://www.neuroml.org/NeuroML2CoreTypes/Inputs.html#pulseGenerator - + Returns the class created. """ - - pg = neuroml.PulseGenerator(id=id, - delay=delay, - duration=duration, - amplitude=amplitude) + + pg = neuroml.PulseGenerator( + id=id, delay=delay, duration=duration, amplitude=amplitude + ) nml_doc.pulse_generators.append(pg) return pg +################################################################################ -################################################################################ - -def _add_voltage_clamp_triple(nml_doc, id, delay, duration, - conditioning_voltage, - testing_voltage, - return_voltage, - simple_series_resistance, - active): - +def _add_voltage_clamp_triple( + nml_doc, + id, + delay, + duration, + conditioning_voltage, + testing_voltage, + return_voltage, + simple_series_resistance, + active, +): """ - Adds a element to the document. See the definition of the + Adds a element to the document. See the definition of the behaviour of this here: https://github.com/NeuroML/NeuroML2/blob/development/Schemas/NeuroML2/NeuroML_v2beta5.xsd - + Returns the class created. """ - - vc = neuroml.VoltageClampTriple(id=id, - delay=delay, - duration=duration, - conditioning_voltage=conditioning_voltage, - testing_voltage=testing_voltage, - return_voltage=return_voltage, - simple_series_resistance=simple_series_resistance, - active=active) + + vc = neuroml.VoltageClampTriple( + id=id, + delay=delay, + duration=duration, + conditioning_voltage=conditioning_voltage, + testing_voltage=testing_voltage, + return_voltage=return_voltage, + simple_series_resistance=simple_series_resistance, + active=active, + ) nml_doc.voltage_clamp_triples.append(vc) return vc - ############################################################################################## + def _add_poisson_firing_synapse(nml_doc, id, average_rate, synapse_id): - """ - Adds a element to the document. See the definition of the + Adds a element to the document. See the definition of the behaviour of this here: https://www.neuroml.org/NeuroML2CoreTypes/Inputs.html#poissonFiringSynapse - + Returns the class created. """ - pfs = neuroml.PoissonFiringSynapse(id=id, - average_rate=average_rate, - synapse=synapse_id, - spike_target="./%s" % synapse_id) + pfs = neuroml.PoissonFiringSynapse( + id=id, + average_rate=average_rate, + synapse=synapse_id, + spike_target="./%s" % synapse_id, + ) nml_doc.poisson_firing_synapses.append(pfs) return pfs - ######################################################################### -def _add_transient_poisson_firing_synapse(nml_doc, id, average_rate, delay, duration, synapse_id): +def _add_transient_poisson_firing_synapse( + nml_doc, id, average_rate, delay, duration, synapse_id +): """ - Adds a element to the document. See the definition of the + Adds a element to the document. See the definition of the behaviour of this here: https://www.neuroml.org/NeuroML2CoreTypes/Inputs.html#transientPoissonFiringSynapse - + Returns the class created. """ - - pfs = neuroml.TransientPoissonFiringSynapse(id=id, - average_rate=average_rate, - delay=delay, - duration=duration, - synapse=synapse_id, - spike_target="./%s" % synapse_id) + + pfs = neuroml.TransientPoissonFiringSynapse( + id=id, + average_rate=average_rate, + delay=delay, + duration=duration, + synapse=synapse_id, + spike_target="./%s" % synapse_id, + ) nml_doc.transient_poisson_firing_synapses.append(pfs) return pfs - ############################################################################################## -def _add_spike_source_poisson(nml_doc, id, start, duration, rate): +def _add_spike_source_poisson(nml_doc, id, start, duration, rate): """ - Adds a element to the document. See the definition of the + Adds a element to the document. See the definition of the behaviour of this here: https://www.neuroml.org/NeuroML2CoreTypes/PyNN.html#SpikeSourcePoisson - + Returns the class created. """ - - ssp = neuroml.SpikeSourcePoisson(id=id, - start=start, - duration=duration, - rate=rate) + + ssp = neuroml.SpikeSourcePoisson(id=id, start=start, duration=duration, rate=rate) nml_doc.SpikeSourcePoisson.append(ssp) return ssp + ############################################################################################## -def _add_population_in_rectangular_region(net, - pop_id, - cell_id, - size, - x_min, - y_min, - z_min, - x_size, - y_size, - z_size, - cell_bodies_overlap=True, - store_soma=False, - population_dictionary=None, - cell_diameter_dict=None, - color=None): +def _add_population_in_rectangular_region( + net, + pop_id, + cell_id, + size, + x_min, + y_min, + z_min, + x_size, + y_size, + z_size, + cell_bodies_overlap=True, + store_soma=False, + population_dictionary=None, + cell_diameter_dict=None, + color=None, +): """ See info at opencortex.core.add_population_in_rectangular_region() """ - pop = neuroml.Population(id=pop_id, component=cell_id, type="populationList", size=size) + pop = neuroml.Population( + id=pop_id, component=cell_id, type="populationList", size=size + ) # TODO ##from neuroml.hdf5.NetworkContainer import PopulationContainer ##pop = PopulationContainer(id=pop_id, component=cell_id, type="populationList", size=size) @@ -2266,54 +2265,49 @@ def _add_population_in_rectangular_region(net, if color is not None: pop.properties.append(neuroml.Property("color", color)) - - # If size == 0, don't add to document, but return placeholder object (with attribute size=0 & id) if size > 0: net.populations.append(pop) if store_soma: - cellPositions = [] - if (not cell_bodies_overlap) and (population_dictionary == None or cell_diameter_dict == None): + if (not cell_bodies_overlap) and ( + population_dictionary == None or cell_diameter_dict == None + ): + error = ( + "Error! Method opencortex.build.%s() called with cell_bodies_overlap set to False but population_dictionary or cell_diameter_dict is None !" + % sys._getframe().f_code.co_name + ) - error = "Error! Method opencortex.build.%s() called with cell_bodies_overlap set to False but population_dictionary or cell_diameter_dict is None !" \ - % sys._getframe().f_code.co_name - opencortex.print_comment_v(error) raise Exception(error) else: - cellPositions = [] for i in range(0, size): - if cell_bodies_overlap: - inst = neuroml.Instance(id=i) X = x_min + (x_size) * random.random() Y = y_min + (y_size) * random.random() Z = z_min + (z_size) * random.random() - inst.location = neuroml.Location(x="%.5f"%X, y="%.5f"%Y, z="%.5f"%Z) - #inst.location = neuroml.Location(x=str(X), y=str(Y), z=str(Z)) + inst.location = neuroml.Location(x="%.5f" % X, y="%.5f" % Y, z="%.5f" % Z) + # inst.location = neuroml.Location(x=str(X), y=str(Y), z=str(Z)) pop.instances.append(inst) if store_soma: cell_position = [] - cell_position.append(X) + cell_position.append(X) cell_position.append(Y) cell_position.append(Z) cellPositions.append(cell_position) else: - cell_position_found = False while not cell_position_found: - X = x_min + (x_size) * random.random() Y = y_min + (y_size) * random.random() Z = z_min + (z_size) * random.random() @@ -2323,69 +2317,80 @@ def _add_population_in_rectangular_region(net, count_overlaps = 0 for cell_index in range(0, len(cellPositions)): - cell_loc = cellPositions[cell_index] - if distance(try_cell_position, cell_loc) < (cell_diameter_dict[cell_id] + cell_diameter_dict[cell_id]) / 2: - + if ( + distance(try_cell_position, cell_loc) + < (cell_diameter_dict[cell_id] + cell_diameter_dict[cell_id]) + / 2 + ): count_overlaps += 1 for pop_id in population_dictionary.keys(): - if population_dictionary[pop_id] != {}: + added_cell_positions = population_dictionary[pop_id][ + "Positions" + ] - added_cell_positions = population_dictionary[pop_id]['Positions'] - - cell_component = population_dictionary[pop_id]['PopObj'].component + cell_component = population_dictionary[pop_id][ + "PopObj" + ].component for cell_index in range(0, len(added_cell_positions)): - cell_loc = added_cell_positions[cell_index] - if distance(try_cell_position, cell_loc) < (cell_diameter_dict[cell_component] + cell_diameter_dict[cell_component]) / 2: - + if ( + distance(try_cell_position, cell_loc) + < ( + cell_diameter_dict[cell_component] + + cell_diameter_dict[cell_component] + ) + / 2 + ): count_overlaps += 1 if count_overlaps == 0: - inst = neuroml.Instance(id=i) - inst.location = neuroml.Location(x="%.5f"%X, y="%.5f"%Y, z="%.5f"%Z) + inst.location = neuroml.Location( + x="%.5f" % X, y="%.5f" % Y, z="%.5f" % Z + ) pop.instances.append(inst) - #inst.location = neuroml.Location(x=str(X), y=str(Y), z=str(Z)) + # inst.location = neuroml.Location(x=str(X), y=str(Y), z=str(Z)) cellPositions.append(try_cell_position) - cell_position_found = True + cell_position_found = True if store_soma: - return pop, cellPositions else: - return pop + ############################################################################################## -def add_population_in_cylindrical_region(net, - pop_id, - cell_id, - size, - cyl_radius, - lower_bound_dim3, - upper_bound_dim3, - base_dim1='x', - base_dim2='z', - cell_bodies_overlap=True, - store_soma=False, - population_dictionary=None, - cell_diameter_dict=None, - num_of_polygon_sides=None, - positions_of_vertices=None, - constants_of_sides=None, - color=None): - - '''Method which create a cell population in the NeuroML2 network and distributes these cells in the cylindrical region. Input arguments are as follows: + +def add_population_in_cylindrical_region( + net, + pop_id, + cell_id, + size, + cyl_radius, + lower_bound_dim3, + upper_bound_dim3, + base_dim1="x", + base_dim2="z", + cell_bodies_overlap=True, + store_soma=False, + population_dictionary=None, + cell_diameter_dict=None, + num_of_polygon_sides=None, + positions_of_vertices=None, + constants_of_sides=None, + color=None, +): + """Method which create a cell population in the NeuroML2 network and distributes these cells in the cylindrical region. Input arguments are as follows: net - reference to the libNeuroML network object; @@ -2397,13 +2402,13 @@ def add_population_in_cylindrical_region(net, cyl_radius - radius of a cylindrical column in which cells will be distributed; - lower_bound_dim3 - lower bound of the cortical column height; + lower_bound_dim3 - lower bound of the cortical column height; upper_bound_dim3 - upper bound of the cortical column height; base_dim1 - specifies which of the 'x', 'y' and 'z' axis corresponds to the first dimension of the transverse plane of the cortical column; - base_dim2 - specifies which of the 'x', 'y' and 'z' axis corresponds to the second dimension of the transverse plane of the cortical column; + base_dim2 - specifies which of the 'x', 'y' and 'z' axis corresponds to the second dimension of the transverse plane of the cortical column; cell_bodies_overlap - boolean value which defines whether cell somata can overlap; default is set to True; @@ -2419,72 +2424,81 @@ def add_population_in_cylindrical_region(net, is None, thus cylindrical but not polygonal shape is built. positions_of_vertices - optional argument which specifies the list of coordinates [dim1, dim2] of vertices of a regular polygon; must be specified if num_of_polygon_sides is not - None; automatic generation of this list is wrapped inside the utils method add_populations_in_cylindrical_layers(); + None; automatic generation of this list is wrapped inside the utils method add_populations_in_cylindrical_layers(); - constants_of_sides - optional argument which specifies the list of y=ax +b coefficients [a, b] which define the lines between vertices of a regular polygon; - if y= b for all values then list element should specify as [None, b]; if x= b for all values of y then list element should specify as [b, None]; - Note that constants_of_sides must be specified if num_of_polygon_sides is not None; - automatic generation of this list is wrapped inside the utils method add_populations_in_cylindrical_layers(); + constants_of_sides - optional argument which specifies the list of y=ax +b coefficients [a, b] which define the lines between vertices of a regular polygon; + if y= b for all values then list element should specify as [None, b]; if x= b for all values of y then list element should specify as [b, None]; + Note that constants_of_sides must be specified if num_of_polygon_sides is not None; + automatic generation of this list is wrapped inside the utils method add_populations_in_cylindrical_layers(); color - optional color, default is None. - ''' + """ - pop = neuroml.Population(id=pop_id, component=cell_id, type="populationList", size=size) + pop = neuroml.Population( + id=pop_id, component=cell_id, type="populationList", size=size + ) # TODO - #from neuroml.hdf5.NetworkContainer import PopulationContainer - #pop = PopulationContainer(id=pop_id, component=cell_id, type="populationList", size=size) + # from neuroml.hdf5.NetworkContainer import PopulationContainer + # pop = PopulationContainer(id=pop_id, component=cell_id, type="populationList", size=size) if color is not None: pop.properties.append(neuroml.Property("color", color)) if size > 0: - net.populations.append(pop) if store_soma: - cellPositions = [] - if (num_of_polygon_sides != None) and (positions_of_vertices == None or constants_of_sides == None): - - opencortex.print_comment_v("Error! Method opencortex.build.%s() called with num_of_polygon_sides set to %d but positions_of_vertices or constants_of_sides " - "is None !. Execution will terminate." % num_of_polygon_sides, sys._getframe().f_code.co_name) + if (num_of_polygon_sides != None) and ( + positions_of_vertices == None or constants_of_sides == None + ): + opencortex.print_comment_v( + "Error! Method opencortex.build.%s() called with num_of_polygon_sides set to %d but positions_of_vertices or constants_of_sides " + "is None !. Execution will terminate." % num_of_polygon_sides, + sys._getframe().f_code.co_name, + ) quit() - if (not cell_bodies_overlap) and (population_dictionary == None or cell_diameter_dict == None): - - opencortex.print_comment_v("Error! Method opencortex.build.%s() called with cell_bodies_overlap set to False but population_dictionary or cell_diameter_dict is None !" - "Execution will terminate." % sys._getframe().f_code.co_name) + if (not cell_bodies_overlap) and ( + population_dictionary == None or cell_diameter_dict == None + ): + opencortex.print_comment_v( + "Error! Method opencortex.build.%s() called with cell_bodies_overlap set to False but population_dictionary or cell_diameter_dict is None !" + "Execution will terminate." % sys._getframe().f_code.co_name + ) quit() else: - cellPositions = [] - all_dims = ['x', 'y', 'z'] + all_dims = ["x", "y", "z"] for dim in all_dims: - if dim != base_dim1 or dim != base_dim2: - all_dims.remove(dim) - map_xyz = {base_dim1:'dim1', base_dim2:'dim2', all_dims[0]:'dim3'} + map_xyz = {base_dim1: "dim1", base_dim2: "dim2", all_dims[0]: "dim3"} for i in range(0, size): - if cell_bodies_overlap: + dim_dict = find_constrained_cell_position( + num_of_polygon_sides, + cyl_radius, + lower_bound_dim3, + upper_bound_dim3, + positions_of_vertices, + constants_of_sides, + ) - dim_dict = find_constrained_cell_position(num_of_polygon_sides, cyl_radius, lower_bound_dim3, upper_bound_dim3, positions_of_vertices, constants_of_sides) - - X = dim_dict[map_xyz['x']] + X = dim_dict[map_xyz["x"]] - Y = dim_dict[map_xyz['y']] + Y = dim_dict[map_xyz["y"]] - Z = dim_dict[map_xyz['z']] + Z = dim_dict[map_xyz["z"]] inst = neuroml.Instance(id=i) @@ -2492,89 +2506,107 @@ def add_population_in_cylindrical_region(net, pop.instances.append(inst) if store_soma: - cell_position = [] - cell_position.append(X) + cell_position.append(X) cell_position.append(Y) cell_position.append(Z) cellPositions.append(cell_position) else: - cell_position_found = False while not cell_position_found: + dim_dict = find_constrained_cell_position( + num_of_polygon_sides, + cyl_radius, + lower_bound_dim3, + upper_bound_dim3, + positions_of_vertices, + constants_of_sides, + ) - dim_dict = find_constrained_cell_position(num_of_polygon_sides, cyl_radius, lower_bound_dim3, upper_bound_dim3, positions_of_vertices, constants_of_sides) + X = dim_dict[map_xyz["x"]] - X = dim_dict[map_xyz['x']] + Y = dim_dict[map_xyz["y"]] - Y = dim_dict[map_xyz['y']] - - Z = dim_dict[map_xyz['z']] + Z = dim_dict[map_xyz["z"]] try_cell_position = [X, Y, Z] count_overlaps = 0 for cell_index in range(0, len(cellPositions)): - cell_loc = cellPositions[cell_index] - if distance(try_cell_position, cell_loc) < (cell_diameter_dict[cell_id] + cell_diameter_dict[cell_id]) / 2: - + if ( + distance(try_cell_position, cell_loc) + < (cell_diameter_dict[cell_id] + cell_diameter_dict[cell_id]) + / 2 + ): count_overlaps += 1 for pop_id in population_dictionary.keys(): - if population_dictionary[pop_id] != {}: + added_cell_positions = population_dictionary[pop_id][ + "Positions" + ] - added_cell_positions = population_dictionary[pop_id]['Positions'] - - cell_component = population_dictionary[pop_id]['PopObj'].component + cell_component = population_dictionary[pop_id][ + "PopObj" + ].component for cell_index in range(0, len(added_cell_positions)): - cell_loc = added_cell_positions[cell_index] - if distance(try_cell_position, cell_loc) < (cell_diameter_dict[cell_component] + cell_diameter_dict[cell_component]) / 2: - + if ( + distance(try_cell_position, cell_loc) + < ( + cell_diameter_dict[cell_component] + + cell_diameter_dict[cell_component] + ) + / 2 + ): count_overlaps += 1 if count_overlaps == 0: - inst = neuroml.Instance(id=i) inst.location = neuroml.Location(x=str(X), y=str(Y), z=str(Z)) pop.instances.append(inst) cellPositions.append(try_cell_position) - cell_position_found = True + cell_position_found = True if store_soma: - return pop, cellPositions else: - return pop ############################################################################################## -def find_constrained_cell_position(num_of_polygon_sides, cyl_radius, lower_bound_dim3, upper_bound_dim3, positions_of_vertices, constants_of_sides): - ''' - Method to find a constrained position of the cell; used inside the method add_population_in_cylindrical_region(). - ''' - if num_of_polygon_sides == None: +def find_constrained_cell_position( + num_of_polygon_sides, + cyl_radius, + lower_bound_dim3, + upper_bound_dim3, + positions_of_vertices, + constants_of_sides, +): + """ + Method to find a constrained position of the cell; used inside the method add_population_in_cylindrical_region(). + """ + if num_of_polygon_sides == None: found_cell_inside_cylinder = False - dim3_val = lower_bound_dim3 + (upper_bound_dim3-lower_bound_dim3) * random.random() + dim3_val = ( + lower_bound_dim3 + (upper_bound_dim3 - lower_bound_dim3) * random.random() + ) while not found_cell_inside_cylinder: - dim_dict = {} dim1_min = -cyl_radius @@ -2588,22 +2620,21 @@ def find_constrained_cell_position(num_of_polygon_sides, cyl_radius, lower_bound test_point_inside_cylinder = [dim1_val, dim2_val] if distance(test_point_inside_cylinder, [0, 0]) <= cyl_radius: + dim_dict = {"dim1": dim1_val, "dim2": dim2_val, "dim3": dim3_val} - dim_dict = {'dim1':dim1_val, 'dim2':dim2_val, 'dim3':dim3_val} - - found_cell_inside_cylinder = True + found_cell_inside_cylinder = True else: - found_constrained_cell_loc = False while not found_constrained_cell_loc: - found_cell_inside_cylinder = False - dim3_val = lower_bound_dim3 + (upper_bound_dim3-lower_bound_dim3) * random.random() + dim3_val = ( + lower_bound_dim3 + + (upper_bound_dim3 - lower_bound_dim3) * random.random() + ) while not found_cell_inside_cylinder: - dim1_min = -cyl_radius dim2_min = -cyl_radius @@ -2615,7 +2646,6 @@ def find_constrained_cell_position(num_of_polygon_sides, cyl_radius, lower_bound test_point_inside_cylinder = [dim1_val, dim2_val] if distance(test_point_inside_cylinder, [0, 0]) <= cyl_radius: - test_point = test_point_inside_cylinder found_cell_inside_cylinder = True @@ -2623,46 +2653,71 @@ def find_constrained_cell_position(num_of_polygon_sides, cyl_radius, lower_bound count_intersections = 0 for side_index in range(0, len(constants_of_sides)): - - if abs(positions_of_vertices[side_index][1] - positions_of_vertices[side_index-1][1]) > 0.0000001: - - if test_point[1] < positions_of_vertices[side_index][1] and test_point[1] > positions_of_vertices[side_index-1][1]: - - opencortex.print_comment_v("Checking a point inside a regular polygon") - - if constants_of_sides[side_index][0] != None and constants_of_sides[side_index][1] == None: - + if ( + abs( + positions_of_vertices[side_index][1] + - positions_of_vertices[side_index - 1][1] + ) + > 0.0000001 + ): + if ( + test_point[1] < positions_of_vertices[side_index][1] + and test_point[1] > positions_of_vertices[side_index - 1][1] + ): + opencortex.print_comment_v( + "Checking a point inside a regular polygon" + ) + + if ( + constants_of_sides[side_index][0] != None + and constants_of_sides[side_index][1] == None + ): if dim1_val <= constants_of_sides[side_index][0]: - count_intersections += 1 - if constants_of_sides[side_index][0] != None and constants_of_sides[side_index][1] != None: - - if dim1_val <= (dim2_val - constants_of_sides[side_index][1]) / constants_of_sides[side_index][0]: - + if ( + constants_of_sides[side_index][0] != None + and constants_of_sides[side_index][1] != None + ): + if ( + dim1_val + <= (dim2_val - constants_of_sides[side_index][1]) + / constants_of_sides[side_index][0] + ): count_intersections += 1 - if test_point[1] < positions_of_vertices[side_index-1][1] and test_point[1] > positions_of_vertices[side_index][1]: - - opencortex.print_comment_v("Checking a point inside a regular polygon") - - if constants_of_sides[side_index][0] != None and constants_of_sides[side_index][1] == None: - + if ( + test_point[1] < positions_of_vertices[side_index - 1][1] + and test_point[1] > positions_of_vertices[side_index][1] + ): + opencortex.print_comment_v( + "Checking a point inside a regular polygon" + ) + + if ( + constants_of_sides[side_index][0] != None + and constants_of_sides[side_index][1] == None + ): if dim1_val <= constants_of_sides[side_index][0]: - count_intersections += 1 - if constants_of_sides[side_index][0] != None and constants_of_sides[side_index][1] != None: - - if dim1_val <= (dim2_val - constants_of_sides[side_index][1]) / constants_of_sides[side_index][0]: - + if ( + constants_of_sides[side_index][0] != None + and constants_of_sides[side_index][1] != None + ): + if ( + dim1_val + <= (dim2_val - constants_of_sides[side_index][1]) + / constants_of_sides[side_index][0] + ): count_intersections += 1 - if count_intersections == 1: - - dim_dict = {'dim1':dim1_val, 'dim2':dim2_val, 'dim3':dim3_val} + if count_intersections == 1: + dim_dict = {"dim1": dim1_val, "dim2": dim2_val, "dim3": dim3_val} - opencortex.print_comment_v("Selected a cell locus inside regular polygon.") + opencortex.print_comment_v( + "Selected a cell locus inside regular polygon." + ) found_constrained_cell_loc = True @@ -2671,26 +2726,24 @@ def find_constrained_cell_position(num_of_polygon_sides, cyl_radius, lower_bound ############################################################################################## -def distance(p, q): +def distance(p, q): return math.sqrt(sum([(a - b) ** 2 for a, b in zip(p, q)])) ############################################################################################## -def get_soma_diameter(cell_name, cell_type=None, dir_to_cell=None): - '''Method to obtain a diameter of a cell soma. ''' +def get_soma_diameter(cell_name, cell_type=None, dir_to_cell=None): + """Method to obtain a diameter of a cell soma.""" loaded_cell_array = {} if dir_to_cell == None: - - cell_nml_file = '%s.cell.nml' % cell_name + cell_nml_file = "%s.cell.nml" % cell_name else: - - cell_nml_file = os.path.join(dir_to_cell, '%s.cell.nml' % cell_name) + cell_nml_file = os.path.join(dir_to_cell, "%s.cell.nml" % cell_name) document_cell = neuroml.loaders.NeuroMLLoader.load(cell_nml_file) @@ -2703,73 +2756,74 @@ def get_soma_diameter(cell_name, cell_type=None, dir_to_cell=None): cell_diameter = 0 for segment in loaded_cell_array[cell_name].morphology.segments: - if segment.id == 0: - proximal_diameter = segment.distal.diameter distal_diameter = segment.proximal.diameter if proximal_diameter > distal_diameter: - cell_diameter = proximal_diameter else: cell_diameter = distal_diameter - break + break return cell_diameter - ############################################################################################## -def add_advanced_inputs_to_population(net, - id, - population, - input_id_list, - seg_length_dict, - subset_dict, - universal_target_segment, - universal_fraction_along, - all_cells=False, - only_cells=None, - weight_dict=None): - - ''' Do not use. Subject to change!!! - + +def add_advanced_inputs_to_population( + net, + id, + population, + input_id_list, + seg_length_dict, + subset_dict, + universal_target_segment, + universal_fraction_along, + all_cells=False, + only_cells=None, + weight_dict=None, +): + """Do not use. Subject to change!!! + This method distributes the poisson input synapses on the specific segment groups of target cells. Input arguments to this method: net- libNeuroML network object; id - unique string that tags the input group created by the method; - + population - libNeuroML population object of a target population; - input_id_list - this is a list that stores lists of poisson synapse ids or pulse generator ids; + input_id_list - this is a list that stores lists of poisson synapse ids or pulse generator ids; if len(input_id_list)== (num of target cells) then each target cell, specified by only_cells or all_cells, has a unique list input components; if len(input_id_list != num, then add_advanced_inputs_to_population assumes that all cells share the same list of input components and thus uses input_id_list[0]. Note that all of the input components (e.g. differing in delays) per given list of input components are mapped on the same membrane point on the target segment of a given cell. - seg_length_dict - a dictionary whose keys are the ids of target segment groups and the values are the segment length dictionaries in the format returned by make_target_dict(); + seg_length_dict - a dictionary whose keys are the ids of target segment groups and the values are the segment length dictionaries in the format returned by make_target_dict(); subset_dict - a dictionary whose keys are the ids of target segment groups and the corresponding dictionary values define the desired number of synaptic connections per target segment group per each postsynaptic cell; universal_target_segment - this should be set to None if subset_dict and seg_length_dict are used; alternatively, universal_target_segment specifies a single target segment on all of the target cells for all input components; then seg_length_dict and subset_dict must be set to None. - universal_fraction_along - this should be set to None if subset_dict and seg_length_dict are used; alternatively, universal_target_fraction specifies a single value of + universal_fraction_along - this should be set to None if subset_dict and seg_length_dict are used; alternatively, universal_target_fraction specifies a single value of fraction along on all of the target segments for all target cells and all input components; then seg_length_dict and subset_dict must bet set to None; all_cells - default value is set to False; if all_cells==True then all cells in a given population will receive the inputs; - only_cells - optional variable which stores the list of ids of specific target cells; cannot be set together with all_cells. - + only_cells - optional variable which stores the list of ids of specific target cells; cannot be set together with all_cells. + weight_dict - id of cell vs weight for each connection - ''' + """ if all_cells and only_cells is not None: - opencortex.print_comment_v("Error! Method opencortex.build.%s() called with both arguments all_cells and only_cells set!" % sys._getframe().f_code.co_name) + opencortex.print_comment_v( + "Error! Method opencortex.build.%s() called with both arguments all_cells and only_cells set!" + % sys._getframe().f_code.co_name + ) exit(-1) cell_ids = [] @@ -2786,17 +2840,16 @@ def add_advanced_inputs_to_population(net, input_counters_final = [] for input_cell in range(0, len(input_id_list)): - input_list_array = [] input_counters = [] for input_index in range(0, len(input_id_list[input_cell])): - - input_list = neuroml.InputList(id=id + "_%d_%d" % (input_cell, input_index), - component=input_id_list[input_cell][input_index], - populations=population.id) - + input_list = neuroml.InputList( + id=id + "_%d_%d" % (input_cell, input_index), + component=input_id_list[input_cell][input_index], + populations=population.id, + ) input_list_array.append(input_list) @@ -2809,119 +2862,155 @@ def add_advanced_inputs_to_population(net, cell_counter = 0 for cell_id in cell_ids: - if len(input_id_list) == len(cell_ids): - cell_index = cell_counter else: - cell_index = 0 - - weight = 1 if (not weight_dict or cell_id not in weight_dict) else _evaluate_expression(weight_dict[cell_id]) - - if subset_dict != None and seg_length_dict == None and universal_target_segment == None and universal_fraction_along == None: + weight = ( + 1 + if (not weight_dict or cell_id not in weight_dict) + else _evaluate_expression(weight_dict[cell_id]) + ) + + if ( + subset_dict != None + and seg_length_dict == None + and universal_target_segment == None + and universal_fraction_along == None + ): if None in subset_dict.keys() and len(subset_dict.keys()) == 1: - for target_point in range(0, subset_dict[None]): - - for input_index in range(0, len(input_list_array_final[cell_index])): - + for input_index in range( + 0, len(input_list_array_final[cell_index]) + ): if weight == 1: - input = neuroml.Input(id=input_counters_final[cell_index][input_index], - target="../%s/%i/%s" % (population.id, cell_id, population.component), - destination="synapses") - - input_list_array_final[cell_index][input_index].input.append(input) + input = neuroml.Input( + id=input_counters_final[cell_index][input_index], + target="../%s/%i/%s" + % (population.id, cell_id, population.component), + destination="synapses", + ) + + input_list_array_final[cell_index][ + input_index + ].input.append(input) else: - input = neuroml.InputW(id=input_counters_final[cell_index][input_index], - target="../%s/%i/%s" % (population.id, cell_id, population.component), - destination="synapses", - weight=weight) - - input_list_array_final[cell_index][input_index].input_ws.append(input) + input = neuroml.InputW( + id=input_counters_final[cell_index][input_index], + target="../%s/%i/%s" + % (population.id, cell_id, population.component), + destination="synapses", + weight=weight, + ) + + input_list_array_final[cell_index][ + input_index + ].input_ws.append(input) input_counters_final[cell_index][input_index] += 1 - elif seg_length_dict != None and subset_dict != None and universal_target_segment == None and universal_fraction_along == None: - - target_seg_array, target_fractions = get_target_segments(seg_length_dict, subset_dict) + elif ( + seg_length_dict != None + and subset_dict != None + and universal_target_segment == None + and universal_fraction_along == None + ): + target_seg_array, target_fractions = get_target_segments( + seg_length_dict, subset_dict + ) for target_point in range(0, len(target_seg_array)): - for input_index in range(0, len(input_list_array_final[cell_index])): - if weight == 1: - input = neuroml.Input(id=input_counters_final[cell_index][input_index], - target="../%s/%i/%s" % (population.id, cell_id, population.component), - destination="synapses", segment_id="%d" % target_seg_array[target_point], fraction_along="%f" % target_fractions[target_point]) - - input_list_array_final[cell_index][input_index].input.append(input) + input = neuroml.Input( + id=input_counters_final[cell_index][input_index], + target="../%s/%i/%s" + % (population.id, cell_id, population.component), + destination="synapses", + segment_id="%d" % target_seg_array[target_point], + fraction_along="%f" % target_fractions[target_point], + ) + + input_list_array_final[cell_index][input_index].input.append( + input + ) else: - input = neuroml.InputW(id=input_counters_final[cell_index][input_index], - target="../%s/%i/%s" % (population.id, cell_id, population.component), - destination="synapses", - segment_id="%d" % target_seg_array[target_point], - fraction_along="%f" % target_fractions[target_point], - weight=weight) - - input_list_array_final[cell_index][input_index].input_ws.append(input) + input = neuroml.InputW( + id=input_counters_final[cell_index][input_index], + target="../%s/%i/%s" + % (population.id, cell_id, population.component), + destination="synapses", + segment_id="%d" % target_seg_array[target_point], + fraction_along="%f" % target_fractions[target_point], + weight=weight, + ) + + input_list_array_final[cell_index][input_index].input_ws.append( + input + ) input_counters_final[cell_index][input_index] += 1 else: - for input_index in range(0, len(input_list_array_final[cell_index])): - if weight == 1: - input = neuroml.Input(id=input_counters_final[cell_index][input_index], - target="../%s/%i/%s" % (population.id, cell_id, population.component), - destination="synapses", segment_id="%d" % universal_target_segment, fraction_along="%f" % universal_fraction_along) - + input = neuroml.Input( + id=input_counters_final[cell_index][input_index], + target="../%s/%i/%s" + % (population.id, cell_id, population.component), + destination="synapses", + segment_id="%d" % universal_target_segment, + fraction_along="%f" % universal_fraction_along, + ) + input_list_array_final[cell_index][input_index].input.append(input) - - else: - input = neuroml.InputW(id=input_counters_final[cell_index][input_index], - target="../%s/%i/%s" % (population.id, cell_id, population.component), - destination="synapses", - segment_id="%d" % universal_target_segment, - fraction_along="%f" % universal_fraction_along, - weight=weight) - input_list_array_final[cell_index][input_index].input_ws.append(input) + else: + input = neuroml.InputW( + id=input_counters_final[cell_index][input_index], + target="../%s/%i/%s" + % (population.id, cell_id, population.component), + destination="synapses", + segment_id="%d" % universal_target_segment, + fraction_along="%f" % universal_fraction_along, + weight=weight, + ) + + input_list_array_final[cell_index][input_index].input_ws.append( + input + ) input_counters_final[cell_index][input_index] += 1 cell_counter += 1 for input_cell in range(0, len(input_list_array_final)): - for input_index in range(0, len(input_list_array_final[input_cell])): - net.input_lists.append(input_list_array_final[input_cell][input_index]) - return input_list_array_final ############################################################################################## -def add_projection_based_inputs(net, - id, - population, - input_id_list, - weight_list, - synapse_id, - seg_length_dict, - subset_dict, - universal_target_segment, - universal_fraction_along, - all_cells=False, - only_cells=None): - - ''' This method builds input projections between the input components and target population. Input arguments to this method: +def add_projection_based_inputs( + net, + id, + population, + input_id_list, + weight_list, + synapse_id, + seg_length_dict, + subset_dict, + universal_target_segment, + universal_fraction_along, + all_cells=False, + only_cells=None, +): + """This method builds input projections between the input components and target population. Input arguments to this method: net- libNeuroML network object; @@ -2939,22 +3028,25 @@ def add_projection_based_inputs(net, synapse_id - unique synapse id for all input components specified in input_id_list; - seg_length_dict - a dictionary whose keys are the ids of target segment groups and the values are the segment length dictionaries in the format returned by make_target_dict(); + seg_length_dict - a dictionary whose keys are the ids of target segment groups and the values are the segment length dictionaries in the format returned by make_target_dict(); subset_dict - a dictionary whose keys are the ids of target segment groups and the corresponding dictionary values define the desired number of synaptic connections per target segment group per each postsynaptic cell; universal_target_segment - this should be set to None if subset_dict and seg_length_dict are used; alternatively, universal_target_segment specifies a single target segment on all of the target cells for all input components; then seg_length_dict and subset_dict must be set to None. - universal_fraction_along - this should be set to None if subset_dict and seg_length_dict are used; alternatively, universal_target_fraction specifies a single value of + universal_fraction_along - this should be set to None if subset_dict and seg_length_dict are used; alternatively, universal_target_fraction specifies a single value of fraction along on all of the target segments for all target cells and all input components; then seg_length_dict and subset_dict must bet set to None; all_cells - default value is set to False; if all_cells==True then all cells in a given population will receive the inputs; - only_cells - optional variable which stores the list of ids of specific target cells; cannot be set together with all_cells. ''' + only_cells - optional variable which stores the list of ids of specific target cells; cannot be set together with all_cells.""" if all_cells and only_cells is not None: - opencortex.print_comment_v("Error! Method opencortex.build.%s() called with both arguments all_cells and only_cells set!" % sys._getframe().f_code.co_name) + opencortex.print_comment_v( + "Error! Method opencortex.build.%s() called with both arguments all_cells and only_cells set!" + % sys._getframe().f_code.co_name + ) exit(-1) cell_ids = [] @@ -2973,7 +3065,6 @@ def add_projection_based_inputs(net, spike_source_counters_final = [] for input_cell in range(0, len(input_id_list)): - spike_source_pops = [] spike_source_projections = [] @@ -2981,22 +3072,25 @@ def add_projection_based_inputs(net, spike_source_counters = [] for input_index in range(0, len(input_id_list[input_cell])): - - spike_source_pop = neuroml.Population(id="Pop_" + id + "_%d_%d" % (input_cell, input_index), - component=input_id_list[input_cell][input_index], - size=population.size) + spike_source_pop = neuroml.Population( + id="Pop_" + id + "_%d_%d" % (input_cell, input_index), + component=input_id_list[input_cell][input_index], + size=population.size, + ) # TODO ##from neuroml.hdf5.NetworkContainer import PopulationContainer - ##spike_source_pop = PopulationContainer(id="Pop_" + id + "_%d_%d" % (input_cell, input_index), - ## component=input_id_list[input_cell][input_index], + ##spike_source_pop = PopulationContainer(id="Pop_" + id + "_%d_%d" % (input_cell, input_index), + ## component=input_id_list[input_cell][input_index], ## size=population.size) net.populations.append(spike_source_pop) - proj = neuroml.Projection(id="Proj_%s_%s" % (spike_source_pop.id, population.id), - presynaptic_population=spike_source_pop.id, - postsynaptic_population=population.id, - synapse=synapse_id) + proj = neuroml.Projection( + id="Proj_%s_%s" % (spike_source_pop.id, population.id), + presynaptic_population=spike_source_pop.id, + postsynaptic_population=population.id, + synapse=synapse_id, + ) spike_source_projections.append(proj) @@ -3013,80 +3107,104 @@ def add_projection_based_inputs(net, cell_counter = 0 for cell_id in cell_ids: - if len(input_id_list) == len(cell_ids): - cell_index = cell_counter else: - cell_index = 0 - if subset_dict != None and seg_length_dict == None and universal_target_segment == None and universal_fraction_along == None: - + if ( + subset_dict != None + and seg_length_dict == None + and universal_target_segment == None + and universal_fraction_along == None + ): if None in subset_dict.keys() and len(subset_dict.keys()) == 1: - for target_point in range(0, subset_dict[None]): - - for input_index in range(0, len(spike_source_pops_final[cell_index])): - - conn = neuroml.ConnectionWD(id=spike_source_counters_final[cell_index][input_index], \ - pre_cell_id="../%s[%s]" % (spike_source_pops_final[cell_index][input_index].id, - spike_source_counters_final[cell_index][input_index]), \ - post_cell_id="../%s/%i/%s" % (population.id, cell_id, population.component), \ - weight=weight_list[cell_index][input_index], - delay="0 ms") - - spike_source_projections_final[cell_index][input_index].connection_wds.append(conn) + for input_index in range( + 0, len(spike_source_pops_final[cell_index]) + ): + conn = neuroml.ConnectionWD( + id=spike_source_counters_final[cell_index][input_index], + pre_cell_id="../%s[%s]" + % ( + spike_source_pops_final[cell_index][input_index].id, + spike_source_counters_final[cell_index][input_index], + ), + post_cell_id="../%s/%i/%s" + % (population.id, cell_id, population.component), + weight=weight_list[cell_index][input_index], + delay="0 ms", + ) + + spike_source_projections_final[cell_index][ + input_index + ].connection_wds.append(conn) spike_source_counters_final[cell_index][input_index] += 1 - elif seg_length_dict != None and subset_dict != None and universal_target_segment == None and universal_fraction_along == None: - - target_seg_array, target_fractions = get_target_segments(seg_length_dict, subset_dict) + elif ( + seg_length_dict != None + and subset_dict != None + and universal_target_segment == None + and universal_fraction_along == None + ): + target_seg_array, target_fractions = get_target_segments( + seg_length_dict, subset_dict + ) for target_point in range(0, len(target_seg_array)): - for input_index in range(0, len(spike_source_pops_final[cell_index])): - - conn = neuroml.ConnectionWD(id=spike_source_counters_final[cell_index][input_index], \ - pre_cell_id="../%s[%s]" % (spike_source_pops_final[cell_index][input_index].id, - spike_source_counters_final[cell_index][input_index]), \ - post_cell_id="../%s/%i/%s" % (population.id, cell_id, population.component), \ - post_segment_id="%d" % target_seg_array[target_point], - post_fraction_along="%f" % target_fractions[target_point], - weight=weight_list[cell_index][input_index], - delay="0 ms") - - spike_source_projections_final[cell_index][input_index].connection_wds.append(conn) + conn = neuroml.ConnectionWD( + id=spike_source_counters_final[cell_index][input_index], + pre_cell_id="../%s[%s]" + % ( + spike_source_pops_final[cell_index][input_index].id, + spike_source_counters_final[cell_index][input_index], + ), + post_cell_id="../%s/%i/%s" + % (population.id, cell_id, population.component), + post_segment_id="%d" % target_seg_array[target_point], + post_fraction_along="%f" % target_fractions[target_point], + weight=weight_list[cell_index][input_index], + delay="0 ms", + ) + + spike_source_projections_final[cell_index][ + input_index + ].connection_wds.append(conn) spike_source_counters_final[cell_index][input_index] += 1 else: - for input_index in range(0, len(spike_source_pops_final[cell_index])): - - conn = neuroml.ConnectionWD(id=spike_source_counters_final[cell_index][input_index], \ - pre_cell_id="../%s[%s]" % (spike_source_pops_final[cell_index][input_index].id, - spike_source_counters_final[cell_index][input_index]), \ - post_cell_id="../%s/%i/%s" % (population.id, cell_id, population.component), \ - post_segment_id="%d" % universal_target_segment, - post_fraction_along="%f" % universal_fraction_along, - weight=weight_list[cell_index][input_index], - delay="0 ms") - - spike_source_projections_final[cell_index][input_index].connection_wds.append(conn) + conn = neuroml.ConnectionWD( + id=spike_source_counters_final[cell_index][input_index], + pre_cell_id="../%s[%s]" + % ( + spike_source_pops_final[cell_index][input_index].id, + spike_source_counters_final[cell_index][input_index], + ), + post_cell_id="../%s/%i/%s" + % (population.id, cell_id, population.component), + post_segment_id="%d" % universal_target_segment, + post_fraction_along="%f" % universal_fraction_along, + weight=weight_list[cell_index][input_index], + delay="0 ms", + ) + + spike_source_projections_final[cell_index][ + input_index + ].connection_wds.append(conn) spike_source_counters_final[cell_index][input_index] += 1 cell_counter += 1 for input_cell in range(0, len(spike_source_projections_final)): - for input_index in range(0, len(spike_source_projections_final[input_cell])): - - net.projections.append(spike_source_projections_final[input_cell][input_index]) - + net.projections.append( + spike_source_projections_final[input_cell][input_index] + ) return spike_source_pops_final - diff --git a/opencortex/core/__init__.py b/opencortex/core/__init__.py index 1ec07cd..6eb190c 100644 --- a/opencortex/core/__init__.py +++ b/opencortex/core/__init__.py @@ -1,10 +1,10 @@ ############################################################### -### +### ### Note: OpenCortex is under active development, the API is subject to change without notice!! -### +### ### Authors: Padraig Gleeson, Rokas Stanislovas ### -### This software has been funded by the Wellcome Trust, as well as a GSoC 2016 project +### This software has been funded by the Wellcome Trust, as well as a GSoC 2016 project ### on Cortical Network develoment ### ############################################################## @@ -32,41 +32,41 @@ def include_cell_prototype(nml_doc, cell_nml2_path): - """ Add a NeuroML2 file containing a cell definition """ - nml_doc.includes.append(neuroml.IncludeType(cell_nml2_path)) + nml_doc.includes.append(neuroml.IncludeType(cell_nml2_path)) ############################################################################################## def include_neuroml2_file(nml_doc, nml2_file_path): - """ Add a NeuroML2 file containing definitions of elements which can be used in the network """ - nml_doc.includes.append(neuroml.IncludeType(nml2_file_path)) - - + nml_doc.includes.append(neuroml.IncludeType(nml2_file_path)) + + ######################################################################################### + def include_neuroml2_cell(nml_doc, cell_nml2_path, cell_id, channels_also=True): - """ Add a cell with id `cell_id` which is in `cell_nml2_path` to the build document, along with all its channels (if channels_also==True) """ - return oc_build._include_neuroml2_cell(nml_doc, cell_nml2_path, cell_id, channels_also=channels_also) - - + return oc_build._include_neuroml2_cell( + nml_doc, cell_nml2_path, cell_id, channels_also=channels_also + ) + + ######################################################################################### + def include_neuroml2_cell_and_channels(nml_doc, cell_nml2_path, cell_id): - """ DEPRECATED TODO: remove, due to include_neuroml2_cell @@ -74,36 +74,37 @@ def include_neuroml2_cell_and_channels(nml_doc, cell_nml2_path, cell_id): along with all its channels """ - return oc_build._include_neuroml2_cell(nml_doc, cell_nml2_path, cell_id, channels_also=True) + return oc_build._include_neuroml2_cell( + nml_doc, cell_nml2_path, cell_id, channels_also=True + ) ######################################################################################### + def include_opencortex_cell(nml_doc, reference): - """ Include a cell from the standard set of NeuroML2 cells included with OpenCortex. See https://github.com/OpenSourceBrain/OpenCortex/tree/master/NeuroML2/prototypes. """ - cell_id = reference.split('/')[1].split('.')[0] - return oc_build._add_cell_and_channels(nml_doc, reference, cell_id, use_prototypes=True) - + cell_id = reference.split("/")[1].split(".")[0] + return oc_build._add_cell_and_channels( + nml_doc, reference, cell_id, use_prototypes=True + ) ############################################################################################## + def add_exp_one_syn(nml_doc, id, gbase, erev, tau_decay): - """ - Adds an element to the document. See the definition of the + Adds an element to the document. See the definition of the behaviour of this here: https://www.neuroml.org/NeuroML2CoreTypes/Synapses.html#expOneSynapse - + Returns the class created. """ - syn0 = neuroml.ExpOneSynapse(id=id, gbase=gbase, - erev=erev, - tau_decay=tau_decay) + syn0 = neuroml.ExpOneSynapse(id=id, gbase=gbase, erev=erev, tau_decay=tau_decay) nml_doc.exp_one_synapses.append(syn0) @@ -112,18 +113,17 @@ def add_exp_one_syn(nml_doc, id, gbase, erev, tau_decay): ############################################################################################## + def add_exp_two_syn(nml_doc, id, gbase, erev, tau_rise, tau_decay): - """ - Adds an element to the document. See the definition of the + Adds an element to the document. See the definition of the behaviour of this here: https://www.neuroml.org/NeuroML2CoreTypes/Synapses.html#expTwoSynapse - + Returns the class created. """ - syn0 = neuroml.ExpTwoSynapse(id=id, gbase=gbase, - erev=erev, - tau_rise=tau_rise, - tau_decay=tau_decay) + syn0 = neuroml.ExpTwoSynapse( + id=id, gbase=gbase, erev=erev, tau_rise=tau_rise, tau_decay=tau_decay + ) nml_doc.exp_two_synapses.append(syn0) @@ -132,15 +132,15 @@ def add_exp_two_syn(nml_doc, id, gbase, erev, tau_rise, tau_decay): ############################################################################################## + def add_gap_junction_synapse(nml_doc, id, conductance): - """ - Adds a element to the document. See the definition of the + Adds a element to the document. See the definition of the behaviour of this here: https://www.neuroml.org/NeuroML2CoreTypes/Synapses.html#gapJunction - + Returns the class created. """ - + syn0 = neuroml.GapJunction(id=id, conductance=conductance) nml_doc.gap_junctions.append(syn0) @@ -150,12 +150,12 @@ def add_gap_junction_synapse(nml_doc, id, conductance): ############################################################################################## + def add_poisson_firing_synapse(nml_doc, id, average_rate, synapse_id): - """ - Adds a element to the document. See the definition of the + Adds a element to the document. See the definition of the behaviour of this here: https://www.neuroml.org/NeuroML2CoreTypes/Inputs.html#poissonFiringSynapse - + Returns the class created. """ @@ -164,86 +164,101 @@ def add_poisson_firing_synapse(nml_doc, id, average_rate, synapse_id): ######################################################################### -def add_transient_poisson_firing_synapse(nml_doc, id, average_rate, delay, duration, synapse_id): +def add_transient_poisson_firing_synapse( + nml_doc, id, average_rate, delay, duration, synapse_id +): """ - Adds a element to the document. See the definition of the + Adds a element to the document. See the definition of the behaviour of this here: https://www.neuroml.org/NeuroML2CoreTypes/Inputs.html#transientPoissonFiringSynapse - + Returns the class created. """ - - return oc_build._add_transient_poisson_firing_synapse(nml_doc, id, average_rate, delay, duration, synapse_id) + return oc_build._add_transient_poisson_firing_synapse( + nml_doc, id, average_rate, delay, duration, synapse_id + ) -################################################################################ -def add_pulse_generator(nml_doc, id, delay, duration, amplitude): +################################################################################ + +def add_pulse_generator(nml_doc, id, delay, duration, amplitude): """ - Adds a element to the document. See the definition of the + Adds a element to the document. See the definition of the behaviour of this here: https://www.neuroml.org/NeuroML2CoreTypes/Inputs.html#pulseGenerator - + Returns the class created. """ return oc_build._add_pulse_generator(nml_doc, id, delay, duration, amplitude) -################################################################################ +################################################################################ -def add_voltage_clamp_triple(nml_doc, id, delay, duration, - conditioning_voltage, - testing_voltage, - return_voltage, - simple_series_resistance, - active = "1"): +def add_voltage_clamp_triple( + nml_doc, + id, + delay, + duration, + conditioning_voltage, + testing_voltage, + return_voltage, + simple_series_resistance, + active="1", +): """ - Adds a element to the document. See the definition of the + Adds a element to the document. See the definition of the behaviour of this here: https://github.com/NeuroML/NeuroML2/blob/development/Schemas/NeuroML2/NeuroML_v2beta5.xsd - + Returns the class created. """ - return oc_build._add_voltage_clamp_triple(nml_doc, id, delay, duration, - conditioning_voltage, - testing_voltage, - return_voltage, - simple_series_resistance, - active) + return oc_build._add_voltage_clamp_triple( + nml_doc, + id, + delay, + duration, + conditioning_voltage, + testing_voltage, + return_voltage, + simple_series_resistance, + active, + ) ############################################################################################## -def add_spike_source_poisson(nml_doc, id, start, duration, rate): +def add_spike_source_poisson(nml_doc, id, start, duration, rate): """ - Adds a element to the document. See the definition of the + Adds a element to the document. See the definition of the behaviour of this here: https://www.neuroml.org/NeuroML2CoreTypes/PyNN.html#SpikeSourcePoisson - + Returns the class created. """ - - return oc_build._add_spike_source_poisson(nml_doc, id, start, duration, rate) + return oc_build._add_spike_source_poisson(nml_doc, id, start, duration, rate) ############################################################################################## + def add_single_cell_population(net, pop_id, cell_id, x=0, y=0, z=0, color=None): - """ - Add a population with id `pop_id` containing a single instance of cell `cell_id`. + Add a population with id `pop_id` containing a single instance of cell `cell_id`. Optionally specify (`x`,`y`,`z`) and the population `color`. """ - pop = neuroml.Population(id=pop_id, component=cell_id, type="populationList", size=1) + pop = neuroml.Population( + id=pop_id, component=cell_id, type="populationList", size=1 + ) # TODO... ##from neuroml.hdf5.NetworkContainer import PopulationContainer ##pop = PopulationContainer(id=pop_id, component=cell_id, type="populationList", size=1) - + if color is not None: pop.properties.append(neuroml.Property("color", color)) net.populations.append(pop) @@ -257,155 +272,166 @@ def add_single_cell_population(net, pop_id, cell_id, x=0, y=0, z=0, color=None): ############################################################################################## -def add_population_in_rectangular_region(net, - pop_id, - cell_id, - size, - x_min, - y_min, - z_min, - x_size, - y_size, - z_size, - cell_bodies_overlap=True, - store_soma=False, - population_dictionary=None, - cell_diameter_dict=None, - color=None): +def add_population_in_rectangular_region( + net, + pop_id, + cell_id, + size, + x_min, + y_min, + z_min, + x_size, + y_size, + z_size, + cell_bodies_overlap=True, + store_soma=False, + population_dictionary=None, + cell_diameter_dict=None, + color=None, +): """ Method which creates a cell population in the NeuroML2 network and distributes these cells in the rectangular region. Input arguments are: `net` reference to the network object previously created - `pop_id` + `pop_id` population id `cell_id` cell component id - `size` + `size` size of a population - `x_min` + `x_min` lower x bound of a rectangular region - `y_min` + `y_min` lower y bound of a rectangular region - `z_min` + `z_min` lower z bound of a rectangular region - `x_size` + `x_size` width of a rectangular region along x axis - `y_size` + `y_size` width of a rectangular region along y axis - `z_size` + `z_size` width of a rectangular region along z axis - `cell_bodies_overlap` + `cell_bodies_overlap` boolean value which defines whether cell somata can overlap; default is set to True - `store_soma` + `store_soma` boolean value which specifies whether soma positions have to be returned in the output array; default is set to False - `population_dictionary` + `population_dictionary` optional argument in the format returned by opencortex.utils.add_populations_in_rectangular_layers; default value is None but it must be specified when cell_bodies_overlap is set to False - `cell_diameter_dict` + `cell_diameter_dict` optional argument in the format {'cell_id1': soma diameter of type 'float', 'cell_id2': soma diameter of type 'float'}; default is None but it must be specified when cell_bodies_overlap is set to False - `color` + `color` optional color (which will be put through to annotation in generated NeuroML); RGB format, 3 floats 0->1, e.g. 1 0 0 for red; default is None """ - return oc_build._add_population_in_rectangular_region(net, - pop_id, - cell_id, - size, - x_min, - y_min, - z_min, - x_size, - y_size, - z_size, - cell_bodies_overlap, - store_soma, - population_dictionary, - cell_diameter_dict, - color) - - - - -############################################################################################## - -def add_probabilistic_projection(net, - prefix, - presynaptic_population, - postsynaptic_population, - synapse_id, - connection_probability, - delay=0, - weight=1): + return oc_build._add_population_in_rectangular_region( + net, + pop_id, + cell_id, + size, + x_min, + y_min, + z_min, + x_size, + y_size, + z_size, + cell_bodies_overlap, + store_soma, + population_dictionary, + cell_diameter_dict, + color, + ) + + +############################################################################################## + + +def add_probabilistic_projection( + net, + prefix, + presynaptic_population, + postsynaptic_population, + synapse_id, + connection_probability, + delay=0, + weight=1, +): """ Add a projection between `presynaptic_population` and `postsynaptic_population` with probability of connection between each pre & post pair of cells given by `connection_probability`. Attributes: - + `net` reference to the network object previously created - + `prefix` prefix to use in the id of the projection - + `presynaptic_population` presynaptic population e.g. added via add_population_in_rectangular_region() - + `postsynaptic_population` postsynaptic population e.g. added via add_population_in_rectangular_region() - + `synapse_id` id of synapse previously added, e.g. added with add_exp_two_syn() - + `connection_probability` For each pre syn cell i and post syn cell j, where i!=j, the chance they will be connected is given by this - + `delay` optional delay for each connection, default 0 ms - + `weight` optional weight for each connection, default 1 - + """ if presynaptic_population.size == 0 or postsynaptic_population.size == 0: return None - proj = neuroml.Projection(id="%s_%s_%s" % (prefix, presynaptic_population.id, postsynaptic_population.id), - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id, - synapse=synapse_id) - + proj = neuroml.Projection( + id="%s_%s_%s" % (prefix, presynaptic_population.id, postsynaptic_population.id), + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + synapse=synapse_id, + ) count = 0 for i in range(0, presynaptic_population.size): for j in range(0, postsynaptic_population.size): if i != j or presynaptic_population.id != postsynaptic_population.id: - if connection_probability >= 1 or random.random() < connection_probability: - oc_build._add_connection(proj, - count, - presynaptic_population, - i, - 0, - postsynaptic_population, - j, - 0, - delay=delay, - weight=weight) + if ( + connection_probability >= 1 + or random.random() < connection_probability + ): + oc_build._add_connection( + proj, + count, + presynaptic_population, + i, + 0, + postsynaptic_population, + j, + 0, + delay=delay, + weight=weight, + ) count += 1 net.projections.append(proj) @@ -415,277 +441,308 @@ def add_probabilistic_projection(net, ############################################################################################## -def add_targeted_projection(net, - prefix, - presynaptic_population, - postsynaptic_population, - targeting_mode, - synapse_list, - number_conns_per_cell, - pre_segment_group=None, - post_segment_group=None, - delays_dict=None, - weights_dict=None): - ''' - Adds (chemical, event based) projection from `presynaptic_population` to `postsynaptic_population`, + +def add_targeted_projection( + net, + prefix, + presynaptic_population, + postsynaptic_population, + targeting_mode, + synapse_list, + number_conns_per_cell, + pre_segment_group=None, + post_segment_group=None, + delays_dict=None, + weights_dict=None, +): + """ + Adds (chemical, event based) projection from `presynaptic_population` to `postsynaptic_population`, specifically limiting connections presynaptically to `pre_segment_group` and postsynaptically to `post_segment_group`. - + `net` reference to the network object previously created - + `prefix` prefix to use in the id of the projection - + `presynaptic_population` presynaptic population e.g. added via add_population_in_rectangular_region() - + `postsynaptic_population` postsynaptic population e.g. added via add_population_in_rectangular_region() - + `targeting_mode` a string that specifies the targeting mode: 'convergent' or 'divergent' `synapse_list` the list of synapse ids that correspond to the individual receptor components on the physical synapse, e.g. the first element is - the id of the AMPA synapse and the second element is the id of the NMDA synapse; these synapse components will be mapped onto + the id of the AMPA synapse and the second element is the id of the NMDA synapse; these synapse components will be mapped onto the same location of the target segment `number_conns_per_cell` - number of connections to make on each cell in the postsynaptic population (when targeting_mode='convergent') or + number of connections to make on each cell in the postsynaptic population (when targeting_mode='convergent') or from each cell in the presynaptic population (when targeting_mode='divergent') - + `pre_segment_group` - which segment_group to target connennections from on the presynaptic population, e.g. axon_group. This can be left out or set to + which segment_group to target connennections from on the presynaptic population, e.g. axon_group. This can be left out or set to None if the presynaptic component has no morphology - + `post_segment_group` - which segment_group to target connennections from on the postsynaptic population, e.g. dendrite_group. This can be left out or set to + which segment_group to target connennections from on the postsynaptic population, e.g. dendrite_group. This can be left out or set to None if the postsynaptic component has no morphology - `delays_dict` + `delays_dict` optional dictionary that specifies the delays (in ms) for individual synapse components, e.g. {'NMDA':5.0} or {'AMPA':3.0,'NMDA':5} `weights_dict` optional dictionary that specifies the weights for individual synapse components, e.g. {'NMDA':1} or {'NMDA':1,'AMPA':2} - ''' + """ if presynaptic_population.size == 0 or postsynaptic_population.size == 0: return None projections = [] - if presynaptic_population.component in oc_build.cell_ids_vs_nml_docs: - pre_cell = oc_build.cell_ids_vs_nml_docs[presynaptic_population.component].get_by_id(presynaptic_population.component) + pre_cell = oc_build.cell_ids_vs_nml_docs[ + presynaptic_population.component + ].get_by_id(presynaptic_population.component) else: pre_cell = "Undetermined" - + if postsynaptic_population.component in oc_build.cell_ids_vs_nml_docs: - post_cell = oc_build.cell_ids_vs_nml_docs[postsynaptic_population.component].get_by_id(postsynaptic_population.component) + post_cell = oc_build.cell_ids_vs_nml_docs[ + postsynaptic_population.component + ].get_by_id(postsynaptic_population.component) else: post_cell = "Undetermined" - if pre_segment_group: - pre_segs = oc_build.extract_seg_ids(pre_cell, - [pre_segment_group], - "segGroups") + pre_segs = oc_build.extract_seg_ids(pre_cell, [pre_segment_group], "segGroups") pre_seg_target_dict = oc_build.make_target_dict(pre_cell, pre_segs) - + else: pre_segs = None pre_seg_target_dict = None - + if post_segment_group: - post_segs = oc_build.extract_seg_ids(post_cell, - [post_segment_group], - "segGroups") + post_segs = oc_build.extract_seg_ids( + post_cell, [post_segment_group], "segGroups" + ) post_seg_target_dict = oc_build.make_target_dict(post_cell, post_segs) else: post_segs = None post_seg_target_dict = None - - #print pre_seg_target_dict, post_seg_target_dict + # print pre_seg_target_dict, post_seg_target_dict for synapse in synapse_list: + proj_id = ( + "%s_%s_%s" % (prefix, presynaptic_population.id, postsynaptic_population.id) + if len(synapse_list) == 1 + else "%s_%s_%s_%s" + % (prefix, presynaptic_population.id, postsynaptic_population.id, synapse) + ) + + opencortex.print_comment_v( + "Adding projection: %s: %s#%s, %s (%s) -> %s#%s, %s (%s)" + % ( + proj_id, + presynaptic_population.id, + presynaptic_population.size, + pre_cell, + pre_segs, + postsynaptic_population.id, + postsynaptic_population.size, + post_cell, + post_segs, + ) + ) + + proj = neuroml.Projection( + id=proj_id, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + synapse=synapse, + ) - proj_id = "%s_%s_%s" % (prefix, presynaptic_population.id, postsynaptic_population.id) if len(synapse_list) == 1 else \ - "%s_%s_%s_%s" % (prefix, presynaptic_population.id, postsynaptic_population.id, synapse) + projections.append(proj) - opencortex.print_comment_v("Adding projection: %s: %s#%s, %s (%s) -> %s#%s, %s (%s)" % (proj_id, - presynaptic_population.id, presynaptic_population.size, - pre_cell, pre_segs, - postsynaptic_population.id, postsynaptic_population.size, - post_cell, post_segs)) + subset_dict = {} # {'dendrite_group':number_conns_per_cell} - proj = neuroml.Projection(id=proj_id, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id, - synapse=synapse) + subset_dict[post_segment_group] = number_conns_per_cell + oc_build.add_targeted_projection_by_dicts( + net, + projections, + presynaptic_population, + postsynaptic_population, + targeting_mode, + synapse_list, + pre_seg_target_dict, + post_seg_target_dict, + subset_dict, + delays_dict, + weights_dict, + ) - projections.append(proj) + return projections - subset_dict = {}#{'dendrite_group':number_conns_per_cell} - subset_dict[post_segment_group] = number_conns_per_cell +############################################################################################## - oc_build.add_targeted_projection_by_dicts(net, - projections, - presynaptic_population, - postsynaptic_population, - targeting_mode, - synapse_list, - pre_seg_target_dict, - post_seg_target_dict, - subset_dict, - delays_dict, - weights_dict) - - return projections - - -############################################################################################## - -def add_targeted_electrical_projection(nml_doc, - net, - prefix, - presynaptic_population, - postsynaptic_population, - targeting_mode, - synapse_list, - number_conns_per_cell, - pre_segment_group, - post_segment_group): - - ''' - Adds (electrical, gap junction mediated) projection from `presynaptic_population` to `postsynaptic_population`, +def add_targeted_electrical_projection( + nml_doc, + net, + prefix, + presynaptic_population, + postsynaptic_population, + targeting_mode, + synapse_list, + number_conns_per_cell, + pre_segment_group, + post_segment_group, +): + """ + Adds (electrical, gap junction mediated) projection from `presynaptic_population` to `postsynaptic_population`, specifically limiting connections presynaptically to `pre_segment_group` and postsynaptically to `post_segment_group`. - ''' + """ if presynaptic_population.size == 0 or postsynaptic_population.size == 0: return None projections = [] - pre_cell = oc_build.cell_ids_vs_nml_docs[presynaptic_population.component].get_by_id(presynaptic_population.component) - post_cell = oc_build.cell_ids_vs_nml_docs[postsynaptic_population.component].get_by_id(postsynaptic_population.component) - - - pre_segs = oc_build.extract_seg_ids(pre_cell, - [pre_segment_group], - "segGroups") - post_segs = oc_build.extract_seg_ids(post_cell, - [post_segment_group], - "segGroups") + pre_cell = oc_build.cell_ids_vs_nml_docs[ + presynaptic_population.component + ].get_by_id(presynaptic_population.component) + post_cell = oc_build.cell_ids_vs_nml_docs[ + postsynaptic_population.component + ].get_by_id(postsynaptic_population.component) + pre_segs = oc_build.extract_seg_ids(pre_cell, [pre_segment_group], "segGroups") + post_segs = oc_build.extract_seg_ids(post_cell, [post_segment_group], "segGroups") pre_seg_target_dict = oc_build.make_target_dict(pre_cell, pre_segs) post_seg_target_dict = oc_build.make_target_dict(post_cell, post_segs) - #print pre_seg_target_dict, post_seg_target_dict + # print pre_seg_target_dict, post_seg_target_dict for synapse in synapse_list: - - proj_id = "%s_%s_%s" % (prefix, presynaptic_population.id, postsynaptic_population.id) if len(synapse_list) == 1 else \ - "%s_%s_%s_%s" % (prefix, presynaptic_population.id, postsynaptic_population.id, synapse) - - opencortex.print_comment_v("Adding projection: %s: %s (%s) -> %s (%s)" % (proj_id, pre_cell.id, pre_segs, post_cell.id, post_segs)) - - proj = neuroml.ElectricalProjection(id=proj_id, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id) - + proj_id = ( + "%s_%s_%s" % (prefix, presynaptic_population.id, postsynaptic_population.id) + if len(synapse_list) == 1 + else "%s_%s_%s_%s" + % (prefix, presynaptic_population.id, postsynaptic_population.id, synapse) + ) + + opencortex.print_comment_v( + "Adding projection: %s: %s (%s) -> %s (%s)" + % (proj_id, pre_cell.id, pre_segs, post_cell.id, post_segs) + ) + + proj = neuroml.ElectricalProjection( + id=proj_id, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + ) projections.append(proj) - subset_dict = {}#{'dendrite_group':number_conns_per_cell} + subset_dict = {} # {'dendrite_group':number_conns_per_cell} subset_dict[post_segment_group] = number_conns_per_cell + oc_build._add_elect_projection( + net, + projections, + presynaptic_population, + postsynaptic_population, + targeting_mode, + synapse_list, + pre_seg_target_dict, + post_seg_target_dict, + subset_dict, + ) - oc_build._add_elect_projection(net, - projections, - presynaptic_population, - postsynaptic_population, - targeting_mode, - synapse_list, - pre_seg_target_dict, - post_seg_target_dict, - subset_dict) - - return projections - + return projections ############################################################################################## -def add_inputs_to_population(net, - id, - population, - input_comp_id, - number_per_cell=1, - all_cells=False, - only_cells=None, - segment_ids=[0], - fraction_alongs=[0.5], - weights=1): - + +def add_inputs_to_population( + net, + id, + population, + input_comp_id, + number_per_cell=1, + all_cells=False, + only_cells=None, + segment_ids=[0], + fraction_alongs=[0.5], + weights=1, +): """ Add current input to the specified population. Attributes: - + `net` reference to the network object previously created - `id` + `id` id of the to be created - - `population` + + `population` the to be targeted - - `input_comp_id` + + `input_comp_id` id of the component to be used for the input (e.g. added with add_pulse_generator()) - + `number_per_cell` how many inputs to apply to each cell of the population. Default 1 - + `all_cells` Whether to target all cells. Default False - + `only_cells` Which specific cells to target. List of ids. Default None - + `segment_ids` List of segment ids to place inputs onto on each cell. Either list of 1 value or list of number_per_cell entries. Default [0] - + `fraction_alongs` List of fractions along the specified segments to place inputs onto on each cell. Either list of 1 value or list of number_per_cell entries. Default [0.5] - + `weights` Either a scalar value (all weights set to this for all inputs), or a function to pick a (random) value per input. Default 1 - + """ if all_cells and only_cells is not None: - error = "Error! Method opencortex.build.%s() called with both arguments all_cells and only_cells set!" % sys._getframe().f_code.co_name + error = ( + "Error! Method opencortex.build.%s() called with both arguments all_cells and only_cells set!" + % sys._getframe().f_code.co_name + ) opencortex.print_comment_v(error) raise Exception(error) - - if len(segment_ids)!=1 and len(segment_ids)!=number_per_cell: - - error = "Error! Attribute segment_ids in method opencortex.build.%s()"% sys._getframe().f_code.co_name+\ - " should be a list of one integer (id of the segment all inputs to each cell go into) or a "+ \ - "list of the same length as number_per_cell; not %s!"% segment_ids + if len(segment_ids) != 1 and len(segment_ids) != number_per_cell: + error = ( + "Error! Attribute segment_ids in method opencortex.build.%s()" + % sys._getframe().f_code.co_name + + " should be a list of one integer (id of the segment all inputs to each cell go into) or a " + + "list of the same length as number_per_cell; not %s!" % segment_ids + ) opencortex.print_comment_v(error) raise Exception(error) - - if len(fraction_alongs)!=1 and len(fraction_alongs)!=number_per_cell: - - error = "Error! Attribute fraction_alongs in method opencortex.build.%s()"% sys._getframe().f_code.co_name+\ - " should be a list of one float (fraction along the segment all inputs to each cell go into) or a "+ \ - "list of the same length as number_per_cell!" + + if len(fraction_alongs) != 1 and len(fraction_alongs) != number_per_cell: + error = ( + "Error! Attribute fraction_alongs in method opencortex.build.%s()" + % sys._getframe().f_code.co_name + + " should be a list of one float (fraction along the segment all inputs to each cell go into) or a " + + "list of the same length as number_per_cell!" + ) opencortex.print_comment_v(error) raise Exception(error) @@ -698,120 +755,128 @@ def add_inputs_to_population(net, return cell_ids = only_cells - input_list = neuroml.InputList(id=id, - component=input_comp_id, - populations=population.id) + input_list = neuroml.InputList( + id=id, component=input_comp_id, populations=population.id + ) count = 0 for cell_id in cell_ids: for i in range(number_per_cell): - segment_id = -1 - if len(segment_ids)==1: + if len(segment_ids) == 1: segment_id = segment_ids[0] else: segment_id = segment_ids[i] - + fraction_along = -1 - if len(fraction_alongs)==1: + if len(fraction_alongs) == 1: fraction_along = fraction_alongs[0] else: fraction_along = fraction_alongs[i] - - if fraction_along<0 or fraction_along>1: - error = "Error! Attribute fraction_along should be >=0 and <=1" + + if fraction_along < 0 or fraction_along > 1: + error = "Error! Attribute fraction_along should be >=0 and <=1" opencortex.print_comment_v(error) raise Exception(error) - + if weights == 1: - input = neuroml.Input(id=count, - target="../%s/%i/%s" % (population.id, cell_id, population.component), - segment_id=segment_id, - fraction_along=fraction_along, - destination="synapses") + input = neuroml.Input( + id=count, + target="../%s/%i/%s" + % (population.id, cell_id, population.component), + segment_id=segment_id, + fraction_along=fraction_along, + destination="synapses", + ) input_list.input.append(input) else: - input = neuroml.InputW(id=count, - target="../%s/%i/%s" % (population.id, cell_id, population.component), - segment_id=segment_id, - fraction_along=fraction_along, - destination="synapses", - weight=oc_build._evaluate_expression(weights)) - + input = neuroml.InputW( + id=count, + target="../%s/%i/%s" + % (population.id, cell_id, population.component), + segment_id=segment_id, + fraction_along=fraction_along, + destination="synapses", + weight=oc_build._evaluate_expression(weights), + ) + input_list.input_ws.append(input) - + count += 1 - if count > 0: + if count > 0: net.input_lists.append(input_list) return input_list - - ############################################################################################## -def add_targeted_inputs_to_population(net, - id, - population, - input_comp_id, - segment_group, - number_per_cell=1, - all_cells=False, - only_cells=None, - weights=1): - + +def add_targeted_inputs_to_population( + net, + id, + population, + input_comp_id, + segment_group, + number_per_cell=1, + all_cells=False, + only_cells=None, + weights=1, +): """ Add current input to the specified population. Attributes: - + `net` reference to the network object previously created - `id` + `id` id of the to be created - - `population` + + `population` the to be targeted - - `input_comp_id` + + `input_comp_id` id of the component to be used for the input (e.g. added with add_pulse_generator()) - + `segment_group` - which segment group on the target cells to limit input locations to + which segment group on the target cells to limit input locations to + - `number_per_cell` How many inputs to apply to each cell of the population. Default 1 - + `all_cells` whether to target all cells. Default False - + `only_cells` which specific cells to target. List of ids. Default None - + `weights` Either a scalar value (all weights set to this for all inputs), or a function to pick a (random) value per input. Default 1 - - + + """ if all_cells and only_cells is not None: - error = "Error! Method opencortex.build.%s() called with both arguments all_cells and only_cells set!" % sys._getframe().f_code.co_name + error = ( + "Error! Method opencortex.build.%s() called with both arguments all_cells and only_cells set!" + % sys._getframe().f_code.co_name + ) opencortex.print_comment_v(error) raise Exception(error) cell_ids = [] - - target_cell = oc_build.cell_ids_vs_nml_docs[population.component].get_by_id(population.component) - target_segs = oc_build.extract_seg_ids(target_cell, - [segment_group], - "segGroups") + target_cell = oc_build.cell_ids_vs_nml_docs[population.component].get_by_id( + population.component + ) + + target_segs = oc_build.extract_seg_ids(target_cell, [segment_group], "segGroups") seg_target_dict = oc_build.make_target_dict(target_cell, target_segs) - + subset_dict = {segment_group: number_per_cell} - + if all_cells: cell_ids = range(population.size) if only_cells is not None: @@ -819,95 +884,113 @@ def add_targeted_inputs_to_population(net, return cell_ids = only_cells - input_list = neuroml.InputList(id=id, - component=input_comp_id, - populations=population.id) + input_list = neuroml.InputList( + id=id, component=input_comp_id, populations=population.id + ) count = 0 for cell_id in cell_ids: - - target_seg_array, target_fractions = oc_build.get_target_segments(seg_target_dict, subset_dict) - + target_seg_array, target_fractions = oc_build.get_target_segments( + seg_target_dict, subset_dict + ) + for i in range(number_per_cell): - if weights == 1: - input = neuroml.Input(id=count, - target="../%s/%i/%s" % (population.id, cell_id, population.component), - segment_id=target_seg_array[i], - fraction_along=target_fractions[i], - destination="synapses") + input = neuroml.Input( + id=count, + target="../%s/%i/%s" + % (population.id, cell_id, population.component), + segment_id=target_seg_array[i], + fraction_along=target_fractions[i], + destination="synapses", + ) input_list.input.append(input) else: - input = neuroml.InputW(id=count, - target="../%s/%i/%s" % (population.id, cell_id, population.component), - segment_id=target_seg_array[i], - fraction_along=target_fractions[i], - destination="synapses", - weight=oc_build._evaluate_expression(weights)) + input = neuroml.InputW( + id=count, + target="../%s/%i/%s" + % (population.id, cell_id, population.component), + segment_id=target_seg_array[i], + fraction_along=target_fractions[i], + destination="synapses", + weight=oc_build._evaluate_expression(weights), + ) input_list.input_ws.append(input) - - + count += 1 - if count > 0: + if count > 0: net.input_lists.append(input_list) return input_list - ############################################################################################## -def generate_network(reference, network_seed=1234, temperature='32degC'): - + +def generate_network(reference, network_seed=1234, temperature="32degC"): """ Generate a network which will contain populations, projections, etc. Arguments: - + `reference` the reference to use as the id for the network - + `network_seed` optional, will be used for random elements of the network, e.g. placement of cells in 3D - + `temperature` optional, will be specified in network and used in temperature dependent elements, e.g. ion channels with Q10. Default: 32degC - + """ del oc_build.all_included_files[:] oc_build.all_cells.clear() - nml_doc = neuroml.NeuroMLDocument(id='%s' % reference) + nml_doc = neuroml.NeuroMLDocument(id="%s" % reference) random.seed(network_seed) nml_doc.properties.append(neuroml.Property("Network seed", network_seed)) # Create network - network = neuroml.Network(id='%s' % reference) + network = neuroml.Network(id="%s" % reference) # TODO ###from neuroml.hdf5.NetworkContainer import NetworkContainer ###network = NetworkContainer(id='%s' % reference) - network.type='networkWithTemperature' - network.temperature=temperature - + network.type = "networkWithTemperature" + network.temperature = temperature + nml_doc.networks.append(network) - opencortex.print_comment_v("Created NeuroMLDocument containing a network with id: %s" % reference) + opencortex.print_comment_v( + "Created NeuroMLDocument containing a network with id: %s" % reference + ) return nml_doc, network ############################################################################################## -def save_network(nml_doc, nml_file_name, validate=True, format='xml', max_memory=None, target_dir='./', use_subfolder=True): - + +def save_network( + nml_doc, + nml_file_name, + validate=True, + format="xml", + max_memory=None, + target_dir="./", + use_subfolder=True, +): """ Save the contents of the built NeuroML document, including the network to the file specified by `nml_file_name`, optionally specifying the `target_dir` """ - - oc_build._finalise_copy_to_dir_for_model(nml_doc, target_dir, use_subfolder =use_subfolder) - info = "\n\nThis NeuroML 2 file was generated by OpenCortex v%s using: \n" % (opencortex.__version__) + oc_build._finalise_copy_to_dir_for_model( + nml_doc, target_dir, use_subfolder=use_subfolder + ) + + info = "\n\nThis NeuroML 2 file was generated by OpenCortex v%s using: \n" % ( + opencortex.__version__ + ) info += " libNeuroML v%s\n" % (neuroml.__version__) info += " pyNeuroML v%s\n\n " % (pyneuroml.__version__) @@ -915,22 +998,22 @@ def save_network(nml_doc, nml_file_name, validate=True, format='xml', max_memory nml_doc.notes += info else: nml_doc.notes = info - - nml_full_file_name = target_dir+'/'+nml_file_name + + nml_full_file_name = target_dir + "/" + nml_file_name abs_path = os.path.abspath(nml_full_file_name) - if format == 'xml': + if format == "xml": writers.NeuroMLWriter.write(nml_doc, abs_path) - elif format == 'hdf5': + elif format == "hdf5": writers.NeuroMLHdf5Writer.write(nml_doc, abs_path) - opencortex.print_comment_v("Saved NeuroML with id: %s to file: %s" % (nml_doc.id, abs_path)) + opencortex.print_comment_v( + "Saved NeuroML with id: %s to file: %s" % (nml_doc.id, abs_path) + ) if not os.path.isfile(abs_path): raise Exception("Problem creating file: %s" % (abs_path)) - if validate: - from pyneuroml.pynml import validate_neuroml2 passed = validate_neuroml2(nml_full_file_name, max_memory=max_memory) @@ -943,31 +1026,33 @@ def save_network(nml_doc, nml_file_name, validate=True, format='xml', max_memory ############################################################################################## -def generate_lems_simulation(nml_doc, - network, - nml_file_name, - duration, - dt, - target_dir='.', - include_extra_lems_files=[], - gen_plots_for_all_v=True, - plot_all_segments=False, - gen_plots_for_quantities={}, # Dict with displays vs lists of quantity paths - gen_plots_for_only_populations=[], # List of populations, all pops if = [] - gen_saves_for_all_v=True, - save_all_segments=False, - gen_saves_for_only_populations=[], # List of populations, all pops if = [] - gen_saves_for_quantities={}, # Dict with file names vs lists of quantity paths - gen_spike_saves_for_all_somas=False, - gen_spike_saves_for_only_populations=[], # List of populations, all pops if = [] - gen_spike_saves_for_cells={}, # Dict with file names vs lists of quantity paths - spike_time_format='ID_TIME', - report_file_name=None, - lems_file_name=None, - lems_file_generate_seed=12345, - simulation_seed=12345, - verbose=False): - + +def generate_lems_simulation( + nml_doc, + network, + nml_file_name, + duration, + dt, + target_dir=".", + include_extra_lems_files=[], + gen_plots_for_all_v=True, + plot_all_segments=False, + gen_plots_for_quantities={}, # Dict with displays vs lists of quantity paths + gen_plots_for_only_populations=[], # List of populations, all pops if = [] + gen_saves_for_all_v=True, + save_all_segments=False, + gen_saves_for_only_populations=[], # List of populations, all pops if = [] + gen_saves_for_quantities={}, # Dict with file names vs lists of quantity paths + gen_spike_saves_for_all_somas=False, + gen_spike_saves_for_only_populations=[], # List of populations, all pops if = [] + gen_spike_saves_for_cells={}, # Dict with file names vs lists of quantity paths + spike_time_format="ID_TIME", + report_file_name=None, + lems_file_name=None, + lems_file_generate_seed=12345, + simulation_seed=12345, + verbose=False, +): """ Generate a LEMS simulation file with which to run simulations of the network. Generated LEMS files can be run with jNeuroML (or converted to simulator specific formats, e.g. NEURON, and run) @@ -978,63 +1063,89 @@ def generate_lems_simulation(nml_doc, include_extra_lems_files.extend(oc_build.all_included_files) - quantities_saved,lems_sim = pyneuroml.lems.generate_lems_file_for_neuroml("Sim_%s" % network.id, - nml_file_name, - network.id, - duration, - dt, - lems_file_name, - target_dir, - include_extra_files=include_extra_lems_files, - gen_plots_for_all_v=gen_plots_for_all_v, - plot_all_segments=plot_all_segments, - gen_plots_for_quantities=gen_plots_for_quantities, - gen_plots_for_only_populations=gen_plots_for_only_populations, - gen_saves_for_all_v=gen_saves_for_all_v, - save_all_segments=save_all_segments, - gen_saves_for_only_populations=gen_saves_for_only_populations, - gen_saves_for_quantities=gen_saves_for_quantities, - gen_spike_saves_for_all_somas=gen_spike_saves_for_all_somas, - gen_spike_saves_for_only_populations=gen_spike_saves_for_only_populations, - gen_spike_saves_for_cells=gen_spike_saves_for_cells, - spike_time_format=spike_time_format, - report_file_name=report_file_name, - lems_file_generate_seed=lems_file_generate_seed, - simulation_seed=simulation_seed, - verbose=verbose) + quantities_saved, lems_sim = pyneuroml.lems.generate_lems_file_for_neuroml( + "Sim_%s" % network.id, + nml_file_name, + network.id, + duration, + dt, + lems_file_name, + target_dir, + include_extra_files=include_extra_lems_files, + gen_plots_for_all_v=gen_plots_for_all_v, + plot_all_segments=plot_all_segments, + gen_plots_for_quantities=gen_plots_for_quantities, + gen_plots_for_only_populations=gen_plots_for_only_populations, + gen_saves_for_all_v=gen_saves_for_all_v, + save_all_segments=save_all_segments, + gen_saves_for_only_populations=gen_saves_for_only_populations, + gen_saves_for_quantities=gen_saves_for_quantities, + gen_spike_saves_for_all_somas=gen_spike_saves_for_all_somas, + gen_spike_saves_for_only_populations=gen_spike_saves_for_only_populations, + gen_spike_saves_for_cells=gen_spike_saves_for_cells, + spike_time_format=spike_time_format, + report_file_name=report_file_name, + lems_file_generate_seed=lems_file_generate_seed, + simulation_seed=simulation_seed, + verbose=verbose, + ) del include_extra_lems_files[:] - return target_dir+'/'+lems_file_name, lems_sim + return target_dir + "/" + lems_file_name, lems_sim ############################################################################################## -def simulate_network(lems_file_name, - simulator, - max_memory='400M', - nogui=True, - load_saved_data=False, - reload_events=False, - plot=False, - verbose=True, - num_processors=1): +def simulate_network( + lems_file_name, + simulator, + max_memory="400M", + nogui=True, + load_saved_data=False, + reload_events=False, + plot=False, + verbose=True, + num_processors=1, +): """ Run a simulation of the LEMS file `lems_file_name` using target platform `simulator` """ if simulator == "jNeuroML": - results = pynml.run_lems_with_jneuroml(lems_file_name, max_memory=max_memory, nogui=nogui, load_saved_data=load_saved_data, reload_events=reload_events, plot=plot, verbose=verbose) + results = pynml.run_lems_with_jneuroml( + lems_file_name, + max_memory=max_memory, + nogui=nogui, + load_saved_data=load_saved_data, + reload_events=reload_events, + plot=plot, + verbose=verbose, + ) elif simulator == "jNeuroML_NEURON": - results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, max_memory=max_memory, nogui=nogui, load_saved_data=load_saved_data, reload_events=reload_events, plot=plot, verbose=verbose) + results = pynml.run_lems_with_jneuroml_neuron( + lems_file_name, + max_memory=max_memory, + nogui=nogui, + load_saved_data=load_saved_data, + reload_events=reload_events, + plot=plot, + verbose=verbose, + ) elif simulator == "jNeuroML_NetPyNE": - results = pynml.run_lems_with_jneuroml_netpyne(lems_file_name, max_memory=max_memory, nogui=nogui, load_saved_data=load_saved_data, reload_events=reload_events, plot=plot, verbose=verbose,num_processors=num_processors) + results = pynml.run_lems_with_jneuroml_netpyne( + lems_file_name, + max_memory=max_memory, + nogui=nogui, + load_saved_data=load_saved_data, + reload_events=reload_events, + plot=plot, + verbose=verbose, + num_processors=num_processors, + ) else: - raise Exception("Simulator %s not yet supported"%simulator) + raise Exception("Simulator %s not yet supported" % simulator) if load_saved_data: return results - - - diff --git a/opencortex/test/test_build_methods.py b/opencortex/test/test_build_methods.py index 9b9707f..f8196d8 100644 --- a/opencortex/test/test_build_methods.py +++ b/opencortex/test/test_build_methods.py @@ -12,7 +12,6 @@ import opencortex.utils as oc_utils import neuroml import numpy as np -import os import random @@ -20,1567 +19,5346 @@ import unittest2 as unittest except ImportError: import unittest - + + class TestNetMorphMethods(unittest.TestCase): + ######################################################################### + def test_extract_seg_ids(self): + cell_nml_file = "Test.cell.nml" + + document_cell = neuroml.loaders.NeuroMLLoader.load(cell_nml_file) + + cell_object = document_cell.cells[0] + + test_return1 = oc_build.extract_seg_ids( + cell_object, + target_compartment_array=["basal_obl_dends", "most_prox_bas_dend"], + targeting_mode="segGroups", + ) + + self.assertEqual( + set(["basal_obl_dends", "most_prox_bas_dend"]), set(test_return1.keys()) + ) + + self.assertEqual( + set(test_return1["basal_obl_dends"]), + set( + [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ] + ), + ) + + self.assertEqual( + set(test_return1["most_prox_bas_dend"]), + set([16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3]), + ) + + test_return2 = oc_build.extract_seg_ids( + cell_object, + target_compartment_array=["Seg1_comp_68", "Seg1_comp_28"], + targeting_mode="segments", + ) + + self.assertEqual( + set(["Seg1_comp_68", "Seg1_comp_28"]), set(test_return2.keys()) + ) + self.assertEqual(set(test_return2["Seg1_comp_68"]), set([135])) + self.assertEqual(set(test_return2["Seg1_comp_28"]), set([55])) + + test_return3 = oc_build.extract_seg_ids( + cell_object, + target_compartment_array=["some_prox"], + targeting_mode="segGroups", + ) + + self.assertEqual(len(test_return3["some_prox"]), 24) + + ############################################################################################################ + def test_get_seg_lengths(self): + cell_nml_file = "Test.cell.nml" + + document_cell = neuroml.loaders.NeuroMLLoader.load(cell_nml_file) + + cell_object = document_cell.cells[0] + + length_dist1, segment_list1 = oc_build.get_seg_lengths(cell_object, [55]) + + length_dist2, segment_list2 = oc_build.get_seg_lengths(cell_object, [135]) + + length_dist3, segment_list3 = oc_build.get_seg_lengths(cell_object, [55, 135]) + + self.assertEqual(len(length_dist1), len(segment_list1)) + + self.assertEqual(len(length_dist3), len(segment_list3)) + + self.assertEqual(length_dist1[0], 25.00030750752478) + + self.assertEqual(length_dist2[0], 24.99966139974902) + + self.assertEqual(set([55, 135]), set(segment_list3)) + + self.assertEqual(length_dist1[0], length_dist3[0]) + + self.assertEqual(length_dist1[0] + length_dist2[0], length_dist3[1]) + + ####################################################################################################################### + def test_make_target_dict(self): + cell_nml_file = "Test.cell.nml" + + document_cell = neuroml.loaders.NeuroMLLoader.load(cell_nml_file) + + cell_object = document_cell.cells[0] + + makeDict1 = oc_build.make_target_dict( + cell_object=cell_object, + target_segs={"Seg1_comp_28": [55], "Seg1_comp_68": [135]}, + ) + + self.assertEqual(set(["Seg1_comp_28", "Seg1_comp_68"]), set(makeDict1.keys())) + self.assertEqual( + set(makeDict1["Seg1_comp_28"].keys()), set(["SegList", "LengthDist"]) + ) + + self.assertEqual( + len(makeDict1["Seg1_comp_68"]["SegList"]), + len(makeDict1["Seg1_comp_68"]["LengthDist"]), + ) + + makeDict2 = oc_build.make_target_dict( + cell_object=cell_object, + target_segs={ + "basal_obl_dends": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "most_prox_bas_dend": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + ], + }, + ) + + self.assertEqual( + len(makeDict2["basal_obl_dends"]["SegList"]), + len(makeDict2["basal_obl_dends"]["LengthDist"]), + ) + + self.assertEqual( + set(makeDict2["most_prox_bas_dend"]["SegList"]), + set([16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3]), + ) + + ####################################################################################################################### + def test_get_target_segments(self): + target_segs1, fractions_list1 = oc_build.get_target_segments( + seg_specifications={ + "Seg1_comp_28": {"SegList": [55], "LengthDist": [25.00030750752478]}, + "Seg1_comp_68": {"SegList": [135], "LengthDist": [24.99966139974902]}, + }, + subset_dict={"Seg1_comp_x": 1, "Seg1_comp_y": 1}, + ) + + self.assertEqual(target_segs1, []) + self.assertEqual(fractions_list1, []) + + target_segs1, fractions_list1 = oc_build.get_target_segments( + seg_specifications={ + "Seg1_comp_28": {"SegList": [55], "LengthDist": [25.00030750752478]}, + "Seg1_comp_68": {"SegList": [135], "LengthDist": [24.99966139974902]}, + }, + subset_dict={"Seg1_comp_28": 1, "Seg1_comp_68": 1}, + ) + + self.assertEqual(len(target_segs1), 2) + self.assertEqual(len(fractions_list1), 2) + + self.assertEqual(set(target_segs1), set([55, 135])) + self.assertEqual(len(np.unique(fractions_list1)), 2) + self.assertTrue(fractions_list1[0] <= 1) + self.assertTrue(fractions_list1[1] <= 1) + + target_segs, fractions_list = oc_build.get_target_segments( + seg_specifications={ + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + }, + "Seg1_comp_68": {"SegList": [135], "LengthDist": [24.99966139974902]}, + }, + subset_dict={"basal_obl_dends": 100, "Seg1_comp_68": 50}, + ) + + self.assertEqual(len(target_segs), 150) + self.assertEqual(len(fractions_list), 150) + basal_obl_dends_count = 0 + seg_comp_68_count = 0 + for ind in range(0, len(target_segs)): + if target_segs[ind] in [135]: + seg_comp_68_count += 1 + + if target_segs[ind] in [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ]: + basal_obl_dends_count += 1 + + self.assertEqual(seg_comp_68_count, 50) + + self.assertEqual(basal_obl_dends_count, 100) + + ############# check the case when subset_dict gives only the total number of target points + + target_segs, fractions_list = oc_build.get_target_segments( + seg_specifications={ + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + }, + "Seg1_comp_68": {"SegList": [135], "LengthDist": [24.99966139974902]}, + }, + subset_dict=100, + ) + + self.assertEqual(len(target_segs), 100) + self.assertEqual(len(fractions_list), 100) + basal_obl_dends_count = 0 + seg_comp_68_count = 0 + for ind in range(0, len(target_segs)): + if target_segs[ind] in [135]: + seg_comp_68_count += 1 + + if target_segs[ind] in [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ]: + basal_obl_dends_count += 1 + + self.assertTrue(seg_comp_68_count != 0) + + self.assertTrue(basal_obl_dends_count != 0) + - ######################################################################### - def test_extract_seg_ids(self): - - cell_nml_file = 'Test.cell.nml' - - document_cell = neuroml.loaders.NeuroMLLoader.load(cell_nml_file) - - cell_object=document_cell.cells[0] - - test_return1=oc_build.extract_seg_ids(cell_object, - target_compartment_array=['basal_obl_dends','most_prox_bas_dend'], - targeting_mode='segGroups') - - - self.assertEqual(set(['basal_obl_dends','most_prox_bas_dend']), set(test_return1.keys())) - - self.assertEqual(set(test_return1['basal_obl_dends']),set([16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67])) - - self.assertEqual(set(test_return1['most_prox_bas_dend']),set([16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3]) ) - - test_return2=oc_build.extract_seg_ids(cell_object, - target_compartment_array=['Seg1_comp_68','Seg1_comp_28'], - targeting_mode='segments') - - self.assertEqual(set(['Seg1_comp_68','Seg1_comp_28']),set(test_return2.keys()) ) - self.assertEqual(set(test_return2['Seg1_comp_68']),set([135]) ) - self.assertEqual(set(test_return2['Seg1_comp_28']),set([55]) ) - - test_return3=oc_build.extract_seg_ids(cell_object, - target_compartment_array=['some_prox'], - targeting_mode='segGroups') - - self.assertEqual(len(test_return3['some_prox']), 24 ) - - ############################################################################################################ - def test_get_seg_lengths(self): - - cell_nml_file = 'Test.cell.nml' - - document_cell = neuroml.loaders.NeuroMLLoader.load(cell_nml_file) - - cell_object=document_cell.cells[0] - - length_dist1,segment_list1=oc_build.get_seg_lengths(cell_object,[55]) - - length_dist2,segment_list2=oc_build.get_seg_lengths(cell_object,[135]) - - length_dist3,segment_list3=oc_build.get_seg_lengths(cell_object,[55,135]) - - self.assertEqual(len(length_dist1),len(segment_list1) ) - - self.assertEqual(len(length_dist3),len(segment_list3) ) - - self.assertEqual(length_dist1[0],25.00030750752478) - - self.assertEqual(length_dist2[0],24.99966139974902) - - self.assertEqual(set([55,135]),set(segment_list3)) - - self.assertEqual(length_dist1[0],length_dist3[0]) - - self.assertEqual(length_dist1[0]+length_dist2[0],length_dist3[1]) - - ####################################################################################################################### - def test_make_target_dict(self): - - cell_nml_file = 'Test.cell.nml' - - document_cell = neuroml.loaders.NeuroMLLoader.load(cell_nml_file) - - cell_object=document_cell.cells[0] - - makeDict1=oc_build.make_target_dict(cell_object=cell_object, - target_segs={'Seg1_comp_28':[55], 'Seg1_comp_68': [135]}) - - self.assertEqual(set(['Seg1_comp_28','Seg1_comp_68']),set(makeDict1.keys())) - self.assertEqual(set(makeDict1['Seg1_comp_28'].keys()),set(['SegList','LengthDist'])) - - self.assertEqual(len(makeDict1['Seg1_comp_68']['SegList']),len(makeDict1['Seg1_comp_68']['LengthDist'])) - - makeDict2=oc_build.make_target_dict(cell_object=cell_object, - target_segs={'basal_obl_dends': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'most_prox_bas_dend': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3]}) - - self.assertEqual(len(makeDict2['basal_obl_dends']['SegList']),len(makeDict2['basal_obl_dends']['LengthDist']) ) - - self.assertEqual(set(makeDict2['most_prox_bas_dend']['SegList']),set([16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3])) - - ####################################################################################################################### - def test_get_target_segments(self): - - target_segs1, fractions_list1=oc_build.get_target_segments(seg_specifications={'Seg1_comp_28': {'SegList': [55], 'LengthDist': [25.00030750752478]}, 'Seg1_comp_68': {'SegList': [135], 'LengthDist': [24.99966139974902]}},subset_dict={'Seg1_comp_x':1,'Seg1_comp_y':1}) - - self.assertEqual(target_segs1,[]) - self.assertEqual(fractions_list1,[]) - - target_segs1, fractions_list1=oc_build.get_target_segments(seg_specifications={'Seg1_comp_28': {'SegList': [55], 'LengthDist': [25.00030750752478]}, 'Seg1_comp_68': {'SegList': [135], 'LengthDist': [24.99966139974902]}},subset_dict={'Seg1_comp_28':1,'Seg1_comp_68':1}) - - self.assertEqual(len(target_segs1),2) - self.assertEqual(len(fractions_list1),2) - - self.assertEqual(set(target_segs1),set([55,135])) - self.assertEqual(len(np.unique(fractions_list1)),2) - self.assertTrue( fractions_list1[0] <=1) - self.assertTrue( fractions_list1[1] <=1) - - - target_segs, fractions_list=oc_build.get_target_segments(seg_specifications={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]},'Seg1_comp_68': {'SegList': [135], 'LengthDist': [24.99966139974902]}},subset_dict={'basal_obl_dends':100,'Seg1_comp_68':50}) - - self.assertEqual(len(target_segs),150) - self.assertEqual(len(fractions_list),150) - basal_obl_dends_count=0 - seg_comp_68_count=0 - for ind in range(0,len(target_segs)): - - if target_segs[ind] in [135]: - - seg_comp_68_count+=1 - - if target_segs[ind] in [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67]: - - basal_obl_dends_count+=1 - - self.assertEqual(seg_comp_68_count,50) - - self.assertEqual(basal_obl_dends_count,100) - - ############# check the case when subset_dict gives only the total number of target points - - target_segs, fractions_list=oc_build.get_target_segments(seg_specifications={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]},'Seg1_comp_68': {'SegList': [135], 'LengthDist': [24.99966139974902]}},subset_dict=100) - - self.assertEqual(len(target_segs),100) - self.assertEqual(len(fractions_list),100) - basal_obl_dends_count=0 - seg_comp_68_count=0 - for ind in range(0,len(target_segs)): - - if target_segs[ind] in [135]: - - seg_comp_68_count+=1 - - if target_segs[ind] in [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67]: - - basal_obl_dends_count+=1 - - self.assertTrue( seg_comp_68_count != 0 ) - - self.assertTrue(basal_obl_dends_count != 0 ) - ####################################################################################################################################################################### class TestNetConnectionMethods(unittest.TestCase): - - def test_add_targeted_projection_by_dicts(self): - ######## Test 1 convergent - network = neuroml.Network(id='Net0') - presynaptic_population = neuroml.Population(id="Pop0", component="L23PyrRS", type="populationList", size=1) - postsynaptic_population=neuroml.Population(id="Pop1", component="L23PyrFRB", type="populationList", size=1) - - synapse_list=['AMPA','NMDA'] - - projection_array=[] - - for synapse_element in range(0,len(synapse_list) ): - - proj = neuroml.Projection(id="Proj%d"%synapse_element, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id, - synapse=synapse_list[synapse_element]) - - projection_array.append(proj) - - - parsed_target_dict={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]}} - - - proj_array=oc_build.add_targeted_projection_by_dicts(net=network, - proj_array=projection_array, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - targeting_mode='convergent', - synapse_list=synapse_list, - pre_seg_target_dict=None, - post_seg_target_dict=parsed_target_dict, - subset_dict={'basal_obl_dends':50}, - delays_dict={'NMDA':5}, - weights_dict={'AMPA':1.5,'NMDA':2}) - - - self.assertEqual(len(network.projections),2) - - self.assertEqual(len(proj_array[0].connection_wds),len(network.projections[0].connection_wds) ) - - self.assertEqual(len(proj_array[0].connection_wds),50) - - pre_cell_AMPA_strings=[] - - post_cell_AMPA_strings=[] - - pre_cell_NMDA_strings=[] - - post_cell_NMDA_strings=[] - - for conn_ind in range(0,50): - - pre_cell_AMPA_strings.append(proj_array[0].connection_wds[conn_ind].pre_cell_id) - - post_cell_AMPA_strings.append(proj_array[0].connection_wds[conn_ind].post_cell_id) - - pre_cell_NMDA_strings.append(proj_array[1].connection_wds[conn_ind].pre_cell_id) - - post_cell_NMDA_strings.append(proj_array[1].connection_wds[conn_ind].post_cell_id) - - self.assertEqual(len(set(pre_cell_AMPA_strings)),1) - - self.assertEqual(len(set(pre_cell_AMPA_strings)),len(set(pre_cell_NMDA_strings)) ) - - self.assertEqual(len(set(post_cell_AMPA_strings)),1) - - self.assertEqual(len(set(post_cell_AMPA_strings)),len(set(post_cell_NMDA_strings)) ) - - self.assertEqual(len(proj_array[0].connection_wds),len(proj_array[1].connection_wds) ) - - self.assertEqual(proj_array[0].synapse,'AMPA') - - self.assertEqual(proj_array[1].synapse,'NMDA') - - ######## Test 2 convergent - network = neuroml.Network(id='Net0') - presynaptic_population = neuroml.Population(id="Pop0", component="L23PyrRS", type="populationList", size=1) - postsynaptic_population=neuroml.Population(id="Pop0", component="L23PyrRS", type="populationList", size=1) - - synapse_list=['AMPA','NMDA'] - - projection_array=[] - - for synapse_element in range(0,len(synapse_list) ): - - proj = neuroml.Projection(id="Proj%d"%synapse_element, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id, - synapse=synapse_list[synapse_element]) - - projection_array.append(proj) - - parsed_target_dict={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]}} - - proj_array=oc_build.add_targeted_projection_by_dicts(net=network, - proj_array=projection_array, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - targeting_mode='convergent', - synapse_list=synapse_list, - pre_seg_target_dict=None, - post_seg_target_dict=parsed_target_dict, - subset_dict={'basal_obl_dends':50}, - delays_dict={'NMDA':5}, - weights_dict={'AMPA':1.5,'NMDA':2}) - - self.assertEqual(len(proj_array[0].connection_wds),0) - - self.assertEqual(len(proj_array[0].connection_wds),len(proj_array[1].connection_wds) ) - - self.assertEqual(proj_array[0].synapse,'AMPA') - - self.assertEqual(proj_array[1].synapse,'NMDA') - - self.assertEqual(len(network.projections),0) - - ######## Test 3 convergent - network = neuroml.Network(id='Net0') - presynaptic_population = neuroml.Population(id="Pop0", component="L23PyrRS", type="populationList", size=50) - postsynaptic_population=neuroml.Population(id="Pop1", component="L23PyrFRB", type="populationList", size=2) - - synapse_list=['AMPA','NMDA'] - - projection_array=[] - - for synapse_element in range(0,len(synapse_list) ): - - proj = neuroml.Projection(id="Proj%d"%synapse_element, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id, - synapse=synapse_list[synapse_element]) - - projection_array.append(proj) - - parsed_target_dict={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]}} - - - proj_array=oc_build.add_targeted_projection_by_dicts(net=network, - proj_array=projection_array, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - targeting_mode='convergent', - synapse_list=synapse_list, - pre_seg_target_dict=None, - post_seg_target_dict=parsed_target_dict, - subset_dict={'basal_obl_dends':50}, - delays_dict={'NMDA':5}, - weights_dict={'AMPA':1.5,'NMDA':2}) - - - self.assertEqual(len(network.projections),2) - - self.assertEqual(len(network.projections[0].connection_wds),len(proj_array[0].connection_wds) ) - - self.assertEqual(len(proj_array[0].connection_wds),100) - - self.assertEqual(len(proj_array[0].connection_wds),len(proj_array[1].connection_wds) ) - - self.assertEqual(proj_array[0].synapse,'AMPA') - - self.assertEqual(proj_array[1].synapse,'NMDA') - - pre_cell_AMPA_strings=[] - - post_cell_AMPA_strings=[] - - pre_cell_NMDA_strings=[] - - post_cell_NMDA_strings=[] - - for conn_ind in range(0,100): - - pre_cell_AMPA_strings.append(proj_array[0].connection_wds[conn_ind].pre_cell_id) - - post_cell_AMPA_strings.append(proj_array[0].connection_wds[conn_ind].post_cell_id) - - pre_cell_NMDA_strings.append(proj_array[1].connection_wds[conn_ind].pre_cell_id) - - post_cell_NMDA_strings.append(proj_array[1].connection_wds[conn_ind].post_cell_id) - - self.assertEqual(proj_array[0].connection_wds[conn_ind].pre_cell_id,proj_array[1].connection_wds[conn_ind].pre_cell_id) - - self.assertEqual(proj_array[0].connection_wds[conn_ind].post_cell_id,proj_array[1].connection_wds[conn_ind].post_cell_id) - - self.assertEqual(proj_array[0].connection_wds[conn_ind].post_segment_id,proj_array[1].connection_wds[conn_ind].post_segment_id) - - self.assertEqual(proj_array[0].connection_wds[conn_ind].pre_segment_id,proj_array[1].connection_wds[conn_ind].pre_segment_id) - - self.assertEqual(proj_array[0].connection_wds[conn_ind].pre_fraction_along,proj_array[1].connection_wds[conn_ind].pre_fraction_along) - - self.assertEqual(proj_array[0].connection_wds[conn_ind].post_fraction_along,proj_array[1].connection_wds[conn_ind].post_fraction_along) - - self.assertNotEqual(proj_array[0].connection_wds[conn_ind].delay,proj_array[1].connection_wds[conn_ind].delay) - - self.assertNotEqual(proj_array[0].connection_wds[conn_ind].weight,proj_array[1].connection_wds[conn_ind].weight) - - self.assertEqual(len(set(pre_cell_AMPA_strings)),50) - - self.assertEqual(len(set(pre_cell_AMPA_strings)),len(set(pre_cell_NMDA_strings)) ) - - self.assertEqual(len(set(post_cell_AMPA_strings)),2) - - self.assertEqual(len(set(post_cell_AMPA_strings)),len(set(post_cell_NMDA_strings)) ) - - ######## Test 4 divergent - network = neuroml.Network(id='Net0') - presynaptic_population = neuroml.Population(id="Pop0", component="L23PyrRS", type="populationList", size=3) - postsynaptic_population=neuroml.Population(id="Pop1", component="L23PyrFRB", type="populationList", size=50) - - synapse_list=['AMPA','NMDA'] - - projection_array=[] - - for synapse_element in range(0,len(synapse_list) ): - - proj = neuroml.Projection(id="Proj%d"%synapse_element, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id, - synapse=synapse_list[synapse_element]) - - projection_array.append(proj) - - parsed_target_dict={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]}} - - proj_array=oc_build.add_targeted_projection_by_dicts(net=network, - proj_array=projection_array, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - targeting_mode='divergent', - synapse_list=synapse_list, - pre_seg_target_dict=None, - post_seg_target_dict=parsed_target_dict, - subset_dict={'basal_obl_dends':50}, - delays_dict={'NMDA':5}, - weights_dict={'AMPA':1.5,'NMDA':2}) - - self.assertEqual(len(network.projections),2) - - self.assertEqual(len(proj_array[0].connection_wds),150) - - self.assertEqual(len(proj_array[0].connection_wds), len(network.projections[0].connection_wds) ) - - self.assertEqual(len(proj_array[0].connection_wds),len(proj_array[1].connection_wds) ) - - self.assertEqual(proj_array[0].synapse,'AMPA') - - self.assertEqual(proj_array[1].synapse,'NMDA') - - pre_cell_AMPA_strings=[] - - post_cell_AMPA_strings=[] - - pre_cell_NMDA_strings=[] - - post_cell_NMDA_strings=[] - - for conn_ind in range(0,150): - - pre_cell_AMPA_strings.append(proj_array[0].connection_wds[conn_ind].pre_cell_id) - - post_cell_AMPA_strings.append(proj_array[0].connection_wds[conn_ind].post_cell_id) - - pre_cell_NMDA_strings.append(proj_array[1].connection_wds[conn_ind].pre_cell_id) - - post_cell_NMDA_strings.append(proj_array[1].connection_wds[conn_ind].post_cell_id) - - self.assertEqual(proj_array[0].connection_wds[conn_ind].pre_cell_id,proj_array[1].connection_wds[conn_ind].pre_cell_id) - - self.assertEqual(proj_array[0].connection_wds[conn_ind].post_cell_id,proj_array[1].connection_wds[conn_ind].post_cell_id) - - self.assertEqual(proj_array[0].connection_wds[conn_ind].post_segment_id,proj_array[1].connection_wds[conn_ind].post_segment_id) - - self.assertEqual(proj_array[0].connection_wds[conn_ind].pre_segment_id,proj_array[1].connection_wds[conn_ind].pre_segment_id) - - self.assertEqual(proj_array[0].connection_wds[conn_ind].pre_fraction_along,proj_array[1].connection_wds[conn_ind].pre_fraction_along) - - self.assertEqual(proj_array[0].connection_wds[conn_ind].post_fraction_along,proj_array[1].connection_wds[conn_ind].post_fraction_along) - - self.assertNotEqual(proj_array[0].connection_wds[conn_ind].delay,proj_array[1].connection_wds[conn_ind].delay) - - self.assertNotEqual(proj_array[0].connection_wds[conn_ind].weight,proj_array[1].connection_wds[conn_ind].weight) - - self.assertEqual(len(set(pre_cell_AMPA_strings)),3) - - self.assertEqual(len(set(pre_cell_AMPA_strings)),len(set(pre_cell_NMDA_strings)) ) - - self.assertEqual(len(set(post_cell_AMPA_strings)),50) - - self.assertEqual(len(set(post_cell_AMPA_strings)),len(set(post_cell_NMDA_strings)) ) - - ######## Test 5 convergent mode, check pre and post segments - network = neuroml.Network(id='Net0') - presynaptic_population = neuroml.Population(id="Pop0", component="L23PyrRS", type="populationList", size=50) - postsynaptic_population=neuroml.Population(id="Pop1", component="L23PyrFRB", type="populationList", size=2) - - synapse_list=['AMPA','NMDA'] - - projection_array=[] - - for synapse_element in range(0,len(synapse_list) ): - - proj = neuroml.Projection(id="Proj%d"%synapse_element, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id, - synapse=synapse_list[synapse_element]) - - projection_array.append(proj) - - parsed_pre_target_dict={'distal_axon': {'SegList': [146, 147, 142, 143], 'LengthDist': [25.00045378088167, 49.999986501514655, 75.00044417652734, 99.9999379546021]}} - - parsed_target_dict={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]}} - - - proj_array=oc_build.add_targeted_projection_by_dicts(net=network, - proj_array=projection_array, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - targeting_mode='convergent', - synapse_list=synapse_list, - pre_seg_target_dict=parsed_pre_target_dict, - post_seg_target_dict=parsed_target_dict, - subset_dict={'basal_obl_dends':50}, - delays_dict={'NMDA':5}, - weights_dict={'AMPA':1.5,'NMDA':2}) - - - - AMPA_proj=network.projections[0].connection_wds - - NMDA_proj=network.projections[1].connection_wds - - for conn_ind in range(0,100): - - self.assertTrue(AMPA_proj[conn_ind].pre_segment_id in parsed_pre_target_dict['distal_axon']['SegList'] ) - - self.assertTrue(AMPA_proj[conn_ind].pre_segment_id== NMDA_proj[conn_ind].pre_segment_id ) - - self.assertTrue(AMPA_proj[conn_ind].post_segment_id in parsed_target_dict['basal_obl_dends']['SegList'] ) - - self.assertTrue(AMPA_proj[conn_ind].post_segment_id == NMDA_proj[conn_ind].post_segment_id ) - - ######## Test 6 convergent mode, check pre and post segments and total number given not in the format of dictionary - network = neuroml.Network(id='Net0') - presynaptic_population = neuroml.Population(id="Pop0", component="L23PyrRS", type="populationList", size=50) - postsynaptic_population=neuroml.Population(id="Pop1", component="L23PyrFRB", type="populationList", size=2) - - synapse_list=['AMPA','NMDA'] - - projection_array=[] - - for synapse_element in range(0,len(synapse_list) ): - - proj = neuroml.Projection(id="Proj%d"%synapse_element, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id, - synapse=synapse_list[synapse_element]) - - projection_array.append(proj) - - parsed_pre_target_dict={'distal_axon': {'SegList': [146, 147, 142, 143], 'LengthDist': [25.00045378088167, 49.999986501514655, 75.00044417652734, 99.9999379546021]}} - - parsed_target_dict={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]},'distal_axon': {'SegList': [146, 147, 142, 143], 'LengthDist': [25.00045378088167, 49.999986501514655, 75.00044417652734, 99.9999379546021]}} - - proj_array=oc_build.add_targeted_projection_by_dicts(net=network, - proj_array=projection_array, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - targeting_mode='convergent', - synapse_list=synapse_list, - pre_seg_target_dict=parsed_pre_target_dict, - post_seg_target_dict=parsed_target_dict, - subset_dict=50, - delays_dict={'NMDA':5}, - weights_dict={'AMPA':1.5,'NMDA':2}) - - AMPA_proj=network.projections[0].connection_wds - - NMDA_proj=network.projections[1].connection_wds - - for conn_ind in range(0,100): - - self.assertTrue(AMPA_proj[conn_ind].pre_segment_id in parsed_pre_target_dict['distal_axon']['SegList'] ) - - self.assertTrue(AMPA_proj[conn_ind].pre_segment_id== NMDA_proj[conn_ind].pre_segment_id ) - - check_basal=AMPA_proj[conn_ind].post_segment_id in parsed_target_dict['basal_obl_dends']['SegList'] - - check_distal=AMPA_proj[conn_ind].post_segment_id in parsed_target_dict['distal_axon']['SegList'] - - self.assertTrue( check_basal or check_distal ) - - self.assertTrue(AMPA_proj[conn_ind].post_segment_id == NMDA_proj[conn_ind].post_segment_id ) - - def test_add_chem_spatial_projection(self): - ######## Test 1 convergent - network = neuroml.Network(id='Net0') - - popDict={} - popDict['CG3D_L23PyrRS'] = (500, 'L23','Test','multi',None) - popDict['CG3D_L23PyrFRB']= (1,'L23','Test2','multi', None) - t1=-0 - t2=-250 - t3=-250 - boundaries={} - boundaries['L1']=[0,t1] - boundaries['L23']=[t1,t1+t2+t3] - xs = [0,500] - zs = [0,500] - - pop_params=oc_utils.add_populations_in_rectangular_layers(net=network, - boundaryDict=boundaries, - popDict=popDict, - x_vector=xs, - z_vector=zs) - - presynaptic_population = pop_params['CG3D_L23PyrRS']['PopObj'] - - postsynaptic_population= pop_params['CG3D_L23PyrFRB']['PopObj'] - - synapse_list=['AMPA','NMDA'] - - projection_array=[] - - for synapse_element in range(0,len(synapse_list) ): - - proj = neuroml.Projection(id="Proj%d"%synapse_element, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id, - synapse=synapse_list[synapse_element]) - - projection_array.append(proj) - - - parsed_target_dict={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]}} - - proj_array=oc_build.add_chem_spatial_projection(net=network, - proj_array=projection_array, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - targeting_mode='convergent', - synapse_list=synapse_list, - pre_seg_target_dict=None, - post_seg_target_dict=parsed_target_dict, - subset_dict={'basal_obl_dends':50}, - distance_rule='- 17.45 + 18.36 / (math.exp((r-267.)/39.) +1)', - pre_cell_positions=pop_params['CG3D_L23PyrRS']['Positions'], - post_cell_positions=pop_params['CG3D_L23PyrFRB']['Positions'], - delays_dict={'NMDA':5}, - weights_dict={'AMPA':1.5,'NMDA':2}) - - self.assertEqual(len(network.projections),2) - - self.assertEqual(len(proj_array[0].connection_wds),len(network.projections[0].connection_wds) ) - - self.assertTrue(len(proj_array[0].connection_wds) <= 50) - - pre_cell_AMPA_strings=[] - - post_cell_AMPA_strings=[] - - pre_cell_NMDA_strings=[] - - post_cell_NMDA_strings=[] - - post_cell_ids=[] - - pre_cell_ids=[] - - for conn_ind in range(0,len(proj_array[0].connection_wds) ): - - post_cell_ids.append(proj_array[0].connection_wds[conn_ind].post_cell_id) - - pre_cell_ids.append(proj_array[0].connection_wds[conn_ind].pre_cell_id) - - pre_cell_AMPA_strings.append(proj_array[0].connection_wds[conn_ind].pre_cell_id) - - post_cell_AMPA_strings.append(proj_array[0].connection_wds[conn_ind].post_cell_id) - - pre_cell_NMDA_strings.append(proj_array[1].connection_wds[conn_ind].pre_cell_id) - - post_cell_NMDA_strings.append(proj_array[1].connection_wds[conn_ind].post_cell_id) - - self.assertEqual(proj_array[0].connection_wds[conn_ind].post_cell_id,proj_array[1].connection_wds[conn_ind].post_cell_id) - - self.assertEqual(proj_array[0].connection_wds[conn_ind].pre_cell_id,proj_array[1].connection_wds[conn_ind].pre_cell_id) - - self.assertTrue( len(set(post_cell_ids)) ==1) - - self.assertTrue(len(proj_array[0].connection_wds) == len(set(pre_cell_ids) )) - - self.assertEqual(len(set(pre_cell_AMPA_strings)),len(set(pre_cell_NMDA_strings)) ) - - self.assertEqual(len(set(post_cell_AMPA_strings)),len(set(post_cell_NMDA_strings)) ) - - self.assertEqual(len(proj_array[0].connection_wds),len(proj_array[1].connection_wds) ) - - self.assertEqual(proj_array[0].synapse,'AMPA') - - self.assertEqual(proj_array[1].synapse,'NMDA') - - ######## Test 2 divergent - network = neuroml.Network(id='Net0') - - popDict={} - popDict['CG3D_L23PyrRS'] = (1, 'L23','Test','multi',None) - popDict['CG3D_L23PyrFRB']= (1000,'L23','Test2','multi',None) - t1=-0 - t2=-250 - t3=-250 - boundaries={} - boundaries['L1']=[0,t1] - boundaries['L23']=[t1,t1+t2+t3] - xs = [0,500] - zs = [0,500] - - pop_params=oc_utils.add_populations_in_rectangular_layers(net=network, - boundaryDict=boundaries, - popDict=popDict, - x_vector=xs, - z_vector=zs) - - presynaptic_population = pop_params['CG3D_L23PyrRS']['PopObj'] - - postsynaptic_population= pop_params['CG3D_L23PyrFRB']['PopObj'] - - synapse_list=['AMPA','NMDA'] - - projection_array=[] - - for synapse_element in range(0,len(synapse_list) ): - - proj = neuroml.Projection(id="Proj%d"%synapse_element, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id, - synapse=synapse_list[synapse_element]) - - projection_array.append(proj) - - - parsed_target_dict={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]}} - - proj_array=oc_build.add_chem_spatial_projection(net=network, - proj_array=projection_array, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - targeting_mode='divergent', - synapse_list=synapse_list, - pre_seg_target_dict=None, - post_seg_target_dict=parsed_target_dict, - subset_dict={'basal_obl_dends':50}, - distance_rule='- 17.45 + 18.36 / (math.exp((r-267.)/39.) +1)', - pre_cell_positions=pop_params['CG3D_L23PyrRS']['Positions'], - post_cell_positions=pop_params['CG3D_L23PyrFRB']['Positions'], - delays_dict={'NMDA':5}, - weights_dict={'AMPA':1.5,'NMDA':2}) - - self.assertEqual(len(network.projections),2) - - self.assertEqual(len(proj_array[0].connection_wds),len(network.projections[0].connection_wds) ) - - self.assertTrue(len(proj_array[0].connection_wds) <= 50) - - pre_cell_AMPA_strings=[] - - post_cell_AMPA_strings=[] - - pre_cell_NMDA_strings=[] - - post_cell_NMDA_strings=[] - - post_cell_ids=[] - - pre_cell_ids=[] - - self.assertTrue(network.projections[0].synapse == 'AMPA') - - self.assertTrue(network.projections[1].synapse == 'NMDA') - - for conn_ind in range(0,len(proj_array[0].connection_wds) ): - - pre_cell_AMPA_strings.append(proj_array[0].connection_wds[conn_ind].pre_cell_id) - - post_cell_AMPA_strings.append(proj_array[0].connection_wds[conn_ind].post_cell_id) - - pre_cell_NMDA_strings.append(proj_array[1].connection_wds[conn_ind].pre_cell_id) - - post_cell_NMDA_strings.append(proj_array[1].connection_wds[conn_ind].post_cell_id) - - self.assertEqual(proj_array[0].connection_wds[conn_ind].post_cell_id,proj_array[1].connection_wds[conn_ind].post_cell_id) - - self.assertEqual(proj_array[0].connection_wds[conn_ind].pre_cell_id,proj_array[1].connection_wds[conn_ind].pre_cell_id) - - self.assertTrue( len(set(pre_cell_AMPA_strings)) ==1) - - self.assertTrue(len(proj_array[0].connection_wds) == len(set(post_cell_AMPA_strings) )) - - self.assertEqual(len(set(pre_cell_AMPA_strings)),len(set(pre_cell_NMDA_strings)) ) - - self.assertEqual(len(set(post_cell_AMPA_strings)),len(set(post_cell_NMDA_strings)) ) - - self.assertEqual(len(proj_array[0].connection_wds),len(proj_array[1].connection_wds) ) - - self.assertEqual(proj_array[0].synapse,'AMPA') - - self.assertEqual(proj_array[1].synapse,'NMDA') - - def test_add_elect_projection(self): - ######## Test 1 convergent - network = neuroml.Network(id='Net0') - presynaptic_population = neuroml.Population(id="Pop0", component="L23PyrRS", type="populationList", size=1) - postsynaptic_population=neuroml.Population(id="Pop0", component="L23PyrFRB", type="populationList", size=1) - - synapse_list=['Elect_1','Elect_2'] - - projection_array=[] - - for synapse_element in range(0,len(synapse_list) ): - - proj = neuroml.ElectricalProjection(id="Proj%d"%synapse_element, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id) - - projection_array.append(proj) - - parsed_target_dict={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]}} - - proj_array=oc_build._add_elect_projection(net=network, - proj_array=projection_array, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - targeting_mode='convergent', - synapse_list=synapse_list, - pre_seg_target_dict=None, - post_seg_target_dict=parsed_target_dict, - subset_dict={'basal_obl_dends':2.5}) - - self.assertEqual(len(network.electrical_projections),0) - - self.assertEqual(len(proj_array[0].electrical_connection_instance_ws),0) - - self.assertEqual(len(proj_array[1].electrical_connection_instance_ws),len(proj_array[0].electrical_connection_instance_ws)) - - ######## Test 2 convergent - network = neuroml.Network(id='Net0') - presynaptic_population = neuroml.Population(id="Pop0", component="L23PyrRS", type="populationList", size=2) - postsynaptic_population=neuroml.Population(id="Pop0", component="L23PyrFRB", type="populationList", size=1) - - synapse_list=['Elect_1','Elect_2'] - - projection_array=[] - - for synapse_element in range(0,len(synapse_list) ): - - proj = neuroml.ElectricalProjection(id="Proj%d"%synapse_element, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id) - - projection_array.append(proj) - - parsed_target_dict={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]}} - - - proj_array=oc_build._add_elect_projection(net=network, - proj_array=projection_array, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - targeting_mode='convergent', - synapse_list=synapse_list, - pre_seg_target_dict=None, - post_seg_target_dict=parsed_target_dict, - subset_dict={'basal_obl_dends':2.5}) - - - self.assertEqual(len(network.electrical_projections),2) - - self.assertEqual(len(proj_array[0].electrical_connection_instance_ws),len(network.electrical_projections[0].electrical_connection_instance_ws) ) - - self.assertEqual(len(proj_array[1].electrical_connection_instance_ws),len(proj_array[0].electrical_connection_instance_ws)) - - self.assertTrue(len(proj_array[0].electrical_connection_instance_ws)==2 or len(proj_array[0].electrical_connection_instance_ws)==3 ) - - self.assertEqual(network.electrical_projections[0].id,proj_array[0].id) - - self.assertEqual(network.electrical_projections[1].id,proj_array[1].id) - - self.assertEqual(network.electrical_projections[0].presynaptic_population,proj_array[0].presynaptic_population) - - self.assertEqual(network.electrical_projections[1].presynaptic_population,proj_array[1].presynaptic_population) - - self.assertEqual(network.electrical_projections[0].postsynaptic_population,proj_array[0].postsynaptic_population) - - self.assertEqual(network.electrical_projections[1].postsynaptic_population,proj_array[1].postsynaptic_population) - - ######## Test 3 convergent - network = neuroml.Network(id='Net0') - presynaptic_population = neuroml.Population(id="Pop0", component="L23PyrRS", type="populationList", size=1) - postsynaptic_population=neuroml.Population(id="Pop1", component="L23PyrFRB", type="populationList", size=1) - - synapse_list=['Elect_1','Elect_2'] - - projection_array=[] - - for synapse_element in range(0,len(synapse_list) ): - - proj = neuroml.ElectricalProjection(id="Proj%d"%synapse_element, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id) - - projection_array.append(proj) - - parsed_target_dict={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]}} - - - proj_array=oc_build._add_elect_projection(net=network, - proj_array=projection_array, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - targeting_mode='convergent', - synapse_list=synapse_list, - pre_seg_target_dict=None, - post_seg_target_dict=parsed_target_dict, - subset_dict={'basal_obl_dends':0.4}) - - self.assertEqual(len(proj_array[1].electrical_connection_instance_ws),len(proj_array[0].electrical_connection_instance_ws)) - - self.assertTrue(len(proj_array[0].electrical_connection_instance_ws)==0 or len(proj_array[0].electrical_connection_instance_ws)==1 ) - - if len(proj_array[0].electrical_connection_instance_ws)==1: - - self.assertEqual(len(network.electrical_projections),2) - - self.assertEqual(len(proj_array[0].electrical_connection_instance_ws),len(network.electrical_projections[0].electrical_connection_instance_ws) ) - - if len(proj_array[0].electrical_connection_instance_ws)==0: - - self.assertEqual(len(network.electrical_projections),0) - - ######## Test 4 divergent and subset_dict is simply a number ( < 1), instead of dictionary - network = neuroml.Network(id='Net0') - presynaptic_population = neuroml.Population(id="Pop0", component="L23PyrRS", type="populationList", size=1) - postsynaptic_population=neuroml.Population(id="Pop1", component="L23PyrFRB", type="populationList", size=50) - - synapse_list=['Elect_1','Elect_2'] - - projection_array=[] - - for synapse_element in range(0,len(synapse_list) ): - - proj = neuroml.ElectricalProjection(id="Proj%d"%synapse_element, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id) - - projection_array.append(proj) - - parsed_target_dict={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]}} - - proj_array=oc_build._add_elect_projection(net=network, - proj_array=projection_array, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - targeting_mode='convergent', - synapse_list=synapse_list, - pre_seg_target_dict=None, - post_seg_target_dict=parsed_target_dict, - subset_dict=0.4) - - self.assertEqual(len(proj_array[1].electrical_connection_instance_ws),len(proj_array[0].electrical_connection_instance_ws)) - - if len(proj_array[0].electrical_connection_instance_ws)==1: - - self.assertEqual(len(network.electrical_projections),2) - - self.assertEqual(len(proj_array[0].electrical_connection_instance_ws),len(network.electrical_projections[0].electrical_connection_instance_ws) ) - - if len(proj_array[0].electrical_connection_instance_ws)==0: - - self.assertEqual(len(network.electrical_projections),0) - - else: - - len(network.electrical_projections[0].electrical_connection_instance_ws) <= 50 - - for elect_conn_ind in range(0, len(network.electrical_projections[0].electrical_connection_instance_ws) ): - - elect_connection_comp1=proj_array[0].electrical_connection_instance_ws[elect_conn_ind] - - elect_connection_comp2=proj_array[1].electrical_connection_instance_ws[elect_conn_ind] - - self.assertTrue(elect_connection_comp1.pre_cell == elect_connection_comp2.pre_cell) - - self.assertTrue(elect_connection_comp1.post_cell == elect_connection_comp2.post_cell) - - self.assertTrue(elect_connection_comp1.synapse == 'Elect_1') - - self.assertTrue(elect_connection_comp2.synapse == 'Elect_2') - - ######## Test 5 divergent and subset_dict is simply a number ( >= 1), instead of dictionary - - network = neuroml.Network(id='Net0') - presynaptic_population = neuroml.Population(id="Pop0", component="L23PyrRS", type="populationList", size=1) - postsynaptic_population=neuroml.Population(id="Pop1", component="L23PyrFRB", type="populationList", size=50) - - synapse_list=['Elect_1','Elect_2'] - - projection_array=[] - - for synapse_element in range(0,len(synapse_list) ): - - proj = neuroml.ElectricalProjection(id="Proj%d"%synapse_element, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id) - - projection_array.append(proj) - - parsed_target_dict={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]}} - - proj_array=oc_build._add_elect_projection(net=network, - proj_array=projection_array, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - targeting_mode='convergent', - synapse_list=synapse_list, - pre_seg_target_dict=None, - post_seg_target_dict=parsed_target_dict, - subset_dict=1) - - self.assertEqual(len(proj_array[1].electrical_connection_instance_ws),len(proj_array[0].electrical_connection_instance_ws)) - - if len(proj_array[0].electrical_connection_instance_ws)==1: - - self.assertEqual(len(network.electrical_projections),2) - - self.assertEqual(len(proj_array[0].electrical_connection_instance_ws),len(network.electrical_projections[0].electrical_connection_instance_ws) ) - - len(network.electrical_projections[0].electrical_connection_instance_ws) == 50 - - for elect_conn_ind in range(0, len(network.electrical_projections[0].electrical_connection_instance_ws) ): - - elect_connection_comp1=proj_array[0].electrical_connection_instance_ws[elect_conn_ind] - - elect_connection_comp2=proj_array[1].electrical_connection_instance_ws[elect_conn_ind] - - self.assertTrue(elect_connection_comp1.pre_cell == elect_connection_comp2.pre_cell) - - self.assertTrue(elect_connection_comp1.post_cell == elect_connection_comp2.post_cell) - - self.assertTrue(elect_connection_comp1.synapse == 'Elect_1') - - self.assertTrue(elect_connection_comp2.synapse == 'Elect_2') - - ######## Test 5 divergent and subset_dict is simply a number ( >= 1), instead of dictionary - - network = neuroml.Network(id='Net0') - presynaptic_population = neuroml.Population(id="Pop0", component="L23PyrRS", type="populationList", size=1) - postsynaptic_population=neuroml.Population(id="Pop1", component="L23PyrFRB", type="populationList", size=50) - - synapse_list=['Elect_1','Elect_2'] - - projection_array=[] - - for synapse_element in range(0,len(synapse_list) ): - - proj = neuroml.ElectricalProjection(id="Proj%d"%synapse_element, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id) - - projection_array.append(proj) - - parsed_target_dict={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]}} - - proj_array=oc_build._add_elect_projection(net=network, - proj_array=projection_array, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - targeting_mode='convergent', - synapse_list=synapse_list, - pre_seg_target_dict=None, - post_seg_target_dict=parsed_target_dict, - subset_dict=2) - - self.assertEqual(len(proj_array[1].electrical_connection_instance_ws),len(proj_array[0].electrical_connection_instance_ws)) - - if len(proj_array[0].electrical_connection_instance_ws)==1: - - self.assertEqual(len(network.electrical_projections),2) - - self.assertEqual(len(proj_array[0].electrical_connection_instance_ws),len(network.electrical_projections[0].electrical_connection_instance_ws) ) - - len(network.electrical_projections[0].electrical_connection_instance_ws) == 100 - - for elect_conn_ind in range(0, len(network.electrical_projections[0].electrical_connection_instance_ws) ): - - elect_connection_comp1=proj_array[0].electrical_connection_instance_ws[elect_conn_ind] - - elect_connection_comp2=proj_array[1].electrical_connection_instance_ws[elect_conn_ind] - - self.assertTrue(elect_connection_comp1.pre_cell == elect_connection_comp2.pre_cell) - - self.assertTrue(elect_connection_comp1.post_cell == elect_connection_comp2.post_cell) - - self.assertTrue(elect_connection_comp1.synapse == 'Elect_1') - - self.assertTrue(elect_connection_comp2.synapse == 'Elect_2') - - def test_add_elect_spatial_projection(self): - - ######## Test 1 convergent - network = neuroml.Network(id='Net0') - - popDict={} - popDict['CG3D_L23PyrRS'] = (1, 'L23','Test','multi',None) - popDict['CG3D_L23PyrFRB']= (1,'L23','Test2','multi',None) - t1=-0 - t2=-250 - t3=-250 - boundaries={} - boundaries['L1']=[0,t1] - boundaries['L23']=[t1,t1+t2+t3] - xs = [0,500] - zs = [0,500] - - pop_params=oc_utils.add_populations_in_rectangular_layers(net=network, - boundaryDict=boundaries, - popDict=popDict, - x_vector=xs, - z_vector=zs) - - presynaptic_population = pop_params['CG3D_L23PyrRS']['PopObj'] - - postsynaptic_population= pop_params['CG3D_L23PyrFRB']['PopObj'] - - synapse_list=['Elect_1','Elect_2'] - - projection_array=[] - - for synapse_element in range(0,len(synapse_list) ): - - proj = neuroml.ElectricalProjection(id="Proj%d"%synapse_element, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id) - - projection_array.append(proj) - - parsed_target_dict={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]}} - - proj_array=oc_build.add_elect_spatial_projection(net=network, - proj_array=projection_array, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - targeting_mode='convergent', - synapse_list=synapse_list, - pre_seg_target_dict=None, - post_seg_target_dict=parsed_target_dict, - subset_dict={'basal_obl_dends':2.5}, - distance_rule='- 17.45 + 18.36 / (math.exp((r-267.)/39.) +1)', - pre_cell_positions=pop_params['CG3D_L23PyrRS']['Positions'], - post_cell_positions=pop_params['CG3D_L23PyrFRB']['Positions']) - - self.assertTrue(len(network.electrical_projections) >= 0 ) - - self.assertTrue(len(proj_array[0].electrical_connection_instance_ws) >= 0) - - self.assertEqual(len(proj_array[1].electrical_connection_instance_ws),len(proj_array[0].electrical_connection_instance_ws)) - - ######## Test 2 convergent - network = neuroml.Network(id='Net0') - - popDict={} - popDict['CG3D_L23PyrRS'] = (500, 'L23','Test','multi',None) - popDict['CG3D_L23PyrFRB']= (1,'L23','Test2','multi',None) - t1=-0 - t2=-250 - t3=-250 - boundaries={} - boundaries['L1']=[0,t1] - boundaries['L23']=[t1,t1+t2+t3] - xs = [0,500] - zs = [0,500] - - pop_params=oc_utils.add_populations_in_rectangular_layers(net=network, - boundaryDict=boundaries, - popDict=popDict, - x_vector=xs, - z_vector=zs) - - presynaptic_population = pop_params['CG3D_L23PyrRS']['PopObj'] - - postsynaptic_population= pop_params['CG3D_L23PyrFRB']['PopObj'] - - synapse_list=['Elect_1','Elect_2'] - - projection_array=[] - - for synapse_element in range(0,len(synapse_list) ): - - proj = neuroml.ElectricalProjection(id="Proj%d"%synapse_element, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id) - - projection_array.append(proj) - - parsed_target_dict={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]}} - - proj_array=oc_build.add_elect_spatial_projection(net=network, - proj_array=projection_array, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - targeting_mode='convergent', - synapse_list=synapse_list, - pre_seg_target_dict=None, - post_seg_target_dict=parsed_target_dict, - subset_dict={'basal_obl_dends':2.5}, - distance_rule='- 17.45 + 18.36 / (math.exp((r-267.)/39.) +1)', - pre_cell_positions=pop_params['CG3D_L23PyrRS']['Positions'], - post_cell_positions=pop_params['CG3D_L23PyrFRB']['Positions']) - - self.assertEqual(len(network.electrical_projections),2) - - self.assertEqual(len(network.electrical_projections[0].electrical_connection_instance_ws),len(network.electrical_projections[1].electrical_connection_instance_ws) ) - - self.assertEqual(len(proj_array[0].electrical_connection_instance_ws),len(network.electrical_projections[0].electrical_connection_instance_ws) ) - - self.assertEqual(len(proj_array[1].electrical_connection_instance_ws),len(proj_array[0].electrical_connection_instance_ws)) - - self.assertTrue(len(proj_array[0].electrical_connection_instance_ws)==2 or len(proj_array[0].electrical_connection_instance_ws)==3 ) - - self.assertEqual(network.electrical_projections[0].id,proj_array[0].id) - - self.assertEqual(network.electrical_projections[1].id,proj_array[1].id) - - self.assertEqual(network.electrical_projections[0].presynaptic_population,proj_array[0].presynaptic_population) - - self.assertEqual(network.electrical_projections[1].presynaptic_population,proj_array[1].presynaptic_population) - - self.assertEqual(network.electrical_projections[0].postsynaptic_population,proj_array[0].postsynaptic_population) - - self.assertEqual(network.electrical_projections[1].postsynaptic_population,proj_array[1].postsynaptic_population) - - pre_cell_Elect1_strings=[] - - post_cell_Elect1_strings=[] - - pre_cell_Elect2_strings=[] - - post_cell_Elect2_strings=[] - - for conn_ind in range(0,len(network.electrical_projections[0].electrical_connection_instance_ws) ): - - self.assertEqual(network.electrical_projections[0].electrical_connection_instance_ws[conn_ind].synapse,'Elect_1') - - self.assertEqual(network.electrical_projections[1].electrical_connection_instance_ws[conn_ind].synapse,'Elect_2') - - pre_cell_Elect1_strings.append(network.electrical_projections[0].electrical_connection_instance_ws[conn_ind].pre_cell) - - post_cell_Elect1_strings.append(network.electrical_projections[0].electrical_connection_instance_ws[conn_ind].post_cell) - - pre_cell_Elect2_strings.append(network.electrical_projections[1].electrical_connection_instance_ws[conn_ind].pre_cell) - - post_cell_Elect2_strings.append(network.electrical_projections[1].electrical_connection_instance_ws[conn_ind].post_cell) - - self.assertEqual(network.electrical_projections[0].electrical_connection_instance_ws[conn_ind].post_cell, - network.electrical_projections[1].electrical_connection_instance_ws[conn_ind].post_cell) - - self.assertEqual(network.electrical_projections[0].electrical_connection_instance_ws[conn_ind].pre_cell, - network.electrical_projections[1].electrical_connection_instance_ws[conn_ind].pre_cell) - - self.assertTrue( len(set(post_cell_Elect1_strings)) ==1) - - self.assertTrue(len(network.electrical_projections[0].electrical_connection_instance_ws) == len(set(pre_cell_Elect1_strings) )) - - self.assertEqual(len(set(pre_cell_Elect1_strings)),len(set(pre_cell_Elect2_strings)) ) - - self.assertEqual(len(set(post_cell_Elect1_strings)),len(set(post_cell_Elect2_strings)) ) - - ######## Test 3 divergent - network = neuroml.Network(id='Net0') - - popDict={} - popDict['CG3D_L23PyrRS'] = (1, 'L23','Test','multi',None) - popDict['CG3D_L23PyrFRB']= (500,'L23','Test2','multi',None) - t1=-0 - t2=-250 - t3=-250 - boundaries={} - boundaries['L1']=[0,t1] - boundaries['L23']=[t1,t1+t2+t3] - xs = [0,500] - zs = [0,500] - - pop_params=oc_utils.add_populations_in_rectangular_layers(net=network, - boundaryDict=boundaries, - popDict=popDict, - x_vector=xs, - z_vector=zs) - - presynaptic_population = pop_params['CG3D_L23PyrRS']['PopObj'] - - postsynaptic_population= pop_params['CG3D_L23PyrFRB']['PopObj'] - - synapse_list=['Elect_1','Elect_2'] - - projection_array=[] - - for synapse_element in range(0,len(synapse_list) ): - - proj = neuroml.ElectricalProjection(id="Proj%d"%synapse_element, - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id) - - projection_array.append(proj) - - parsed_target_dict={'basal_obl_dends': {'SegList': [16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67], 'LengthDist': [25.0, 50.0, 75.0, 100.0, 125.0, 150.0, 175.0, 200.0, 225.0000012807632, 249.99999701896448, 274.9999982997277, 299.9999413836009, 324.99994266436414, 349.99992870308233, 374.99992998384556, 399.9999756051272, 424.9999756051272, 449.9999756051272, 474.9999756051272, 499.9999756051272, 524.9999756051272, 549.9999756051272, 574.9999756051272, 599.9999756051272, 624.9999756051272, 649.9999756051272, 674.9999756051272, 699.9999756051272, 724.9999756051272, 749.9999756051272, 774.9999756051272, 799.9999756051272, 824.9999741146091, 849.9995943443294, 874.9996247235468, 899.9999308454469, 924.9999175769843, 950.0002631896537, 975.0002596206808, 1000.0001576712268, 1025.0001576712268, 1050.0001576712268, 1075.0001576712268, 1100.0001576712268, 1125.0001576712268, 1150.0001576712268, 1175.0001576712268, 1200.0001576712268, 1225.0001576712268, 1250.0001576712268, 1275.0001576712268, 1300.0001576712268, 1325.0001576712268, 1350.0001576712268, 1375.0001576712268, 1400.0001576712268, 1425.0010159713997, 1450.0009008583847, 1475.0002938437874, 1500.000601351312, 1525.0002368231228, 1549.9998501247107, 1575.0001714886703, 1599.9998485298981, 1624.9998485298981, 1649.9998485298981, 1674.9998485298981, 1699.9998485298981, 1724.9998485298981, 1749.9998485298981, 1774.9998485298981, 1799.9998485298981]}} - - proj_array=oc_build.add_elect_spatial_projection(net=network, - proj_array=projection_array, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - targeting_mode='divergent', - synapse_list=synapse_list, - pre_seg_target_dict=None, - post_seg_target_dict=parsed_target_dict, - subset_dict={'basal_obl_dends':2.5}, - distance_rule='- 17.45 + 18.36 / (math.exp((r-267.)/39.) +1)', - pre_cell_positions=pop_params['CG3D_L23PyrRS']['Positions'], - post_cell_positions=pop_params['CG3D_L23PyrFRB']['Positions']) - - self.assertEqual(len(network.electrical_projections),2) - - self.assertEqual(len(network.electrical_projections[0].electrical_connection_instance_ws),len(network.electrical_projections[1].electrical_connection_instance_ws) ) - - self.assertEqual(len(proj_array[0].electrical_connection_instance_ws),len(network.electrical_projections[0].electrical_connection_instance_ws) ) - - self.assertEqual(len(proj_array[1].electrical_connection_instance_ws),len(proj_array[0].electrical_connection_instance_ws)) - - self.assertTrue(len(proj_array[0].electrical_connection_instance_ws)==2 or len(proj_array[0].electrical_connection_instance_ws)==3 ) - - self.assertEqual(network.electrical_projections[0].id,proj_array[0].id) - - self.assertEqual(network.electrical_projections[1].id,proj_array[1].id) - - self.assertEqual(network.electrical_projections[0].presynaptic_population,proj_array[0].presynaptic_population) - - self.assertEqual(network.electrical_projections[1].presynaptic_population,proj_array[1].presynaptic_population) - - self.assertEqual(network.electrical_projections[0].postsynaptic_population,proj_array[0].postsynaptic_population) - - self.assertEqual(network.electrical_projections[1].postsynaptic_population,proj_array[1].postsynaptic_population) - - pre_cell_Elect1_strings=[] - - post_cell_Elect1_strings=[] - - pre_cell_Elect2_strings=[] - - post_cell_Elect2_strings=[] - - for conn_ind in range(0,len(network.electrical_projections[0].electrical_connection_instance_ws) ): - - self.assertEqual(network.electrical_projections[0].electrical_connection_instance_ws[conn_ind].synapse,'Elect_1') - - self.assertEqual(network.electrical_projections[1].electrical_connection_instance_ws[conn_ind].synapse,'Elect_2') - - pre_cell_Elect1_strings.append(network.electrical_projections[0].electrical_connection_instance_ws[conn_ind].pre_cell) - - post_cell_Elect1_strings.append(network.electrical_projections[0].electrical_connection_instance_ws[conn_ind].post_cell) - - pre_cell_Elect2_strings.append(network.electrical_projections[1].electrical_connection_instance_ws[conn_ind].pre_cell) - - post_cell_Elect2_strings.append(network.electrical_projections[1].electrical_connection_instance_ws[conn_ind].post_cell) - - self.assertEqual(network.electrical_projections[0].electrical_connection_instance_ws[conn_ind].post_cell, - network.electrical_projections[1].electrical_connection_instance_ws[conn_ind].post_cell) - - self.assertEqual(network.electrical_projections[0].electrical_connection_instance_ws[conn_ind].pre_cell, - network.electrical_projections[1].electrical_connection_instance_ws[conn_ind].pre_cell) - - self.assertTrue( len(set(pre_cell_Elect1_strings)) ==1) - - self.assertTrue(len(network.electrical_projections[0].electrical_connection_instance_ws) == len(set(post_cell_Elect1_strings) )) - - self.assertEqual(len(set(pre_cell_Elect1_strings)),len(set(pre_cell_Elect2_strings)) ) - - self.assertEqual(len(set(post_cell_Elect1_strings)),len(set(post_cell_Elect2_strings)) ) - - def test_add_probabilistic_projection_list(self): - - random.seed(1234) - - ######## Test 1 convergent - network = neuroml.Network(id='Net0') - presynaptic_population = neuroml.Population(id="Pop0", component="L23PyrRS", type="populationList", size=50) - postsynaptic_population=neuroml.Population(id="Pop0", component="L23PyrFRB", type="populationList", size=50) - - synapse_list=['Syn_1','Syn_2'] - - returned_projs=oc_build.add_probabilistic_projection_list(net=network, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - synapse_list=synapse_list, - connection_probability=0.5, - delay=0.05, - weight=2, - std_delay=None, - std_weight=None) - - - self.assertEqual(len(network.projections),2) - self.assertEqual(len(network.projections[0].connection_wds), len(network.projections[1].connection_wds) ) - - for proj_ind in range(0,len(network.projections) ): - - self.assertTrue( 'Syn_1' in network.projections[proj_ind].id or 'Syn_2' in network.projections[proj_ind].id ) - - self.assertTrue( network.projections[proj_ind].synapse == 'Syn_1' or network.projections[proj_ind].synapse == 'Syn_2' ) - - for conn_ind in range(0,len(network.projections[proj_ind].connection_wds)): - - connection=network.projections[proj_ind].connection_wds[conn_ind] - - self.assertTrue( connection.get_delay_in_ms() == 0.05) - - self.assertTrue( 2==connection.weight) - - ######## Test 2 convergent connection_probability =0 - - network.projections=[] - - returned_projs=oc_build.add_probabilistic_projection_list(net=network, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - synapse_list=synapse_list, - connection_probability=0, - delay=0.05, - weight=2, - std_delay=None, - std_weight=None) - - - self.assertEqual(len(network.projections),0) - - self.assertTrue( returned_projs == None) - - ######## Test 3 delay list: - - returned_projs=oc_build.add_probabilistic_projection_list(net=network, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - synapse_list=synapse_list, - connection_probability=0.5, - delay=[0.05,0.01], - weight=2, - std_delay=None, - std_weight=None) - - - self.assertEqual(len(network.projections),2) - - self.assertEqual(len(network.projections[0].connection_wds), len(network.projections[1].connection_wds) ) - - for proj_ind in range(0,len(network.projections) ): - - self.assertTrue( 'Syn_1' in network.projections[proj_ind].id or 'Syn_2' in network.projections[proj_ind].id ) - - self.assertTrue( network.projections[proj_ind].synapse == 'Syn_1' or network.projections[proj_ind].synapse == 'Syn_2' ) - - for conn_ind in range(0,len(network.projections[proj_ind].connection_wds)): - - connection=network.projections[proj_ind].connection_wds[conn_ind] - - if 'Syn_1' in network.projections[proj_ind].id: - - self.assertTrue( connection.get_delay_in_ms() == 0.05 ) - - if 'Syn_2' in network.projections[proj_ind].id: - - self.assertTrue( connection.get_delay_in_ms() == 0.01 ) - - self.assertTrue( 2==connection.weight) - - ######## Test 3 weight list: - - network.projections=[] - - returned_projs=oc_build.add_probabilistic_projection_list(net=network, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - synapse_list=synapse_list, - connection_probability=0.5, - delay=0.05, - weight=[2,2.5], - std_delay=None, - std_weight=None) - - - self.assertEqual(len(network.projections),2) - - self.assertEqual(len(network.projections[0].connection_wds), len(network.projections[1].connection_wds) ) - - for proj_ind in range(0,len(network.projections) ): - - self.assertTrue( 'Syn_1' in network.projections[proj_ind].id or 'Syn_2' in network.projections[proj_ind].id ) - - self.assertTrue( network.projections[proj_ind].synapse == 'Syn_1' or network.projections[proj_ind].synapse == 'Syn_2' ) - - for conn_ind in range(0,len(network.projections[proj_ind].connection_wds)): - - connection=network.projections[proj_ind].connection_wds[conn_ind] - - if 'Syn_1' in network.projections[proj_ind].id: - - self.assertTrue( 2==connection.weight ) - - if 'Syn_2' in network.projections[proj_ind].id: - - self.assertTrue( 2.5==connection.weight ) - - self.assertTrue( connection.get_delay_in_ms() == 0.05 ) - - ######## Test 3 std weight: - - network.projections=[] - - returned_projs=oc_build.add_probabilistic_projection_list(net=network, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - synapse_list=synapse_list, - connection_probability=0.5, - delay=0.05, - weight=[2,2.5], - std_delay=None, - std_weight=0.1) - - - self.assertEqual(len(network.projections),2) - - self.assertEqual(len(network.projections[0].connection_wds), len(network.projections[1].connection_wds) ) - - for proj_ind in range(0,len(network.projections) ): - - self.assertTrue( 'Syn_1' in network.projections[proj_ind].id or 'Syn_2' in network.projections[proj_ind].id ) - - self.assertTrue( network.projections[proj_ind].synapse == 'Syn_1' or network.projections[proj_ind].synapse == 'Syn_2' ) - - for conn_ind in range(0,len(network.projections[proj_ind].connection_wds)): - - connection=network.projections[proj_ind].connection_wds[conn_ind] - - if 'Syn_1' in network.projections[proj_ind].id: - - self.assertTrue( connection.weight !=2 and connection.weight>0 and connection.weight < 5) - - if 'Syn_2' in network.projections[proj_ind].id: - - self.assertTrue( connection.weight != 2.5 and connection.weight>0 and connection.weight < 5) - - self.assertTrue( connection.get_delay_in_ms() == 0.05) - - ######## Test 4 std delay: - - network.projections=[] - - returned_projs=oc_build.add_probabilistic_projection_list(net=network, - presynaptic_population=presynaptic_population, - postsynaptic_population=postsynaptic_population, - synapse_list=synapse_list, - connection_probability=0.5, - delay=[5,1], - weight=[2,2.5], - std_delay=[0.01,0.001], - std_weight=None) - - - self.assertEqual(len(network.projections),2) - - self.assertEqual(len(network.projections[0].connection_wds), len(network.projections[1].connection_wds) ) - - for proj_ind in range(0,len(network.projections) ): - - self.assertTrue( 'Syn_1' in network.projections[proj_ind].id or 'Syn_2' in network.projections[proj_ind].id ) - - self.assertTrue( network.projections[proj_ind].synapse == 'Syn_1' or network.projections[proj_ind].synapse == 'Syn_2' ) - - for conn_ind in range(0,len(network.projections[proj_ind].connection_wds)): - - connection=network.projections[proj_ind].connection_wds[conn_ind] - - if 'Syn_1' in network.projections[proj_ind].id: - - self.assertTrue( 2==connection.weight ) - - self.assertTrue( connection.get_delay_in_ms() != 5 and connection.get_delay_in_ms()>3 and connection.get_delay_in_ms()< 7) - - if 'Syn_2' in network.projections[proj_ind].id: - - self.assertTrue( 2.5 ==connection.weight ) - - self.assertTrue( connection.get_delay_in_ms() != 1 and connection.get_delay_in_ms()>0 and connection.get_delay_in_ms()< 2) - - - - - - - - - - - - + def test_add_targeted_projection_by_dicts(self): + ######## Test 1 convergent + network = neuroml.Network(id="Net0") + presynaptic_population = neuroml.Population( + id="Pop0", component="L23PyrRS", type="populationList", size=1 + ) + postsynaptic_population = neuroml.Population( + id="Pop1", component="L23PyrFRB", type="populationList", size=1 + ) + + synapse_list = ["AMPA", "NMDA"] + + projection_array = [] + + for synapse_element in range(0, len(synapse_list)): + proj = neuroml.Projection( + id="Proj%d" % synapse_element, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + synapse=synapse_list[synapse_element], + ) + + projection_array.append(proj) + + parsed_target_dict = { + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + } + } + + proj_array = oc_build.add_targeted_projection_by_dicts( + net=network, + proj_array=projection_array, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + targeting_mode="convergent", + synapse_list=synapse_list, + pre_seg_target_dict=None, + post_seg_target_dict=parsed_target_dict, + subset_dict={"basal_obl_dends": 50}, + delays_dict={"NMDA": 5}, + weights_dict={"AMPA": 1.5, "NMDA": 2}, + ) + + self.assertEqual(len(network.projections), 2) + + self.assertEqual( + len(proj_array[0].connection_wds), + len(network.projections[0].connection_wds), + ) + + self.assertEqual(len(proj_array[0].connection_wds), 50) + + pre_cell_AMPA_strings = [] + + post_cell_AMPA_strings = [] + + pre_cell_NMDA_strings = [] + + post_cell_NMDA_strings = [] + + for conn_ind in range(0, 50): + pre_cell_AMPA_strings.append( + proj_array[0].connection_wds[conn_ind].pre_cell_id + ) + + post_cell_AMPA_strings.append( + proj_array[0].connection_wds[conn_ind].post_cell_id + ) + + pre_cell_NMDA_strings.append( + proj_array[1].connection_wds[conn_ind].pre_cell_id + ) + + post_cell_NMDA_strings.append( + proj_array[1].connection_wds[conn_ind].post_cell_id + ) + + self.assertEqual(len(set(pre_cell_AMPA_strings)), 1) + + self.assertEqual( + len(set(pre_cell_AMPA_strings)), len(set(pre_cell_NMDA_strings)) + ) + + self.assertEqual(len(set(post_cell_AMPA_strings)), 1) + + self.assertEqual( + len(set(post_cell_AMPA_strings)), len(set(post_cell_NMDA_strings)) + ) + + self.assertEqual( + len(proj_array[0].connection_wds), len(proj_array[1].connection_wds) + ) + + self.assertEqual(proj_array[0].synapse, "AMPA") + + self.assertEqual(proj_array[1].synapse, "NMDA") + + ######## Test 2 convergent + network = neuroml.Network(id="Net0") + presynaptic_population = neuroml.Population( + id="Pop0", component="L23PyrRS", type="populationList", size=1 + ) + postsynaptic_population = neuroml.Population( + id="Pop0", component="L23PyrRS", type="populationList", size=1 + ) + + synapse_list = ["AMPA", "NMDA"] + + projection_array = [] + + for synapse_element in range(0, len(synapse_list)): + proj = neuroml.Projection( + id="Proj%d" % synapse_element, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + synapse=synapse_list[synapse_element], + ) + + projection_array.append(proj) + + parsed_target_dict = { + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + } + } + + proj_array = oc_build.add_targeted_projection_by_dicts( + net=network, + proj_array=projection_array, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + targeting_mode="convergent", + synapse_list=synapse_list, + pre_seg_target_dict=None, + post_seg_target_dict=parsed_target_dict, + subset_dict={"basal_obl_dends": 50}, + delays_dict={"NMDA": 5}, + weights_dict={"AMPA": 1.5, "NMDA": 2}, + ) + + self.assertEqual(len(proj_array[0].connection_wds), 0) + + self.assertEqual( + len(proj_array[0].connection_wds), len(proj_array[1].connection_wds) + ) + + self.assertEqual(proj_array[0].synapse, "AMPA") + + self.assertEqual(proj_array[1].synapse, "NMDA") + + self.assertEqual(len(network.projections), 0) + + ######## Test 3 convergent + network = neuroml.Network(id="Net0") + presynaptic_population = neuroml.Population( + id="Pop0", component="L23PyrRS", type="populationList", size=50 + ) + postsynaptic_population = neuroml.Population( + id="Pop1", component="L23PyrFRB", type="populationList", size=2 + ) + + synapse_list = ["AMPA", "NMDA"] + + projection_array = [] + + for synapse_element in range(0, len(synapse_list)): + proj = neuroml.Projection( + id="Proj%d" % synapse_element, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + synapse=synapse_list[synapse_element], + ) + + projection_array.append(proj) + + parsed_target_dict = { + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + } + } + + proj_array = oc_build.add_targeted_projection_by_dicts( + net=network, + proj_array=projection_array, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + targeting_mode="convergent", + synapse_list=synapse_list, + pre_seg_target_dict=None, + post_seg_target_dict=parsed_target_dict, + subset_dict={"basal_obl_dends": 50}, + delays_dict={"NMDA": 5}, + weights_dict={"AMPA": 1.5, "NMDA": 2}, + ) + + self.assertEqual(len(network.projections), 2) + + self.assertEqual( + len(network.projections[0].connection_wds), + len(proj_array[0].connection_wds), + ) + + self.assertEqual(len(proj_array[0].connection_wds), 100) + + self.assertEqual( + len(proj_array[0].connection_wds), len(proj_array[1].connection_wds) + ) + + self.assertEqual(proj_array[0].synapse, "AMPA") + + self.assertEqual(proj_array[1].synapse, "NMDA") + + pre_cell_AMPA_strings = [] + + post_cell_AMPA_strings = [] + + pre_cell_NMDA_strings = [] + + post_cell_NMDA_strings = [] + + for conn_ind in range(0, 100): + pre_cell_AMPA_strings.append( + proj_array[0].connection_wds[conn_ind].pre_cell_id + ) + + post_cell_AMPA_strings.append( + proj_array[0].connection_wds[conn_ind].post_cell_id + ) + + pre_cell_NMDA_strings.append( + proj_array[1].connection_wds[conn_ind].pre_cell_id + ) + + post_cell_NMDA_strings.append( + proj_array[1].connection_wds[conn_ind].post_cell_id + ) + + self.assertEqual( + proj_array[0].connection_wds[conn_ind].pre_cell_id, + proj_array[1].connection_wds[conn_ind].pre_cell_id, + ) + + self.assertEqual( + proj_array[0].connection_wds[conn_ind].post_cell_id, + proj_array[1].connection_wds[conn_ind].post_cell_id, + ) + + self.assertEqual( + proj_array[0].connection_wds[conn_ind].post_segment_id, + proj_array[1].connection_wds[conn_ind].post_segment_id, + ) + + self.assertEqual( + proj_array[0].connection_wds[conn_ind].pre_segment_id, + proj_array[1].connection_wds[conn_ind].pre_segment_id, + ) + + self.assertEqual( + proj_array[0].connection_wds[conn_ind].pre_fraction_along, + proj_array[1].connection_wds[conn_ind].pre_fraction_along, + ) + + self.assertEqual( + proj_array[0].connection_wds[conn_ind].post_fraction_along, + proj_array[1].connection_wds[conn_ind].post_fraction_along, + ) + + self.assertNotEqual( + proj_array[0].connection_wds[conn_ind].delay, + proj_array[1].connection_wds[conn_ind].delay, + ) + + self.assertNotEqual( + proj_array[0].connection_wds[conn_ind].weight, + proj_array[1].connection_wds[conn_ind].weight, + ) + + self.assertEqual(len(set(pre_cell_AMPA_strings)), 50) + + self.assertEqual( + len(set(pre_cell_AMPA_strings)), len(set(pre_cell_NMDA_strings)) + ) + + self.assertEqual(len(set(post_cell_AMPA_strings)), 2) + + self.assertEqual( + len(set(post_cell_AMPA_strings)), len(set(post_cell_NMDA_strings)) + ) + + ######## Test 4 divergent + network = neuroml.Network(id="Net0") + presynaptic_population = neuroml.Population( + id="Pop0", component="L23PyrRS", type="populationList", size=3 + ) + postsynaptic_population = neuroml.Population( + id="Pop1", component="L23PyrFRB", type="populationList", size=50 + ) + + synapse_list = ["AMPA", "NMDA"] + + projection_array = [] + + for synapse_element in range(0, len(synapse_list)): + proj = neuroml.Projection( + id="Proj%d" % synapse_element, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + synapse=synapse_list[synapse_element], + ) + + projection_array.append(proj) + + parsed_target_dict = { + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + } + } + + proj_array = oc_build.add_targeted_projection_by_dicts( + net=network, + proj_array=projection_array, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + targeting_mode="divergent", + synapse_list=synapse_list, + pre_seg_target_dict=None, + post_seg_target_dict=parsed_target_dict, + subset_dict={"basal_obl_dends": 50}, + delays_dict={"NMDA": 5}, + weights_dict={"AMPA": 1.5, "NMDA": 2}, + ) + + self.assertEqual(len(network.projections), 2) + + self.assertEqual(len(proj_array[0].connection_wds), 150) + + self.assertEqual( + len(proj_array[0].connection_wds), + len(network.projections[0].connection_wds), + ) + + self.assertEqual( + len(proj_array[0].connection_wds), len(proj_array[1].connection_wds) + ) + + self.assertEqual(proj_array[0].synapse, "AMPA") + + self.assertEqual(proj_array[1].synapse, "NMDA") + + pre_cell_AMPA_strings = [] + + post_cell_AMPA_strings = [] + + pre_cell_NMDA_strings = [] + + post_cell_NMDA_strings = [] + + for conn_ind in range(0, 150): + pre_cell_AMPA_strings.append( + proj_array[0].connection_wds[conn_ind].pre_cell_id + ) + + post_cell_AMPA_strings.append( + proj_array[0].connection_wds[conn_ind].post_cell_id + ) + + pre_cell_NMDA_strings.append( + proj_array[1].connection_wds[conn_ind].pre_cell_id + ) + + post_cell_NMDA_strings.append( + proj_array[1].connection_wds[conn_ind].post_cell_id + ) + + self.assertEqual( + proj_array[0].connection_wds[conn_ind].pre_cell_id, + proj_array[1].connection_wds[conn_ind].pre_cell_id, + ) + + self.assertEqual( + proj_array[0].connection_wds[conn_ind].post_cell_id, + proj_array[1].connection_wds[conn_ind].post_cell_id, + ) + + self.assertEqual( + proj_array[0].connection_wds[conn_ind].post_segment_id, + proj_array[1].connection_wds[conn_ind].post_segment_id, + ) + + self.assertEqual( + proj_array[0].connection_wds[conn_ind].pre_segment_id, + proj_array[1].connection_wds[conn_ind].pre_segment_id, + ) + + self.assertEqual( + proj_array[0].connection_wds[conn_ind].pre_fraction_along, + proj_array[1].connection_wds[conn_ind].pre_fraction_along, + ) + + self.assertEqual( + proj_array[0].connection_wds[conn_ind].post_fraction_along, + proj_array[1].connection_wds[conn_ind].post_fraction_along, + ) + + self.assertNotEqual( + proj_array[0].connection_wds[conn_ind].delay, + proj_array[1].connection_wds[conn_ind].delay, + ) + + self.assertNotEqual( + proj_array[0].connection_wds[conn_ind].weight, + proj_array[1].connection_wds[conn_ind].weight, + ) + + self.assertEqual(len(set(pre_cell_AMPA_strings)), 3) + + self.assertEqual( + len(set(pre_cell_AMPA_strings)), len(set(pre_cell_NMDA_strings)) + ) + + self.assertEqual(len(set(post_cell_AMPA_strings)), 50) + + self.assertEqual( + len(set(post_cell_AMPA_strings)), len(set(post_cell_NMDA_strings)) + ) + + ######## Test 5 convergent mode, check pre and post segments + network = neuroml.Network(id="Net0") + presynaptic_population = neuroml.Population( + id="Pop0", component="L23PyrRS", type="populationList", size=50 + ) + postsynaptic_population = neuroml.Population( + id="Pop1", component="L23PyrFRB", type="populationList", size=2 + ) + + synapse_list = ["AMPA", "NMDA"] + + projection_array = [] + + for synapse_element in range(0, len(synapse_list)): + proj = neuroml.Projection( + id="Proj%d" % synapse_element, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + synapse=synapse_list[synapse_element], + ) + + projection_array.append(proj) + + parsed_pre_target_dict = { + "distal_axon": { + "SegList": [146, 147, 142, 143], + "LengthDist": [ + 25.00045378088167, + 49.999986501514655, + 75.00044417652734, + 99.9999379546021, + ], + } + } + + parsed_target_dict = { + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + } + } + + proj_array = oc_build.add_targeted_projection_by_dicts( + net=network, + proj_array=projection_array, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + targeting_mode="convergent", + synapse_list=synapse_list, + pre_seg_target_dict=parsed_pre_target_dict, + post_seg_target_dict=parsed_target_dict, + subset_dict={"basal_obl_dends": 50}, + delays_dict={"NMDA": 5}, + weights_dict={"AMPA": 1.5, "NMDA": 2}, + ) + + AMPA_proj = network.projections[0].connection_wds + + NMDA_proj = network.projections[1].connection_wds + + for conn_ind in range(0, 100): + self.assertTrue( + AMPA_proj[conn_ind].pre_segment_id + in parsed_pre_target_dict["distal_axon"]["SegList"] + ) + + self.assertTrue( + AMPA_proj[conn_ind].pre_segment_id == NMDA_proj[conn_ind].pre_segment_id + ) + + self.assertTrue( + AMPA_proj[conn_ind].post_segment_id + in parsed_target_dict["basal_obl_dends"]["SegList"] + ) + + self.assertTrue( + AMPA_proj[conn_ind].post_segment_id + == NMDA_proj[conn_ind].post_segment_id + ) + + ######## Test 6 convergent mode, check pre and post segments and total number given not in the format of dictionary + network = neuroml.Network(id="Net0") + presynaptic_population = neuroml.Population( + id="Pop0", component="L23PyrRS", type="populationList", size=50 + ) + postsynaptic_population = neuroml.Population( + id="Pop1", component="L23PyrFRB", type="populationList", size=2 + ) + + synapse_list = ["AMPA", "NMDA"] + + projection_array = [] + + for synapse_element in range(0, len(synapse_list)): + proj = neuroml.Projection( + id="Proj%d" % synapse_element, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + synapse=synapse_list[synapse_element], + ) + + projection_array.append(proj) + + parsed_pre_target_dict = { + "distal_axon": { + "SegList": [146, 147, 142, 143], + "LengthDist": [ + 25.00045378088167, + 49.999986501514655, + 75.00044417652734, + 99.9999379546021, + ], + } + } + + parsed_target_dict = { + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + }, + "distal_axon": { + "SegList": [146, 147, 142, 143], + "LengthDist": [ + 25.00045378088167, + 49.999986501514655, + 75.00044417652734, + 99.9999379546021, + ], + }, + } + + proj_array = oc_build.add_targeted_projection_by_dicts( + net=network, + proj_array=projection_array, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + targeting_mode="convergent", + synapse_list=synapse_list, + pre_seg_target_dict=parsed_pre_target_dict, + post_seg_target_dict=parsed_target_dict, + subset_dict=50, + delays_dict={"NMDA": 5}, + weights_dict={"AMPA": 1.5, "NMDA": 2}, + ) + + AMPA_proj = network.projections[0].connection_wds + + NMDA_proj = network.projections[1].connection_wds + + for conn_ind in range(0, 100): + self.assertTrue( + AMPA_proj[conn_ind].pre_segment_id + in parsed_pre_target_dict["distal_axon"]["SegList"] + ) + + self.assertTrue( + AMPA_proj[conn_ind].pre_segment_id == NMDA_proj[conn_ind].pre_segment_id + ) + + check_basal = ( + AMPA_proj[conn_ind].post_segment_id + in parsed_target_dict["basal_obl_dends"]["SegList"] + ) + + check_distal = ( + AMPA_proj[conn_ind].post_segment_id + in parsed_target_dict["distal_axon"]["SegList"] + ) + + self.assertTrue(check_basal or check_distal) + + self.assertTrue( + AMPA_proj[conn_ind].post_segment_id + == NMDA_proj[conn_ind].post_segment_id + ) + + def test_add_chem_spatial_projection(self): + ######## Test 1 convergent + network = neuroml.Network(id="Net0") + + popDict = {} + popDict["CG3D_L23PyrRS"] = (500, "L23", "Test", "multi", None) + popDict["CG3D_L23PyrFRB"] = (1, "L23", "Test2", "multi", None) + t1 = -0 + t2 = -250 + t3 = -250 + boundaries = {} + boundaries["L1"] = [0, t1] + boundaries["L23"] = [t1, t1 + t2 + t3] + xs = [0, 500] + zs = [0, 500] + + pop_params = oc_utils.add_populations_in_rectangular_layers( + net=network, + boundaryDict=boundaries, + popDict=popDict, + x_vector=xs, + z_vector=zs, + ) + + presynaptic_population = pop_params["CG3D_L23PyrRS"]["PopObj"] + + postsynaptic_population = pop_params["CG3D_L23PyrFRB"]["PopObj"] + + synapse_list = ["AMPA", "NMDA"] + + projection_array = [] + + for synapse_element in range(0, len(synapse_list)): + proj = neuroml.Projection( + id="Proj%d" % synapse_element, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + synapse=synapse_list[synapse_element], + ) + + projection_array.append(proj) + + parsed_target_dict = { + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + } + } + + proj_array = oc_build.add_chem_spatial_projection( + net=network, + proj_array=projection_array, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + targeting_mode="convergent", + synapse_list=synapse_list, + pre_seg_target_dict=None, + post_seg_target_dict=parsed_target_dict, + subset_dict={"basal_obl_dends": 50}, + distance_rule="- 17.45 + 18.36 / (math.exp((r-267.)/39.) +1)", + pre_cell_positions=pop_params["CG3D_L23PyrRS"]["Positions"], + post_cell_positions=pop_params["CG3D_L23PyrFRB"]["Positions"], + delays_dict={"NMDA": 5}, + weights_dict={"AMPA": 1.5, "NMDA": 2}, + ) + + self.assertEqual(len(network.projections), 2) + + self.assertEqual( + len(proj_array[0].connection_wds), + len(network.projections[0].connection_wds), + ) + + self.assertTrue(len(proj_array[0].connection_wds) <= 50) + + pre_cell_AMPA_strings = [] + + post_cell_AMPA_strings = [] + + pre_cell_NMDA_strings = [] + + post_cell_NMDA_strings = [] + + post_cell_ids = [] + + pre_cell_ids = [] + + for conn_ind in range(0, len(proj_array[0].connection_wds)): + post_cell_ids.append(proj_array[0].connection_wds[conn_ind].post_cell_id) + + pre_cell_ids.append(proj_array[0].connection_wds[conn_ind].pre_cell_id) + + pre_cell_AMPA_strings.append( + proj_array[0].connection_wds[conn_ind].pre_cell_id + ) + + post_cell_AMPA_strings.append( + proj_array[0].connection_wds[conn_ind].post_cell_id + ) + + pre_cell_NMDA_strings.append( + proj_array[1].connection_wds[conn_ind].pre_cell_id + ) + + post_cell_NMDA_strings.append( + proj_array[1].connection_wds[conn_ind].post_cell_id + ) + + self.assertEqual( + proj_array[0].connection_wds[conn_ind].post_cell_id, + proj_array[1].connection_wds[conn_ind].post_cell_id, + ) + + self.assertEqual( + proj_array[0].connection_wds[conn_ind].pre_cell_id, + proj_array[1].connection_wds[conn_ind].pre_cell_id, + ) + + self.assertTrue(len(set(post_cell_ids)) == 1) + + self.assertTrue(len(proj_array[0].connection_wds) == len(set(pre_cell_ids))) + + self.assertEqual( + len(set(pre_cell_AMPA_strings)), len(set(pre_cell_NMDA_strings)) + ) + + self.assertEqual( + len(set(post_cell_AMPA_strings)), len(set(post_cell_NMDA_strings)) + ) + + self.assertEqual( + len(proj_array[0].connection_wds), len(proj_array[1].connection_wds) + ) + + self.assertEqual(proj_array[0].synapse, "AMPA") + + self.assertEqual(proj_array[1].synapse, "NMDA") + + ######## Test 2 divergent + network = neuroml.Network(id="Net0") + + popDict = {} + popDict["CG3D_L23PyrRS"] = (1, "L23", "Test", "multi", None) + popDict["CG3D_L23PyrFRB"] = (1000, "L23", "Test2", "multi", None) + t1 = -0 + t2 = -250 + t3 = -250 + boundaries = {} + boundaries["L1"] = [0, t1] + boundaries["L23"] = [t1, t1 + t2 + t3] + xs = [0, 500] + zs = [0, 500] + + pop_params = oc_utils.add_populations_in_rectangular_layers( + net=network, + boundaryDict=boundaries, + popDict=popDict, + x_vector=xs, + z_vector=zs, + ) + + presynaptic_population = pop_params["CG3D_L23PyrRS"]["PopObj"] + + postsynaptic_population = pop_params["CG3D_L23PyrFRB"]["PopObj"] + + synapse_list = ["AMPA", "NMDA"] + + projection_array = [] + + for synapse_element in range(0, len(synapse_list)): + proj = neuroml.Projection( + id="Proj%d" % synapse_element, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + synapse=synapse_list[synapse_element], + ) + + projection_array.append(proj) + + parsed_target_dict = { + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + } + } + + proj_array = oc_build.add_chem_spatial_projection( + net=network, + proj_array=projection_array, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + targeting_mode="divergent", + synapse_list=synapse_list, + pre_seg_target_dict=None, + post_seg_target_dict=parsed_target_dict, + subset_dict={"basal_obl_dends": 50}, + distance_rule="- 17.45 + 18.36 / (math.exp((r-267.)/39.) +1)", + pre_cell_positions=pop_params["CG3D_L23PyrRS"]["Positions"], + post_cell_positions=pop_params["CG3D_L23PyrFRB"]["Positions"], + delays_dict={"NMDA": 5}, + weights_dict={"AMPA": 1.5, "NMDA": 2}, + ) + + self.assertEqual(len(network.projections), 2) + + self.assertEqual( + len(proj_array[0].connection_wds), + len(network.projections[0].connection_wds), + ) + + self.assertTrue(len(proj_array[0].connection_wds) <= 50) + + pre_cell_AMPA_strings = [] + + post_cell_AMPA_strings = [] + + pre_cell_NMDA_strings = [] + + post_cell_NMDA_strings = [] + + post_cell_ids = [] + + pre_cell_ids = [] + + self.assertTrue(network.projections[0].synapse == "AMPA") + + self.assertTrue(network.projections[1].synapse == "NMDA") + + for conn_ind in range(0, len(proj_array[0].connection_wds)): + pre_cell_AMPA_strings.append( + proj_array[0].connection_wds[conn_ind].pre_cell_id + ) + + post_cell_AMPA_strings.append( + proj_array[0].connection_wds[conn_ind].post_cell_id + ) + + pre_cell_NMDA_strings.append( + proj_array[1].connection_wds[conn_ind].pre_cell_id + ) + + post_cell_NMDA_strings.append( + proj_array[1].connection_wds[conn_ind].post_cell_id + ) + + self.assertEqual( + proj_array[0].connection_wds[conn_ind].post_cell_id, + proj_array[1].connection_wds[conn_ind].post_cell_id, + ) + + self.assertEqual( + proj_array[0].connection_wds[conn_ind].pre_cell_id, + proj_array[1].connection_wds[conn_ind].pre_cell_id, + ) + + self.assertTrue(len(set(pre_cell_AMPA_strings)) == 1) + + self.assertTrue( + len(proj_array[0].connection_wds) == len(set(post_cell_AMPA_strings)) + ) + + self.assertEqual( + len(set(pre_cell_AMPA_strings)), len(set(pre_cell_NMDA_strings)) + ) + + self.assertEqual( + len(set(post_cell_AMPA_strings)), len(set(post_cell_NMDA_strings)) + ) + + self.assertEqual( + len(proj_array[0].connection_wds), len(proj_array[1].connection_wds) + ) + + self.assertEqual(proj_array[0].synapse, "AMPA") + + self.assertEqual(proj_array[1].synapse, "NMDA") + + def test_add_elect_projection(self): + ######## Test 1 convergent + network = neuroml.Network(id="Net0") + presynaptic_population = neuroml.Population( + id="Pop0", component="L23PyrRS", type="populationList", size=1 + ) + postsynaptic_population = neuroml.Population( + id="Pop0", component="L23PyrFRB", type="populationList", size=1 + ) + + synapse_list = ["Elect_1", "Elect_2"] + + projection_array = [] + + for synapse_element in range(0, len(synapse_list)): + proj = neuroml.ElectricalProjection( + id="Proj%d" % synapse_element, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + ) + + projection_array.append(proj) + + parsed_target_dict = { + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + } + } + + proj_array = oc_build._add_elect_projection( + net=network, + proj_array=projection_array, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + targeting_mode="convergent", + synapse_list=synapse_list, + pre_seg_target_dict=None, + post_seg_target_dict=parsed_target_dict, + subset_dict={"basal_obl_dends": 2.5}, + ) + + self.assertEqual(len(network.electrical_projections), 0) + + self.assertEqual(len(proj_array[0].electrical_connection_instance_ws), 0) + + self.assertEqual( + len(proj_array[1].electrical_connection_instance_ws), + len(proj_array[0].electrical_connection_instance_ws), + ) + + ######## Test 2 convergent + network = neuroml.Network(id="Net0") + presynaptic_population = neuroml.Population( + id="Pop0", component="L23PyrRS", type="populationList", size=2 + ) + postsynaptic_population = neuroml.Population( + id="Pop0", component="L23PyrFRB", type="populationList", size=1 + ) + + synapse_list = ["Elect_1", "Elect_2"] + + projection_array = [] + + for synapse_element in range(0, len(synapse_list)): + proj = neuroml.ElectricalProjection( + id="Proj%d" % synapse_element, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + ) + + projection_array.append(proj) + + parsed_target_dict = { + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + } + } + + proj_array = oc_build._add_elect_projection( + net=network, + proj_array=projection_array, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + targeting_mode="convergent", + synapse_list=synapse_list, + pre_seg_target_dict=None, + post_seg_target_dict=parsed_target_dict, + subset_dict={"basal_obl_dends": 2.5}, + ) + + self.assertEqual(len(network.electrical_projections), 2) + + self.assertEqual( + len(proj_array[0].electrical_connection_instance_ws), + len(network.electrical_projections[0].electrical_connection_instance_ws), + ) + + self.assertEqual( + len(proj_array[1].electrical_connection_instance_ws), + len(proj_array[0].electrical_connection_instance_ws), + ) + + self.assertTrue( + len(proj_array[0].electrical_connection_instance_ws) == 2 + or len(proj_array[0].electrical_connection_instance_ws) == 3 + ) + + self.assertEqual(network.electrical_projections[0].id, proj_array[0].id) + + self.assertEqual(network.electrical_projections[1].id, proj_array[1].id) + + self.assertEqual( + network.electrical_projections[0].presynaptic_population, + proj_array[0].presynaptic_population, + ) + + self.assertEqual( + network.electrical_projections[1].presynaptic_population, + proj_array[1].presynaptic_population, + ) + + self.assertEqual( + network.electrical_projections[0].postsynaptic_population, + proj_array[0].postsynaptic_population, + ) + + self.assertEqual( + network.electrical_projections[1].postsynaptic_population, + proj_array[1].postsynaptic_population, + ) + + ######## Test 3 convergent + network = neuroml.Network(id="Net0") + presynaptic_population = neuroml.Population( + id="Pop0", component="L23PyrRS", type="populationList", size=1 + ) + postsynaptic_population = neuroml.Population( + id="Pop1", component="L23PyrFRB", type="populationList", size=1 + ) + + synapse_list = ["Elect_1", "Elect_2"] + + projection_array = [] + + for synapse_element in range(0, len(synapse_list)): + proj = neuroml.ElectricalProjection( + id="Proj%d" % synapse_element, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + ) + + projection_array.append(proj) + + parsed_target_dict = { + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + } + } + + proj_array = oc_build._add_elect_projection( + net=network, + proj_array=projection_array, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + targeting_mode="convergent", + synapse_list=synapse_list, + pre_seg_target_dict=None, + post_seg_target_dict=parsed_target_dict, + subset_dict={"basal_obl_dends": 0.4}, + ) + + self.assertEqual( + len(proj_array[1].electrical_connection_instance_ws), + len(proj_array[0].electrical_connection_instance_ws), + ) + + self.assertTrue( + len(proj_array[0].electrical_connection_instance_ws) == 0 + or len(proj_array[0].electrical_connection_instance_ws) == 1 + ) + + if len(proj_array[0].electrical_connection_instance_ws) == 1: + self.assertEqual(len(network.electrical_projections), 2) + + self.assertEqual( + len(proj_array[0].electrical_connection_instance_ws), + len( + network.electrical_projections[0].electrical_connection_instance_ws + ), + ) + + if len(proj_array[0].electrical_connection_instance_ws) == 0: + self.assertEqual(len(network.electrical_projections), 0) + + ######## Test 4 divergent and subset_dict is simply a number ( < 1), instead of dictionary + network = neuroml.Network(id="Net0") + presynaptic_population = neuroml.Population( + id="Pop0", component="L23PyrRS", type="populationList", size=1 + ) + postsynaptic_population = neuroml.Population( + id="Pop1", component="L23PyrFRB", type="populationList", size=50 + ) + + synapse_list = ["Elect_1", "Elect_2"] + + projection_array = [] + + for synapse_element in range(0, len(synapse_list)): + proj = neuroml.ElectricalProjection( + id="Proj%d" % synapse_element, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + ) + + projection_array.append(proj) + + parsed_target_dict = { + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + } + } + + proj_array = oc_build._add_elect_projection( + net=network, + proj_array=projection_array, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + targeting_mode="convergent", + synapse_list=synapse_list, + pre_seg_target_dict=None, + post_seg_target_dict=parsed_target_dict, + subset_dict=0.4, + ) + + self.assertEqual( + len(proj_array[1].electrical_connection_instance_ws), + len(proj_array[0].electrical_connection_instance_ws), + ) + + if len(proj_array[0].electrical_connection_instance_ws) == 1: + self.assertEqual(len(network.electrical_projections), 2) + + self.assertEqual( + len(proj_array[0].electrical_connection_instance_ws), + len( + network.electrical_projections[0].electrical_connection_instance_ws + ), + ) + + if len(proj_array[0].electrical_connection_instance_ws) == 0: + self.assertEqual(len(network.electrical_projections), 0) + + else: + len( + network.electrical_projections[0].electrical_connection_instance_ws + ) <= 50 + + for elect_conn_ind in range( + 0, + len( + network.electrical_projections[0].electrical_connection_instance_ws + ), + ): + elect_connection_comp1 = proj_array[ + 0 + ].electrical_connection_instance_ws[elect_conn_ind] + + elect_connection_comp2 = proj_array[ + 1 + ].electrical_connection_instance_ws[elect_conn_ind] + + self.assertTrue( + elect_connection_comp1.pre_cell == elect_connection_comp2.pre_cell + ) + + self.assertTrue( + elect_connection_comp1.post_cell == elect_connection_comp2.post_cell + ) + + self.assertTrue(elect_connection_comp1.synapse == "Elect_1") + + self.assertTrue(elect_connection_comp2.synapse == "Elect_2") + + ######## Test 5 divergent and subset_dict is simply a number ( >= 1), instead of dictionary + + network = neuroml.Network(id="Net0") + presynaptic_population = neuroml.Population( + id="Pop0", component="L23PyrRS", type="populationList", size=1 + ) + postsynaptic_population = neuroml.Population( + id="Pop1", component="L23PyrFRB", type="populationList", size=50 + ) + + synapse_list = ["Elect_1", "Elect_2"] + + projection_array = [] + + for synapse_element in range(0, len(synapse_list)): + proj = neuroml.ElectricalProjection( + id="Proj%d" % synapse_element, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + ) + + projection_array.append(proj) + + parsed_target_dict = { + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + } + } + + proj_array = oc_build._add_elect_projection( + net=network, + proj_array=projection_array, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + targeting_mode="convergent", + synapse_list=synapse_list, + pre_seg_target_dict=None, + post_seg_target_dict=parsed_target_dict, + subset_dict=1, + ) + + self.assertEqual( + len(proj_array[1].electrical_connection_instance_ws), + len(proj_array[0].electrical_connection_instance_ws), + ) + + if len(proj_array[0].electrical_connection_instance_ws) == 1: + self.assertEqual(len(network.electrical_projections), 2) + + self.assertEqual( + len(proj_array[0].electrical_connection_instance_ws), + len( + network.electrical_projections[0].electrical_connection_instance_ws + ), + ) + + len(network.electrical_projections[0].electrical_connection_instance_ws) == 50 + + for elect_conn_ind in range( + 0, len(network.electrical_projections[0].electrical_connection_instance_ws) + ): + elect_connection_comp1 = proj_array[0].electrical_connection_instance_ws[ + elect_conn_ind + ] + + elect_connection_comp2 = proj_array[1].electrical_connection_instance_ws[ + elect_conn_ind + ] + + self.assertTrue( + elect_connection_comp1.pre_cell == elect_connection_comp2.pre_cell + ) + + self.assertTrue( + elect_connection_comp1.post_cell == elect_connection_comp2.post_cell + ) + + self.assertTrue(elect_connection_comp1.synapse == "Elect_1") + + self.assertTrue(elect_connection_comp2.synapse == "Elect_2") + + ######## Test 5 divergent and subset_dict is simply a number ( >= 1), instead of dictionary + + network = neuroml.Network(id="Net0") + presynaptic_population = neuroml.Population( + id="Pop0", component="L23PyrRS", type="populationList", size=1 + ) + postsynaptic_population = neuroml.Population( + id="Pop1", component="L23PyrFRB", type="populationList", size=50 + ) + + synapse_list = ["Elect_1", "Elect_2"] + + projection_array = [] + + for synapse_element in range(0, len(synapse_list)): + proj = neuroml.ElectricalProjection( + id="Proj%d" % synapse_element, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + ) + + projection_array.append(proj) + + parsed_target_dict = { + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + } + } + + proj_array = oc_build._add_elect_projection( + net=network, + proj_array=projection_array, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + targeting_mode="convergent", + synapse_list=synapse_list, + pre_seg_target_dict=None, + post_seg_target_dict=parsed_target_dict, + subset_dict=2, + ) + + self.assertEqual( + len(proj_array[1].electrical_connection_instance_ws), + len(proj_array[0].electrical_connection_instance_ws), + ) + + if len(proj_array[0].electrical_connection_instance_ws) == 1: + self.assertEqual(len(network.electrical_projections), 2) + + self.assertEqual( + len(proj_array[0].electrical_connection_instance_ws), + len( + network.electrical_projections[0].electrical_connection_instance_ws + ), + ) + + len(network.electrical_projections[0].electrical_connection_instance_ws) == 100 + + for elect_conn_ind in range( + 0, len(network.electrical_projections[0].electrical_connection_instance_ws) + ): + elect_connection_comp1 = proj_array[0].electrical_connection_instance_ws[ + elect_conn_ind + ] + + elect_connection_comp2 = proj_array[1].electrical_connection_instance_ws[ + elect_conn_ind + ] + + self.assertTrue( + elect_connection_comp1.pre_cell == elect_connection_comp2.pre_cell + ) + + self.assertTrue( + elect_connection_comp1.post_cell == elect_connection_comp2.post_cell + ) + + self.assertTrue(elect_connection_comp1.synapse == "Elect_1") + + self.assertTrue(elect_connection_comp2.synapse == "Elect_2") + + def test_add_elect_spatial_projection(self): + ######## Test 1 convergent + network = neuroml.Network(id="Net0") + + popDict = {} + popDict["CG3D_L23PyrRS"] = (1, "L23", "Test", "multi", None) + popDict["CG3D_L23PyrFRB"] = (1, "L23", "Test2", "multi", None) + t1 = -0 + t2 = -250 + t3 = -250 + boundaries = {} + boundaries["L1"] = [0, t1] + boundaries["L23"] = [t1, t1 + t2 + t3] + xs = [0, 500] + zs = [0, 500] + + pop_params = oc_utils.add_populations_in_rectangular_layers( + net=network, + boundaryDict=boundaries, + popDict=popDict, + x_vector=xs, + z_vector=zs, + ) + + presynaptic_population = pop_params["CG3D_L23PyrRS"]["PopObj"] + + postsynaptic_population = pop_params["CG3D_L23PyrFRB"]["PopObj"] + + synapse_list = ["Elect_1", "Elect_2"] + + projection_array = [] + + for synapse_element in range(0, len(synapse_list)): + proj = neuroml.ElectricalProjection( + id="Proj%d" % synapse_element, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + ) + + projection_array.append(proj) + + parsed_target_dict = { + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + } + } + + proj_array = oc_build.add_elect_spatial_projection( + net=network, + proj_array=projection_array, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + targeting_mode="convergent", + synapse_list=synapse_list, + pre_seg_target_dict=None, + post_seg_target_dict=parsed_target_dict, + subset_dict={"basal_obl_dends": 2.5}, + distance_rule="- 17.45 + 18.36 / (math.exp((r-267.)/39.) +1)", + pre_cell_positions=pop_params["CG3D_L23PyrRS"]["Positions"], + post_cell_positions=pop_params["CG3D_L23PyrFRB"]["Positions"], + ) + + self.assertTrue(len(network.electrical_projections) >= 0) + + self.assertTrue(len(proj_array[0].electrical_connection_instance_ws) >= 0) + + self.assertEqual( + len(proj_array[1].electrical_connection_instance_ws), + len(proj_array[0].electrical_connection_instance_ws), + ) + + ######## Test 2 convergent + network = neuroml.Network(id="Net0") + + popDict = {} + popDict["CG3D_L23PyrRS"] = (500, "L23", "Test", "multi", None) + popDict["CG3D_L23PyrFRB"] = (1, "L23", "Test2", "multi", None) + t1 = -0 + t2 = -250 + t3 = -250 + boundaries = {} + boundaries["L1"] = [0, t1] + boundaries["L23"] = [t1, t1 + t2 + t3] + xs = [0, 500] + zs = [0, 500] + + pop_params = oc_utils.add_populations_in_rectangular_layers( + net=network, + boundaryDict=boundaries, + popDict=popDict, + x_vector=xs, + z_vector=zs, + ) + + presynaptic_population = pop_params["CG3D_L23PyrRS"]["PopObj"] + + postsynaptic_population = pop_params["CG3D_L23PyrFRB"]["PopObj"] + + synapse_list = ["Elect_1", "Elect_2"] + + projection_array = [] + + for synapse_element in range(0, len(synapse_list)): + proj = neuroml.ElectricalProjection( + id="Proj%d" % synapse_element, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + ) + + projection_array.append(proj) + + parsed_target_dict = { + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + } + } + + proj_array = oc_build.add_elect_spatial_projection( + net=network, + proj_array=projection_array, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + targeting_mode="convergent", + synapse_list=synapse_list, + pre_seg_target_dict=None, + post_seg_target_dict=parsed_target_dict, + subset_dict={"basal_obl_dends": 2.5}, + distance_rule="- 17.45 + 18.36 / (math.exp((r-267.)/39.) +1)", + pre_cell_positions=pop_params["CG3D_L23PyrRS"]["Positions"], + post_cell_positions=pop_params["CG3D_L23PyrFRB"]["Positions"], + ) + + self.assertEqual(len(network.electrical_projections), 2) + + self.assertEqual( + len(network.electrical_projections[0].electrical_connection_instance_ws), + len(network.electrical_projections[1].electrical_connection_instance_ws), + ) + + self.assertEqual( + len(proj_array[0].electrical_connection_instance_ws), + len(network.electrical_projections[0].electrical_connection_instance_ws), + ) + + self.assertEqual( + len(proj_array[1].electrical_connection_instance_ws), + len(proj_array[0].electrical_connection_instance_ws), + ) + + self.assertTrue( + len(proj_array[0].electrical_connection_instance_ws) == 2 + or len(proj_array[0].electrical_connection_instance_ws) == 3 + ) + + self.assertEqual(network.electrical_projections[0].id, proj_array[0].id) + + self.assertEqual(network.electrical_projections[1].id, proj_array[1].id) + + self.assertEqual( + network.electrical_projections[0].presynaptic_population, + proj_array[0].presynaptic_population, + ) + + self.assertEqual( + network.electrical_projections[1].presynaptic_population, + proj_array[1].presynaptic_population, + ) + + self.assertEqual( + network.electrical_projections[0].postsynaptic_population, + proj_array[0].postsynaptic_population, + ) + + self.assertEqual( + network.electrical_projections[1].postsynaptic_population, + proj_array[1].postsynaptic_population, + ) + + pre_cell_Elect1_strings = [] + + post_cell_Elect1_strings = [] + + pre_cell_Elect2_strings = [] + + post_cell_Elect2_strings = [] + + for conn_ind in range( + 0, len(network.electrical_projections[0].electrical_connection_instance_ws) + ): + self.assertEqual( + network.electrical_projections[0] + .electrical_connection_instance_ws[conn_ind] + .synapse, + "Elect_1", + ) + + self.assertEqual( + network.electrical_projections[1] + .electrical_connection_instance_ws[conn_ind] + .synapse, + "Elect_2", + ) + + pre_cell_Elect1_strings.append( + network.electrical_projections[0] + .electrical_connection_instance_ws[conn_ind] + .pre_cell + ) + + post_cell_Elect1_strings.append( + network.electrical_projections[0] + .electrical_connection_instance_ws[conn_ind] + .post_cell + ) + + pre_cell_Elect2_strings.append( + network.electrical_projections[1] + .electrical_connection_instance_ws[conn_ind] + .pre_cell + ) + + post_cell_Elect2_strings.append( + network.electrical_projections[1] + .electrical_connection_instance_ws[conn_ind] + .post_cell + ) + + self.assertEqual( + network.electrical_projections[0] + .electrical_connection_instance_ws[conn_ind] + .post_cell, + network.electrical_projections[1] + .electrical_connection_instance_ws[conn_ind] + .post_cell, + ) + + self.assertEqual( + network.electrical_projections[0] + .electrical_connection_instance_ws[conn_ind] + .pre_cell, + network.electrical_projections[1] + .electrical_connection_instance_ws[conn_ind] + .pre_cell, + ) + + self.assertTrue(len(set(post_cell_Elect1_strings)) == 1) + + self.assertTrue( + len(network.electrical_projections[0].electrical_connection_instance_ws) + == len(set(pre_cell_Elect1_strings)) + ) + + self.assertEqual( + len(set(pre_cell_Elect1_strings)), len(set(pre_cell_Elect2_strings)) + ) + + self.assertEqual( + len(set(post_cell_Elect1_strings)), len(set(post_cell_Elect2_strings)) + ) + + ######## Test 3 divergent + network = neuroml.Network(id="Net0") + + popDict = {} + popDict["CG3D_L23PyrRS"] = (1, "L23", "Test", "multi", None) + popDict["CG3D_L23PyrFRB"] = (500, "L23", "Test2", "multi", None) + t1 = -0 + t2 = -250 + t3 = -250 + boundaries = {} + boundaries["L1"] = [0, t1] + boundaries["L23"] = [t1, t1 + t2 + t3] + xs = [0, 500] + zs = [0, 500] + + pop_params = oc_utils.add_populations_in_rectangular_layers( + net=network, + boundaryDict=boundaries, + popDict=popDict, + x_vector=xs, + z_vector=zs, + ) + + presynaptic_population = pop_params["CG3D_L23PyrRS"]["PopObj"] + + postsynaptic_population = pop_params["CG3D_L23PyrFRB"]["PopObj"] + + synapse_list = ["Elect_1", "Elect_2"] + + projection_array = [] + + for synapse_element in range(0, len(synapse_list)): + proj = neuroml.ElectricalProjection( + id="Proj%d" % synapse_element, + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + ) + + projection_array.append(proj) + + parsed_target_dict = { + "basal_obl_dends": { + "SegList": [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ], + "LengthDist": [ + 25.0, + 50.0, + 75.0, + 100.0, + 125.0, + 150.0, + 175.0, + 200.0, + 225.0000012807632, + 249.99999701896448, + 274.9999982997277, + 299.9999413836009, + 324.99994266436414, + 349.99992870308233, + 374.99992998384556, + 399.9999756051272, + 424.9999756051272, + 449.9999756051272, + 474.9999756051272, + 499.9999756051272, + 524.9999756051272, + 549.9999756051272, + 574.9999756051272, + 599.9999756051272, + 624.9999756051272, + 649.9999756051272, + 674.9999756051272, + 699.9999756051272, + 724.9999756051272, + 749.9999756051272, + 774.9999756051272, + 799.9999756051272, + 824.9999741146091, + 849.9995943443294, + 874.9996247235468, + 899.9999308454469, + 924.9999175769843, + 950.0002631896537, + 975.0002596206808, + 1000.0001576712268, + 1025.0001576712268, + 1050.0001576712268, + 1075.0001576712268, + 1100.0001576712268, + 1125.0001576712268, + 1150.0001576712268, + 1175.0001576712268, + 1200.0001576712268, + 1225.0001576712268, + 1250.0001576712268, + 1275.0001576712268, + 1300.0001576712268, + 1325.0001576712268, + 1350.0001576712268, + 1375.0001576712268, + 1400.0001576712268, + 1425.0010159713997, + 1450.0009008583847, + 1475.0002938437874, + 1500.000601351312, + 1525.0002368231228, + 1549.9998501247107, + 1575.0001714886703, + 1599.9998485298981, + 1624.9998485298981, + 1649.9998485298981, + 1674.9998485298981, + 1699.9998485298981, + 1724.9998485298981, + 1749.9998485298981, + 1774.9998485298981, + 1799.9998485298981, + ], + } + } + + proj_array = oc_build.add_elect_spatial_projection( + net=network, + proj_array=projection_array, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + targeting_mode="divergent", + synapse_list=synapse_list, + pre_seg_target_dict=None, + post_seg_target_dict=parsed_target_dict, + subset_dict={"basal_obl_dends": 2.5}, + distance_rule="- 17.45 + 18.36 / (math.exp((r-267.)/39.) +1)", + pre_cell_positions=pop_params["CG3D_L23PyrRS"]["Positions"], + post_cell_positions=pop_params["CG3D_L23PyrFRB"]["Positions"], + ) + + self.assertEqual(len(network.electrical_projections), 2) + + self.assertEqual( + len(network.electrical_projections[0].electrical_connection_instance_ws), + len(network.electrical_projections[1].electrical_connection_instance_ws), + ) + + self.assertEqual( + len(proj_array[0].electrical_connection_instance_ws), + len(network.electrical_projections[0].electrical_connection_instance_ws), + ) + + self.assertEqual( + len(proj_array[1].electrical_connection_instance_ws), + len(proj_array[0].electrical_connection_instance_ws), + ) + + self.assertTrue( + len(proj_array[0].electrical_connection_instance_ws) == 2 + or len(proj_array[0].electrical_connection_instance_ws) == 3 + ) + + self.assertEqual(network.electrical_projections[0].id, proj_array[0].id) + + self.assertEqual(network.electrical_projections[1].id, proj_array[1].id) + + self.assertEqual( + network.electrical_projections[0].presynaptic_population, + proj_array[0].presynaptic_population, + ) + + self.assertEqual( + network.electrical_projections[1].presynaptic_population, + proj_array[1].presynaptic_population, + ) + + self.assertEqual( + network.electrical_projections[0].postsynaptic_population, + proj_array[0].postsynaptic_population, + ) + + self.assertEqual( + network.electrical_projections[1].postsynaptic_population, + proj_array[1].postsynaptic_population, + ) + + pre_cell_Elect1_strings = [] + + post_cell_Elect1_strings = [] + + pre_cell_Elect2_strings = [] + + post_cell_Elect2_strings = [] + + for conn_ind in range( + 0, len(network.electrical_projections[0].electrical_connection_instance_ws) + ): + self.assertEqual( + network.electrical_projections[0] + .electrical_connection_instance_ws[conn_ind] + .synapse, + "Elect_1", + ) + + self.assertEqual( + network.electrical_projections[1] + .electrical_connection_instance_ws[conn_ind] + .synapse, + "Elect_2", + ) + + pre_cell_Elect1_strings.append( + network.electrical_projections[0] + .electrical_connection_instance_ws[conn_ind] + .pre_cell + ) + + post_cell_Elect1_strings.append( + network.electrical_projections[0] + .electrical_connection_instance_ws[conn_ind] + .post_cell + ) + + pre_cell_Elect2_strings.append( + network.electrical_projections[1] + .electrical_connection_instance_ws[conn_ind] + .pre_cell + ) + + post_cell_Elect2_strings.append( + network.electrical_projections[1] + .electrical_connection_instance_ws[conn_ind] + .post_cell + ) + + self.assertEqual( + network.electrical_projections[0] + .electrical_connection_instance_ws[conn_ind] + .post_cell, + network.electrical_projections[1] + .electrical_connection_instance_ws[conn_ind] + .post_cell, + ) + + self.assertEqual( + network.electrical_projections[0] + .electrical_connection_instance_ws[conn_ind] + .pre_cell, + network.electrical_projections[1] + .electrical_connection_instance_ws[conn_ind] + .pre_cell, + ) + + self.assertTrue(len(set(pre_cell_Elect1_strings)) == 1) + + self.assertTrue( + len(network.electrical_projections[0].electrical_connection_instance_ws) + == len(set(post_cell_Elect1_strings)) + ) + + self.assertEqual( + len(set(pre_cell_Elect1_strings)), len(set(pre_cell_Elect2_strings)) + ) + + self.assertEqual( + len(set(post_cell_Elect1_strings)), len(set(post_cell_Elect2_strings)) + ) + + def test_add_probabilistic_projection_list(self): + random.seed(1234) + + ######## Test 1 convergent + network = neuroml.Network(id="Net0") + presynaptic_population = neuroml.Population( + id="Pop0", component="L23PyrRS", type="populationList", size=50 + ) + postsynaptic_population = neuroml.Population( + id="Pop0", component="L23PyrFRB", type="populationList", size=50 + ) + + synapse_list = ["Syn_1", "Syn_2"] + + returned_projs = oc_build.add_probabilistic_projection_list( + net=network, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + synapse_list=synapse_list, + connection_probability=0.5, + delay=0.05, + weight=2, + std_delay=None, + std_weight=None, + ) + + self.assertEqual(len(network.projections), 2) + self.assertEqual( + len(network.projections[0].connection_wds), + len(network.projections[1].connection_wds), + ) + + for proj_ind in range(0, len(network.projections)): + self.assertTrue( + "Syn_1" in network.projections[proj_ind].id + or "Syn_2" in network.projections[proj_ind].id + ) + + self.assertTrue( + network.projections[proj_ind].synapse == "Syn_1" + or network.projections[proj_ind].synapse == "Syn_2" + ) + + for conn_ind in range(0, len(network.projections[proj_ind].connection_wds)): + connection = network.projections[proj_ind].connection_wds[conn_ind] + + self.assertTrue(connection.get_delay_in_ms() == 0.05) + + self.assertTrue(2 == connection.weight) + + ######## Test 2 convergent connection_probability =0 + + network.projections = [] + + returned_projs = oc_build.add_probabilistic_projection_list( + net=network, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + synapse_list=synapse_list, + connection_probability=0, + delay=0.05, + weight=2, + std_delay=None, + std_weight=None, + ) + + self.assertEqual(len(network.projections), 0) + + self.assertTrue(returned_projs == None) + + ######## Test 3 delay list: + + returned_projs = oc_build.add_probabilistic_projection_list( + net=network, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + synapse_list=synapse_list, + connection_probability=0.5, + delay=[0.05, 0.01], + weight=2, + std_delay=None, + std_weight=None, + ) + + self.assertEqual(len(network.projections), 2) + + self.assertEqual( + len(network.projections[0].connection_wds), + len(network.projections[1].connection_wds), + ) + + for proj_ind in range(0, len(network.projections)): + self.assertTrue( + "Syn_1" in network.projections[proj_ind].id + or "Syn_2" in network.projections[proj_ind].id + ) + + self.assertTrue( + network.projections[proj_ind].synapse == "Syn_1" + or network.projections[proj_ind].synapse == "Syn_2" + ) + + for conn_ind in range(0, len(network.projections[proj_ind].connection_wds)): + connection = network.projections[proj_ind].connection_wds[conn_ind] + + if "Syn_1" in network.projections[proj_ind].id: + self.assertTrue(connection.get_delay_in_ms() == 0.05) + + if "Syn_2" in network.projections[proj_ind].id: + self.assertTrue(connection.get_delay_in_ms() == 0.01) + + self.assertTrue(2 == connection.weight) + + ######## Test 3 weight list: + + network.projections = [] + + returned_projs = oc_build.add_probabilistic_projection_list( + net=network, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + synapse_list=synapse_list, + connection_probability=0.5, + delay=0.05, + weight=[2, 2.5], + std_delay=None, + std_weight=None, + ) + + self.assertEqual(len(network.projections), 2) + + self.assertEqual( + len(network.projections[0].connection_wds), + len(network.projections[1].connection_wds), + ) + + for proj_ind in range(0, len(network.projections)): + self.assertTrue( + "Syn_1" in network.projections[proj_ind].id + or "Syn_2" in network.projections[proj_ind].id + ) + + self.assertTrue( + network.projections[proj_ind].synapse == "Syn_1" + or network.projections[proj_ind].synapse == "Syn_2" + ) + + for conn_ind in range(0, len(network.projections[proj_ind].connection_wds)): + connection = network.projections[proj_ind].connection_wds[conn_ind] + + if "Syn_1" in network.projections[proj_ind].id: + self.assertTrue(2 == connection.weight) + + if "Syn_2" in network.projections[proj_ind].id: + self.assertTrue(2.5 == connection.weight) + + self.assertTrue(connection.get_delay_in_ms() == 0.05) + + ######## Test 3 std weight: + + network.projections = [] + + returned_projs = oc_build.add_probabilistic_projection_list( + net=network, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + synapse_list=synapse_list, + connection_probability=0.5, + delay=0.05, + weight=[2, 2.5], + std_delay=None, + std_weight=0.1, + ) + + self.assertEqual(len(network.projections), 2) + + self.assertEqual( + len(network.projections[0].connection_wds), + len(network.projections[1].connection_wds), + ) + + for proj_ind in range(0, len(network.projections)): + self.assertTrue( + "Syn_1" in network.projections[proj_ind].id + or "Syn_2" in network.projections[proj_ind].id + ) + + self.assertTrue( + network.projections[proj_ind].synapse == "Syn_1" + or network.projections[proj_ind].synapse == "Syn_2" + ) + + for conn_ind in range(0, len(network.projections[proj_ind].connection_wds)): + connection = network.projections[proj_ind].connection_wds[conn_ind] + + if "Syn_1" in network.projections[proj_ind].id: + self.assertTrue( + connection.weight != 2 + and connection.weight > 0 + and connection.weight < 5 + ) + + if "Syn_2" in network.projections[proj_ind].id: + self.assertTrue( + connection.weight != 2.5 + and connection.weight > 0 + and connection.weight < 5 + ) + + self.assertTrue(connection.get_delay_in_ms() == 0.05) + + ######## Test 4 std delay: + + network.projections = [] + + returned_projs = oc_build.add_probabilistic_projection_list( + net=network, + presynaptic_population=presynaptic_population, + postsynaptic_population=postsynaptic_population, + synapse_list=synapse_list, + connection_probability=0.5, + delay=[5, 1], + weight=[2, 2.5], + std_delay=[0.01, 0.001], + std_weight=None, + ) + + self.assertEqual(len(network.projections), 2) + + self.assertEqual( + len(network.projections[0].connection_wds), + len(network.projections[1].connection_wds), + ) + + for proj_ind in range(0, len(network.projections)): + self.assertTrue( + "Syn_1" in network.projections[proj_ind].id + or "Syn_2" in network.projections[proj_ind].id + ) + + self.assertTrue( + network.projections[proj_ind].synapse == "Syn_1" + or network.projections[proj_ind].synapse == "Syn_2" + ) + + for conn_ind in range(0, len(network.projections[proj_ind].connection_wds)): + connection = network.projections[proj_ind].connection_wds[conn_ind] + + if "Syn_1" in network.projections[proj_ind].id: + self.assertTrue(2 == connection.weight) + + self.assertTrue( + connection.get_delay_in_ms() != 5 + and connection.get_delay_in_ms() > 3 + and connection.get_delay_in_ms() < 7 + ) + + if "Syn_2" in network.projections[proj_ind].id: + self.assertTrue(2.5 == connection.weight) + self.assertTrue( + connection.get_delay_in_ms() != 1 + and connection.get_delay_in_ms() > 0 + and connection.get_delay_in_ms() < 2 + ) diff --git a/opencortex/test/test_utils_methods.py b/opencortex/test/test_utils_methods.py index 8051d8e..1585bc4 100644 --- a/opencortex/test/test_utils_methods.py +++ b/opencortex/test/test_utils_methods.py @@ -13,1286 +13,1579 @@ import opencortex.utils as oc_utils import neuroml import numpy as np -import os import math try: import unittest2 as unittest except ImportError: import unittest - + class TestUtilsMethods(unittest.TestCase): + def test_read_connectivity(self): + proj_info = oc_utils.read_connectivity( + pre_pop="CG3D_L23PyrRS", + post_pop="CG3D_L23PyrFRB", + path_to_txt_file="ConnListTest", + ) + + self.assertTrue(isinstance(proj_info, list)) + + for proj_ind in range(0, len(proj_info)): + self.assertEqual( + len(proj_info[proj_ind].keys()), len(proj_info[proj_ind].values()) + ) + + self.assertTrue("SynapseList" in proj_info[proj_ind].keys()) + self.assertTrue("PreCellGroup" in proj_info[proj_ind].keys()) + self.assertTrue("PostCellGroup" in proj_info[proj_ind].keys()) + self.assertTrue("Type" in proj_info[proj_ind].keys()) + self.assertTrue("LocOnPostCell" in proj_info[proj_ind].keys()) + self.assertTrue( + "NumPerPostCell" in proj_info[proj_ind].keys() + or "NumPerPreCell" in proj_info[proj_ind].keys() + ) + + def test_add_populations_in_rectangular_layers(self): + network = neuroml.Network(id="Net0") + popDict = {} + popDict["CG3D_L23PyrRS"] = (1000, "L23", "Test", "multi", None) + popDict["CG3D_L23PyrFRB"] = (50, "L23", "Test2", "multi", None) + t1 = -0 + t2 = -250 + t3 = -250 + boundaries = {} + boundaries["L1"] = [0, t1] + boundaries["L23"] = [t1, t1 + t2 + t3] + xs = [0, 500] + zs = [0, 500] + + pop_params = oc_utils.add_populations_in_rectangular_layers( + net=network, + boundaryDict=boundaries, + popDict=popDict, + x_vector=xs, + z_vector=zs, + storeSoma=False, + ) + + for cell_pop in popDict.keys(): + self.assertTrue(cell_pop in pop_params.keys()) + + self.assertTrue("PopObj" in pop_params[cell_pop]) + + self.assertTrue("Positions" in pop_params[cell_pop]) + + self.assertTrue("Compartments" in pop_params[cell_pop]) + + self.assertTrue(pop_params[cell_pop]["Positions"] == None) + + for pop_index in range(0, len(network.populations)): + pop = network.populations[pop_index] + + self.assertTrue(pop.id in popDict.keys()) + + self.assertTrue(popDict[pop.id][2] == pop.component) + + self.assertTrue(popDict[pop.id][0] == pop.size) + + for cell_loc in range(0, len(pop.instances)): + instance_case = pop.instances[cell_loc] + + location = instance_case.location + + self.assertTrue(xs[0] <= location.x and location.x <= xs[1]) + + self.assertTrue(zs[0] <= location.z and location.z <= zs[1]) + + self.assertTrue( + boundaries[popDict[pop.id][1]][0] >= location.y + and location.y >= boundaries[popDict[pop.id][1]][1] + ) + + ###### check storing of soma positions + + network = neuroml.Network(id="Net1") + + pop_params = oc_utils.add_populations_in_rectangular_layers( + net=network, + boundaryDict=boundaries, + popDict=popDict, + x_vector=xs, + z_vector=zs, + ) + + for pop_index in range(0, len(network.populations)): + pop = network.populations[pop_index] + + stored_cell_positions = pop_params[pop.id]["Positions"] + + for cell_loc in range(0, len(pop.instances)): + instance_case = pop.instances[cell_loc] + + location = instance_case.location + + check_x = abs(location.x - stored_cell_positions[cell_loc][0]) < 0.00005 + check_y = abs(location.y - stored_cell_positions[cell_loc][1]) < 0.00005 + check_z = abs(location.z - stored_cell_positions[cell_loc][2]) < 0.00005 + + self.assertTrue(check_x) + + self.assertTrue(check_y) + + self.assertTrue(check_z) + + ###### check distances between somata + + network = neuroml.Network(id="Net1") + + cell_diameters = {} + + for pop_id in popDict.keys(): + cell_diameter = oc_build.get_soma_diameter(popDict[pop_id][2]) + + cell_diameters[popDict[pop_id][2]] = cell_diameter + + pop_params = oc_utils.add_populations_in_rectangular_layers( + net=network, + boundaryDict=boundaries, + popDict=popDict, + x_vector=xs, + z_vector=zs, + cellBodiesOverlap=False, + cellDiameterArray=cell_diameters, + ) + + for pop_index in range(0, len(network.populations)): + pop = network.populations[pop_index] + + stored_cell_positions = pop_params[pop.id]["Positions"] + + for cell_loc in range(0, len(pop.instances)): + instance_case = pop.instances[cell_loc] + + location = instance_case.location + + check_x = abs(location.x - stored_cell_positions[cell_loc][0]) < 0.00001 + + check_y = abs(location.y - stored_cell_positions[cell_loc][1]) < 0.00001 + + check_z = abs(location.z - stored_cell_positions[cell_loc][2]) < 0.00001 + + self.assertTrue(check_x) + + self.assertTrue(check_y) + + self.assertTrue(check_z) + + for cell_loc_inner in range(0, len(pop.instances)): + if cell_loc != cell_loc_inner: + inner_instance_case = pop.instances[cell_loc] + + inner_location = inner_instance_case.location + + d = oc_build.distance( + [location.x, location.y, location.z], + [inner_location.x, inner_location.y, inner_location.z], + ) + + self.assertTrue( + d + < ( + cell_diameters[pop.component] + + cell_diameters[pop.component] + ) + / 2 + ) + + for pop_index_inner in range(0, len(network.populations)): + pop_inner = network.populations[pop_index_inner] + + if pop.id != pop_inner.id: + for cell_loc_inner in range(0, len(pop_inner.instances)): + if cell_loc != cell_loc_inner: + inner_instance_case = pop.instances[cell_loc] + + inner_location = inner_instance_case.location + + d = oc_build.distance( + [location.x, location.y, location.z], + [ + inner_location.x, + inner_location.y, + inner_location.z, + ], + ) + + self.assertTrue( + d + < ( + cell_diameters[pop_inner.component] + + cell_diameters[pop_inner.component] + ) + / 2 + ) + + def test_add_populations_in_cylindrical_layers(self): + network = neuroml.Network(id="Net0") + popDict = {} + popDict["CG3D_L23PyrRS"] = (1000, "L23", "Test", "multi", None) + popDict["CG3D_L23PyrFRB"] = (50, "L23", "Test2", "multi", None) + t1 = -0 + t2 = -250 + t3 = -250 + boundaries = {} + boundaries["L1"] = [0, t1] + boundaries["L23"] = [t1, t1 + t2 + t3] + xs = [0, 500] + zs = [0, 500] + + pop_params = oc_utils.add_populations_in_cylindrical_layers( + net=network, + boundaryDict=boundaries, + popDict=popDict, + radiusOfCylinder=250, + storeSoma=False, + ) + + for cell_pop in popDict.keys(): + self.assertTrue(cell_pop in pop_params.keys()) + + self.assertTrue("PopObj" in pop_params[cell_pop]) + + self.assertTrue("Positions" in pop_params[cell_pop]) + + self.assertTrue("Compartments" in pop_params[cell_pop]) + + self.assertTrue(pop_params[cell_pop]["Positions"] == None) + + for pop_index in range(0, len(network.populations)): + pop = network.populations[pop_index] + + self.assertTrue(pop.id in popDict.keys()) + + self.assertTrue(popDict[pop.id][2] == pop.component) + + self.assertTrue(popDict[pop.id][0] == pop.size) + + for cell_loc in range(0, len(pop.instances)): + instance_case = pop.instances[cell_loc] + + location = instance_case.location + + self.assertTrue( + oc_build.distance([location.x, location.z], [0, 0]) <= 250 + ) + + self.assertTrue( + boundaries[popDict[pop.id][1]][0] >= location.y + and location.y >= boundaries[popDict[pop.id][1]][1] + ) + + ###### check storing of soma positions + + network = neuroml.Network(id="Net1") + + pop_params = oc_utils.add_populations_in_cylindrical_layers( + net=network, boundaryDict=boundaries, popDict=popDict, radiusOfCylinder=250 + ) + + for pop_index in range(0, len(network.populations)): + pop = network.populations[pop_index] + + stored_cell_positions = pop_params[pop.id]["Positions"] + + for cell_loc in range(0, len(pop.instances)): + instance_case = pop.instances[cell_loc] + + location = instance_case.location + + check_x = ( + abs(location.x - stored_cell_positions[cell_loc][0]) < 0.00000001 + ) + + check_y = ( + abs(location.y - stored_cell_positions[cell_loc][1]) < 0.00000001 + ) + + check_z = ( + abs(location.z - stored_cell_positions[cell_loc][2]) < 0.00000001 + ) + + self.assertTrue(check_x) + + self.assertTrue(check_y) + + self.assertTrue(check_z) + + ###### check distances between somata + + network = neuroml.Network(id="Net1") + + cell_diameters = {} + + for pop_id in popDict.keys(): + cell_diameter = oc_build.get_soma_diameter(popDict[pop_id][2]) + + cell_diameters[popDict[pop_id][2]] = cell_diameter + + pop_params = oc_utils.add_populations_in_cylindrical_layers( + net=network, + boundaryDict=boundaries, + popDict=popDict, + radiusOfCylinder=250, + cellBodiesOverlap=False, + cellDiameterArray=cell_diameters, + ) + + for pop_index in range(0, len(network.populations)): + pop = network.populations[pop_index] + + stored_cell_positions = pop_params[pop.id]["Positions"] + + for cell_loc in range(0, len(pop.instances)): + instance_case = pop.instances[cell_loc] + + location = instance_case.location + + check_x = ( + abs(location.x - stored_cell_positions[cell_loc][0]) < 0.00000001 + ) + + check_y = ( + abs(location.y - stored_cell_positions[cell_loc][1]) < 0.00000001 + ) + + check_z = ( + abs(location.z - stored_cell_positions[cell_loc][2]) < 0.00000001 + ) + + self.assertTrue(check_x) + + self.assertTrue(check_y) + + self.assertTrue(check_z) + + for cell_loc_inner in range(0, len(pop.instances)): + if cell_loc != cell_loc_inner: + inner_instance_case = pop.instances[cell_loc] + + inner_location = inner_instance_case.location + + d = oc_build.distance( + [location.x, location.y, location.z], + [inner_location.x, inner_location.y, inner_location.z], + ) + + self.assertTrue( + d + < ( + cell_diameters[pop.component] + + cell_diameters[pop.component] + ) + / 2 + ) + + for pop_index_inner in range(0, len(network.populations)): + pop_inner = network.populations[pop_index_inner] + + if pop.id != pop_inner.id: + for cell_loc_inner in range(0, len(pop_inner.instances)): + if cell_loc != cell_loc_inner: + inner_instance_case = pop.instances[cell_loc] + + inner_location = inner_instance_case.location + + d = oc_build.distance( + [location.x, location.y, location.z], + [ + inner_location.x, + inner_location.y, + inner_location.z, + ], + ) + + self.assertTrue( + d + < ( + cell_diameters[pop_inner.component] + + cell_diameters[pop_inner.component] + ) + / 2 + ) + + #### check cell distribution in the regular polygon, number of sides =6 + + network = neuroml.Network(id="Net1") + + pop_params = oc_utils.add_populations_in_cylindrical_layers( + net=network, + boundaryDict=boundaries, + popDict=popDict, + radiusOfCylinder=250, + numOfSides=6, + ) + + for cell_pop in popDict.keys(): + self.assertTrue(cell_pop in pop_params.keys()) + + self.assertTrue("PopObj" in pop_params[cell_pop]) + + self.assertTrue("Positions" in pop_params[cell_pop]) + + self.assertTrue("Compartments" in pop_params[cell_pop]) + + vertex_array = [] + + xy_sides = [] + + angle_array = np.linspace(0, 2 * math.pi * (1 - (1.0 / 6)), 6) + + for angle in angle_array: + vertex = [] + + x = 250 * math.cos(angle) + + y = 250 * math.sin(angle) + + vertex.append(x) + + vertex.append(y) + + vertex_array.append(vertex) + + for v_ind in range(0, len(vertex_array)): + v1 = vertex_array[v_ind] + + v2 = vertex_array[v_ind - 1] + + if abs(v1[0] - v2[0]) > 0.00000001 and abs(v1[1] - v2[1]) > 0.00000001: + A = np.array([[v1[0], 1], [v2[0], 1]]) + + b = np.array([v1[1], v2[1]]) + + xcyc = np.linalg.solve(A, b) - def test_read_connectivity(self): - - proj_info=oc_utils.read_connectivity(pre_pop='CG3D_L23PyrRS',post_pop='CG3D_L23PyrFRB',path_to_txt_file='ConnListTest') - - self.assertTrue(isinstance(proj_info,list)) - - for proj_ind in range(0,len(proj_info)): - - self.assertEqual(len(proj_info[proj_ind].keys() ), len(proj_info[proj_ind].values() ) ) - - self.assertTrue( 'SynapseList' in proj_info[proj_ind].keys() ) - self.assertTrue( 'PreCellGroup' in proj_info[proj_ind].keys() ) - self.assertTrue( 'PostCellGroup' in proj_info[proj_ind].keys() ) - self.assertTrue( 'Type' in proj_info[proj_ind].keys() ) - self.assertTrue( 'LocOnPostCell' in proj_info[proj_ind].keys() ) - self.assertTrue( 'NumPerPostCell' in proj_info[proj_ind].keys() or 'NumPerPreCell' in proj_info[proj_ind].keys() ) - - - def test_add_populations_in_rectangular_layers(self): - - network = neuroml.Network(id='Net0') - popDict={} - popDict['CG3D_L23PyrRS'] = (1000, 'L23','Test','multi',None) - popDict['CG3D_L23PyrFRB']= (50,'L23','Test2','multi',None) - t1=-0 - t2=-250 - t3=-250 - boundaries={} - boundaries['L1']=[0,t1] - boundaries['L23']=[t1,t1+t2+t3] - xs = [0,500] - zs = [0,500] - - pop_params=oc_utils.add_populations_in_rectangular_layers(net=network, - boundaryDict=boundaries, - popDict=popDict, - x_vector=xs, - z_vector=zs, - storeSoma=False) - - for cell_pop in popDict.keys(): - - self.assertTrue( cell_pop in pop_params.keys() ) - - self.assertTrue('PopObj' in pop_params[cell_pop] ) - - self.assertTrue('Positions' in pop_params[cell_pop] ) - - self.assertTrue('Compartments' in pop_params[cell_pop] ) - - self.assertTrue(pop_params[cell_pop]['Positions']==None) - - for pop_index in range(0,len(network.populations)): - - pop=network.populations[pop_index] - - self.assertTrue(pop.id in popDict.keys() ) - - self.assertTrue(popDict[pop.id][2]==pop.component ) - - self.assertTrue(popDict[pop.id][0]==pop.size ) - - for cell_loc in range(0,len(pop.instances) ): - - instance_case=pop.instances[cell_loc] - - location=instance_case.location - - self.assertTrue(xs[0] <= location.x and location.x <=xs[1] ) - - self.assertTrue(zs[0] <= location.z and location.z <= zs[1] ) - - self.assertTrue(boundaries[popDict[pop.id][1]][0] >= location.y and location.y >= boundaries[popDict[pop.id][1]][1] ) - - ###### check storing of soma positions - - network = neuroml.Network(id='Net1') - - pop_params=oc_utils.add_populations_in_rectangular_layers(net=network, - boundaryDict=boundaries, - popDict=popDict, - x_vector=xs, - z_vector=zs) - - for pop_index in range(0,len(network.populations)): - - pop=network.populations[pop_index] - - stored_cell_positions=pop_params[pop.id]['Positions'] - - for cell_loc in range(0,len(pop.instances) ): - - instance_case=pop.instances[cell_loc] - - location=instance_case.location - - check_x= abs(location.x-stored_cell_positions[cell_loc][0]) < 0.00005 - check_y= abs(location.y-stored_cell_positions[cell_loc][1]) < 0.00005 - check_z= abs(location.z-stored_cell_positions[cell_loc][2]) < 0.00005 - - self.assertTrue(check_x) - - self.assertTrue(check_y) - - self.assertTrue(check_z) - - ###### check distances between somata - - network = neuroml.Network(id='Net1') - - cell_diameters={} - - for pop_id in popDict.keys(): - - cell_diameter=oc_build.get_soma_diameter(popDict[pop_id][2]) - - cell_diameters[popDict[pop_id][2]]=cell_diameter - - pop_params=oc_utils.add_populations_in_rectangular_layers(net=network, - boundaryDict=boundaries, - popDict=popDict, - x_vector=xs, - z_vector=zs, - cellBodiesOverlap=False, - cellDiameterArray=cell_diameters) - - for pop_index in range(0,len(network.populations)): - - pop=network.populations[pop_index] - - stored_cell_positions=pop_params[pop.id]['Positions'] - - for cell_loc in range(0,len(pop.instances) ): - - instance_case=pop.instances[cell_loc] - - location=instance_case.location - - check_x= abs(location.x-stored_cell_positions[cell_loc][0]) < 0.00001 - - check_y= abs(location.y-stored_cell_positions[cell_loc][1]) < 0.00001 - - check_z= abs(location.z-stored_cell_positions[cell_loc][2]) < 0.00001 - - self.assertTrue(check_x) - - self.assertTrue(check_y) - - self.assertTrue(check_z) - - for cell_loc_inner in range(0,len(pop.instances) ): - - if cell_loc != cell_loc_inner: - - inner_instance_case=pop.instances[cell_loc] - - inner_location=inner_instance_case.location - - d=oc_build.distance([location.x, location.y,location.z],[inner_location.x,inner_location.y,inner_location.z]) - - self.assertTrue( d < (cell_diameters[pop.component]+cell_diameters[pop.component] )/2 ) - - for pop_index_inner in range(0,len(network.populations)): - - pop_inner=network.populations[pop_index_inner] - - if pop.id != pop_inner.id: - - for cell_loc_inner in range(0,len(pop_inner.instances) ): - - if cell_loc != cell_loc_inner: - - inner_instance_case=pop.instances[cell_loc] - - inner_location=inner_instance_case.location - - d=oc_build.distance([location.x, location.y,location.z],[inner_location.x,inner_location.y,inner_location.z]) - - self.assertTrue( d < (cell_diameters[pop_inner.component]+cell_diameters[pop_inner.component] )/2 ) - - - def test_add_populations_in_cylindrical_layers(self): - - network = neuroml.Network(id='Net0') - popDict={} - popDict['CG3D_L23PyrRS'] = (1000, 'L23','Test','multi',None) - popDict['CG3D_L23PyrFRB']= (50,'L23','Test2','multi',None) - t1=-0 - t2=-250 - t3=-250 - boundaries={} - boundaries['L1']=[0,t1] - boundaries['L23']=[t1,t1+t2+t3] - xs = [0,500] - zs = [0,500] - - pop_params=oc_utils.add_populations_in_cylindrical_layers(net=network, - boundaryDict=boundaries, - popDict=popDict, - radiusOfCylinder=250, - storeSoma=False) - - for cell_pop in popDict.keys(): - - self.assertTrue( cell_pop in pop_params.keys() ) - - self.assertTrue('PopObj' in pop_params[cell_pop] ) - - self.assertTrue('Positions' in pop_params[cell_pop] ) - - self.assertTrue('Compartments' in pop_params[cell_pop] ) - - self.assertTrue(pop_params[cell_pop]['Positions']==None) - - for pop_index in range(0,len(network.populations)): - - pop=network.populations[pop_index] - - self.assertTrue(pop.id in popDict.keys() ) - - self.assertTrue(popDict[pop.id][2]==pop.component ) - - self.assertTrue(popDict[pop.id][0]==pop.size ) - - for cell_loc in range(0,len(pop.instances) ): - - instance_case=pop.instances[cell_loc] - - location=instance_case.location - - self.assertTrue(oc_build.distance([location.x,location.z],[0,0]) <= 250 ) - - self.assertTrue(boundaries[popDict[pop.id][1]][0] >= location.y and location.y >= boundaries[popDict[pop.id][1]][1] ) - - ###### check storing of soma positions - - network = neuroml.Network(id='Net1') - - pop_params=oc_utils.add_populations_in_cylindrical_layers(net=network, - boundaryDict=boundaries, - popDict=popDict, - radiusOfCylinder=250) - - for pop_index in range(0,len(network.populations)): - - pop=network.populations[pop_index] - - stored_cell_positions=pop_params[pop.id]['Positions'] - - for cell_loc in range(0,len(pop.instances) ): - - instance_case=pop.instances[cell_loc] - - location=instance_case.location - - check_x= abs(location.x-stored_cell_positions[cell_loc][0]) < 0.00000001 - - check_y= abs(location.y-stored_cell_positions[cell_loc][1]) < 0.00000001 - - check_z= abs(location.z-stored_cell_positions[cell_loc][2]) < 0.00000001 - - self.assertTrue(check_x) - - self.assertTrue(check_y) - - self.assertTrue(check_z) - - ###### check distances between somata - - network = neuroml.Network(id='Net1') - - cell_diameters={} - - for pop_id in popDict.keys(): - - cell_diameter=oc_build.get_soma_diameter(popDict[pop_id][2]) - - cell_diameters[popDict[pop_id][2]]=cell_diameter - - pop_params=oc_utils.add_populations_in_cylindrical_layers(net=network, - boundaryDict=boundaries, - popDict=popDict, - radiusOfCylinder=250, - cellBodiesOverlap=False, - cellDiameterArray=cell_diameters) - - for pop_index in range(0,len(network.populations)): - - pop=network.populations[pop_index] - - stored_cell_positions=pop_params[pop.id]['Positions'] - - for cell_loc in range(0,len(pop.instances) ): - - instance_case=pop.instances[cell_loc] - - location=instance_case.location - - check_x= abs(location.x-stored_cell_positions[cell_loc][0]) < 0.00000001 - - check_y= abs(location.y-stored_cell_positions[cell_loc][1]) < 0.00000001 - - check_z= abs(location.z-stored_cell_positions[cell_loc][2]) < 0.00000001 - - self.assertTrue(check_x) - - self.assertTrue(check_y) - - self.assertTrue(check_z) - - for cell_loc_inner in range(0,len(pop.instances) ): - - if cell_loc != cell_loc_inner: - - inner_instance_case=pop.instances[cell_loc] - - inner_location=inner_instance_case.location - - d=oc_build.distance([location.x, location.y,location.z],[inner_location.x,inner_location.y,inner_location.z]) - - self.assertTrue( d < (cell_diameters[pop.component]+cell_diameters[pop.component] )/2 ) - - for pop_index_inner in range(0,len(network.populations)): - - pop_inner=network.populations[pop_index_inner] - - if pop.id != pop_inner.id: - - for cell_loc_inner in range(0,len(pop_inner.instances) ): - - if cell_loc != cell_loc_inner: - - inner_instance_case=pop.instances[cell_loc] - - inner_location=inner_instance_case.location - - d=oc_build.distance([location.x, location.y,location.z],[inner_location.x,inner_location.y,inner_location.z]) - - self.assertTrue( d < (cell_diameters[pop_inner.component]+cell_diameters[pop_inner.component] )/2 ) - - #### check cell distribution in the regular polygon, number of sides =6 - - network = neuroml.Network(id='Net1') - - pop_params=oc_utils.add_populations_in_cylindrical_layers(net=network, - boundaryDict=boundaries, - popDict=popDict, - radiusOfCylinder=250, - numOfSides=6) - - for cell_pop in popDict.keys(): - - self.assertTrue( cell_pop in pop_params.keys() ) - - self.assertTrue('PopObj' in pop_params[cell_pop] ) - - self.assertTrue('Positions' in pop_params[cell_pop] ) - - self.assertTrue('Compartments' in pop_params[cell_pop] ) - - vertex_array=[] - - xy_sides=[] - - angle_array=np.linspace(0, 2*math.pi*(1-(1.0 /6) ),6) - - for angle in angle_array: - - vertex=[] - - x=250*math.cos(angle) - - y=250*math.sin(angle) - - vertex.append(x) - - vertex.append(y) - - vertex_array.append(vertex) - - for v_ind in range(0,len(vertex_array)): - - v1=vertex_array[v_ind] - - v2=vertex_array[v_ind-1] - - if abs(v1[0] - v2[0]) > 0.00000001 and abs(v1[1] -v2[1]) > 0.00000001: - - A=np.array([[v1[0],1],[v2[0],1]]) - - b=np.array([v1[1],v2[1]]) - - xcyc=np.linalg.solve(A,b) - xy_sides.append(list(xcyc)) - - else: - + + else: if abs(v1[0] - v2[0]) <= 0.00000001: - - xy_sides.append([v1[0], None] ) - - if abs(v1[1] -v2[1] ) <= 0.00000001: - - xy_sides.append([None,v1[1]] ) - - for pop_index in range(0,len(network.populations)): - - pop=network.populations[pop_index] - - self.assertTrue(pop.id in popDict.keys() ) - - self.assertTrue(popDict[pop.id][2]==pop.component ) - - self.assertTrue(popDict[pop.id][0]==pop.size ) - - for cell_loc in range(0,len(pop.instances) ): - - instance_case=pop.instances[cell_loc] - - location=instance_case.location - - self.assertTrue(oc_build.distance([location.x,location.z],[0,0]) <= 250 ) - - self.assertTrue(boundaries[popDict[pop.id][1]][0] >= location.y and location.y >= boundaries[popDict[pop.id][1]][1] ) - - count_intersections=0 - - for side_index in range(0,len(xy_sides) ): - - if abs(vertex_array[side_index][1] - vertex_array[side_index-1][1]) > 0.0000001: - - if location.z < vertex_array[side_index][1] and location.z > vertex_array[side_index-1][1] : - - if xy_sides[side_index][0] !=None and xy_sides[side_index][1]==None : - + xy_sides.append([v1[0], None]) + + if abs(v1[1] - v2[1]) <= 0.00000001: + xy_sides.append([None, v1[1]]) + + for pop_index in range(0, len(network.populations)): + pop = network.populations[pop_index] + + self.assertTrue(pop.id in popDict.keys()) + + self.assertTrue(popDict[pop.id][2] == pop.component) + + self.assertTrue(popDict[pop.id][0] == pop.size) + + for cell_loc in range(0, len(pop.instances)): + instance_case = pop.instances[cell_loc] + + location = instance_case.location + + self.assertTrue( + oc_build.distance([location.x, location.z], [0, 0]) <= 250 + ) + + self.assertTrue( + boundaries[popDict[pop.id][1]][0] >= location.y + and location.y >= boundaries[popDict[pop.id][1]][1] + ) + + count_intersections = 0 + + for side_index in range(0, len(xy_sides)): + if ( + abs( + vertex_array[side_index][1] + - vertex_array[side_index - 1][1] + ) + > 0.0000001 + ): + if ( + location.z < vertex_array[side_index][1] + and location.z > vertex_array[side_index - 1][1] + ): + if ( + xy_sides[side_index][0] != None + and xy_sides[side_index][1] == None + ): + if location.x <= xy_sides[side_index][0]: + count_intersections += 1 + + if ( + xy_sides[side_index][0] != None + and xy_sides[side_index][1] != None + ): + if ( + location.x + <= (location.z - xy_sides[side_index][1]) + / xy_sides[side_index][0] + ): + count_intersections += 1 + + if ( + location.z < vertex_array[side_index - 1][1] + and location.z > vertex_array[side_index][1] + ): + if ( + xy_sides[side_index][0] != None + and xy_sides[side_index][1] == None + ): if location.x <= xy_sides[side_index][0]: - - count_intersections+=1 - - if xy_sides[side_index][0] != None and xy_sides[side_index][1] != None: - - if location.x <= (location.z - xy_sides[side_index][1]) / xy_sides[side_index][0]: - - count_intersections +=1 - - if location.z < vertex_array[side_index-1][1] and location.z > vertex_array[side_index][1]: - - if xy_sides[side_index][0] !=None and xy_sides[side_index][1]==None : - - if location.x <= xy_sides[side_index][0]: - - count_intersections+=1 - - if xy_sides[side_index][0] != None and xy_sides[side_index][1] != None: - - if location.x <= (location.z - xy_sides[side_index][1]) / xy_sides[side_index][0]: - - count_intersections +=1 - - self.assertTrue( count_intersections ==1) - ############################################################################# - - def test_check_cached_dicts(self): - - cached_target_dict={} - - PostSegLengthDict, cached_target_dict =oc_utils.check_cached_dicts(cell_component="Test", - cached_dicts=cached_target_dict, - list_of_target_seg_groups=['basal_obl_dends'], - path_to_nml2=None) - - self.assertTrue( 'basal_obl_dends' in PostSegLengthDict.keys() ) - - self.assertTrue('SegList' in PostSegLengthDict['basal_obl_dends'].keys() ) - - self.assertTrue(PostSegLengthDict['basal_obl_dends']['SegList'] != None) - - self.assertTrue('LengthDist' in PostSegLengthDict['basal_obl_dends'].keys() ) - - self.assertTrue(PostSegLengthDict['basal_obl_dends']['LengthDist'] != None ) - - self.assertTrue( 'Test' in cached_target_dict.keys() ) - - self.assertTrue( 'TargetDict' in cached_target_dict['Test'].keys() ) - - self.assertTrue( cached_target_dict['Test']['TargetDict']['basal_obl_dends']['SegList'] != None) - - self.assertTrue( cached_target_dict['Test']['TargetDict']['basal_obl_dends']['LengthDist'] != None) - - self.assertTrue( 'CellObject' in cached_target_dict['Test'].keys() ) - - self.assertTrue(cached_target_dict['Test']['CellObject'].id =="L23PyrRS" ) - - PostSegLengthDict, cached_target_dict =oc_utils.check_cached_dicts(cell_component="Test", - cached_dicts=cached_target_dict, - list_of_target_seg_groups=['distal_axon'], - path_to_nml2=None) - - self.assertTrue( 'basal_obl_dends' not in PostSegLengthDict.keys() ) - - self.assertTrue( 'distal_axon' in PostSegLengthDict.keys() ) - - self.assertTrue('SegList' in PostSegLengthDict['distal_axon'].keys() ) - - self.assertTrue(PostSegLengthDict['distal_axon']['SegList'] != None) - - self.assertTrue('LengthDist' in PostSegLengthDict['distal_axon'].keys() ) - - self.assertTrue(PostSegLengthDict['distal_axon']['LengthDist'] != None ) - - self.assertTrue( 'Test' in cached_target_dict.keys() ) - - self.assertTrue( 'TargetDict' in cached_target_dict['Test'].keys() ) - - self.assertTrue( cached_target_dict['Test']['TargetDict']['basal_obl_dends']['SegList'] != None) - - self.assertTrue( cached_target_dict['Test']['TargetDict']['basal_obl_dends']['LengthDist'] != None) - - self.assertTrue( cached_target_dict['Test']['TargetDict']['distal_axon']['SegList'] != None) - - self.assertTrue( cached_target_dict['Test']['TargetDict']['distal_axon']['LengthDist'] != None) - - self.assertTrue( 'CellObject' in cached_target_dict['Test'].keys() ) - - self.assertTrue(cached_target_dict['Test']['CellObject'].id =="L23PyrRS" ) - - def test_build_connectivity(self): - - network = neuroml.Network(id='Net0') - popDict={} - popDict['CG3D_L23PyrRS'] = (1000, 'L23','Test','multi',None) - popDict['CG3D_L23PyrFRB']= (50,'L23','Test2','multi',None) - t1=-0 - t2=-250 - t3=-250 - boundaries={} - boundaries['L1']=[0,t1] - boundaries['L23']=[t1,t1+t2+t3] - xs = [0,500] - zs = [0,500] - - pop_params=oc_utils.add_populations_in_rectangular_layers(net=network, - boundaryDict=boundaries, - popDict=popDict, - x_vector=xs, - z_vector=zs) - - all_synapse_components,proj_array,cached_segment_dicts=oc_utils.build_connectivity(net=network, - pop_objects=pop_params, - path_to_cells=None, - full_path_to_conn_summary='ConnListTest', - pre_segment_group_info=[{'PreSegGroup':"distal_axon",'ProjType':'Chem'}], - synaptic_scaling_params=[{'weight':2.0, - 'synComp':'AMPA', - 'synEndsWith':[], - 'targetCellGroup':[]}], - synaptic_delay_params=[{'delay':0.05,'synComp':'all'}]) - - - self.assertTrue(all_synapse_components != []) - - self.assertTrue(proj_array != []) - - self.assertTrue(cached_segment_dicts != []) - - self.assertTrue( network.projections != []) - - self.assertTrue( network.electrical_projections != []) - - self.assertTrue(len(network.projections)==8) - - num_of_checked_chemical_projections=0 - - num_of_checked_electrical_projections=0 - - test_group_segments={} - - for pre_pop_id in popDict.keys(): - - for post_pop_id in popDict.keys(): - - proj_summary=oc_utils.read_connectivity(pre_pop=pre_pop_id,post_pop=post_pop_id,path_to_txt_file='ConnListTest') - - for proj_ind in range(0,len(proj_summary)): - - projInfo=proj_summary[proj_ind] - - synapse_list=projInfo['SynapseList'] - - num_per_post_cell=float(projInfo['NumPerPostCell']) - - for syn_ind in range(0,len(synapse_list) ): - - if projInfo['Type']=='Chem': - - for net_proj in range(0,len(network.projections) ): - - proj=network.projections[net_proj] - - if proj.presynaptic_population==pre_pop_id and proj.postsynaptic_population==post_pop_id and proj.synapse==synapse_list[syn_ind]: - - num_of_checked_chemical_projections+=1 - - pre_segments=[146, 147, 142, 143] - - post_segments=[16, 17, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 24, 25, 22, 23, 20, 21, 18, 19, 40, 41, 38, 39, 36, 37, 34, 35, 32, 33, 30, 31, 28, 29, 26, 27, 48, 49, 46, 47, 44, 45, 42, 43, 64, 65, 62, 63, 60, 61, 58, 59, 56, 57, 54, 55, 52, 53, 50, 51, 72, 73, 70, 71, 68, 69, 66, 67] - - self.assertTrue( len(proj.connection_wds) ==float(num_per_post_cell) * popDict[post_pop_id][0] ) - - for conn_index in range(0,len(proj.connection_wds) ): - - connection=proj.connection_wds[conn_index] - - self.assertTrue( connection.pre_segment_id in pre_segments ) - - self.assertTrue( connection.post_segment_id in post_segments ) - - delay_value=float(connection.delay.split(" ")[0] ) - - self.assertTrue( delay_value == 0.05) - - if 'AMPA' in proj.synapse: - - self.assertTrue(connection.weight ==2 ) - + count_intersections += 1 + + if ( + xy_sides[side_index][0] != None + and xy_sides[side_index][1] != None + ): + if ( + location.x + <= (location.z - xy_sides[side_index][1]) + / xy_sides[side_index][0] + ): + count_intersections += 1 + + self.assertTrue(count_intersections == 1) + + ############################################################################# + + def test_check_cached_dicts(self): + cached_target_dict = {} + + PostSegLengthDict, cached_target_dict = oc_utils.check_cached_dicts( + cell_component="Test", + cached_dicts=cached_target_dict, + list_of_target_seg_groups=["basal_obl_dends"], + path_to_nml2=None, + ) + + self.assertTrue("basal_obl_dends" in PostSegLengthDict.keys()) + + self.assertTrue("SegList" in PostSegLengthDict["basal_obl_dends"].keys()) + + self.assertTrue(PostSegLengthDict["basal_obl_dends"]["SegList"] != None) + + self.assertTrue("LengthDist" in PostSegLengthDict["basal_obl_dends"].keys()) + + self.assertTrue(PostSegLengthDict["basal_obl_dends"]["LengthDist"] != None) + + self.assertTrue("Test" in cached_target_dict.keys()) + + self.assertTrue("TargetDict" in cached_target_dict["Test"].keys()) + + self.assertTrue( + cached_target_dict["Test"]["TargetDict"]["basal_obl_dends"]["SegList"] + != None + ) + + self.assertTrue( + cached_target_dict["Test"]["TargetDict"]["basal_obl_dends"]["LengthDist"] + != None + ) + + self.assertTrue("CellObject" in cached_target_dict["Test"].keys()) + + self.assertTrue(cached_target_dict["Test"]["CellObject"].id == "L23PyrRS") + + PostSegLengthDict, cached_target_dict = oc_utils.check_cached_dicts( + cell_component="Test", + cached_dicts=cached_target_dict, + list_of_target_seg_groups=["distal_axon"], + path_to_nml2=None, + ) + + self.assertTrue("basal_obl_dends" not in PostSegLengthDict.keys()) + + self.assertTrue("distal_axon" in PostSegLengthDict.keys()) + + self.assertTrue("SegList" in PostSegLengthDict["distal_axon"].keys()) + + self.assertTrue(PostSegLengthDict["distal_axon"]["SegList"] != None) + + self.assertTrue("LengthDist" in PostSegLengthDict["distal_axon"].keys()) + + self.assertTrue(PostSegLengthDict["distal_axon"]["LengthDist"] != None) + + self.assertTrue("Test" in cached_target_dict.keys()) + + self.assertTrue("TargetDict" in cached_target_dict["Test"].keys()) + + self.assertTrue( + cached_target_dict["Test"]["TargetDict"]["basal_obl_dends"]["SegList"] + != None + ) + + self.assertTrue( + cached_target_dict["Test"]["TargetDict"]["basal_obl_dends"]["LengthDist"] + != None + ) + + self.assertTrue( + cached_target_dict["Test"]["TargetDict"]["distal_axon"]["SegList"] != None + ) + + self.assertTrue( + cached_target_dict["Test"]["TargetDict"]["distal_axon"]["LengthDist"] + != None + ) + + self.assertTrue("CellObject" in cached_target_dict["Test"].keys()) + + self.assertTrue(cached_target_dict["Test"]["CellObject"].id == "L23PyrRS") + + def test_build_connectivity(self): + network = neuroml.Network(id="Net0") + popDict = {} + popDict["CG3D_L23PyrRS"] = (1000, "L23", "Test", "multi", None) + popDict["CG3D_L23PyrFRB"] = (50, "L23", "Test2", "multi", None) + t1 = -0 + t2 = -250 + t3 = -250 + boundaries = {} + boundaries["L1"] = [0, t1] + boundaries["L23"] = [t1, t1 + t2 + t3] + xs = [0, 500] + zs = [0, 500] + + pop_params = oc_utils.add_populations_in_rectangular_layers( + net=network, + boundaryDict=boundaries, + popDict=popDict, + x_vector=xs, + z_vector=zs, + ) + + all_synapse_components, proj_array, cached_segment_dicts = ( + oc_utils.build_connectivity( + net=network, + pop_objects=pop_params, + path_to_cells=None, + full_path_to_conn_summary="ConnListTest", + pre_segment_group_info=[ + {"PreSegGroup": "distal_axon", "ProjType": "Chem"} + ], + synaptic_scaling_params=[ + { + "weight": 2.0, + "synComp": "AMPA", + "synEndsWith": [], + "targetCellGroup": [], + } + ], + synaptic_delay_params=[{"delay": 0.05, "synComp": "all"}], + ) + ) + + self.assertTrue(all_synapse_components != []) + + self.assertTrue(proj_array != []) + + self.assertTrue(cached_segment_dicts != []) + + self.assertTrue(network.projections != []) + + self.assertTrue(network.electrical_projections != []) + + self.assertTrue(len(network.projections) == 8) + + num_of_checked_chemical_projections = 0 + + num_of_checked_electrical_projections = 0 + + test_group_segments = {} + + for pre_pop_id in popDict.keys(): + for post_pop_id in popDict.keys(): + proj_summary = oc_utils.read_connectivity( + pre_pop=pre_pop_id, + post_pop=post_pop_id, + path_to_txt_file="ConnListTest", + ) + + for proj_ind in range(0, len(proj_summary)): + projInfo = proj_summary[proj_ind] + + synapse_list = projInfo["SynapseList"] + + num_per_post_cell = float(projInfo["NumPerPostCell"]) + + for syn_ind in range(0, len(synapse_list)): + if projInfo["Type"] == "Chem": + for net_proj in range(0, len(network.projections)): + proj = network.projections[net_proj] + + if ( + proj.presynaptic_population == pre_pop_id + and proj.postsynaptic_population == post_pop_id + and proj.synapse == synapse_list[syn_ind] + ): + num_of_checked_chemical_projections += 1 + + pre_segments = [146, 147, 142, 143] + + post_segments = [ + 16, + 17, + 14, + 15, + 12, + 13, + 10, + 11, + 8, + 9, + 6, + 7, + 4, + 5, + 2, + 3, + 24, + 25, + 22, + 23, + 20, + 21, + 18, + 19, + 40, + 41, + 38, + 39, + 36, + 37, + 34, + 35, + 32, + 33, + 30, + 31, + 28, + 29, + 26, + 27, + 48, + 49, + 46, + 47, + 44, + 45, + 42, + 43, + 64, + 65, + 62, + 63, + 60, + 61, + 58, + 59, + 56, + 57, + 54, + 55, + 52, + 53, + 50, + 51, + 72, + 73, + 70, + 71, + 68, + 69, + 66, + 67, + ] + + self.assertTrue( + len(proj.connection_wds) + == float(num_per_post_cell) + * popDict[post_pop_id][0] + ) + + for conn_index in range( + 0, len(proj.connection_wds) + ): + connection = proj.connection_wds[conn_index] + + self.assertTrue( + connection.pre_segment_id in pre_segments + ) + + self.assertTrue( + connection.post_segment_id in post_segments + ) + + delay_value = float( + connection.delay.split(" ")[0] + ) + + self.assertTrue(delay_value == 0.05) + + if "AMPA" in proj.synapse: + self.assertTrue(connection.weight == 2) + break - - if projInfo['Type']=='Elect': - - for net_proj in range(0,len(network.electrical_projections) ): - - proj=network.electrical_projections[net_proj] - - check_synapse=proj.electrical_connection_instance_ws[0].synapse==synapse_list[syn_ind] - - if proj.presynaptic_population==pre_pop_id and proj.postsynaptic_population==post_pop_id and check_synapse: - - num_of_checked_electrical_projections+=1 - - pre_segments=[136, 137, 138, 139, 144, 145, 140, 141, 146, 147, 142, 143] - - post_segments=[136, 137, 138, 139, 144, 145, 140, 141, 146, 147, 142, 143] - - for conn_index in range(0,len(proj.electrical_connection_instance_ws) ): - - connection= proj.electrical_connection_instance_ws[conn_index] - - self.assertTrue( connection.pre_segment in pre_segments ) - - self.assertTrue( connection.post_segment in post_segments ) - + + if projInfo["Type"] == "Elect": + for net_proj in range( + 0, len(network.electrical_projections) + ): + proj = network.electrical_projections[net_proj] + + check_synapse = ( + proj.electrical_connection_instance_ws[0].synapse + == synapse_list[syn_ind] + ) + + if ( + proj.presynaptic_population == pre_pop_id + and proj.postsynaptic_population == post_pop_id + and check_synapse + ): + num_of_checked_electrical_projections += 1 + + pre_segments = [ + 136, + 137, + 138, + 139, + 144, + 145, + 140, + 141, + 146, + 147, + 142, + 143, + ] + + post_segments = [ + 136, + 137, + 138, + 139, + 144, + 145, + 140, + 141, + 146, + 147, + 142, + 143, + ] + + for conn_index in range( + 0, len(proj.electrical_connection_instance_ws) + ): + connection = ( + proj.electrical_connection_instance_ws[ + conn_index + ] + ) + + self.assertTrue( + connection.pre_segment in pre_segments + ) + + self.assertTrue( + connection.post_segment in post_segments + ) + break - - self.assertTrue(num_of_checked_chemical_projections == 8) - - def test_probability_based_connectivity(self): - - network = neuroml.Network(id='Net0') - popDict={} - popDict['CG3D_L23PyrRS'] = (1000, 'L23','Test','single',None) - popDict['CG3D_L23PyrFRB']= (50,'L23','Test2','single',None) - t1=-0 - t2=-250 - t3=-250 - boundaries={} - boundaries['L1']=[0,t1] - boundaries['L23']=[t1,t1+t2+t3] - xs = [0,500] - zs = [0,500] - - pop_params=oc_utils.add_populations_in_rectangular_layers(net=network, - boundaryDict=boundaries, - popDict=popDict, - x_vector=xs, - z_vector=zs) - - prob_matrix=[[0.0,0.5], - [0.9,0.0]] - - syn_matrix=[[None,['Syn1','Syn2']], - [['Syn1','Syn2'],None]] - - pop_tags=['L23PyrRS','L23PyrFRB'] - - w_matrix=[[None,2.0], - [1.0,None]] - - d_matrix=[[0.05,0.05], - [0.05,0.05]] - - proj_array=oc_utils.build_probability_based_connectivity(net=network, - pop_params=pop_params, - probability_matrix=prob_matrix, - synapse_matrix=syn_matrix, - weight_matrix=w_matrix, - delay_matrix=d_matrix, - tags_on_populations=pop_tags, - std_weight_matrix=None, - std_delay_matrix=None) - - - self.assertTrue(len(network.projections)==4) - - found_projections=0 - - count_zero_projections=0 - - source_L23PyrFRB_projections=[] - - source_L23PyrRS_projections=[] - - for proj_ind in range(0,len(network.projections) ): - - proj=network.projections[proj_ind] - - pre_id=proj.presynaptic_population - - post_id=proj.postsynaptic_population - - if pre_id =='CG3D_L23PyrFRB': - + + self.assertTrue(num_of_checked_chemical_projections == 8) + + def test_probability_based_connectivity(self): + network = neuroml.Network(id="Net0") + popDict = {} + popDict["CG3D_L23PyrRS"] = (1000, "L23", "Test", "single", None) + popDict["CG3D_L23PyrFRB"] = (50, "L23", "Test2", "single", None) + t1 = -0 + t2 = -250 + t3 = -250 + boundaries = {} + boundaries["L1"] = [0, t1] + boundaries["L23"] = [t1, t1 + t2 + t3] + xs = [0, 500] + zs = [0, 500] + + pop_params = oc_utils.add_populations_in_rectangular_layers( + net=network, + boundaryDict=boundaries, + popDict=popDict, + x_vector=xs, + z_vector=zs, + ) + + prob_matrix = [[0.0, 0.5], [0.9, 0.0]] + + syn_matrix = [[None, ["Syn1", "Syn2"]], [["Syn1", "Syn2"], None]] + + pop_tags = ["L23PyrRS", "L23PyrFRB"] + + w_matrix = [[None, 2.0], [1.0, None]] + + d_matrix = [[0.05, 0.05], [0.05, 0.05]] + + proj_array = oc_utils.build_probability_based_connectivity( + net=network, + pop_params=pop_params, + probability_matrix=prob_matrix, + synapse_matrix=syn_matrix, + weight_matrix=w_matrix, + delay_matrix=d_matrix, + tags_on_populations=pop_tags, + std_weight_matrix=None, + std_delay_matrix=None, + ) + + self.assertTrue(len(network.projections) == 4) + + found_projections = 0 + + count_zero_projections = 0 + + source_L23PyrFRB_projections = [] + + source_L23PyrRS_projections = [] + + for proj_ind in range(0, len(network.projections)): + proj = network.projections[proj_ind] + + pre_id = proj.presynaptic_population + + post_id = proj.postsynaptic_population + + if pre_id == "CG3D_L23PyrFRB": source_L23PyrFRB_projections.append(proj.synapse) - - if post_id == 'CG3D_L23PyrRS': - + + if post_id == "CG3D_L23PyrRS": source_L23PyrRS_projections.append(proj.synapse) - - for pop_tag_index in range(0,len(pop_tags)): - - if pop_tags[pop_tag_index] in pre_id: - - pre_pop_index=pop_tag_index - - if pop_tags[pop_tag_index] in post_id: - - post_pop_index=pop_tag_index - - for row_index in range(0,len(syn_matrix)): - - for col_index in range(0,len(syn_matrix[row_index])): - - if isinstance(syn_matrix[row_index][col_index], list): - - for syn_component in range(0,len(syn_matrix[row_index][col_index])): - - check_component=syn_matrix[row_index][col_index][syn_component] == proj.synapse - - check_pre_pop=pop_tags[col_index] in pre_id - - check_post_pop=pop_tags[row_index] in post_id - + + for pop_tag_index in range(0, len(pop_tags)): + if pop_tags[pop_tag_index] in pre_id: + pre_pop_index = pop_tag_index + + if pop_tags[pop_tag_index] in post_id: + post_pop_index = pop_tag_index + + for row_index in range(0, len(syn_matrix)): + for col_index in range(0, len(syn_matrix[row_index])): + if isinstance(syn_matrix[row_index][col_index], list): + for syn_component in range( + 0, len(syn_matrix[row_index][col_index]) + ): + check_component = ( + syn_matrix[row_index][col_index][syn_component] + == proj.synapse + ) + + check_pre_pop = pop_tags[col_index] in pre_id + + check_post_pop = pop_tags[row_index] in post_id + if check_component and check_pre_pop and check_post_pop: - - found_projections+=1 - - for conn_index in range(0,len(network.projections[proj_ind].connection_wds)): - - connection=network.projections[proj_ind].connection_wds[conn_index] - - self.assertTrue( connection.weight == w_matrix[post_pop_index][pre_pop_index] ) - - self.assertTrue(str( d_matrix[post_pop_index][pre_pop_index]) in connection.delay ) - - self.assertTrue( found_projections ==4) - - self.assertTrue( set(source_L23PyrFRB_projections) == set (['Syn1','Syn2']) ) - - self.assertTrue( set( source_L23PyrRS_projections) == set(['Syn1','Syn2']) ) - - def test_build_inputs(self): - - nml_doc, network = oc.generate_network('Net0') - popDict={} - popDict['CG3D_L23PyrRS'] = (2, 'L23','Test','multi',None) - popDict['CG3D_L23PyrFRB']= (10,'L23','Test2','multi',None) - popDict['CG3D_PointNeurons']=(1,'L23','SingleCompartment','single',None) - t1=-0 - t2=-250 - t3=-250 - boundaries={} - boundaries['L1']=[0,t1] - boundaries['L23']=[t1,t1+t2+t3] - xs = [0,50] - zs = [0,50] - - pop_params=oc_utils.add_populations_in_rectangular_layers(net=network, - boundaryDict=boundaries, - popDict=popDict, - x_vector=xs, - z_vector=zs) - - all_synapse_components,proj_array,cached_segment_dicts=oc_utils.build_connectivity(net=network, - pop_objects=pop_params, - path_to_cells=None, - full_path_to_conn_summary='ConnListTest', - pre_segment_group_info=[{'PreSegGroup':"distal_axon",'ProjType':'Chem'}], - synaptic_scaling_params=[{'weight':2.0, - 'synComp':'AMPA', - 'synEndsWith':[], - 'targetCellGroup':[]}], - synaptic_delay_params=[{'delay':0.05,'synComp':'all'}]) - - - cell_nml_file = 'Test.cell.nml' - - document_cell = neuroml.loaders.NeuroMLLoader.load(cell_nml_file) - - cell_object=document_cell.cells[0] - - CG3D_L23PyrRS_target_segs=oc_build.extract_seg_ids(cell_object, - target_compartment_array=['dendrite_group'], - targeting_mode='segGroups') - - - CG3D_L23PyrRS_target_segs=CG3D_L23PyrRS_target_segs['dendrite_group'] - - cell_nml_file = 'Test2.cell.nml' - - document_cell = neuroml.loaders.NeuroMLLoader.load(cell_nml_file) - - cell_object=document_cell.cells[0] - - CG3D_L23PyrFRB_target_segs=oc_build.extract_seg_ids(cell_object, - target_compartment_array=['dendrite_group'], - targeting_mode='segGroups') - - CG3D_L23PyrFRB_target_segs=CG3D_L23PyrFRB_target_segs['dendrite_group'] - - input_params ={'CG3D_L23PyrRS':[{'InputType':'PulseGenerators', - 'InputName':"DepCurr_L23RS", - 'Noise':True, - 'SmallestAmplitudeList':[5.0E-5], - 'LargestAmplitudeList':[1.0E-4], - 'DurationList':[20000.0], - 'DelayList':[0.0], - 'TimeUnits':'ms', - 'AmplitudeUnits':'uA', - 'FractionToTarget':1.0, - 'LocationSpecific':False, - 'UniversalTargetSegmentID':0, - 'UniversalFractionAlong':0.5}, - - {'InputType':'GeneratePoissonTrains', - 'InputName':"BackgroundL23RS", - 'TrainType':'persistent', - 'Synapse':'Syn_AMPA_SupPyr_SupPyr', - 'AverageRateList':[30.0], - 'RateUnits':'Hz', - 'FractionToTarget':1.0, - 'LocationSpecific':False, - 'TargetDict':{'dendrite_group':100} } ], - - 'CG3D_L23PyrFRB':[{'InputType':'GeneratePoissonTrains', - 'InputName':"EctopicStimL23FRB", - 'TrainType':'transient', - 'Synapse':'SynForEctStim', - 'AverageRateList':[150.0], - 'DurationList':[1000.0], - 'DelayList':[5000.0], - 'RateUnits':'Hz', - 'TimeUnits':'ms', - 'FractionToTarget':0.5, - 'LocationSpecific':False, - 'UniversalTargetSegmentID':143, - 'UniversalFractionAlong':0.5}, - - {'InputType':'PulseGenerators', - 'InputName':"DepCurr_L23FRB_spatial", - 'Noise':False, - 'AmplitudeList':[2.5E-4,3.0E-4], - 'DurationList':[20000.0,10000.0], - 'DelayList':[0.0,20000.0], - 'TimeUnits':'ms', - 'AmplitudeUnits':'uA', - 'FractionToTarget':1.0, - 'LocationSpecific':True, - 'TargetRegions':[{'XVector': [0,50],'YVector':[0,-500],'ZVector': [0,50]}], - 'TargetDict':{'dendrite_group':100} }], - - 'CG3D_PointNeurons':[{'InputType':'PulseGenerators', - 'InputName':"DepCurr_CG3D_PointNeurons", - 'Noise':True, - 'SmallestAmplitudeList':[5.0E-5], - 'LargestAmplitudeList':[1.0E-4], - 'DurationList':[20000.0], - 'DelayList':[0.0], - 'TimeUnits':'ms', - 'AmplitudeUnits':'nA', - 'FractionToTarget':1.0, - 'LocationSpecific':False, - 'TargetDict': {None:100} }, - - {'InputType':'GenerateSpikeSourcePoisson', - 'InputName':"SpikeSource", - 'AverageRateList':[8.0], - 'DurationList':[300.0], - 'DelayList':[0.0], - 'WeightList':[2.5], - 'Synapse':'exp_curr_syn_all', - 'RateUnits':'Hz', - 'TimeUnits':'ms', - 'FractionToTarget':1.0, - 'LocationSpecific':False, - 'TargetDict':{None:10} } ] } - - input_list_array_final, input_synapse_list=oc_utils.build_inputs(nml_doc=nml_doc, - net=network, - population_params=pop_params, - input_params=input_params, - cached_dicts=cached_segment_dicts, - path_to_cells=None, - path_to_synapses=None) - - self.assertTrue(isinstance(input_list_array_final,list) and len(input_list_array_final) >=0) - - CG3D_L23PyrRS_pulses=[] - - CG3D_PointNeurons_spike_sources=[] - - CG3D_PointNeurons_spike_source_pops=[] - - CG3D_PointNeurons_pulses=[] - - CG3D_L23PyrFRB_spatial_pulses0=[] - - CG3D_L23PyrFRB_spatial_pulses1=[] - - CG3D_L23PyrRS_pulse_input_lists=[] - - CG3D_PointNeurons_spike_source_projections=[] - - CG3D_PointNeurons_pulse_input_lists=[] - - CG3D_PointNeurons_pulse_input_list_instances=[] - - CG3D_L23PyrFRB_spatial_pulse0_input_lists=[] - - CG3D_L23PyrFRB_spatial_pulse1_input_lists=[] - - G3D_L23PyrFRB_spatial_pulse0_input_list_instances=[] - - G3D_L23PyrFRB_spatial_pulse1_input_list_instances=[] - - CG3D_L23PyrRS_spike_source_proj_connections=[] - - CG3D_L23PyrRS_persistent_synapses=[] - - CG3D_L23PyrRS_persistent_synapse_input_lists=[] - - CG3D_L23PyrRS_persistent_synapse_input_list_instances=[] - - CG3D_L23PyrFRB_transient_synapses=[] - - CG3D_L23PyrFRB_transient_synapse_input_lists=[] - - CG3D_L23PyrFRB_transient_synapse_input_list_instances=[] - - for pulse_index in range(0,len(nml_doc.pulse_generators)): - - pulse_group=nml_doc.pulse_generators[pulse_index] - - delay=float(pulse_group.delay.split(" ")[0]) - - amplitude=float(pulse_group.amplitude.split(" ")[0]) - - duration=float(pulse_group.duration.split(" ")[0]) - - delay_units=pulse_group.delay.split(" ")[1] - - amplitude_units=pulse_group.amplitude.split(" ")[1] - - duration_units=pulse_group.duration.split(" ")[1] - - if "DepCurr_L23RS" in pulse_group.id: - - CG3D_L23PyrRS_pulses.append(pulse_group.id) - - ###self.assertTrue( amplitude <=1.0E-4 and amplitude >= 5.0E-5) - - self.assertTrue( duration == 20000.0) - - self.assertTrue( delay == 0.0 ) - - self.assertTrue( delay_units=="ms") - - self.assertTrue( amplitude_units=='uA') - - self.assertTrue( duration_units=="ms" ) - - if ("DepCurr_L23FRB_spatial" in pulse_group.id) and ("Pulse0" in pulse_group.id): - - CG3D_L23PyrFRB_spatial_pulses0.append(pulse_group.id) - - self.assertTrue( amplitude == 2.5E-4) - - self.assertTrue( duration == 20000.0) - - self.assertTrue( delay == 0.0 ) - - self.assertTrue( delay_units=="ms") - - self.assertTrue( amplitude_units=='uA') - - self.assertTrue( duration_units=="ms" ) - - if ("DepCurr_L23FRB_spatial" in pulse_group.id) and ("Pulse1" in pulse_group.id): - - CG3D_L23PyrFRB_spatial_pulses1.append(pulse_group.id) - - self.assertTrue( amplitude== 3.0E-4) - - self.assertTrue( duration == 10000.0) - - self.assertTrue( delay == 20000.0 ) - - self.assertTrue( delay_units=="ms") - - self.assertTrue( amplitude_units=='uA') - - self.assertTrue( duration_units=="ms" ) - - if "DepCurr_CG3D_PointNeurons" in pulse_group.id: - - CG3D_PointNeurons_pulses.append(pulse_group.id) - - ##self.assertTrue(amplitude <=1.0E-4 and amplitude >= 5.0E-5 ) - - self.assertTrue( duration == 20000.0) - - self.assertTrue( delay == 0.0 ) - - self.assertTrue( delay_units=="ms") - - self.assertTrue( amplitude_units=='nA') - - self.assertTrue( duration_units=="ms" ) - - for poisson_index in range(0,len(nml_doc.poisson_firing_synapses)): - - poisson_synapse_case=nml_doc.poisson_firing_synapses[poisson_index] - - if "BackgroundL23RS" in poisson_synapse_case.id: - - CG3D_L23PyrRS_persistent_synapses.append(poisson_synapse_case.id) - - rate=float(poisson_synapse_case.average_rate.split(" ")[0]) - - rate_units=poisson_synapse_case.average_rate.split(" ")[1] - - self.assertTrue( rate == 30.0 ) - - self.assertTrue( rate_units == "Hz") - - for pop_index in range(0,len(network.populations)): - - pop=network.populations[pop_index] - - if "SpikeSource" in pop.component: - - CG3D_PointNeurons_spike_source_pops.append(pop.id) - - for spike_source_index in range(0,len(nml_doc.SpikeSourcePoisson)): - - spike_source_case=nml_doc.SpikeSourcePoisson[spike_source_index] - - if "SpikeSource" in spike_source_case.id: - - CG3D_PointNeurons_spike_sources.append(spike_source_case.id) - - rate=float(spike_source_case.rate.split(" ")[0]) - - rate_units=spike_source_case.rate.split(" ")[1] - - self.assertTrue( rate == 8.0 ) - - self.assertTrue( rate_units == "Hz") - - start=float(spike_source_case.start.split(" ")[0]) - - start_units=spike_source_case.start.split(" ")[1] - - self.assertTrue( start== 0.0 ) - - self.assertTrue( start_units == "ms") - - duration=float(spike_source_case.duration.split(" ")[0]) - - duration_units=spike_source_case.duration.split(" ")[1] - - self.assertTrue( duration == 300.0 ) - - self.assertTrue( duration_units == "ms" ) - - for poisson_index in range(0,len(nml_doc.transient_poisson_firing_synapses)): - - poisson_synapse_case=nml_doc.transient_poisson_firing_synapses[poisson_index] - - if "EctopicStimL23FRB" in poisson_synapse_case.id: - - CG3D_L23PyrFRB_transient_synapses.append(poisson_synapse_case.id) - - rate=float(poisson_synapse_case.average_rate.split(" ")[0]) - - rate_units=poisson_synapse_case.average_rate.split(" ")[1] - - self.assertTrue( rate == 150.0 ) - - self.assertTrue( rate_units == "Hz") - - duration=float(poisson_synapse_case.duration.split(" ")[0]) - - duration_units=poisson_synapse_case.duration.split(" ")[1] - - delay=float(poisson_synapse_case.delay.split(" ")[0]) - - delay_units=poisson_synapse_case.delay.split(" ")[1] - - self.assertTrue( duration == 1000.0 ) - - self.assertTrue( delay ==5000.0 ) - - self.assertTrue( duration_units == "ms") - - self.assertTrue( delay_units == "ms" ) - - for proj_index in range(0,len(network.projections)): - - proj=network.projections[proj_index] - - if (proj.presynaptic_population in CG3D_PointNeurons_spike_source_pops) and (proj.postsynaptic_population == 'CG3D_PointNeurons' ) \ - and proj.synapse=='exp_curr_syn_all': - - CG3D_PointNeurons_spike_source_projections.append(proj.id) - - self.assertTrue(len(proj.connection_wds),10) - - for conn_index in range(0,len(proj.connection_wds)): - - conn=proj.connection_wds[conn_index] - - self.assertEqual(conn.weight,2.5 ) - - self.assertEqual( '../CG3D_PointNeurons/0/SingleCompartment', conn.post_cell_id) - - for input_list_index in range(0,len(network.input_lists)): - - input_list_instance=network.input_lists[input_list_index] - - if "BackgroundL23RS" in input_list_instance.id and "BackgroundL23RS" in input_list_instance.component: - - CG3D_L23PyrRS_persistent_synapse_input_lists.append(input_list_instance.id) - - for input_index in range(0,len(input_list_instance.input)): - - input_case=input_list_instance.input[input_index] - - CG3D_L23PyrRS_persistent_synapse_input_list_instances.append(input_case.id) - - self.assertTrue(int(input_case.segment_id) in CG3D_L23PyrRS_target_segs) - - self.assertTrue(float(input_case.fraction_along) >=0 and float(input_case.fraction_along) <=1) - - if "EctopicStimL23FRB" in input_list_instance.id and "EctopicStimL23FRB" in input_list_instance.component: - - CG3D_L23PyrFRB_transient_synapse_input_lists.append(input_list_instance.id) - - for input_index in range(0,len(input_list_instance.input)): - - input_case=input_list_instance.input[input_index] - - CG3D_L23PyrFRB_transient_synapse_input_list_instances.append(input_case.id) - - self.assertTrue(int(input_case.segment_id) ==143) - - self.assertTrue(float(input_case.fraction_along) ==0.5) - - if "DepCurr_L23FRB_spatial" in input_list_instance.id and ("DepCurr_L23FRB_spatial" in input_list_instance.component and \ - "Pulse0" in input_list_instance.component): - - CG3D_L23PyrFRB_spatial_pulse0_input_lists.append(input_list_instance.id) - - for input_index in range(0,len(input_list_instance.input)): - - input_case=input_list_instance.input[input_index] - - G3D_L23PyrFRB_spatial_pulse0_input_list_instances.append(input_case.id) - - self.assertTrue(int(input_case.segment_id) in CG3D_L23PyrFRB_target_segs) - - self.assertTrue(float(input_case.fraction_along) >=0 and float(input_case.fraction_along) <=1) - - if "DepCurr_L23FRB_spatial" in input_list_instance.id and ("DepCurr_L23FRB_spatial" in input_list_instance.component and \ - 'Pulse1' in input_list_instance.component): - - CG3D_L23PyrFRB_spatial_pulse1_input_lists.append(input_list_instance.id) - - for input_index in range(0,len(input_list_instance.input)): - - input_case=input_list_instance.input[input_index] - - G3D_L23PyrFRB_spatial_pulse1_input_list_instances.append(input_case.id) - - self.assertTrue(int(input_case.segment_id) in CG3D_L23PyrFRB_target_segs) - - self.assertTrue(float(input_case.fraction_along) >=0 and float(input_case.fraction_along) <=1) - - if "DepCurr_L23RS" in input_list_instance.id and "DepCurr_L23RS" in input_list_instance.component: - - CG3D_L23PyrRS_pulse_input_lists.append(input_list_instance.id) - - for input_index in range(0,len(input_list_instance.input)): - - input_case=input_list_instance.input[input_index] - - self.assertTrue( 0 ==int(input_case.segment_id) ) - - self.assertTrue( 0.5 == float(input_case.fraction_along) ) - - if "DepCurr_CG3D_PointNeurons" in input_list_instance.id and "DepCurr_CG3D_PointNeurons" in input_list_instance.component: - - CG3D_PointNeurons_pulse_input_lists.append(input_list_instance.id) - - for input_index in range(0,len(input_list_instance.input)): - - input_case=input_list_instance.input[input_index] - - CG3D_PointNeurons_pulse_input_list_instances.append(input_case.id) - - self.assertEqual(len(set(CG3D_L23PyrRS_pulses)),1) - - self.assertEqual( len(set(CG3D_L23PyrRS_pulses)),len(set(CG3D_L23PyrRS_pulse_input_lists)) ) - - self.assertEqual( len(set(CG3D_L23PyrFRB_spatial_pulses0)), 1) - - self.assertEqual(len(set(CG3D_L23PyrFRB_spatial_pulse0_input_lists)),1 ) - - self.assertEqual( len(set(CG3D_L23PyrFRB_spatial_pulses1)), 1) - - self.assertEqual(len(set(CG3D_L23PyrFRB_spatial_pulse1_input_lists)), 1 ) - - self.assertEqual(len(set(G3D_L23PyrFRB_spatial_pulse0_input_list_instances)), 1000) - - self.assertEqual(len(set(G3D_L23PyrFRB_spatial_pulse1_input_list_instances)), 1000) - - self.assertEqual(len(set(CG3D_PointNeurons_pulses)), 1) - - self.assertEqual(len(set(CG3D_PointNeurons_pulse_input_lists)), 1) - - ##self.assertEqual(len(set(CG3D_PointNeurons_pulse_input_list_instances)), 100) - - self.assertEqual(len(set(CG3D_L23PyrRS_persistent_synapses)), 1) - - self.assertEqual(len(set(CG3D_L23PyrRS_persistent_synapse_input_lists)), 1) - - self.assertEqual(len(set(CG3D_L23PyrRS_persistent_synapse_input_list_instances)), 200) - - self.assertEqual(len(set(CG3D_L23PyrFRB_transient_synapses)), 1) - - self.assertEqual(len(set(CG3D_L23PyrFRB_transient_synapse_input_lists)), 1) - ### testing whether 50 % of cells are targeted, see input params - self.assertEqual(len(set(CG3D_L23PyrFRB_transient_synapse_input_list_instances)), 5) - - self.assertTrue(len(set(CG3D_PointNeurons_spike_sources)), 1) - - self.assertTrue(len(set(CG3D_PointNeurons_spike_source_pops)),len(set(CG3D_PointNeurons_spike_sources)) ) - - self.assertTrue(len(set(CG3D_PointNeurons_spike_source_projections)),len(set(CG3D_PointNeurons_spike_sources)) ) - - - + found_projections += 1 + + for conn_index in range( + 0, len(network.projections[proj_ind].connection_wds) + ): + connection = network.projections[proj_ind].connection_wds[conn_index] + + self.assertTrue( + connection.weight == w_matrix[post_pop_index][pre_pop_index] + ) + + self.assertTrue( + str(d_matrix[post_pop_index][pre_pop_index]) in connection.delay + ) + + self.assertTrue(found_projections == 4) + + self.assertTrue(set(source_L23PyrFRB_projections) == set(["Syn1", "Syn2"])) + + self.assertTrue(set(source_L23PyrRS_projections) == set(["Syn1", "Syn2"])) + + def test_build_inputs(self): + nml_doc, network = oc.generate_network("Net0") + popDict = {} + popDict["CG3D_L23PyrRS"] = (2, "L23", "Test", "multi", None) + popDict["CG3D_L23PyrFRB"] = (10, "L23", "Test2", "multi", None) + popDict["CG3D_PointNeurons"] = (1, "L23", "SingleCompartment", "single", None) + t1 = -0 + t2 = -250 + t3 = -250 + boundaries = {} + boundaries["L1"] = [0, t1] + boundaries["L23"] = [t1, t1 + t2 + t3] + xs = [0, 50] + zs = [0, 50] + + pop_params = oc_utils.add_populations_in_rectangular_layers( + net=network, + boundaryDict=boundaries, + popDict=popDict, + x_vector=xs, + z_vector=zs, + ) + + all_synapse_components, proj_array, cached_segment_dicts = ( + oc_utils.build_connectivity( + net=network, + pop_objects=pop_params, + path_to_cells=None, + full_path_to_conn_summary="ConnListTest", + pre_segment_group_info=[ + {"PreSegGroup": "distal_axon", "ProjType": "Chem"} + ], + synaptic_scaling_params=[ + { + "weight": 2.0, + "synComp": "AMPA", + "synEndsWith": [], + "targetCellGroup": [], + } + ], + synaptic_delay_params=[{"delay": 0.05, "synComp": "all"}], + ) + ) + + cell_nml_file = "Test.cell.nml" + + document_cell = neuroml.loaders.NeuroMLLoader.load(cell_nml_file) + + cell_object = document_cell.cells[0] + + CG3D_L23PyrRS_target_segs = oc_build.extract_seg_ids( + cell_object, + target_compartment_array=["dendrite_group"], + targeting_mode="segGroups", + ) + + CG3D_L23PyrRS_target_segs = CG3D_L23PyrRS_target_segs["dendrite_group"] + + cell_nml_file = "Test2.cell.nml" + + document_cell = neuroml.loaders.NeuroMLLoader.load(cell_nml_file) + + cell_object = document_cell.cells[0] + + CG3D_L23PyrFRB_target_segs = oc_build.extract_seg_ids( + cell_object, + target_compartment_array=["dendrite_group"], + targeting_mode="segGroups", + ) + + CG3D_L23PyrFRB_target_segs = CG3D_L23PyrFRB_target_segs["dendrite_group"] + + input_params = { + "CG3D_L23PyrRS": [ + { + "InputType": "PulseGenerators", + "InputName": "DepCurr_L23RS", + "Noise": True, + "SmallestAmplitudeList": [5.0e-5], + "LargestAmplitudeList": [1.0e-4], + "DurationList": [20000.0], + "DelayList": [0.0], + "TimeUnits": "ms", + "AmplitudeUnits": "uA", + "FractionToTarget": 1.0, + "LocationSpecific": False, + "UniversalTargetSegmentID": 0, + "UniversalFractionAlong": 0.5, + }, + { + "InputType": "GeneratePoissonTrains", + "InputName": "BackgroundL23RS", + "TrainType": "persistent", + "Synapse": "Syn_AMPA_SupPyr_SupPyr", + "AverageRateList": [30.0], + "RateUnits": "Hz", + "FractionToTarget": 1.0, + "LocationSpecific": False, + "TargetDict": {"dendrite_group": 100}, + }, + ], + "CG3D_L23PyrFRB": [ + { + "InputType": "GeneratePoissonTrains", + "InputName": "EctopicStimL23FRB", + "TrainType": "transient", + "Synapse": "SynForEctStim", + "AverageRateList": [150.0], + "DurationList": [1000.0], + "DelayList": [5000.0], + "RateUnits": "Hz", + "TimeUnits": "ms", + "FractionToTarget": 0.5, + "LocationSpecific": False, + "UniversalTargetSegmentID": 143, + "UniversalFractionAlong": 0.5, + }, + { + "InputType": "PulseGenerators", + "InputName": "DepCurr_L23FRB_spatial", + "Noise": False, + "AmplitudeList": [2.5e-4, 3.0e-4], + "DurationList": [20000.0, 10000.0], + "DelayList": [0.0, 20000.0], + "TimeUnits": "ms", + "AmplitudeUnits": "uA", + "FractionToTarget": 1.0, + "LocationSpecific": True, + "TargetRegions": [ + {"XVector": [0, 50], "YVector": [0, -500], "ZVector": [0, 50]} + ], + "TargetDict": {"dendrite_group": 100}, + }, + ], + "CG3D_PointNeurons": [ + { + "InputType": "PulseGenerators", + "InputName": "DepCurr_CG3D_PointNeurons", + "Noise": True, + "SmallestAmplitudeList": [5.0e-5], + "LargestAmplitudeList": [1.0e-4], + "DurationList": [20000.0], + "DelayList": [0.0], + "TimeUnits": "ms", + "AmplitudeUnits": "nA", + "FractionToTarget": 1.0, + "LocationSpecific": False, + "TargetDict": {None: 100}, + }, + { + "InputType": "GenerateSpikeSourcePoisson", + "InputName": "SpikeSource", + "AverageRateList": [8.0], + "DurationList": [300.0], + "DelayList": [0.0], + "WeightList": [2.5], + "Synapse": "exp_curr_syn_all", + "RateUnits": "Hz", + "TimeUnits": "ms", + "FractionToTarget": 1.0, + "LocationSpecific": False, + "TargetDict": {None: 10}, + }, + ], + } + + input_list_array_final, input_synapse_list = oc_utils.build_inputs( + nml_doc=nml_doc, + net=network, + population_params=pop_params, + input_params=input_params, + cached_dicts=cached_segment_dicts, + path_to_cells=None, + path_to_synapses=None, + ) + + self.assertTrue( + isinstance(input_list_array_final, list) + and len(input_list_array_final) >= 0 + ) + + CG3D_L23PyrRS_pulses = [] + + CG3D_PointNeurons_spike_sources = [] + + CG3D_PointNeurons_spike_source_pops = [] + + CG3D_PointNeurons_pulses = [] + + CG3D_L23PyrFRB_spatial_pulses0 = [] + + CG3D_L23PyrFRB_spatial_pulses1 = [] + + CG3D_L23PyrRS_pulse_input_lists = [] + + CG3D_PointNeurons_spike_source_projections = [] + + CG3D_PointNeurons_pulse_input_lists = [] + + CG3D_PointNeurons_pulse_input_list_instances = [] + + CG3D_L23PyrFRB_spatial_pulse0_input_lists = [] + + CG3D_L23PyrFRB_spatial_pulse1_input_lists = [] + + G3D_L23PyrFRB_spatial_pulse0_input_list_instances = [] + + G3D_L23PyrFRB_spatial_pulse1_input_list_instances = [] + + CG3D_L23PyrRS_spike_source_proj_connections = [] + + CG3D_L23PyrRS_persistent_synapses = [] + + CG3D_L23PyrRS_persistent_synapse_input_lists = [] + + CG3D_L23PyrRS_persistent_synapse_input_list_instances = [] + + CG3D_L23PyrFRB_transient_synapses = [] + + CG3D_L23PyrFRB_transient_synapse_input_lists = [] + + CG3D_L23PyrFRB_transient_synapse_input_list_instances = [] + + for pulse_index in range(0, len(nml_doc.pulse_generators)): + pulse_group = nml_doc.pulse_generators[pulse_index] + + delay = float(pulse_group.delay.split(" ")[0]) + + amplitude = float(pulse_group.amplitude.split(" ")[0]) + + duration = float(pulse_group.duration.split(" ")[0]) + + delay_units = pulse_group.delay.split(" ")[1] + + amplitude_units = pulse_group.amplitude.split(" ")[1] + + duration_units = pulse_group.duration.split(" ")[1] + + if "DepCurr_L23RS" in pulse_group.id: + CG3D_L23PyrRS_pulses.append(pulse_group.id) + + ###self.assertTrue( amplitude <=1.0E-4 and amplitude >= 5.0E-5) + + self.assertTrue(duration == 20000.0) + + self.assertTrue(delay == 0.0) + + self.assertTrue(delay_units == "ms") + + self.assertTrue(amplitude_units == "uA") + + self.assertTrue(duration_units == "ms") + + if ("DepCurr_L23FRB_spatial" in pulse_group.id) and ( + "Pulse0" in pulse_group.id + ): + CG3D_L23PyrFRB_spatial_pulses0.append(pulse_group.id) + + self.assertTrue(amplitude == 2.5e-4) + + self.assertTrue(duration == 20000.0) + + self.assertTrue(delay == 0.0) + + self.assertTrue(delay_units == "ms") + + self.assertTrue(amplitude_units == "uA") + + self.assertTrue(duration_units == "ms") + + if ("DepCurr_L23FRB_spatial" in pulse_group.id) and ( + "Pulse1" in pulse_group.id + ): + CG3D_L23PyrFRB_spatial_pulses1.append(pulse_group.id) + + self.assertTrue(amplitude == 3.0e-4) + + self.assertTrue(duration == 10000.0) + + self.assertTrue(delay == 20000.0) + + self.assertTrue(delay_units == "ms") + + self.assertTrue(amplitude_units == "uA") + + self.assertTrue(duration_units == "ms") + + if "DepCurr_CG3D_PointNeurons" in pulse_group.id: + CG3D_PointNeurons_pulses.append(pulse_group.id) + + ##self.assertTrue(amplitude <=1.0E-4 and amplitude >= 5.0E-5 ) + + self.assertTrue(duration == 20000.0) + + self.assertTrue(delay == 0.0) + + self.assertTrue(delay_units == "ms") + + self.assertTrue(amplitude_units == "nA") + + self.assertTrue(duration_units == "ms") + + for poisson_index in range(0, len(nml_doc.poisson_firing_synapses)): + poisson_synapse_case = nml_doc.poisson_firing_synapses[poisson_index] + + if "BackgroundL23RS" in poisson_synapse_case.id: + CG3D_L23PyrRS_persistent_synapses.append(poisson_synapse_case.id) + + rate = float(poisson_synapse_case.average_rate.split(" ")[0]) + + rate_units = poisson_synapse_case.average_rate.split(" ")[1] + + self.assertTrue(rate == 30.0) + + self.assertTrue(rate_units == "Hz") + + for pop_index in range(0, len(network.populations)): + pop = network.populations[pop_index] + + if "SpikeSource" in pop.component: + CG3D_PointNeurons_spike_source_pops.append(pop.id) + + for spike_source_index in range(0, len(nml_doc.SpikeSourcePoisson)): + spike_source_case = nml_doc.SpikeSourcePoisson[spike_source_index] + + if "SpikeSource" in spike_source_case.id: + CG3D_PointNeurons_spike_sources.append(spike_source_case.id) + + rate = float(spike_source_case.rate.split(" ")[0]) + + rate_units = spike_source_case.rate.split(" ")[1] + + self.assertTrue(rate == 8.0) + + self.assertTrue(rate_units == "Hz") + + start = float(spike_source_case.start.split(" ")[0]) + + start_units = spike_source_case.start.split(" ")[1] + + self.assertTrue(start == 0.0) + + self.assertTrue(start_units == "ms") + + duration = float(spike_source_case.duration.split(" ")[0]) + + duration_units = spike_source_case.duration.split(" ")[1] + + self.assertTrue(duration == 300.0) + + self.assertTrue(duration_units == "ms") + + for poisson_index in range(0, len(nml_doc.transient_poisson_firing_synapses)): + poisson_synapse_case = nml_doc.transient_poisson_firing_synapses[ + poisson_index + ] + + if "EctopicStimL23FRB" in poisson_synapse_case.id: + CG3D_L23PyrFRB_transient_synapses.append(poisson_synapse_case.id) + + rate = float(poisson_synapse_case.average_rate.split(" ")[0]) + + rate_units = poisson_synapse_case.average_rate.split(" ")[1] + + self.assertTrue(rate == 150.0) + + self.assertTrue(rate_units == "Hz") + + duration = float(poisson_synapse_case.duration.split(" ")[0]) + + duration_units = poisson_synapse_case.duration.split(" ")[1] + + delay = float(poisson_synapse_case.delay.split(" ")[0]) + + delay_units = poisson_synapse_case.delay.split(" ")[1] + + self.assertTrue(duration == 1000.0) + + self.assertTrue(delay == 5000.0) + + self.assertTrue(duration_units == "ms") + + self.assertTrue(delay_units == "ms") + + for proj_index in range(0, len(network.projections)): + proj = network.projections[proj_index] + + if ( + (proj.presynaptic_population in CG3D_PointNeurons_spike_source_pops) + and (proj.postsynaptic_population == "CG3D_PointNeurons") + and proj.synapse == "exp_curr_syn_all" + ): + CG3D_PointNeurons_spike_source_projections.append(proj.id) + + self.assertTrue(len(proj.connection_wds), 10) + + for conn_index in range(0, len(proj.connection_wds)): + conn = proj.connection_wds[conn_index] + + self.assertEqual(conn.weight, 2.5) + + self.assertEqual( + "../CG3D_PointNeurons/0/SingleCompartment", conn.post_cell_id + ) + + for input_list_index in range(0, len(network.input_lists)): + input_list_instance = network.input_lists[input_list_index] + + if ( + "BackgroundL23RS" in input_list_instance.id + and "BackgroundL23RS" in input_list_instance.component + ): + CG3D_L23PyrRS_persistent_synapse_input_lists.append( + input_list_instance.id + ) + + for input_index in range(0, len(input_list_instance.input)): + input_case = input_list_instance.input[input_index] + + CG3D_L23PyrRS_persistent_synapse_input_list_instances.append( + input_case.id + ) + + self.assertTrue( + int(input_case.segment_id) in CG3D_L23PyrRS_target_segs + ) + + self.assertTrue( + float(input_case.fraction_along) >= 0 + and float(input_case.fraction_along) <= 1 + ) + + if ( + "EctopicStimL23FRB" in input_list_instance.id + and "EctopicStimL23FRB" in input_list_instance.component + ): + CG3D_L23PyrFRB_transient_synapse_input_lists.append( + input_list_instance.id + ) + + for input_index in range(0, len(input_list_instance.input)): + input_case = input_list_instance.input[input_index] + + CG3D_L23PyrFRB_transient_synapse_input_list_instances.append( + input_case.id + ) + + self.assertTrue(int(input_case.segment_id) == 143) + + self.assertTrue(float(input_case.fraction_along) == 0.5) + + if "DepCurr_L23FRB_spatial" in input_list_instance.id and ( + "DepCurr_L23FRB_spatial" in input_list_instance.component + and "Pulse0" in input_list_instance.component + ): + CG3D_L23PyrFRB_spatial_pulse0_input_lists.append(input_list_instance.id) + + for input_index in range(0, len(input_list_instance.input)): + input_case = input_list_instance.input[input_index] + + G3D_L23PyrFRB_spatial_pulse0_input_list_instances.append( + input_case.id + ) + + self.assertTrue( + int(input_case.segment_id) in CG3D_L23PyrFRB_target_segs + ) + + self.assertTrue( + float(input_case.fraction_along) >= 0 + and float(input_case.fraction_along) <= 1 + ) + + if "DepCurr_L23FRB_spatial" in input_list_instance.id and ( + "DepCurr_L23FRB_spatial" in input_list_instance.component + and "Pulse1" in input_list_instance.component + ): + CG3D_L23PyrFRB_spatial_pulse1_input_lists.append(input_list_instance.id) + + for input_index in range(0, len(input_list_instance.input)): + input_case = input_list_instance.input[input_index] + + G3D_L23PyrFRB_spatial_pulse1_input_list_instances.append( + input_case.id + ) + + self.assertTrue( + int(input_case.segment_id) in CG3D_L23PyrFRB_target_segs + ) + + self.assertTrue( + float(input_case.fraction_along) >= 0 + and float(input_case.fraction_along) <= 1 + ) + + if ( + "DepCurr_L23RS" in input_list_instance.id + and "DepCurr_L23RS" in input_list_instance.component + ): + CG3D_L23PyrRS_pulse_input_lists.append(input_list_instance.id) + + for input_index in range(0, len(input_list_instance.input)): + input_case = input_list_instance.input[input_index] + + self.assertTrue(0 == int(input_case.segment_id)) + + self.assertTrue(0.5 == float(input_case.fraction_along)) + + if ( + "DepCurr_CG3D_PointNeurons" in input_list_instance.id + and "DepCurr_CG3D_PointNeurons" in input_list_instance.component + ): + CG3D_PointNeurons_pulse_input_lists.append(input_list_instance.id) + + for input_index in range(0, len(input_list_instance.input)): + input_case = input_list_instance.input[input_index] + + CG3D_PointNeurons_pulse_input_list_instances.append(input_case.id) + + self.assertEqual(len(set(CG3D_L23PyrRS_pulses)), 1) + + self.assertEqual( + len(set(CG3D_L23PyrRS_pulses)), len(set(CG3D_L23PyrRS_pulse_input_lists)) + ) + + self.assertEqual(len(set(CG3D_L23PyrFRB_spatial_pulses0)), 1) + + self.assertEqual(len(set(CG3D_L23PyrFRB_spatial_pulse0_input_lists)), 1) + + self.assertEqual(len(set(CG3D_L23PyrFRB_spatial_pulses1)), 1) + + self.assertEqual(len(set(CG3D_L23PyrFRB_spatial_pulse1_input_lists)), 1) + + self.assertEqual( + len(set(G3D_L23PyrFRB_spatial_pulse0_input_list_instances)), 1000 + ) + + self.assertEqual( + len(set(G3D_L23PyrFRB_spatial_pulse1_input_list_instances)), 1000 + ) + + self.assertEqual(len(set(CG3D_PointNeurons_pulses)), 1) + + self.assertEqual(len(set(CG3D_PointNeurons_pulse_input_lists)), 1) + + ##self.assertEqual(len(set(CG3D_PointNeurons_pulse_input_list_instances)), 100) + + self.assertEqual(len(set(CG3D_L23PyrRS_persistent_synapses)), 1) + + self.assertEqual(len(set(CG3D_L23PyrRS_persistent_synapse_input_lists)), 1) + + self.assertEqual( + len(set(CG3D_L23PyrRS_persistent_synapse_input_list_instances)), 200 + ) + + self.assertEqual(len(set(CG3D_L23PyrFRB_transient_synapses)), 1) + + self.assertEqual(len(set(CG3D_L23PyrFRB_transient_synapse_input_lists)), 1) + ### testing whether 50 % of cells are targeted, see input params + self.assertEqual( + len(set(CG3D_L23PyrFRB_transient_synapse_input_list_instances)), 5 + ) + + self.assertTrue(len(set(CG3D_PointNeurons_spike_sources)), 1) + + self.assertTrue( + len(set(CG3D_PointNeurons_spike_source_pops)), + len(set(CG3D_PointNeurons_spike_sources)), + ) + self.assertTrue( + len(set(CG3D_PointNeurons_spike_source_projections)), + len(set(CG3D_PointNeurons_spike_sources)), + ) diff --git a/opencortex/utils/__init__.py b/opencortex/utils/__init__.py index 1893a83..e6eb14e 100644 --- a/opencortex/utils/__init__.py +++ b/opencortex/utils/__init__.py @@ -1,10 +1,10 @@ ############################################################### -### +### ### Note: OpenCortex is under active development, the API is subject to change without notice!! -### +### ### Authors: Padraig Gleeson, Rokas Stanislovas ### -### This software has been funded by the Wellcome Trust, as well as a GSoC 2016 project +### This software has been funded by the Wellcome Trust, as well as a GSoC 2016 project ### on Cortical Network develoment ### ############################################################## @@ -30,139 +30,161 @@ ############################################################################################## -def add_populations_in_rectangular_layers(net, boundaryDict, popDict, x_vector, z_vector, storeSoma=True, cellBodiesOverlap=True, cellDiameterArray=None): - '''This method distributes the cells in rectangular layers. The input arguments: +def add_populations_in_rectangular_layers( + net, + boundaryDict, + popDict, + x_vector, + z_vector, + storeSoma=True, + cellBodiesOverlap=True, + cellDiameterArray=None, +): + """This method distributes the cells in rectangular layers. The input arguments: - net - libNeuroML network object; + net - libNeuroML network object; - popDict - a dictionary whose keys are unique cell population ids; each key entry stores a tuple of five elements: population size, Layer tag, cell model id, compartmentalization, color; + popDict - a dictionary whose keys are unique cell population ids; each key entry stores a tuple of five elements: population size, Layer tag, cell model id, compartmentalization, color; - layer tags (of type string) must make up the keys() of boundaryDict; + layer tags (of type string) must make up the keys() of boundaryDict; - boundaryDict have layer pointers as keys; each entry stores the left and right bound of the layer in the list format , e.g. [L3_min, L3_max] + boundaryDict have layer pointers as keys; each entry stores the left and right bound of the layer in the list format , e.g. [L3_min, L3_max] - x_vector - a vector that stores the left and right bounds of the cortical column along x dimension + x_vector - a vector that stores the left and right bounds of the cortical column along x dimension - y_vector - a vector that stores the left and right bounds of the cortical column along y dimension + y_vector - a vector that stores the left and right bounds of the cortical column along y dimension - storeSoma - specifies whether soma positions have to be stored in the output array (default is set to True). + storeSoma - specifies whether soma positions have to be stored in the output array (default is set to True). - cellBodiesOverlap - boolean value which defines whether cell somata can overlap; default is set to True; + cellBodiesOverlap - boolean value which defines whether cell somata can overlap; default is set to True; - cellDiameterArray - optional dictionary of cell model diameters required when cellBodiesOverlap is set to False; + cellDiameterArray - optional dictionary of cell model diameters required when cellBodiesOverlap is set to False; - This method returns the dictionary; each key is a unique cell population id and the corresponding value is a dictionary - which refers to libNeuroML population object (key 'PopObj') and cell position array ('Positions') which by default is None.''' + This method returns the dictionary; each key is a unique cell population id and the corresponding value is a dictionary + which refers to libNeuroML population object (key 'PopObj') and cell position array ('Positions') which by default is None.""" return_pops = {} for cell_pop in popDict.keys(): - size, layer, cell_model, compartmentalization, color = popDict[cell_pop] if size > 0: - return_pops[cell_pop] = {} - xl = x_vector[1]-x_vector[0] + xl = x_vector[1] - x_vector[0] - yl = boundaryDict[layer][1]-boundaryDict[layer][0] + yl = boundaryDict[layer][1] - boundaryDict[layer][0] - zl = z_vector[1]-z_vector[0] + zl = z_vector[1] - z_vector[0] if storeSoma: - - pop, cellPositions = oc_build._add_population_in_rectangular_region(net, - cell_pop, - cell_model, - size, - x_vector[0], - boundaryDict[layer][0], - z_vector[0], - xl, - yl, - zl, - cell_bodies_overlap=cellBodiesOverlap, - store_soma=storeSoma, - population_dictionary=return_pops, - cell_diameter_dict=cellDiameterArray, - color=color) + pop, cellPositions = oc_build._add_population_in_rectangular_region( + net, + cell_pop, + cell_model, + size, + x_vector[0], + boundaryDict[layer][0], + z_vector[0], + xl, + yl, + zl, + cell_bodies_overlap=cellBodiesOverlap, + store_soma=storeSoma, + population_dictionary=return_pops, + cell_diameter_dict=cellDiameterArray, + color=color, + ) else: - - pop = oc_build._add_population_in_rectangular_region(net, - cell_pop, - cell_model, - size, - x_vector[0], - boundaryDict[layer][0], - z_vector[0], - xl, - yl, - zl, - cell_bodies_overlap=cellBodiesOverlap, - store_soma=storeSoma, - population_dictionary=return_pops, - cell_diameter_dict=cellDiameterArray) + pop = oc_build._add_population_in_rectangular_region( + net, + cell_pop, + cell_model, + size, + x_vector[0], + boundaryDict[layer][0], + z_vector[0], + xl, + yl, + zl, + cell_bodies_overlap=cellBodiesOverlap, + store_soma=storeSoma, + population_dictionary=return_pops, + cell_diameter_dict=cellDiameterArray, + ) cellPositions = None - return_pops[cell_pop]['PopObj'] = pop - return_pops[cell_pop]['Positions'] = cellPositions - return_pops[cell_pop]['Compartments'] = compartmentalization + return_pops[cell_pop]["PopObj"] = pop + return_pops[cell_pop]["Positions"] = cellPositions + return_pops[cell_pop]["Compartments"] = compartmentalization - opencortex.print_comment_v("This is a final list of cell population ids: %s" % return_pops.keys()) + opencortex.print_comment_v( + "This is a final list of cell population ids: %s" % return_pops.keys() + ) return return_pops ############################################################################################## -def add_populations_in_cylindrical_layers(net, boundaryDict, popDict, radiusOfCylinder, storeSoma=True, cellBodiesOverlap=True, cellDiameterArray=None, numOfSides=None): - '''This method distributes the cells in cylindrical layers. The input arguments: +def add_populations_in_cylindrical_layers( + net, + boundaryDict, + popDict, + radiusOfCylinder, + storeSoma=True, + cellBodiesOverlap=True, + cellDiameterArray=None, + numOfSides=None, +): + """This method distributes the cells in cylindrical layers. The input arguments: - net - libNeuroML network object; + net - libNeuroML network object; - popDict - a dictionary whose keys are unique cell population ids; each key entry stores a tuple of five elements: population size, Layer tag, cell model id, compartmentalization, color; + popDict - a dictionary whose keys are unique cell population ids; each key entry stores a tuple of five elements: population size, Layer tag, cell model id, compartmentalization, color; - layer tags (of type string) must make up the keys() of boundaryDict; + layer tags (of type string) must make up the keys() of boundaryDict; - boundaryDict have layer pointers as keys; each entry stores the left and right bound of the layer in the list format , e.g. [L3_min, L3_max] + boundaryDict have layer pointers as keys; each entry stores the left and right bound of the layer in the list format , e.g. [L3_min, L3_max] - x_vector - a vector that stores the left and right bounds of the cortical column along x dimension + x_vector - a vector that stores the left and right bounds of the cortical column along x dimension - y_vector - a vector that stores the left and right bounds of the cortical column along y dimension + y_vector - a vector that stores the left and right bounds of the cortical column along y dimension - radiusOfCylinder - radius of cylindrical column in which cortical cells will be distributed. + radiusOfCylinder - radius of cylindrical column in which cortical cells will be distributed. - storeSoma - specifies whether soma positions have to be stored in the output array (default is set to True); + storeSoma - specifies whether soma positions have to be stored in the output array (default is set to True); - cellBodiesOverlap - boolean value which defines whether cell somata can overlap; default is set to True; + cellBodiesOverlap - boolean value which defines whether cell somata can overlap; default is set to True; - cellDiameterArray - optional dictionary of cell model diameters required when cellBodiesOverlap is set to False; + cellDiameterArray - optional dictionary of cell model diameters required when cellBodiesOverlap is set to False; - numOfSides - optional argument which specifies the number of sides of regular polygon which is inscribed in the cylindrical column of a given radius; default value is None, - thus cylindrical but not polygonal shape is built. + numOfSides - optional argument which specifies the number of sides of regular polygon which is inscribed in the cylindrical column of a given radius; default value is None, + thus cylindrical but not polygonal shape is built. - This method returns the dictionary; each key is a unique cell population id and the corresponding value is a dictionary - which refers to libNeuroML population object (key 'PopObj') and cell position array ('Positions') which by default is None.''' + This method returns the dictionary; each key is a unique cell population id and the corresponding value is a dictionary + which refers to libNeuroML population object (key 'PopObj') and cell position array ('Positions') which by default is None.""" if numOfSides != None: - - if numOfSides >= 3: - + if numOfSides >= 3: vertex_array = [] xy_sides = [] - angle_array = np.linspace(0, 2 * math.pi * (1-(1.0 / numOfSides)), numOfSides) + angle_array = np.linspace( + 0, 2 * math.pi * (1 - (1.0 / numOfSides)), numOfSides + ) - opencortex.print_comment_v("Generated the angles of the regular polygon with %d sides: %s" % (numOfSides, angle_array)) + opencortex.print_comment_v( + "Generated the angles of the regular polygon with %d sides: %s" + % (numOfSides, angle_array) + ) for angle in angle_array: - vertex = [] x = radiusOfCylinder * math.cos(angle) @@ -175,16 +197,17 @@ def add_populations_in_cylindrical_layers(net, boundaryDict, popDict, radiusOfCy vertex_array.append(vertex) - opencortex.print_comment_v("Generated the vertices of the regular polygon with %d sides: %s" % (numOfSides, vertex_array)) + opencortex.print_comment_v( + "Generated the vertices of the regular polygon with %d sides: %s" + % (numOfSides, vertex_array) + ) for v_ind in range(0, len(vertex_array)): - v1 = vertex_array[v_ind] - v2 = vertex_array[v_ind-1] - - if abs(v1[0] - v2[0]) > 0.00000001 and abs(v1[1] -v2[1]) > 0.00000001: + v2 = vertex_array[v_ind - 1] + if abs(v1[0] - v2[0]) > 0.00000001 and abs(v1[1] - v2[1]) > 0.00000001: A = np.array([[v1[0], 1], [v2[0], 1]]) b = np.array([v1[1], v2[1]]) @@ -194,24 +217,22 @@ def add_populations_in_cylindrical_layers(net, boundaryDict, popDict, radiusOfCy xy_sides.append(list(xcyc)) else: - if abs(v1[0] - v2[0]) <= 0.00000001: - xy_sides.append([v1[0], None]) - if abs(v1[1] -v2[1]) <= 0.00000001: - + if abs(v1[1] - v2[1]) <= 0.00000001: xy_sides.append([None, v1[1]]) else: - - opencortex.print_comment_v("Error! Method opencortex.build.%s() called with numOfSides set to %d but regular polygon must contain at least 3 vertices." - "Execution will terminate." % sys._getframe().f_code.co_name, numOfSides) + opencortex.print_comment_v( + "Error! Method opencortex.build.%s() called with numOfSides set to %d but regular polygon must contain at least 3 vertices." + "Execution will terminate." % sys._getframe().f_code.co_name, + numOfSides, + ) quit() else: - vertex_array = None xy_sides = None @@ -219,80 +240,82 @@ def add_populations_in_cylindrical_layers(net, boundaryDict, popDict, radiusOfCy return_pops = {} for cell_pop in popDict.keys(): - size, layer, cell_model, compartmentalization, color = popDict[cell_pop] if size > 0: - return_pops[cell_pop] = {} if storeSoma: - - pop, cellPositions = oc_build.add_population_in_cylindrical_region(net=net, - pop_id=cell_pop, - cell_id=cell_model, - size=size, - cyl_radius=radiusOfCylinder, - lower_bound_dim3=boundaryDict[layer][0], - upper_bound_dim3=boundaryDict[layer][1], - cell_bodies_overlap=cellBodiesOverlap, - store_soma=storeSoma, - population_dictionary=return_pops, - cell_diameter_dict=cellDiameterArray, - num_of_polygon_sides=numOfSides, - positions_of_vertices=vertex_array, - constants_of_sides=xy_sides, - color = color) + pop, cellPositions = oc_build.add_population_in_cylindrical_region( + net=net, + pop_id=cell_pop, + cell_id=cell_model, + size=size, + cyl_radius=radiusOfCylinder, + lower_bound_dim3=boundaryDict[layer][0], + upper_bound_dim3=boundaryDict[layer][1], + cell_bodies_overlap=cellBodiesOverlap, + store_soma=storeSoma, + population_dictionary=return_pops, + cell_diameter_dict=cellDiameterArray, + num_of_polygon_sides=numOfSides, + positions_of_vertices=vertex_array, + constants_of_sides=xy_sides, + color=color, + ) else: + pop = oc_build.add_population_in_cylindrical_region( + net=net, + pop_id=cell_pop, + cell_id=cell_model, + size=size, + cyl_radius=radiusOfCylinder, + lower_bound_dim3=boundaryDict[layer][0], + upper_bound_dim3=boundaryDict[layer][1], + cell_bodies_overlap=cellBodiesOverlap, + store_soma=storeSoma, + population_dictionary=return_pops, + cell_diameter_dict=cellDiameterArray, + num_of_polygon_sides=numOfSides, + positions_of_vertices=vertex_array, + constants_of_sides=xy_sides, + ) - pop = oc_build.add_population_in_cylindrical_region(net=net, - pop_id=cell_pop, - cell_id=cell_model, - size=size, - cyl_radius=radiusOfCylinder, - lower_bound_dim3=boundaryDict[layer][0], - upper_bound_dim3=boundaryDict[layer][1], - cell_bodies_overlap=cellBodiesOverlap, - store_soma=storeSoma, - population_dictionary=return_pops, - cell_diameter_dict=cellDiameterArray, - num_of_polygon_sides=numOfSides, - positions_of_vertices=vertex_array, - constants_of_sides=xy_sides) - - - cellPositions = None + cellPositions = None - return_pops[cell_pop]['PopObj'] = pop - return_pops[cell_pop]['Positions'] = cellPositions - return_pops[cell_pop]['Compartments'] = compartmentalization + return_pops[cell_pop]["PopObj"] = pop + return_pops[cell_pop]["Positions"] = cellPositions + return_pops[cell_pop]["Compartments"] = compartmentalization - opencortex.print_comment_v("This is a final list of cell population ids: %s" % return_pops.keys()) + opencortex.print_comment_v( + "This is a final list of cell population ids: %s" % return_pops.keys() + ) return return_pops ############################################################################################## -def build_projection(net, - proj_counter, - proj_type, - presynaptic_population, - postsynaptic_population, - synapse_list, - targeting_mode, - pre_seg_length_dict, - post_seg_length_dict, - num_of_conn_dict, - distance_dependent_rule=None, - pre_cell_positions=None, - post_cell_positions=None, - delays_dict=None, - weights_dict=None): - - - '''This method calls the appropriate methods that construct chemical or electrical projections. The input arguments are as follows: + +def build_projection( + net, + proj_counter, + proj_type, + presynaptic_population, + postsynaptic_population, + synapse_list, + targeting_mode, + pre_seg_length_dict, + post_seg_length_dict, + num_of_conn_dict, + distance_dependent_rule=None, + pre_cell_positions=None, + post_cell_positions=None, + delays_dict=None, + weights_dict=None, +): + """This method calls the appropriate methods that construct chemical or electrical projections. The input arguments are as follows: net - the network object created using libNeuroML ( neuroml.Network() ); @@ -313,7 +336,7 @@ def build_projection(net, post_seg_length_dict - a dictionary whose keys are the ids of target segment groups and the values are dictionaries in the format returned by make_target_dict(); - num_of_conn_dict - a dictionary whose keys are the ids of target segment groups with the corresponding values of type 'int' specifying the number of connections per + num_of_conn_dict - a dictionary whose keys are the ids of target segment groups with the corresponding values of type 'int' specifying the number of connections per tarrget segment group per each cell. distance_dependent_rule - optional string which defines the distance dependent rule of connectivity - soma to soma distance must be represented by the string character 'r'; @@ -324,8 +347,7 @@ def build_projection(net, delays_dict - optional dictionary that specifies the delays (in ms) for individual synapse components, e.g. {'NMDA':5.0} or {'AMPA':3.0,'NMDA':5}; - weights_dict - optional dictionary that specifies the weights for individual synapse components, e.g. {'NMDA':1} or {'NMDA':1,'AMPA':2}.''' - + weights_dict - optional dictionary that specifies the weights for individual synapse components, e.g. {'NMDA':1} or {'NMDA':1,'AMPA':2}.""" if presynaptic_population.size == 0 or postsynaptic_population.size == 0: return None @@ -336,105 +358,121 @@ def build_projection(net, synapse_list = list(set(synapse_list)) for synapse_id in synapse_list: - - if proj_type == 'Elect': - - proj = neuroml.ElectricalProjection(id="Proj%dsyn%d_%s_%s" % (proj_counter, syn_counter, presynaptic_population.id, postsynaptic_population.id), - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id) + if proj_type == "Elect": + proj = neuroml.ElectricalProjection( + id="Proj%dsyn%d_%s_%s" + % ( + proj_counter, + syn_counter, + presynaptic_population.id, + postsynaptic_population.id, + ), + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + ) syn_counter += 1 proj_array.append(proj) - if proj_type == 'Chem': + if proj_type == "Chem": + proj = neuroml.Projection( + id="Proj%dsyn%d_%s_%s" + % ( + proj_counter, + syn_counter, + presynaptic_population.id, + postsynaptic_population.id, + ), + presynaptic_population=presynaptic_population.id, + postsynaptic_population=postsynaptic_population.id, + synapse=synapse_id, + ) - proj = neuroml.Projection(id="Proj%dsyn%d_%s_%s" % (proj_counter, syn_counter, presynaptic_population.id, postsynaptic_population.id), - presynaptic_population=presynaptic_population.id, - postsynaptic_population=postsynaptic_population.id, - synapse=synapse_id) - - syn_counter += 1 + syn_counter += 1 proj_array.append(proj) - if distance_dependent_rule == None: - - if proj_type == 'Chem': - proj_array = oc_build.add_targeted_projection_by_dicts(net, - proj_array, - presynaptic_population, - postsynaptic_population, - targeting_mode, - synapse_list, - pre_seg_length_dict, - post_seg_length_dict, - num_of_conn_dict, - delays_dict, - weights_dict) - - if proj_type == 'Elect': - proj_array = oc_build._add_elect_projection(net, - proj_array, - presynaptic_population, - postsynaptic_population, - targeting_mode, - synapse_list, - pre_seg_length_dict, - post_seg_length_dict, - num_of_conn_dict) + if proj_type == "Chem": + proj_array = oc_build.add_targeted_projection_by_dicts( + net, + proj_array, + presynaptic_population, + postsynaptic_population, + targeting_mode, + synapse_list, + pre_seg_length_dict, + post_seg_length_dict, + num_of_conn_dict, + delays_dict, + weights_dict, + ) + + if proj_type == "Elect": + proj_array = oc_build._add_elect_projection( + net, + proj_array, + presynaptic_population, + postsynaptic_population, + targeting_mode, + synapse_list, + pre_seg_length_dict, + post_seg_length_dict, + num_of_conn_dict, + ) else: - - if proj_type == 'Chem': - proj_array = oc_build.add_chem_spatial_projection(net, - proj_array, - presynaptic_population, - postsynaptic_population, - targeting_mode, - synapse_list, - pre_seg_length_dict, - post_seg_length_dict, - num_of_conn_dict, - distance_dependent_rule, - pre_cell_positions, - post_cell_positions, - delays_dict, - weights_dict) - - if proj_type == 'Elect': - proj_array = oc_build.add_elect_spatial_projection(net, - proj_array, - presynaptic_population, - postsynaptic_population, - targeting_mode, - synapse_list, - pre_seg_length_dict, - post_seg_length_dict, - num_of_conn_dict, - distance_dependent_rule, - pre_cell_positions, - post_cell_positions) - - - + if proj_type == "Chem": + proj_array = oc_build.add_chem_spatial_projection( + net, + proj_array, + presynaptic_population, + postsynaptic_population, + targeting_mode, + synapse_list, + pre_seg_length_dict, + post_seg_length_dict, + num_of_conn_dict, + distance_dependent_rule, + pre_cell_positions, + post_cell_positions, + delays_dict, + weights_dict, + ) + + if proj_type == "Elect": + proj_array = oc_build.add_elect_spatial_projection( + net, + proj_array, + presynaptic_population, + postsynaptic_population, + targeting_mode, + synapse_list, + pre_seg_length_dict, + post_seg_length_dict, + num_of_conn_dict, + distance_dependent_rule, + pre_cell_positions, + post_cell_positions, + ) return proj_array, proj_counter - ############################################################################################## -def build_connectivity(net, - pop_objects, - path_to_cells, - full_path_to_conn_summary, - pre_segment_group_info=[], - return_cached_dicts=True, - synaptic_scaling_params=None, - synaptic_delay_params=None, - distance_dependence_params=None, - ignore_synapses=[]): - '''This method calls the appropriate build and utils methods to build connectivity of the NeuroML2 cortical network. Input arguments are as follows: +def build_connectivity( + net, + pop_objects, + path_to_cells, + full_path_to_conn_summary, + pre_segment_group_info=[], + return_cached_dicts=True, + synaptic_scaling_params=None, + synaptic_delay_params=None, + distance_dependence_params=None, + ignore_synapses=[], +): + """This method calls the appropriate build and utils methods to build connectivity of the NeuroML2 cortical network. Input arguments are as follows: net- NeuroML2 network object; @@ -442,15 +480,15 @@ def build_connectivity(net, path_to_cells - dir path to the folder where target NeuroML2 .cell.nml files are found; - full_path_to_conn_sumary - full path to the file which stores the connectivity summary, e.g. file named netConnList in the current working dir, + full_path_to_conn_sumary - full path to the file which stores the connectivity summary, e.g. file named netConnList in the current working dir, then this string must be "netConnList"; - pre_segment_group_info - input argument of type 'list' which specifies presynaptic segment groups; made to supplement connectivity summary of type netConnList - in the Thalamocortical project; default value is []; alternatively it might have one value of type'dict' or several values of type 'dict'; in the former case, + pre_segment_group_info - input argument of type 'list' which specifies presynaptic segment groups; made to supplement connectivity summary of type netConnList + in the Thalamocortical project; default value is []; alternatively it might have one value of type'dict' or several values of type 'dict'; in the former case, dict should contain the fields 'PreSegGroup' and 'ProjType'; in the latter case each dictionary should contain the fields 'PrePop', 'PostPop', 'PreSegGroup' and 'ProjType', which uniquely specifies one presynaptic segment group per pair of cell populations per type of projection. - return_cached_dicts - boolean-type argument which specifies whether build_connectivity returns the cached dictionary of cummulative distributions of segment lengths + return_cached_dicts - boolean-type argument which specifies whether build_connectivity returns the cached dictionary of cummulative distributions of segment lengths for all of the target segment groups. If return_cached_dicts is set to True the last output argument that is returned by build_connectivity is a cached target dictionary; the cached target dictionary is specifically built by the method check_cached_dicts inside utils; @@ -470,80 +508,78 @@ def build_connectivity(net, distance_dependent_params - optional input argument, default value is None. Alternatively, it take the format of - [{'PrePopID':'Pop1','PostPopID':'Pop2','DistDependConn':'- 17.45 + 18.36 / (math.exp((r-267.)/39.) +1)','Type':'Elect'}]. ''' + [{'PrePopID':'Pop1','PostPopID':'Pop2','DistDependConn':'- 17.45 + 18.36 / (math.exp((r-267.)/39.) +1)','Type':'Elect'}].""" final_synapse_list = [] final_proj_array = [] - cached_target_dict = {} + cached_target_dict = {} proj_counter = 0 for prePop in pop_objects.keys(): - preCellObject = pop_objects[prePop] for postPop in pop_objects.keys(): - postCellObject = pop_objects[postPop] - if preCellObject['PopObj'].size != 0 and postCellObject['PopObj'].size != 0: - - proj_summary = read_connectivity(prePop, - postPop, - full_path_to_conn_summary, - ignore_synapses=ignore_synapses) + if preCellObject["PopObj"].size != 0 and postCellObject["PopObj"].size != 0: + proj_summary = read_connectivity( + prePop, + postPop, + full_path_to_conn_summary, + ignore_synapses=ignore_synapses, + ) if proj_summary != []: - for proj_ind in range(0, len(proj_summary)): - projInfo = proj_summary[proj_ind] - target_comp_groups = projInfo['LocOnPostCell'] + target_comp_groups = projInfo["LocOnPostCell"] - synapseList = projInfo['SynapseList'] + synapseList = projInfo["SynapseList"] - final_synapse_list.extend(projInfo['SynapseList']) + final_synapse_list.extend(projInfo["SynapseList"]) - if 'NumPerPostCell' in projInfo: + if "NumPerPostCell" in projInfo: + targetingMode = "convergent" - targetingMode = 'convergent' + mode_string = "NumPerPostCell" - mode_string = 'NumPerPostCell' + if "NumPerPreCell" in projInfo: + targetingMode = "divergent" - if 'NumPerPreCell' in projInfo: - - targetingMode = 'divergent' - - mode_string = 'NumPerPreCell' + mode_string = "NumPerPreCell" if synaptic_scaling_params != None: - - weights = parse_weights(synaptic_scaling_params, postPop, synapseList) + weights = parse_weights( + synaptic_scaling_params, postPop, synapseList + ) else: - weights = None if synaptic_delay_params != None: - - delays = parse_delays(synaptic_delay_params, postPop, synapseList) + delays = parse_delays( + synaptic_delay_params, postPop, synapseList + ) else: - delays = None if distance_dependence_params != None: - - dist_par = parse_distance_dependent_rule(distance_dependence_params, prePop, postPop, projInfo['Type']) + dist_par = parse_distance_dependent_rule( + distance_dependence_params, + prePop, + postPop, + projInfo["Type"], + ) else: - dist_par = None - ### assumes one target segment group per given projection in the format of netConnLists ### + ### assumes one target segment group per given projection in the format of netConnLists ### subset_dict = {} subset_dict[target_comp_groups] = float(projInfo[mode_string]) @@ -551,130 +587,159 @@ def build_connectivity(net, target_comp_groups = [target_comp_groups] ############################################################################################# - PostSegLengthDict, cached_target_dict = check_cached_dicts(postCellObject['PopObj'].component, - cached_target_dict, - target_comp_groups, - path_to_nml2=path_to_cells) + PostSegLengthDict, cached_target_dict = check_cached_dicts( + postCellObject["PopObj"].component, + cached_target_dict, + target_comp_groups, + path_to_nml2=path_to_cells, + ) if pre_segment_group_info != []: - - passed_pre_seg_groups = check_pre_segment_groups(pre_segment_group_info) + passed_pre_seg_groups = check_pre_segment_groups( + pre_segment_group_info + ) if not passed_pre_seg_groups: - - opencortex.print_comment_v("Error: the list pre_segment_group_info was not correctly specified. Execution will terminate.") + opencortex.print_comment_v( + "Error: the list pre_segment_group_info was not correctly specified. Execution will terminate." + ) quit() else: ############# this block is tailored for handling the connectivity summary in the format of netConnList in the Thalamocortical project. if len(pre_segment_group_info) == 1: - - if pre_segment_group_info[0]['ProjType'] == projInfo['Type']: - - PreSegLengthDict, cached_target_dict = check_cached_dicts(preCellObject['PopObj'].component, - cached_target_dict, - [pre_segment_group_info[0]['PreSegGroup']], - path_to_nml2=path_to_cells) + if ( + pre_segment_group_info[0]["ProjType"] + == projInfo["Type"] + ): + PreSegLengthDict, cached_target_dict = ( + check_cached_dicts( + preCellObject["PopObj"].component, + cached_target_dict, + [ + pre_segment_group_info[0][ + "PreSegGroup" + ] + ], + path_to_nml2=path_to_cells, + ) + ) else: - - if projInfo['Type'] == 'Elect': - - PreSegLengthDict, cached_target_dict = check_cached_dicts(preCellObject['PopObj'].component, - cached_target_dict, - target_comp_groups, - path_to_nml2=path_to_cells) + if projInfo["Type"] == "Elect": + PreSegLengthDict, cached_target_dict = ( + check_cached_dicts( + preCellObject["PopObj"].component, + cached_target_dict, + target_comp_groups, + path_to_nml2=path_to_cells, + ) + ) else: - PreSegLengthDict = None - ############################################################## + ############################################################## if len(pre_segment_group_info) > 1: - found_pre_segment_group = False for proj in range(0, len(pre_segment_group_info)): - - check_pre_pop = pre_segment_group_info[proj]['PrePop'] == prePop - - check_post_pop = pre_segment_group_info[proj]['PostPop'] == postPop - - check_proj_type = pre_segment_group_info[proj]['ProjType'] == projInfo['Type'] - - if check_pre_pop and check_post_pop and check_proj_type: - - PreSegLengthDict, cached_target_dict = check_cached_dicts(preCellObject['PopObj'].component, - cached_target_dict, - [pre_segment_group_info[proj]['PreSegGroup']], - path_to_nml2=path_to_cells) + check_pre_pop = ( + pre_segment_group_info[proj]["PrePop"] + == prePop + ) + + check_post_pop = ( + pre_segment_group_info[proj]["PostPop"] + == postPop + ) + + check_proj_type = ( + pre_segment_group_info[proj]["ProjType"] + == projInfo["Type"] + ) + + if ( + check_pre_pop + and check_post_pop + and check_proj_type + ): + PreSegLengthDict, cached_target_dict = ( + check_cached_dicts( + preCellObject["PopObj"].component, + cached_target_dict, + [ + pre_segment_group_info[proj][ + "PreSegGroup" + ] + ], + path_to_nml2=path_to_cells, + ) + ) found_pre_segment_group = True break - if not found_pre_segment_group: - - PreSegLengthDict = None + PreSegLengthDict = None else: - - PreSegLengthDict = None - - compound_proj = build_projection(net=net, - proj_counter=proj_counter, - proj_type=projInfo['Type'], - presynaptic_population=preCellObject['PopObj'], - postsynaptic_population=postCellObject['PopObj'], - synapse_list=synapseList, - targeting_mode=targetingMode, - pre_seg_length_dict=PreSegLengthDict, - post_seg_length_dict=PostSegLengthDict, - num_of_conn_dict=subset_dict, - distance_dependent_rule=dist_par, - pre_cell_positions=preCellObject['Positions'], - post_cell_positions=postCellObject['Positions'], - delays_dict=delays, - weights_dict=weights) - - - proj_counter += 1 + PreSegLengthDict = None + + compound_proj = build_projection( + net=net, + proj_counter=proj_counter, + proj_type=projInfo["Type"], + presynaptic_population=preCellObject["PopObj"], + postsynaptic_population=postCellObject["PopObj"], + synapse_list=synapseList, + targeting_mode=targetingMode, + pre_seg_length_dict=PreSegLengthDict, + post_seg_length_dict=PostSegLengthDict, + num_of_conn_dict=subset_dict, + distance_dependent_rule=dist_par, + pre_cell_positions=preCellObject["Positions"], + post_cell_positions=postCellObject["Positions"], + delays_dict=delays, + weights_dict=weights, + ) + + proj_counter += 1 final_proj_array.extend(compound_proj) - final_synapse_list = np.unique(final_synapse_list) final_synapse_list = list(final_synapse_list) if return_cached_dicts: - return final_synapse_list, final_proj_array, cached_target_dict else: - return final_synapse_list, final_proj_array ############################################################################################## -def build_probability_based_connectivity(net, - pop_params, - probability_matrix, - synapse_matrix, - weight_matrix, - delay_matrix, - tags_on_populations, - std_weight_matrix=None, - std_delay_matrix=None): - ''''Method which build network projections based on the probability matrix which specifies the probabilities between given populations. Input arguments: +def build_probability_based_connectivity( + net, + pop_params, + probability_matrix, + synapse_matrix, + weight_matrix, + delay_matrix, + tags_on_populations, + std_weight_matrix=None, + std_delay_matrix=None, +): + """'Method which build network projections based on the probability matrix which specifies the probabilities between given populations. Input arguments: net- NeuroML2 network object; pop_params - dictionary of population parameters in the format returned by the utils method add_populations_in_rectangular_layers() or add_populations_in_cylindrical_layers(); - probability_matrix - n by n array (list of lists or numpy array) which specifies the connection probabilities between the presynaptic and postsynaptic populations; - the first index is for the target population (postsynaptic) and the second index is for the source population (presynaptic); can be 1 by 1 matrix , then probability - is applied to all pairs of populations; probability values must be of type 'float'; + probability_matrix - n by n array (list of lists or numpy array) which specifies the connection probabilities between the presynaptic and postsynaptic populations; + the first index is for the target population (postsynaptic) and the second index is for the source population (presynaptic); can be 1 by 1 matrix , then probability + is applied to all pairs of populations; probability values must be of type 'float'; synapse_matrix - n by n array (list of lists) which specifies the synapse components per projections; each element has be of the type 'list' because generically physical projection can contain multiple synaptic components; @@ -685,8 +750,8 @@ def build_probability_based_connectivity(net, delay_matrix - n by n array (list of lists or numpy array) which specifies the delay values for projections; each matrix element should be of type 'float' or if synaptic components per given projection differ in delays, then a corresponding matrix elment must be a list containing 'float' values; - tags_on_populations - a list of n strings which tags the network populations; cannot have length larger than the number of populations; index of the population tag in - tags_on_populations must correspond to the position of the matrix element in a standard way, e.g. + tags_on_populations - a list of n strings which tags the network populations; cannot have length larger than the number of populations; index of the population tag in + tags_on_populations must correspond to the position of the matrix element in a standard way, e.g. tags_on_populations= [ 'pop1', 'pop2' ], thus 'pop1' index is 0 and 'pop2' index is 1; @@ -703,216 +768,243 @@ def build_probability_based_connectivity(net, std_weight_matrix - optional matrix in the format weight_synapse which specifies the corresponding standard deviations of synaptic weights; default is set to None; - std_delay_matrix - optional matrix in the format delay_synapse which specifies the corresponding standard deviations of synaptic delays; default is set to None.''' + std_delay_matrix - optional matrix in the format delay_synapse which specifies the corresponding standard deviations of synaptic delays; default is set to None.""" errors_found = 0 matrices_with_errors = [] - passed_probs = check_matrix_size_and_type(matrix_of_params=probability_matrix, num_of_pop_tags=len(tags_on_populations), type_of_matrix=float) + passed_probs = check_matrix_size_and_type( + matrix_of_params=probability_matrix, + num_of_pop_tags=len(tags_on_populations), + type_of_matrix=float, + ) if not passed_probs: - errors_found += 1 - matrices_with_errors.append('matrix of connection probabilities') + matrices_with_errors.append("matrix of connection probabilities") - passed_syns = check_matrix_size_and_type(matrix_of_params=synapse_matrix, num_of_pop_tags=len(tags_on_populations), type_of_matrix=str) + passed_syns = check_matrix_size_and_type( + matrix_of_params=synapse_matrix, + num_of_pop_tags=len(tags_on_populations), + type_of_matrix=str, + ) if not passed_syns: - errors_found += 1 - matrices_with_errors.append('matrix of synapse component ids') + matrices_with_errors.append("matrix of synapse component ids") - passed_weights = check_matrix_size_and_type(matrix_of_params=weight_matrix, num_of_pop_tags=len(tags_on_populations), type_of_matrix=float) + passed_weights = check_matrix_size_and_type( + matrix_of_params=weight_matrix, + num_of_pop_tags=len(tags_on_populations), + type_of_matrix=float, + ) if not passed_weights: - errors_found += 1 - matrices_with_errors.append('matrix of mean values for synaptic weights') + matrices_with_errors.append("matrix of mean values for synaptic weights") - passed_delays = check_matrix_size_and_type(matrix_of_params=delay_matrix, num_of_pop_tags=len(tags_on_populations), type_of_matrix=float) + passed_delays = check_matrix_size_and_type( + matrix_of_params=delay_matrix, + num_of_pop_tags=len(tags_on_populations), + type_of_matrix=float, + ) if not passed_delays: - errors_found += 1 - matrices_with_errors.append('matrix of mean values for synaptic delays') + matrices_with_errors.append("matrix of mean values for synaptic delays") if std_weight_matrix != None: - - passed_std_weights = check_matrix_size_and_type(matrix_of_params=std_weight_matrix, num_of_pop_tags=len(tags_on_populations), type_of_matrix=float) + passed_std_weights = check_matrix_size_and_type( + matrix_of_params=std_weight_matrix, + num_of_pop_tags=len(tags_on_populations), + type_of_matrix=float, + ) if not passed_std_weights: - errors_found += 1 - matrices_with_errors.append('matrix of standard deviations for synaptic weights') + matrices_with_errors.append( + "matrix of standard deviations for synaptic weights" + ) if std_delay_matrix != None: - - passed_std_delays = check_matrix_size_and_type(matrix_of_params=std_delay_matrix, num_of_pop_tags=len(tags_on_populations), type_of_matrix=float) + passed_std_delays = check_matrix_size_and_type( + matrix_of_params=std_delay_matrix, + num_of_pop_tags=len(tags_on_populations), + type_of_matrix=float, + ) if not passed_std_delays: - errors_found += 1 - matrices_with_errors.append('matrix of standard deviations for synaptic delays') + matrices_with_errors.append( + "matrix of standard deviations for synaptic delays" + ) if errors_found == 0: - - opencortex.print_comment_v("All of the connectivity matrices were specified correctly.") + opencortex.print_comment_v( + "All of the connectivity matrices were specified correctly." + ) else: - - opencortex.print_comment_v("The connectivity matrices in %s were not specified correctly; execution will terminate." % matrices_with_errors) + opencortex.print_comment_v( + "The connectivity matrices in %s were not specified correctly; execution will terminate." + % matrices_with_errors + ) quit() proj_array = [] for pre_pop_id in pop_params.keys(): - for post_pop_id in pop_params.keys(): - found_pre_pop = False found_post_pop = False for tag_ind in range(0, len(tags_on_populations)): - tag = tags_on_populations[tag_ind] if tag in pre_pop_id: - column_index = tag_ind found_pre_pop = True if tag in post_pop_id: - row_index = tag_ind found_post_pop = True if found_pre_pop and found_post_pop: + pre_pop_obj = pop_params[pre_pop_id]["PopObj"] - pre_pop_obj = pop_params[pre_pop_id]['PopObj'] - - post_pop_obj = pop_params[post_pop_id]['PopObj'] + post_pop_obj = pop_params[post_pop_id]["PopObj"] #################################################################### - prob_val = parse_parameter_value(parameter_matrix=probability_matrix, - row_ind=row_index, - col_ind=column_index, - checks_passed=True) - - synapse_list = parse_parameter_value(parameter_matrix=synapse_matrix, - row_ind=row_index, - col_ind=column_index, - checks_passed=True) - - ####################################################################### + prob_val = parse_parameter_value( + parameter_matrix=probability_matrix, + row_ind=row_index, + col_ind=column_index, + checks_passed=True, + ) + + synapse_list = parse_parameter_value( + parameter_matrix=synapse_matrix, + row_ind=row_index, + col_ind=column_index, + checks_passed=True, + ) + + ####################################################################### if prob_val != 0 and pre_pop_obj.size != 0 and post_pop_obj.size != 0: - if synapse_list != None: - if not isinstance(synapse_list, list): - synapse_list = [synapse_list] - ########################################################################## - weight_list = parse_parameter_value(parameter_matrix=weight_matrix, - row_ind=row_index, - col_ind=column_index, - checks_passed=True) - - ########################################################################### - delay_list = parse_parameter_value(parameter_matrix=delay_matrix, - row_ind=row_index, - col_ind=column_index, - checks_passed=True) - - ############################################################################ + ########################################################################## + weight_list = parse_parameter_value( + parameter_matrix=weight_matrix, + row_ind=row_index, + col_ind=column_index, + checks_passed=True, + ) + + ########################################################################### + delay_list = parse_parameter_value( + parameter_matrix=delay_matrix, + row_ind=row_index, + col_ind=column_index, + checks_passed=True, + ) + + ############################################################################ if std_weight_matrix != None: - - std_weight_list = parse_parameter_value(parameter_matrix=std_weight_matrix, - row_ind=row_index, - col_ind=column_index, - checks_passed=True) + std_weight_list = parse_parameter_value( + parameter_matrix=std_weight_matrix, + row_ind=row_index, + col_ind=column_index, + checks_passed=True, + ) else: - std_weight_list = None - ############################################################################# + ############################################################################# if std_delay_matrix != None: - - std_delay_list = parse_parameter_value(parameter_matrix=std_delay_matrix, - row_ind=row_index, - col_ind=column_index, - checks_passed=True) + std_delay_list = parse_parameter_value( + parameter_matrix=std_delay_matrix, + row_ind=row_index, + col_ind=column_index, + checks_passed=True, + ) else: - std_delay_list = None ############################################################################### - returned_projs = oc_build.add_probabilistic_projection_list(net=net, - presynaptic_population=pre_pop_obj, - postsynaptic_population=post_pop_obj, - synapse_list=synapse_list, - connection_probability=prob_val, - delay=delay_list, - weight=weight_list, - std_delay=std_delay_list, - std_weight=std_weight_list) + returned_projs = oc_build.add_probabilistic_projection_list( + net=net, + presynaptic_population=pre_pop_obj, + postsynaptic_population=post_pop_obj, + synapse_list=synapse_list, + connection_probability=prob_val, + delay=delay_list, + weight=weight_list, + std_delay=std_delay_list, + std_weight=std_weight_list, + ) if returned_projs != None: - - opencortex.print_comment_v("Addded a projection between %s and %s" % (pre_pop_id, post_pop_id)) + opencortex.print_comment_v( + "Addded a projection between %s and %s" + % (pre_pop_id, post_pop_id) + ) proj_array.extend(returned_projs) else: - - opencortex.print_comment_v("Error in opencortex.utils.build_probability_based_connectivity(): connection probability is not equal to 0 but synapse list is None" - " for the projection between presynaptic population id=%s and postsynaptic population id= %s. Execution will terminate." % (pre_pop_id, post_pop_id)) + opencortex.print_comment_v( + "Error in opencortex.utils.build_probability_based_connectivity(): connection probability is not equal to 0 but synapse list is None" + " for the projection between presynaptic population id=%s and postsynaptic population id= %s. Execution will terminate." + % (pre_pop_id, post_pop_id) + ) quit() else: - if not found_pre_pop: - - opencortex.print_comment_v("Error in build_probability_based_connectivity(): input argument tags_on_populations in build_probability_based_connectivity()" - " does not contain a string tag for the population %s. Execution will terminate." % pre_pop_id) + opencortex.print_comment_v( + "Error in build_probability_based_connectivity(): input argument tags_on_populations in build_probability_based_connectivity()" + " does not contain a string tag for the population %s. Execution will terminate." + % pre_pop_id + ) quit() if not found_post_pop: - - opencortex.print_comment_v("Error in build_probability_based_connectivity(): input argument tags_on_populations in build_probability_based_connectivity()" - " does not contain a string tag for the population %s. Execution will terminate." % post_pop_id) + opencortex.print_comment_v( + "Error in build_probability_based_connectivity(): input argument tags_on_populations in build_probability_based_connectivity()" + " does not contain a string tag for the population %s. Execution will terminate." + % post_pop_id + ) quit() - return proj_array + return proj_array ############################################################################################## -def read_connectivity(pre_pop, - post_pop, - path_to_txt_file, - ignore_synapses=[]): - '''Method that reads the txt file in the format of netConnList found in: Thalamocortical/neuroConstruct/pythonScripts/netbuild.''' +def read_connectivity(pre_pop, post_pop, path_to_txt_file, ignore_synapses=[]): + """Method that reads the txt file in the format of netConnList found in: Thalamocortical/neuroConstruct/pythonScripts/netbuild.""" proj_summary = [] - with open(path_to_txt_file, 'r') as file: - + with open(path_to_txt_file, "r") as file: lines = file.readlines() num_per_post_cell = False @@ -920,135 +1012,114 @@ def read_connectivity(pre_pop, num_per_pre_cell = False for line in lines: - - if 'NumPerPostCell' in line: - + if "NumPerPostCell" in line: num_per_post_cell = True break - if 'NumPerPreCell' in line: - + if "NumPerPreCell" in line: num_per_pre_cell = True break for line in lines: - split_line = line.split(" ") extract_info = [] for string_index in range(0, len(split_line)): - - if split_line[string_index] != '': - + if split_line[string_index] != "": extract_info.append(split_line[string_index]) - counter = 0 + counter = 0 if pre_pop in extract_info[0] and post_pop in extract_info[1]: - proj_info = {} - proj_info['PreCellGroup'] = pre_pop + proj_info["PreCellGroup"] = pre_pop - proj_info['PostCellGroup'] = post_pop + proj_info["PostCellGroup"] = post_pop synapse_list = [] - if ',' in extract_info[2]: - synapse_list_string = extract_info[2].split(',') + if "," in extract_info[2]: + synapse_list_string = extract_info[2].split(",") else: synapse_list_string = [extract_info[2]] for synapse_string in synapse_list_string: + if "[" and "]" in synapse_string: + left = synapse_string.find("[") - if '[' and ']' in synapse_string: - - left = synapse_string.find('[') + right = synapse_string.find("]") - right = synapse_string.find(']') - - synapse = synapse_string[left + 1:right] + synapse = synapse_string[left + 1 : right] synapse_list.append(synapse) continue - if '[' in synapse_string: - - left = synapse_string.find('[') + if "[" in synapse_string: + left = synapse_string.find("[") - synapse = synapse_string[left + 1:] + synapse = synapse_string[left + 1 :] synapse_list.append(synapse) continue - if ']' in synapse_string: - - right = synapse_string.find(']') + if "]" in synapse_string: + right = synapse_string.find("]") synapse = synapse_string[0:right] synapse_list.append(synapse) - continue + continue for syn in ignore_synapses: - if syn in synapse_list: synapse_list.remove(syn) + if syn in synapse_list: + synapse_list.remove(syn) + proj_info["SynapseList"] = synapse_list - proj_info['SynapseList'] = synapse_list - - if 'Elect' in extract_info[2]: - proj_info['Type'] = 'Elect' + if "Elect" in extract_info[2]: + proj_info["Type"] = "Elect" else: - proj_info['Type'] = 'Chem' + proj_info["Type"] = "Chem" if num_per_post_cell: - - proj_info['NumPerPostCell'] = extract_info[3] + proj_info["NumPerPostCell"] = extract_info[3] if num_per_pre_cell: + proj_info["NumPerPreCell"] = extract_info[3] - proj_info['NumPerPreCell'] = extract_info[3] - - if '\n' in extract_info[4]: - - proj_info['LocOnPostCell'] = extract_info[4][0:-1] + if "\n" in extract_info[4]: + proj_info["LocOnPostCell"] = extract_info[4][0:-1] else: + proj_info["LocOnPostCell"] = extract_info[4] - proj_info['LocOnPostCell'] = extract_info[4] - - proj_summary.append(proj_info) - + proj_summary.append(proj_info) return proj_summary ############################################################################################## -def parse_parameter_value(parameter_matrix, row_ind, col_ind, checks_passed=False): - '''Method to parse one of the connectivity parameters; by default assumes that checks are carried out by the method check_matrix_size_and_type().''' +def parse_parameter_value(parameter_matrix, row_ind, col_ind, checks_passed=False): + """Method to parse one of the connectivity parameters; by default assumes that checks are carried out by the method check_matrix_size_and_type().""" if not checks_passed: - return None else: - if len(parameter_matrix) == 1: - parameter_val = parameter_matrix[0] - else: - + else: parameter_val = parameter_matrix[row_ind][col_ind] if type(parameter_matrix).__module__ == np.__name__: - parameter_val = parameter_matrix[row_ind][col_ind] return parameter_val @@ -1056,98 +1127,117 @@ def parse_parameter_value(parameter_matrix, row_ind, col_ind, checks_passed=Fals ############################################################################################## -def check_matrix_size_and_type(matrix_of_params, num_of_pop_tags, type_of_matrix): - '''Method to check whether the size and the type of the connection parameter matrix, corresponds to the number of tags provided for the list of populations.''' +def check_matrix_size_and_type(matrix_of_params, num_of_pop_tags, type_of_matrix): + """Method to check whether the size and the type of the connection parameter matrix, corresponds to the number of tags provided for the list of populations.""" passed = True if isinstance(matrix_of_params, list): - if len(matrix_of_params) == 1: - if matrix_of_params[0] != None: - - if (not isinstance(matrix_of_params[0], list)): - + if not isinstance(matrix_of_params[0], list): if not isinstance(matrix_of_params[0], type_of_matrix): - - opencortex.print_comment_v("Error in check_matrix_size(): argument matrix_of_params is a list which contains one element but it is not of type %s;" - " the current type is %s." % (type_of_matrix, type(matrix_of_params[0]))) + opencortex.print_comment_v( + "Error in check_matrix_size(): argument matrix_of_params is a list which contains one element but it is not of type %s;" + " the current type is %s." + % (type_of_matrix, type(matrix_of_params[0])) + ) passed = False else: - for component_index in range(0, len(matrix_of_params[0])): - - if not isinstance(matrix_of_params[0][component_index], type_of_matrix): - - opencortex.print_comment_v("Error in check_matrix_size(): argument matrix_of_params is a list which contains a list but not all of its elements are of type %s;" - " the current type is %s." % (type_of_matrix, type(matrix_of_params[0][component]))) + if not isinstance( + matrix_of_params[0][component_index], type_of_matrix + ): + opencortex.print_comment_v( + "Error in check_matrix_size(): argument matrix_of_params is a list which contains a list but not all of its elements are of type %s;" + " the current type is %s." + % (type_of_matrix, type(matrix_of_params[0][component])) + ) passed = False else: - num_of_elements = 0 for row_ind in range(0, len(matrix_of_params)): - for col_ind in range(0, len(matrix_of_params[row_ind])): - - if (matrix_of_params[row_ind][col_ind] != None): - - if (not isinstance(matrix_of_params[row_ind][col_ind], list)): - - if not isinstance(matrix_of_params[row_ind][col_ind], type_of_matrix): - - opencortex.print_comment_v("Error in check_matrix_size(): argument matrix_of_params is a list of lists (matrix) but there is an element inside which is not" - " of type %s; the current type is %s." % (type_of_matrix, type(matrix_of_params[row_ind][col_ind]))) + if matrix_of_params[row_ind][col_ind] != None: + if not isinstance(matrix_of_params[row_ind][col_ind], list): + if not isinstance( + matrix_of_params[row_ind][col_ind], type_of_matrix + ): + opencortex.print_comment_v( + "Error in check_matrix_size(): argument matrix_of_params is a list of lists (matrix) but there is an element inside which is not" + " of type %s; the current type is %s." + % ( + type_of_matrix, + type(matrix_of_params[row_ind][col_ind]), + ) + ) passed = False else: - - for component_index in range(0, len(matrix_of_params[row_ind][col_ind])): - - if not isinstance(matrix_of_params[row_ind][col_ind][component_index], type_of_matrix): - - opencortex.print_comment_v("Error in check_matrix_size(): argument matrix_of_params is a list of lists (matrix) but list elements inside are not" - "of type %s; the current type is %s." % (type_of_matrix, type(matrix_of_params[row_ind][col_ind][component_index]))) + for component_index in range( + 0, len(matrix_of_params[row_ind][col_ind]) + ): + if not isinstance( + matrix_of_params[row_ind][col_ind][component_index], + type_of_matrix, + ): + opencortex.print_comment_v( + "Error in check_matrix_size(): argument matrix_of_params is a list of lists (matrix) but list elements inside are not" + "of type %s; the current type is %s." + % ( + type_of_matrix, + type( + matrix_of_params[row_ind][col_ind][ + component_index + ] + ), + ) + ) passed = False num_of_elements = num_of_elements + len(matrix_of_params[row_ind]) if len(matrix_of_params[row_ind]) != num_of_pop_tags: - - opencortex.print_comment_v("Error in check_matrix_size(): each list element of the argument matrix_of_params must have length = %d;" - " the current length is %d." % (num_of_pop_tags, len(matrix_of_params[row_ind]))) + opencortex.print_comment_v( + "Error in check_matrix_size(): each list element of the argument matrix_of_params must have length = %d;" + " the current length is %d." + % (num_of_pop_tags, len(matrix_of_params[row_ind])) + ) passed = False if num_of_elements != num_of_pop_tags * num_of_pop_tags: - - opencortex.print_comment_v("Error in check_matrix_size(): argument matrix_of_params is a list but not in the format of an %d by %d matrix." - % (num_of_pop_tags, num_of_pop_tags)) + opencortex.print_comment_v( + "Error in check_matrix_size(): argument matrix_of_params is a list but not in the format of an %d by %d matrix." + % (num_of_pop_tags, num_of_pop_tags) + ) passed = False elif type(matrix_of_params).__module__ == np.__name__: - rows_cols = matrix_of_params.size - if (rows_cols[0] != num_of_pop_tags or rows_cols[1] != num_of_pop_tags): - - opencortex.print_comment_v("Error in check_matrix_size(): argument matrix_of_params is a numpy array but not of size (%d, %d) (not a square matrix)." % num_of_pop_tags) + if rows_cols[0] != num_of_pop_tags or rows_cols[1] != num_of_pop_tags: + opencortex.print_comment_v( + "Error in check_matrix_size(): argument matrix_of_params is a numpy array but not of size (%d, %d) (not a square matrix)." + % num_of_pop_tags + ) passed = False else: - - opencortex.print_comment_v("Error in check_matrix_size(): argument matrix_of_params must be a list or numpy array; the current type is %s." - % type(matrix_of_params)) + opencortex.print_comment_v( + "Error in check_matrix_size(): argument matrix_of_params must be a list or numpy array; the current type is %s." + % type(matrix_of_params) + ) passed = False @@ -1156,14 +1246,15 @@ def check_matrix_size_and_type(matrix_of_params, num_of_pop_tags, type_of_matrix ############################################################################################## -def check_cached_dicts(cell_component, cached_dicts, list_of_target_seg_groups, path_to_nml2=None): - '''This method checks whether information is missing on target segment groups and updates the output dictionary with new information for the target cell component. ''' +def check_cached_dicts( + cell_component, cached_dicts, list_of_target_seg_groups, path_to_nml2=None +): + """This method checks whether information is missing on target segment groups and updates the output dictionary with new information for the target cell component.""" segLengthDict = {} if cell_component in cached_dicts.keys(): - target_groups_to_include = [] new_segment_groups = False @@ -1171,148 +1262,163 @@ def check_cached_dicts(cell_component, cached_dicts, list_of_target_seg_groups, segLengthDict = {} for target_group in list_of_target_seg_groups: - - if target_group not in cached_dicts[cell_component]['TargetDict'].keys(): - + if target_group not in cached_dicts[cell_component]["TargetDict"].keys(): target_groups_to_include.append(target_group) new_segment_groups = True else: - - segLengthDict[target_group] = cached_dicts[cell_component]['TargetDict'][target_group] + segLengthDict[target_group] = cached_dicts[cell_component][ + "TargetDict" + ][target_group] if new_segment_groups: + cellObject = cached_dicts[cell_component]["CellObject"] - cellObject = cached_dicts[cell_component]['CellObject'] + target_segments = oc_build.extract_seg_ids( + cell_object=cellObject, + target_compartment_array=target_groups_to_include, + targeting_mode="segGroups", + ) - target_segments = oc_build.extract_seg_ids(cell_object=cellObject, target_compartment_array=target_groups_to_include, targeting_mode='segGroups') - - new_seg_length_dict = oc_build.make_target_dict(cell_object=cellObject, target_segs=target_segments) + new_seg_length_dict = oc_build.make_target_dict( + cell_object=cellObject, target_segs=target_segments + ) for new_target_group in new_seg_length_dict.keys(): + cached_dicts[cell_component]["TargetDict"][new_target_group] = ( + new_seg_length_dict[new_target_group] + ) - cached_dicts[cell_component]['TargetDict'][new_target_group] = new_seg_length_dict[new_target_group] - - segLengthDict[new_target_group] = new_seg_length_dict[new_target_group] + segLengthDict[new_target_group] = new_seg_length_dict[ + new_target_group + ] else: - - cell_nml_file = '%s.cell.nml' % cell_component + cell_nml_file = "%s.cell.nml" % cell_component if path_to_nml2 != None: - - document_cell = neuroml.loaders.NeuroMLLoader.load(os.path.join(path_to_nml2, cell_nml_file)) + document_cell = neuroml.loaders.NeuroMLLoader.load( + os.path.join(path_to_nml2, cell_nml_file) + ) else: - document_cell = neuroml.loaders.NeuroMLLoader.load(cell_nml_file) cellObject = document_cell.cells[0] - target_segments = oc_build.extract_seg_ids(cell_object=cellObject, target_compartment_array=list_of_target_seg_groups, targeting_mode='segGroups') + target_segments = oc_build.extract_seg_ids( + cell_object=cellObject, + target_compartment_array=list_of_target_seg_groups, + targeting_mode="segGroups", + ) - segLengthDict = oc_build.make_target_dict(cell_object=cellObject, target_segs=target_segments) + segLengthDict = oc_build.make_target_dict( + cell_object=cellObject, target_segs=target_segments + ) cached_dicts[cell_component] = {} - cached_dicts[cell_component]['CellObject'] = cellObject + cached_dicts[cell_component]["CellObject"] = cellObject - cached_dicts[cell_component]['TargetDict'] = segLengthDict + cached_dicts[cell_component]["TargetDict"] = segLengthDict return segLengthDict, cached_dicts ############################################################################################## -def check_pre_segment_groups(pre_segment_group_info): +def check_pre_segment_groups(pre_segment_group_info): error_counter = 0 passed = False if len(pre_segment_group_info) == 1: - if isinstance(pre_segment_group_info[0], dict): + check_pre_seg = "PreSegGroup" in pre_segment_group_info[0].keys() - check_pre_seg = 'PreSegGroup' in pre_segment_group_info[0].keys() - - check_proj_type = 'ProjType' in pre_segment_group_info[0].keys() + check_proj_type = "ProjType" in pre_segment_group_info[0].keys() if not check_pre_seg: - - opencortex.print_comment_v("Error in build connectivity: the key 'PreSegGroup' is not in the dictionary keys inside pre_segment_group_info.") + opencortex.print_comment_v( + "Error in build connectivity: the key 'PreSegGroup' is not in the dictionary keys inside pre_segment_group_info." + ) error_counter += 1 else: - - if not isinstance(pre_segment_group_info[0]['PreSegGroup'], str): - - opencortex.print_comment_v("Error in build connectivity: the value of the key 'PreSegGroup' in the dictionary keys inside pre_segment_group_info" - " must be of type 'str'. Only one presynaptic segment group is allowed per projection.") - error_counter += 1 + if not isinstance(pre_segment_group_info[0]["PreSegGroup"], str): + opencortex.print_comment_v( + "Error in build connectivity: the value of the key 'PreSegGroup' in the dictionary keys inside pre_segment_group_info" + " must be of type 'str'. Only one presynaptic segment group is allowed per projection." + ) + error_counter += 1 if not check_proj_type: - - opencortex.print_comment_v("Error in build connectivity: the key 'ProjType' is not in the dictionary keys inside pre_segment_group_info.") + opencortex.print_comment_v( + "Error in build connectivity: the key 'ProjType' is not in the dictionary keys inside pre_segment_group_info." + ) error_counter += 1 else: - - opencortex.print_comment_v("Error in build_connectivity: the list pre_segment_group_info has only one element but it is not of type 'dict'." - " The current type is %s." % (type(pre_segment_group_info[0]))) + opencortex.print_comment_v( + "Error in build_connectivity: the list pre_segment_group_info has only one element but it is not of type 'dict'." + " The current type is %s." % (type(pre_segment_group_info[0])) + ) error_counter += 1 if len(pre_segment_group_info) > 1: - for proj in range(0, len(pre_segment_group_info)): - if isinstance(pre_segment_group_info[proj], dict): + check_pre_seg = "PreSegGroup" in pre_segment_group_info[proj].keys() - check_pre_seg = 'PreSegGroup' in pre_segment_group_info[proj].keys() - - check_pre_pop = 'PrePop' in pre_segment_group_info[proj].keys() + check_pre_pop = "PrePop" in pre_segment_group_info[proj].keys() - check_post_pop = 'PostPop' in pre_segment_group_info[proj].keys() + check_post_pop = "PostPop" in pre_segment_group_info[proj].keys() - check_proj_type = 'ProjType' in pre_segment_group_info[proj].keys() + check_proj_type = "ProjType" in pre_segment_group_info[proj].keys() if not check_pre_seg: - - opencortex.print_comment_v("Error in build connectivity: the key 'PreSegGroup' is not in the dictionary keys inside pre_segment_group_info.") + opencortex.print_comment_v( + "Error in build connectivity: the key 'PreSegGroup' is not in the dictionary keys inside pre_segment_group_info." + ) error_counter += 1 else: - - if not isinstance(pre_segment_group_info[proj]['PreSegGroup'], str): - - opencortex.print_comment_v("Error in build connectivity: the value of the key 'PreSegGroup' in the dictionary keys inside pre_segment_group_info" - " must be of type 'str'. Only one presynaptic segment group is allowed per projection.") + if not isinstance(pre_segment_group_info[proj]["PreSegGroup"], str): + opencortex.print_comment_v( + "Error in build connectivity: the value of the key 'PreSegGroup' in the dictionary keys inside pre_segment_group_info" + " must be of type 'str'. Only one presynaptic segment group is allowed per projection." + ) error_counter += 1 if not check_pre_pop: - - opencortex.print_comment_v("Error in build connectivity: the key 'PrePop' is not in the dictionary keys inside pre_segment_group_info.") + opencortex.print_comment_v( + "Error in build connectivity: the key 'PrePop' is not in the dictionary keys inside pre_segment_group_info." + ) error_counter += 1 if not check_post_pop: - - opencortex.print_comment_v("Error in build connectivity: the key 'PostPop' is not in the dictionary keys inside pre_segment_group_info.") + opencortex.print_comment_v( + "Error in build connectivity: the key 'PostPop' is not in the dictionary keys inside pre_segment_group_info." + ) error_counter += 1 if not check_proj_type: - - opencortex.print_comment_v("Error in build connectivity: the key 'ProjType' is not in the dictionary keys inside pre_segment_group_info.") + opencortex.print_comment_v( + "Error in build connectivity: the key 'ProjType' is not in the dictionary keys inside pre_segment_group_info." + ) error_counter += 1 else: - - opencortex.print_comment_v("Error in build_connectivity: the list elements in the pre_segment_group_info must be dictionaries with fields" - " 'PreSegGroup', 'PrePop', 'PostPop' and 'ProjType'. The current type is %s." % (type(pre_segment_group_info[proj]))) + opencortex.print_comment_v( + "Error in build_connectivity: the list elements in the pre_segment_group_info must be dictionaries with fields" + " 'PreSegGroup', 'PrePop', 'PostPop' and 'ProjType'. The current type is %s." + % (type(pre_segment_group_info[proj])) + ) error_counter += 1 if error_counter == 0: - passed = True return passed @@ -1320,9 +1426,17 @@ def check_pre_segment_groups(pre_segment_group_info): ############################################################################################## -def build_inputs(nml_doc, net, population_params, input_params, cached_dicts=None, path_to_cells=None, path_to_synapses=None): - ''' +def build_inputs( + nml_doc, + net, + population_params, + input_params, + cached_dicts=None, + path_to_cells=None, + path_to_synapses=None, +): + """ a wrapper method that calls appropriate methods to build inputs to the NeuroML2 network. Input arguments: nml_doc - a libNeuroML doc object; @@ -1345,7 +1459,7 @@ def build_inputs(nml_doc, net, population_params, input_params, cached_dicts=Non 'FractionToTarget':1.0, 'LocationSpecific':False, 'TargetRegions':[{'XVector':[2,12],'YVector':[3,5],'ZVector':[0,5]}], - 'TargetDict':{'dendrite_group':1000 } }] } + 'TargetDict':{'dendrite_group':1000 } }] } Example 2: input_params={'TCR':[{'InputType':'PulseGenerators', 'InputName':'PulseGenerator0', @@ -1355,7 +1469,7 @@ def build_inputs(nml_doc, net, population_params, input_params, cached_dicts=Non 'DelayList':[50.0,200.0], 'FractionToTarget':1.0, 'LocationSpecific':False, - 'TargetDict':{'dendrite_group':2 } }] } + 'TargetDict':{'dendrite_group':2 } }] } Example 3: input_params={'CG3D_L23PyrRS':[{'InputType':'PulseGenerators', 'InputName':'PulseGenerator0', @@ -1375,51 +1489,49 @@ def build_inputs(nml_doc, net, population_params, input_params, cached_dicts=Non path_to_cells - dir where NeuroML2 cell files are found; - path_to_synapses - dir where NeuroML2 synapse files are found. ''' + path_to_synapses - dir where NeuroML2 synapse files are found.""" - passed_inputs = check_inputs(input_params, population_params, path_to_cells, path_to_synapses) + passed_inputs = check_inputs( + input_params, population_params, path_to_cells, path_to_synapses + ) if passed_inputs: - opencortex.print_comment_v("Input parameters were specified correctly.") else: - - opencortex.print_comment_v("Input parameters were specified incorrectly; execution will terminate.") + opencortex.print_comment_v( + "Input parameters were specified incorrectly; execution will terminate." + ) quit() - input_list_array_final = [] + input_list_array_final = [] - input_synapse_list = [] + input_synapse_list = [] for cell_tag in input_params.keys(): - for cell_population in population_params.keys(): - if cell_tag in cell_population: - - pop = population_params[cell_population]['PopObj'] + pop = population_params[cell_population]["PopObj"] cell_component = pop.component for input_group_ind in range(0, len(input_params[cell_tag])): - input_group_params = input_params[cell_tag][input_group_ind] - input_group_tag = input_group_params['InputName'] + "_TO_" + pop.id + input_group_tag = input_group_params["InputName"] + "_TO_" + pop.id popID = cell_population - fraction_to_target = input_group_params['FractionToTarget'] + fraction_to_target = input_group_params["FractionToTarget"] - if not input_group_params['LocationSpecific']: - - target_cell_ids = oc_build.get_target_cells(population=pop, fraction_to_target=fraction_to_target) + if not input_group_params["LocationSpecific"]: + target_cell_ids = oc_build.get_target_cells( + population=pop, fraction_to_target=fraction_to_target + ) else: - - list_of_regions = input_group_params['TargetRegions'] + list_of_regions = input_group_params["TargetRegions"] x_list = [] @@ -1428,225 +1540,346 @@ def build_inputs(nml_doc, net, population_params, input_params, cached_dicts=Non z_list = [] for region_index in range(0, len(list_of_regions)): + x_list.append(list_of_regions[region_index]["XVector"]) - x_list.append(list_of_regions[region_index]['XVector']) + y_list.append(list_of_regions[region_index]["YVector"]) - y_list.append(list_of_regions[region_index]['YVector']) + z_list.append(list_of_regions[region_index]["ZVector"]) - z_list.append(list_of_regions[region_index]['ZVector']) - - target_cell_ids = oc_build.get_target_cells(population=pop, - fraction_to_target=fraction_to_target, - list_of_xvectors=x_list, - list_of_yvectors=y_list, - list_of_zvectors=z_list) + target_cell_ids = oc_build.get_target_cells( + population=pop, + fraction_to_target=fraction_to_target, + list_of_xvectors=x_list, + list_of_yvectors=y_list, + list_of_zvectors=z_list, + ) if target_cell_ids != []: - input_ids_final = [] weight_list_final = [] - condition1 = 'TargetDict' in input_group_params.keys() + condition1 = "TargetDict" in input_group_params.keys() - condition2 = 'UniversalTargetSegmentID' not in input_group_params.keys() + condition2 = ( + "UniversalTargetSegmentID" not in input_group_params.keys() + ) + + condition3 = ( + "UniversalFractionAlong" not in input_group_params.keys() + ) - condition3 = 'UniversalFractionAlong' not in input_group_params.keys() - weight_dict = {} if condition1 and condition2 and condition3: - - subset_dict = input_group_params['TargetDict'] + subset_dict = input_group_params["TargetDict"] target_segment = None fraction_along = None - if None not in input_group_params['TargetDict'].keys(): - + if None not in input_group_params["TargetDict"].keys(): target_group_list = subset_dict.keys() if cached_dicts != None: - - segLengthDict, cached_dicts = check_cached_dicts(cell_component, cached_dicts, target_group_list, path_to_nml2=path_to_cells) + segLengthDict, cached_dicts = check_cached_dicts( + cell_component, + cached_dicts, + target_group_list, + path_to_nml2=path_to_cells, + ) else: - - target_segments = oc_build.extract_seg_ids(cell_object=cellObject, - target_compartment_array=input_group_params['TargetDict'].keys(), - targeting_mode='segGroups') - - segLengthDict = oc_build.make_target_dict(cell_object=cellObject, target_segs=target_segments) + target_segments = oc_build.extract_seg_ids( + cell_object=cellObject, + target_compartment_array=input_group_params[ + "TargetDict" + ].keys(), + targeting_mode="segGroups", + ) + + segLengthDict = oc_build.make_target_dict( + cell_object=cellObject, + target_segs=target_segments, + ) else: - segLengthDict = None else: + target_segment = input_group_params[ + "UniversalTargetSegmentID" + ] - target_segment = input_group_params['UniversalTargetSegmentID'] - - fraction_along = input_group_params['UniversalFractionAlong'] + fraction_along = input_group_params[ + "UniversalFractionAlong" + ] segLengthDict = None subset_dict = None - if input_group_params['InputType'] == 'GeneratePoissonTrains': - + if input_group_params["InputType"] == "GeneratePoissonTrains": list_of_input_ids = [] - if input_group_params['TrainType'] == 'transient': - - for input_index in range(0, len(input_group_params['AverageRateList'])): - - tpfs = oc_build._add_transient_poisson_firing_synapse(nml_doc=nml_doc, - id=input_group_tag + "_TransPoiSyn%d" % input_index, - average_rate="%f %s" % (input_group_params['AverageRateList'][input_index], input_group_params['RateUnits']), - delay="%f %s" % (input_group_params['DelayList'][input_index], input_group_params['TimeUnits']), - duration="%f %s" % (input_group_params['DurationList'][input_index], input_group_params['TimeUnits']), - synapse_id=input_group_params['Synapse']) - - input_synapse_list.append(input_group_params['Synapse']) + if input_group_params["TrainType"] == "transient": + for input_index in range( + 0, len(input_group_params["AverageRateList"]) + ): + tpfs = ( + oc_build._add_transient_poisson_firing_synapse( + nml_doc=nml_doc, + id=input_group_tag + + "_TransPoiSyn%d" % input_index, + average_rate="%f %s" + % ( + input_group_params["AverageRateList"][ + input_index + ], + input_group_params["RateUnits"], + ), + delay="%f %s" + % ( + input_group_params["DelayList"][ + input_index + ], + input_group_params["TimeUnits"], + ), + duration="%f %s" + % ( + input_group_params["DurationList"][ + input_index + ], + input_group_params["TimeUnits"], + ), + synapse_id=input_group_params["Synapse"], + ) + ) + + input_synapse_list.append( + input_group_params["Synapse"] + ) list_of_input_ids.append(tpfs.id) - if input_group_params['TrainType'] == 'persistent': - - for input_index in range(0, len(input_group_params['AverageRateList'])): - - pfs = oc_build._add_poisson_firing_synapse(nml_doc=nml_doc, - id=input_group_tag + "_PoiSyn%d" % input_index, - average_rate="%f %s" % (input_group_params['AverageRateList'][input_index], input_group_params['RateUnits']), - synapse_id=input_group_params['Synapse']) - - input_synapse_list.append(input_group_params['Synapse']) + if input_group_params["TrainType"] == "persistent": + for input_index in range( + 0, len(input_group_params["AverageRateList"]) + ): + pfs = oc_build._add_poisson_firing_synapse( + nml_doc=nml_doc, + id=input_group_tag + "_PoiSyn%d" % input_index, + average_rate="%f %s" + % ( + input_group_params["AverageRateList"][ + input_index + ], + input_group_params["RateUnits"], + ), + synapse_id=input_group_params["Synapse"], + ) + + input_synapse_list.append( + input_group_params["Synapse"] + ) list_of_input_ids.append(pfs.id) input_ids_final.append(list_of_input_ids) - if input_group_params['InputType'] == 'PulseGenerators': - - if not input_group_params['Noise']: - + if input_group_params["InputType"] == "PulseGenerators": + if not input_group_params["Noise"]: list_of_input_ids = [] - for input_index in range(0, len(input_group_params['AmplitudeList'])): - - pg = oc_build._add_pulse_generator(nml_doc=nml_doc, - id=input_group_tag + "_Pulse%d" % input_index, - delay="%f %s" % (input_group_params['DelayList'][input_index], input_group_params['TimeUnits']), - duration="%f %s" % (input_group_params['DurationList'][input_index], input_group_params['TimeUnits']), - amplitude="%f %s" % (input_group_params['AmplitudeList'][input_index], input_group_params['AmplitudeUnits'])) + for input_index in range( + 0, len(input_group_params["AmplitudeList"]) + ): + pg = oc_build._add_pulse_generator( + nml_doc=nml_doc, + id=input_group_tag + "_Pulse%d" % input_index, + delay="%f %s" + % ( + input_group_params["DelayList"][ + input_index + ], + input_group_params["TimeUnits"], + ), + duration="%f %s" + % ( + input_group_params["DurationList"][ + input_index + ], + input_group_params["TimeUnits"], + ), + amplitude="%f %s" + % ( + input_group_params["AmplitudeList"][ + input_index + ], + input_group_params["AmplitudeUnits"], + ), + ) list_of_input_ids.append(pg.id) input_ids_final.append(list_of_input_ids) else: - for cell_id in target_cell_ids: - - assert len(input_group_params['SmallestAmplitudeList'])==1 - - for input_index in range(0, len(input_group_params['SmallestAmplitudeList'])): + assert ( + len(input_group_params["SmallestAmplitudeList"]) + == 1 + ) + + for input_index in range( + 0, + len( + input_group_params["SmallestAmplitudeList"] + ), + ): + random_amplitude = random.uniform( + input_group_params["SmallestAmplitudeList"][ + input_index + ], + input_group_params["LargestAmplitudeList"][ + input_index + ], + ) - random_amplitude = random.uniform(input_group_params['SmallestAmplitudeList'][input_index], input_group_params['LargestAmplitudeList'][input_index]) - weight_dict[cell_id] = random_amplitude - + list_of_input_ids = [] - pg = oc_build._add_pulse_generator(nml_doc=nml_doc, - id=input_group_tag + "_Pulse", - delay="%s %s" % (input_group_params['DelayList'][0], input_group_params['TimeUnits']), - duration="%s %s" % (input_group_params['DurationList'][0], input_group_params['TimeUnits']), - amplitude="%s %s" % (1, input_group_params['AmplitudeUnits'])) + pg = oc_build._add_pulse_generator( + nml_doc=nml_doc, + id=input_group_tag + "_Pulse", + delay="%s %s" + % ( + input_group_params["DelayList"][0], + input_group_params["TimeUnits"], + ), + duration="%s %s" + % ( + input_group_params["DurationList"][0], + input_group_params["TimeUnits"], + ), + amplitude="%s %s" + % (1, input_group_params["AmplitudeUnits"]), + ) list_of_input_ids.append(pg.id) input_ids_final.append(list_of_input_ids) - if input_group_params['InputType'] == 'GenerateSpikeSourcePoisson': - - list_of_input_ids = [] - - weight_list = [] - - for input_index in range(0, len(input_group_params['AverageRateList'])): - - ssp = oc_build._add_spike_source_poisson(nml_doc=nml_doc, - id=input_group_tag + "_SpSourcePoi%d" % input_index, - start="%f %s" % (input_group_params['DelayList'][input_index], input_group_params['TimeUnits']), - duration="%f %s" % (input_group_params['DurationList'][input_index], input_group_params['TimeUnits']), - rate="%f %s" % (input_group_params['AverageRateList'][input_index], input_group_params['RateUnits'])) + if ( + input_group_params["InputType"] + == "GenerateSpikeSourcePoisson" + ): + list_of_input_ids = [] - input_synapse_list.append(input_group_params['Synapse']) + weight_list = [] + + for input_index in range( + 0, len(input_group_params["AverageRateList"]) + ): + ssp = oc_build._add_spike_source_poisson( + nml_doc=nml_doc, + id=input_group_tag + "_SpSourcePoi%d" % input_index, + start="%f %s" + % ( + input_group_params["DelayList"][input_index], + input_group_params["TimeUnits"], + ), + duration="%f %s" + % ( + input_group_params["DurationList"][input_index], + input_group_params["TimeUnits"], + ), + rate="%f %s" + % ( + input_group_params["AverageRateList"][ + input_index + ], + input_group_params["RateUnits"], + ), + ) + + input_synapse_list.append(input_group_params["Synapse"]) list_of_input_ids.append(ssp.id) - weight_list.append(input_group_params['WeightList'][input_index]) + weight_list.append( + input_group_params["WeightList"][input_index] + ) input_ids_final.append(list_of_input_ids) weight_list_final.append(weight_list) - if input_group_params['InputType'] == 'GeneratePoissonTrains' or input_group_params['InputType'] == 'PulseGenerators': - - input_list_array = oc_build.add_advanced_inputs_to_population(net=net, - id=input_group_tag, - population=pop, - input_id_list=input_ids_final, - seg_length_dict=segLengthDict, - subset_dict=subset_dict, - universal_target_segment=target_segment, - universal_fraction_along=fraction_along, - only_cells=target_cell_ids, - weight_dict=weight_dict) - - if input_group_params['InputType'] == 'GenerateSpikeSourcePoisson': - - input_list_array = oc_build.add_projection_based_inputs(net=net, - id=input_group_tag, - population=pop, - input_id_list=input_ids_final, - weight_list=weight_list_final, - synapse_id=input_group_params['Synapse'], - seg_length_dict=segLengthDict, - subset_dict=subset_dict, - universal_target_segment=target_segment, - universal_fraction_along=fraction_along, - only_cells=target_cell_ids) - + if ( + input_group_params["InputType"] == "GeneratePoissonTrains" + or input_group_params["InputType"] == "PulseGenerators" + ): + input_list_array = ( + oc_build.add_advanced_inputs_to_population( + net=net, + id=input_group_tag, + population=pop, + input_id_list=input_ids_final, + seg_length_dict=segLengthDict, + subset_dict=subset_dict, + universal_target_segment=target_segment, + universal_fraction_along=fraction_along, + only_cells=target_cell_ids, + weight_dict=weight_dict, + ) + ) + + if ( + input_group_params["InputType"] + == "GenerateSpikeSourcePoisson" + ): + input_list_array = oc_build.add_projection_based_inputs( + net=net, + id=input_group_tag, + population=pop, + input_id_list=input_ids_final, + weight_list=weight_list_final, + synapse_id=input_group_params["Synapse"], + seg_length_dict=segLengthDict, + subset_dict=subset_dict, + universal_target_segment=target_segment, + universal_fraction_along=fraction_along, + only_cells=target_cell_ids, + ) input_list_array_final.append(input_list_array) - input_synapse_list = list(set(input_synapse_list)) + input_synapse_list = list(set(input_synapse_list)) - return input_list_array_final, input_synapse_list + return input_list_array_final, input_synapse_list ############################################################################################## -def replace_cell_types(net_file_name, - path_to_net, - new_net_id, - cell_types_to_be_replaced, - cell_types_replaced_by, - dir_to_new_components, - dir_to_old_components, - reduced_to_single_compartment=True, - validate_nml2=True, - return_synapses=False, - connection_segment_groups=None, - input_segment_groups=None, - synapse_file_tags=None): - - '''This method substitutes the target cell types to a given NeuroML2 cortical network. ''' - if len(cell_types_to_be_replaced) == len(cell_types_replaced_by): +def replace_cell_types( + net_file_name, + path_to_net, + new_net_id, + cell_types_to_be_replaced, + cell_types_replaced_by, + dir_to_new_components, + dir_to_old_components, + reduced_to_single_compartment=True, + validate_nml2=True, + return_synapses=False, + connection_segment_groups=None, + input_segment_groups=None, + synapse_file_tags=None, +): + """This method substitutes the target cell types to a given NeuroML2 cortical network.""" - nml2_file_path = os.path.join(path_to_net, net_file_name + ".net.nml") + if len(cell_types_to_be_replaced) == len(cell_types_replaced_by): + nml2_file_path = os.path.join(path_to_net, net_file_name + ".net.nml") net_doc = pynml.read_neuroml2_file(nml2_file_path) @@ -1657,21 +1890,16 @@ def replace_cell_types(net_file_name, list_of_synapses = [] if synapse_file_tags != None: - for include_index in range(0, len(net_doc.includes)): - found_synapse = False for synapse_tag in synapse_file_tags: - if synapse_tag in net_doc.includes[include_index].href: - found_synapse = True break if found_synapse: - include_synapses.append(net_doc.includes[include_index]) list_of_synapses.append(net_doc.includes[include_index].href) @@ -1679,11 +1907,11 @@ def replace_cell_types(net_file_name, net_doc.includes = [] for syn_index in range(0, len(include_synapses)): + net_doc.includes.append(include_synapses[syn_index]) - net_doc.includes.append(include_synapses[syn_index]) - - if (not reduced_to_single_compartment) and (connection_segment_groups != None or input_segment_groups != None): - + if (not reduced_to_single_compartment) and ( + connection_segment_groups != None or input_segment_groups != None + ): cached_target_dict = {} net = net_doc.networks[0] @@ -1695,30 +1923,29 @@ def replace_cell_types(net_file_name, all_old_components = [] for pop_counter in range(0, len(net.populations)): - pop = net.populations[pop_counter] all_old_components.append(pop.component) for cell_index in range(0, len(cell_types_replaced_by)): - if pop.component == cell_types_to_be_replaced[cell_index]: - conversion_dict = {} - conversion_dict['OldPopID'] = pop.id + conversion_dict["OldPopID"] = pop.id - conversion_dict['OldCellComponent'] = pop.component + conversion_dict["OldCellComponent"] = pop.component pop.component = cell_types_replaced_by[cell_index] if cell_types_to_be_replaced[cell_index] in pop.id: + pop.id = pop.id.replace( + cell_types_to_be_replaced[cell_index], + cell_types_replaced_by[cell_index], + ) - pop.id = pop.id.replace(cell_types_to_be_replaced[cell_index], cell_types_replaced_by[cell_index]) + conversion_dict["NewPopID"] = pop.id - conversion_dict['NewPopID'] = pop.id - - conversion_dict['NewCellComponent'] = pop.component + conversion_dict["NewCellComponent"] = pop.component old_to_new.append(conversion_dict) @@ -1726,36 +1953,32 @@ def replace_cell_types(net_file_name, all_projections_final = [] - if hasattr(net, 'projections'): - + if hasattr(net, "projections"): chemical_projections = {} - chemical_projections['Type'] = 'Chem' + chemical_projections["Type"] = "Chem" - chemical_projections['Projs'] = net.projections + chemical_projections["Projs"] = net.projections all_projections_final.append(chemical_projections) - if hasattr(net, 'electrical_projections'): - + if hasattr(net, "electrical_projections"): electrical_projections = {} - electrical_projections['Type'] = 'Elect' + electrical_projections["Type"] = "Elect" - electrical_projections['Projs'] = net.electrical_projections + electrical_projections["Projs"] = net.electrical_projections all_projections_final.append(electrical_projections) for proj_group_index in range(0, len(all_projections_final)): - proj_dict = all_projections_final[proj_group_index] - projections = proj_dict['Projs'] + projections = proj_dict["Projs"] - proj_type = proj_dict['Type'] + proj_type = proj_dict["Type"] for proj_counter in range(0, len(projections)): - proj = projections[proj_counter] replaced_pre_pop = False @@ -1763,32 +1986,33 @@ def replace_cell_types(net_file_name, replaced_post_pop = False for conversion_index in range(0, len(old_to_new)): - conversion_params = old_to_new[conversion_index] - if proj.presynaptic_population == conversion_params['OldPopID']: - + if proj.presynaptic_population == conversion_params["OldPopID"]: replaced_pre_pop = True pre_pop_index = conversion_index if proj.presynaptic_population in proj.id: + proj.id = proj.id.replace( + proj.presynaptic_population, + conversion_params["NewPopID"], + ) - proj.id = proj.id.replace(proj.presynaptic_population, conversion_params['NewPopID']) - - proj.presynaptic_population = conversion_params['NewPopID'] - - if proj.postsynaptic_population == conversion_params['OldPopID']: + proj.presynaptic_population = conversion_params["NewPopID"] + if proj.postsynaptic_population == conversion_params["OldPopID"]: replaced_post_pop = True post_pop_index = conversion_index if proj.postsynaptic_population in proj.id: + proj.id = proj.id.replace( + proj.postsynaptic_population, + conversion_params["NewPopID"], + ) - proj.id = proj.id.replace(proj.postsynaptic_population, conversion_params['NewPopID']) - - proj.postsynaptic_population = conversion_params['NewPopID'] + proj.postsynaptic_population = conversion_params["NewPopID"] pre_seg_length_dict = None @@ -1798,295 +2022,354 @@ def replace_cell_types(net_file_name, post_subset_dict = None - if (not reduced_to_single_compartment) and connection_segment_groups != None: - + if ( + not reduced_to_single_compartment + ) and connection_segment_groups != None: if replaced_pre_pop and replaced_post_pop: - for index in range(0, len(connection_segment_groups)): - proj_info = connection_segment_groups[index] - check_pre_cell_type = old_to_new[pre_pop_index]['NewCellComponent'] == proj_info['PreCellType'] - - check_post_cell_type = old_to_new[post_pop_index]['NewCellComponent'] == proj_info['PostCellType'] - - check_proj_type = proj_info['Type'] == proj_type - - if check_pre_cell_type and check_post_cell_type and check_proj_type: - - pre_seg_length_dict, cached_target_dict = check_cached_dicts(old_to_new[pre_pop_index]['NewCellComponent'], - cached_target_dict, - [proj_info['PreSegGroup']], - path_to_nml2=dir_to_new_components) + check_pre_cell_type = ( + old_to_new[pre_pop_index]["NewCellComponent"] + == proj_info["PreCellType"] + ) + + check_post_cell_type = ( + old_to_new[post_pop_index]["NewCellComponent"] + == proj_info["PostCellType"] + ) + + check_proj_type = proj_info["Type"] == proj_type + + if ( + check_pre_cell_type + and check_post_cell_type + and check_proj_type + ): + pre_seg_length_dict, cached_target_dict = ( + check_cached_dicts( + old_to_new[pre_pop_index]["NewCellComponent"], + cached_target_dict, + [proj_info["PreSegGroup"]], + path_to_nml2=dir_to_new_components, + ) + ) pre_subset_dict = {} - pre_subset_dict[proj_info['PreSegGroup']] = 1 + pre_subset_dict[proj_info["PreSegGroup"]] = 1 - post_seg_length_dict, cached_target_dict = check_cached_dicts(old_to_new[post_pop_index]['NewCellComponent'], - cached_target_dict, - [proj_info['PostSegGroup']], - path_to_nml2=dir_to_new_components) + post_seg_length_dict, cached_target_dict = ( + check_cached_dicts( + old_to_new[post_pop_index]["NewCellComponent"], + cached_target_dict, + [proj_info["PostSegGroup"]], + path_to_nml2=dir_to_new_components, + ) + ) post_subset_dict = {} - post_subset_dict[proj_info['PostSegGroup']] = 1 + post_subset_dict[proj_info["PostSegGroup"]] = 1 break - - if hasattr(proj, 'connection_wds'): - + if hasattr(proj, "connection_wds"): if proj.connection_wds != []: - connections = proj.connection_wds id_tag = True - elif hasattr(proj, 'connections'): - + elif hasattr(proj, "connections"): if proj.connections != []: - connections = proj.connections id_tag = True - elif hasattr(proj, 'electrical_connection_instance_ws'): - + elif hasattr(proj, "electrical_connection_instance_ws"): if proj.electrical_connection_instance_ws != []: - connections = proj.electrical_connection_instance_ws id_tag = False else: - if proj.electrical_connections != []: - connections = proj.electrical_connections id_tag = False for conn_counter in range(0, len(connections)): - connection = connections[conn_counter] if replaced_post_pop: - if id_tag: + if ( + old_to_new[post_pop_index]["OldCellComponent"] + in connection.post_cell_id + ): + connection.post_cell_id = ( + connection.post_cell_id.replace( + old_to_new[post_pop_index]["OldCellComponent"], + old_to_new[post_pop_index]["NewCellComponent"], + ) + ) + + if ( + old_to_new[post_pop_index]["OldPopID"] + in connection.post_cell_id + ): + connection.post_cell_id = ( + connection.post_cell_id.replace( + old_to_new[post_pop_index]["OldPopID"], + old_to_new[post_pop_index]["NewPopID"], + ) + ) - if old_to_new[post_pop_index]['OldCellComponent'] in connection.post_cell_id: + else: + if ( + old_to_new[post_pop_index]["OldCellComponent"] + in connection.post_cell + ): + connection.post_cell = connection.post_cell.replace( + old_to_new[post_pop_index]["OldCellComponent"], + old_to_new[post_pop_index]["NewCellComponent"], + ) + + if ( + old_to_new[post_pop_index]["OldPopID"] + in connection.post_cell + ): + connection.post_cell = connection.post_cell.replace( + old_to_new[post_pop_index]["OldPopID"], + old_to_new[post_pop_index]["NewPopID"], + ) - connection.post_cell_id = connection.post_cell_id.replace(old_to_new[post_pop_index]['OldCellComponent'], old_to_new[post_pop_index]['NewCellComponent']) - - if old_to_new[post_pop_index]['OldPopID'] in connection.post_cell_id: - - connection.post_cell_id = connection.post_cell_id.replace(old_to_new[post_pop_index]['OldPopID'], old_to_new[post_pop_index]['NewPopID']) - - else: - - if old_to_new[post_pop_index]['OldCellComponent'] in connection.post_cell: - - connection.post_cell = connection.post_cell.replace(old_to_new[post_pop_index]['OldCellComponent'], old_to_new[post_pop_index]['NewCellComponent']) - - if old_to_new[post_pop_index]['OldPopID'] in connection.post_cell: - - connection.post_cell = connection.post_cell.replace(old_to_new[post_pop_index]['OldPopID'], old_to_new[post_pop_index]['NewPopID']) - - if post_seg_length_dict != None and post_subset_dict != None: - - post_target_seg_array, post_target_fractions = oc_build.get_target_segments(post_seg_length_dict, post_subset_dict) + if post_seg_length_dict != None and post_subset_dict != None: + post_target_seg_array, post_target_fractions = ( + oc_build.get_target_segments( + post_seg_length_dict, post_subset_dict + ) + ) if id_tag: - connection.post_segment_id = post_target_seg_array[0] else: - connection.post_segment = post_target_seg_array[0] connection.post_fraction_along = post_target_fractions[0] else: - if reduced_to_single_compartment: - if id_tag: - connection.post_segment_id = 0 else: - connection.post_segment = 0 connection.post_fraction_along = 0.5 if replaced_pre_pop: - if id_tag: - - if old_to_new[pre_pop_index]['OldCellComponent'] in connection.pre_cell_id: - - connection.pre_cell_id = connection.pre_cell_id.replace(old_to_new[pre_pop_index]['OldCellComponent'], old_to_new[pre_pop_index]['NewCellComponent']) - - if old_to_new[pre_pop_index]['OldPopID'] in connection.pre_cell_id: - - connection.pre_cell_id = connection.pre_cell_id.replace(old_to_new[pre_pop_index]['OldPopID'], old_to_new[pre_pop_index]['NewPopID']) + if ( + old_to_new[pre_pop_index]["OldCellComponent"] + in connection.pre_cell_id + ): + connection.pre_cell_id = connection.pre_cell_id.replace( + old_to_new[pre_pop_index]["OldCellComponent"], + old_to_new[pre_pop_index]["NewCellComponent"], + ) + + if ( + old_to_new[pre_pop_index]["OldPopID"] + in connection.pre_cell_id + ): + connection.pre_cell_id = connection.pre_cell_id.replace( + old_to_new[pre_pop_index]["OldPopID"], + old_to_new[pre_pop_index]["NewPopID"], + ) else: - - if old_to_new[pre_pop_index]['OldCellComponent'] in connection.pre_cell: - - connection.pre_cell = connection.pre_cell.replace(old_to_new[pre_pop_index]['OldCellComponent'], old_to_new[pre_pop_index]['NewCellComponent']) - - if old_to_new[pre_pop_index]['OldPopID'] in connection.pre_cell: - - connection.pre_cell = connection.pre_cell.replace(old_to_new[pre_pop_index]['OldPopID'], old_to_new[pre_pop_index]['NewPopID']) + if ( + old_to_new[pre_pop_index]["OldCellComponent"] + in connection.pre_cell + ): + connection.pre_cell = connection.pre_cell.replace( + old_to_new[pre_pop_index]["OldCellComponent"], + old_to_new[pre_pop_index]["NewCellComponent"], + ) + + if ( + old_to_new[pre_pop_index]["OldPopID"] + in connection.pre_cell + ): + connection.pre_cell = connection.pre_cell.replace( + old_to_new[pre_pop_index]["OldPopID"], + old_to_new[pre_pop_index]["NewPopID"], + ) if pre_seg_length_dict != None and pre_subset_dict != None: - - pre_target_seg_array, pre_target_fractions = oc_build.get_target_segments(pre_seg_length_dict, pre_subset_dict) + pre_target_seg_array, pre_target_fractions = ( + oc_build.get_target_segments( + pre_seg_length_dict, pre_subset_dict + ) + ) if id_tag: - connection.pre_segment_id = pre_target_seg_array[0] else: - connection.pre_segment = pre_target_seg_array[0] connection.pre_fraction_along = pre_target_fractions[0] else: - if reduced_to_single_compartment: - if id_tag: - connection.pre_segment_id = 0 else: - connection.pre_segment = 0 connection.pre_fraction_along = 0.5 for input_list_index in range(0, len(net.input_lists)): - input_list_obj = net.input_lists[input_list_index] for conversion_index in range(0, len(old_to_new)): - conversion_params = old_to_new[conversion_index] - if conversion_params['OldPopID'] == input_list_obj.populations: - - input_list_obj.populations = conversion_params['NewPopID'] + if conversion_params["OldPopID"] == input_list_obj.populations: + input_list_obj.populations = conversion_params["NewPopID"] require_segment_groups = False - if (not reduced_to_single_compartment) and input_segment_groups != None: - + if ( + not reduced_to_single_compartment + ) and input_segment_groups != None: for index in range(0, len(input_segment_groups)): - input_group_info = input_segment_groups[index] - check_post_cell_type = conversion_params['NewCellComponent'] == input_group_info['PostCellType'] + check_post_cell_type = ( + conversion_params["NewCellComponent"] + == input_group_info["PostCellType"] + ) if check_post_cell_type: - - target_segment_dict, cached_target_dict = check_cached_dicts(conversion_params['NewCellComponent'], - cached_target_dict, - [input_group_info['PostSegGroup']], - path_to_nml2=dir_to_new_components) + target_segment_dict, cached_target_dict = ( + check_cached_dicts( + conversion_params["NewCellComponent"], + cached_target_dict, + [input_group_info["PostSegGroup"]], + path_to_nml2=dir_to_new_components, + ) + ) target_subset_dict = {} - target_subset_dict[input_group_info['PostSegGroup']] = 1 + target_subset_dict[input_group_info["PostSegGroup"]] = 1 require_segment_groups = True break for input_index in range(0, len(input_list_obj.input)): - input_obj = input_list_obj.input[input_index] - if conversion_params['OldPopID'] in input_obj.target: - - input_obj.target = input_obj.target.replace(conversion_params['OldPopID'], conversion_params['NewPopID']) - - if conversion_params['OldCellComponent'] in input_obj.target: + if conversion_params["OldPopID"] in input_obj.target: + input_obj.target = input_obj.target.replace( + conversion_params["OldPopID"], + conversion_params["NewPopID"], + ) - input_obj.target = input_obj.target.replace(conversion_params['OldCellComponent'], conversion_params['NewCellComponent']) + if conversion_params["OldCellComponent"] in input_obj.target: + input_obj.target = input_obj.target.replace( + conversion_params["OldCellComponent"], + conversion_params["NewCellComponent"], + ) if require_segment_groups: - if input_obj.segment_id != 0: - - target_seg_array, target_fractions = oc_build.get_target_segments(target_segment_dict, target_subset_dict) + target_seg_array, target_fractions = ( + oc_build.get_target_segments( + target_segment_dict, target_subset_dict + ) + ) input_obj.segment_id = target_seg_array[0] input_obj.fraction_along = target_fractions[0] else: - input_obj.segment_id = 0 input_obj.fraction_along = 0.5 - - break + break replaced_components_final = [] for changed_cell in range(0, len(old_to_new)): + cell_model = old_to_new[changed_cell]["NewCellComponent"] - cell_model = old_to_new[changed_cell]['NewCellComponent'] - - replaced_components_final.append(old_to_new[changed_cell]['OldCellComponent']) + replaced_components_final.append( + old_to_new[changed_cell]["OldCellComponent"] + ) - oc_build.add_cell_and_channels(net_doc, os.path.join(dir_to_new_components, "%s.cell.nml" % cell_model), cell_model, use_prototypes=False) + oc_build.add_cell_and_channels( + net_doc, + os.path.join(dir_to_new_components, "%s.cell.nml" % cell_model), + cell_model, + use_prototypes=False, + ) for cell_model in all_old_components: - if cell_model not in replaced_components_final: - - oc_build.add_cell_and_channels(net_doc, os.path.join(dir_to_old_components, "%s.cell.nml" % cell_model), cell_model, use_prototypes=False) + oc_build.add_cell_and_channels( + net_doc, + os.path.join(dir_to_old_components, "%s.cell.nml" % cell_model), + cell_model, + use_prototypes=False, + ) nml_file_name = "%s.net.nml" % new_net_id oc_build.save_network(net_doc, nml_file_name, validate=validate_nml2) if return_synapses: - return list_of_synapses else: - - opencortex.print_comment_v("Error: the number of cell types in the list cell_types_to_be_replaced is not equal to the number of new cell types in the list" - " cell_types_replaced_by.") + opencortex.print_comment_v( + "Error: the number of cell types in the list cell_types_to_be_replaced is not equal to the number of new cell types in the list" + " cell_types_replaced_by." + ) quit() ############################################################################################## -def parse_distance_dependence_params(distance_dependence_params, pre_pop, post_pop, proj_type): +def parse_distance_dependence_params( + distance_dependence_params, pre_pop, post_pop, proj_type +): dist_rule = None for distance_param in range(0, len(distance_dependence_params)): + check_pre_pop = ( + distance_dependence_params[distance_param]["PrePopID"] == pre_pop + ) - check_pre_pop = distance_dependence_params[distance_param]['PrePopID'] == pre_pop - - check_post_pop = distance_dependence_params[distance_param]['PostPopID'] == post_pop + check_post_pop = ( + distance_dependence_params[distance_param]["PostPopID"] == post_pop + ) - check_proj_type = distance_dependence_params[distance_param]['Type'] == proj_type + check_proj_type = ( + distance_dependence_params[distance_param]["Type"] == proj_type + ) if check_pre_pop and check_post_pop and check_proj_type: - - dist_rule = distance_dependence_params['DistDependConn'] + dist_rule = distance_dependence_params["DistDependConn"] break @@ -2095,65 +2378,55 @@ def parse_distance_dependence_params(distance_dependence_params, pre_pop, post_p ############################################################################################## -def parse_delays(delays_params, post_pop, synapse_list): +def parse_delays(delays_params, post_pop, synapse_list): delays = {} for syn_ind in range(0, len(synapse_list)): - for delay_param in range(0, len(delays_params)): - - if delays_params[delay_param]['synComp'] == 'all': - - delays[synapse_list[syn_ind]] = float(delays_params[delay_param]['delay']) + if delays_params[delay_param]["synComp"] == "all": + delays[synapse_list[syn_ind]] = float( + delays_params[delay_param]["delay"] + ) else: - passed_synComp = False - if delays_params[delay_param]['synComp'] in synapse_list[syn_ind]: - + if delays_params[delay_param]["synComp"] in synapse_list[syn_ind]: passed_synComp = True passed_synEndsWith = False - if delays_params[delay_param]['synEndsWith'] == []: - + if delays_params[delay_param]["synEndsWith"] == []: passed_synEndsWith = True else: - - for syn_end in delays_params[delay_param]['synEndsWith']: - + for syn_end in delays_params[delay_param]["synEndsWith"]: if synapse_list[syn_ind].endswith(syn_end): - passed_synEndsWith = True break passed_targetCellGroup = False - if delays_params[delay_param]['targetCellGroup'] == []: - + if delays_params[delay_param]["targetCellGroup"] == []: passed_targetCellGroup = True else: - - for target_cell_group in delays_params[delay_param]['targetCellGroup']: - + for target_cell_group in delays_params[delay_param][ + "targetCellGroup" + ]: if target_cell_group in post_pop: - passed_targetCellGroup = True break if passed_synComp and passed_synEndsWith and passed_targetCellGroup: - - delays[synapse_list[syn_ind]] = float(delays_params[delay_param]['delay']) - + delays[synapse_list[syn_ind]] = float( + delays_params[delay_param]["delay"] + ) if delays.keys() == []: - delays = None return delays @@ -2161,65 +2434,55 @@ def parse_delays(delays_params, post_pop, synapse_list): ############################################################################################## -def parse_weights(weights_params, post_pop, synapse_list): +def parse_weights(weights_params, post_pop, synapse_list): weights = {} for syn_ind in range(0, len(synapse_list)): - for weight_param in range(0, len(weights_params)): - - if weights_params[weight_param]['synComp'] == 'all': - - weights[synapse_list[syn_ind]] = float(weights_params[weight_param]['weight']) + if weights_params[weight_param]["synComp"] == "all": + weights[synapse_list[syn_ind]] = float( + weights_params[weight_param]["weight"] + ) else: - passed_synComp = False - if weights_params[weight_param]['synComp'] in synapse_list[syn_ind]: - + if weights_params[weight_param]["synComp"] in synapse_list[syn_ind]: passed_synComp = True passed_synEndsWith = False - if weights_params[weight_param]['synEndsWith'] == []: - + if weights_params[weight_param]["synEndsWith"] == []: passed_synEndsWith = True else: - - for syn_end in weights_params[weight_param]['synEndsWith']: - + for syn_end in weights_params[weight_param]["synEndsWith"]: if synapse_list[syn_ind].endswith(syn_end): - passed_synEndsWith = True break passed_targetCellGroup = False - if weights_params[weight_param]['targetCellGroup'] == []: - + if weights_params[weight_param]["targetCellGroup"] == []: passed_targetCellGroup = True else: - - for target_cell_group in weights_params[weight_param]['targetCellGroup']: - + for target_cell_group in weights_params[weight_param][ + "targetCellGroup" + ]: if target_cell_group in post_pop: - passed_targetCellGroup = True break if passed_synComp and passed_synEndsWith and passed_targetCellGroup: - - weights[synapse_list[syn_ind]] = float(weights_params[weight_param]['weight']) - + weights[synapse_list[syn_ind]] = float( + weights_params[weight_param]["weight"] + ) if weights.keys() == []: - weights = None return weights @@ -2227,16 +2490,13 @@ def parse_weights(weights_params, post_pop, synapse_list): ############################################################################################## -def check_includes_in_cells(dir_to_cells, - list_of_cell_ids, - extra_channel_tags=None): +def check_includes_in_cells(dir_to_cells, list_of_cell_ids, extra_channel_tags=None): passed = True list_of_cell_file_names = [] for cell_id in list_of_cell_ids: - list_of_cell_file_names.append(cell_id + ".cell.nml") all_src_files = os.listdir(dir_to_cells) @@ -2244,33 +2504,32 @@ def check_includes_in_cells(dir_to_cells, target_files = list_of_cell_file_names for src_file in all_src_files: - if src_file not in target_files: - target_files.append(src_file) for cell_file_name in target_files: - full_path_to_cell = os.path.join(dir_to_cells, cell_file_name) if not os.path.exists(full_path_to_cell): - passed = False - opencortex.print_comment_v("Error: path %s does not exist; use method copy_nml2_source to copy nml2 files from the source directory to the appropriate NeuroML2 component directories." % full_path_to_cell) + opencortex.print_comment_v( + "Error: path %s does not exist; use method copy_nml2_source to copy nml2 files from the source directory to the appropriate NeuroML2 component directories." + % full_path_to_cell + ) break else: - - nml2_doc_cell = pynml.read_neuroml2_file(full_path_to_cell, include_includes=False) + nml2_doc_cell = pynml.read_neuroml2_file( + full_path_to_cell, include_includes=False + ) for included in nml2_doc_cell.includes: - - if '.channel.nml' in included.href: - - if ('../channels/' not in included.href) or ('..\channels\'' not in included.href): - + if ".channel.nml" in included.href: + if ("../channels/" not in included.href) or ( + "..\channels'" not in included.href + ): channel_dir = os.path.join("..", "channels") included.href = os.path.join(channel_dir, included.href) @@ -2278,129 +2537,142 @@ def check_includes_in_cells(dir_to_cells, continue else: - if extra_channel_tags != None: - for channel_tag in included.href: - if channel_tag in included.href: - - if ('../channels/' not in included.href) or ('..\channels\'' not in included.href): - + if ("../channels/" not in included.href) or ( + "..\channels'" not in included.href + ): channel_dir = os.path.join("..", "channels") - included.href = os.path.join(channel_dir, included.href) + included.href = os.path.join( + channel_dir, included.href + ) break - pynml.write_neuroml2_file(nml2_doc_cell, full_path_to_cell) + pynml.write_neuroml2_file(nml2_doc_cell, full_path_to_cell) return passed ############################################################################################## -def check_pop_dict_and_layers(pop_dict, boundary_dict): +def check_pop_dict_and_layers(pop_dict, boundary_dict): error_counter = 0 passed = False for cell_population in pop_dict.keys(): - if not isinstance(pop_dict[cell_population], tuple): - - print("TypeError in population parameters: the values stored in the population dictionary must be tuples.") + print( + "TypeError in population parameters: the values stored in the population dictionary must be tuples." + ) print("The current type is %s" % (type(pop_dict[cell_population]))) error_counter += 1 else: - if len(pop_dict[cell_population]) != 5: - - print("ValueError in population parameters: tuples in the population dictionary must contain four elements in the following order and type: " - "population size ('int'), layer ('str'), cell type ('str'), compartmentalization type ('single' or 'multi'), color ('str', e.g. '1 0 0' for red).") + print( + "ValueError in population parameters: tuples in the population dictionary must contain four elements in the following order and type: " + "population size ('int'), layer ('str'), cell type ('str'), compartmentalization type ('single' or 'multi'), color ('str', e.g. '1 0 0' for red)." + ) error_counter += 1 else: - if not isinstance(pop_dict[cell_population][0], int): - - print("TypeError in population parameters: the first element in tuples in the population dictionary must be of type 'int'") - print(" as it specifies the size of cell population. The current type of the first element is %s" % (type(pop_dict[cell_population][0]))) + print( + "TypeError in population parameters: the first element in tuples in the population dictionary must be of type 'int'" + ) + print( + " as it specifies the size of cell population. The current type of the first element is %s" + % (type(pop_dict[cell_population][0])) + ) error_counter += 1 if not isinstance(pop_dict[cell_population][1], str): - - print("TypeError in population parameters: the second element in tuples in the population dictionary must be of type 'string'") - print(" as it specifies the layer of cell population. The current type of the second element is %s" % (type(pop_dict[cell_population][1]))) + print( + "TypeError in population parameters: the second element in tuples in the population dictionary must be of type 'string'" + ) + print( + " as it specifies the layer of cell population. The current type of the second element is %s" + % (type(pop_dict[cell_population][1])) + ) error_counter += 1 else: - try: - test_layer = boundary_dict[pop_dict[cell_population][1]] except KeyError: - - print("KeyError in the layer boundary dictionary: cell population id '%s' is not in the keys of the layer boundary dictionary" % cell_population) + print( + "KeyError in the layer boundary dictionary: cell population id '%s' is not in the keys of the layer boundary dictionary" + % cell_population + ) error_counter += 1 if not isinstance(pop_dict[cell_population][2], str): - - print("TypeError in population parameters: the third element in tuples in the population dictionary must be of type 'string'") - print(" as it specifies the cell model for a given population. The current type of the third element is %s" % (type(pp_dict[cell_population][2]))) + print( + "TypeError in population parameters: the third element in tuples in the population dictionary must be of type 'string'" + ) + print( + " as it specifies the cell model for a given population. The current type of the third element is %s" + % (type(pp_dict[cell_population][2])) + ) error_counter += 1 if not isinstance(pop_dict[cell_population][3], str): - - print("TypeError in population parameters: the fourth element in tuples in the population dictionary must be of type 'string'") - print(" as it specifies the compartmentalization for a given cell type. The current type of the fourth element is %s" % (type(pp_dict[cell_population][2]))) + print( + "TypeError in population parameters: the fourth element in tuples in the population dictionary must be of type 'string'" + ) + print( + " as it specifies the compartmentalization for a given cell type. The current type of the fourth element is %s" + % (type(pp_dict[cell_population][2])) + ) error_counter += 1 else: - - if not (pop_dict[cell_population][3] == 'single' or pop_dict[cell_population][3] == 'multi'): - - print("ValueError in population parameters: the fourth element in tuples in the population dictionary must be equal to 'single' or 'multi'" - " as it specifies the compartmentalization for a given cell type. The current type of the fourth element is %s") + if not ( + pop_dict[cell_population][3] == "single" + or pop_dict[cell_population][3] == "multi" + ): + print( + "ValueError in population parameters: the fourth element in tuples in the population dictionary must be equal to 'single' or 'multi'" + " as it specifies the compartmentalization for a given cell type. The current type of the fourth element is %s" + ) error_counter += 1 if error_counter == 0: - - passed = True - + passed = True return passed ############################################################################################## -def check_synapse_location(synapse_id, pathToSynapses): +def check_synapse_location(synapse_id, pathToSynapses): found = False src_files = os.listdir(pathToSynapses) for file_name in src_files: if synapse_id in file_name: - found = True + found = True - return found + return found ############################################################################################## -def get_segment_groups(cell_id, path_to_cells): +def get_segment_groups(cell_id, path_to_cells): if path_to_cells != None: - - cell_nml_file = os.path.join(path_to_cells, '%s.cell.nml' % cell_id) + cell_nml_file = os.path.join(path_to_cells, "%s.cell.nml" % cell_id) else: - - cell_nml_file = '%s.cell.nml' % cell_id + cell_nml_file = "%s.cell.nml" % cell_id document_cell = neuroml.loaders.NeuroMLLoader.load(cell_nml_file) @@ -2409,7 +2681,6 @@ def get_segment_groups(cell_id, path_to_cells): segment_groups = [] for segment_group in cell_object.morphology.segment_groups: - segment_groups.append(segment_group.id) return segment_groups @@ -2417,6 +2688,7 @@ def get_segment_groups(cell_id, path_to_cells): ############################################################################################## + def check_segment_group(segment_groups, target_segment_group): segment_group_exist = False if target_segment_group in segment_groups: @@ -2426,1047 +2698,1192 @@ def check_segment_group(segment_groups, target_segment_group): ############################################################################################## -def check_weight_params(weight_params): +def check_weight_params(weight_params): error_counter = 0 if not isinstance(weight_params, list): - - print("TypeError in weight parameters: weight parameters must be of type 'list'. The current type is '%s'." % (type(weight_params))) + print( + "TypeError in weight parameters: weight parameters must be of type 'list'. The current type is '%s'." + % (type(weight_params)) + ) error_counter += 1 else: - for weight_param in range(0, len(weight_params)): - if not isinstance(weight_params[weight_param], dict): - - print("TypeError in weight parameters: list elements in weight parameters must be of type 'dict'. The current type is '%s'." % (type(weight_params[weight_param]))) + print( + "TypeError in weight parameters: list elements in weight parameters must be of type 'dict'. The current type is '%s'." + % (type(weight_params[weight_param])) + ) error_counter += 1 else: - try: - - test_weight_field = weight_params[weight_param]['weight'] + test_weight_field = weight_params[weight_param]["weight"] except KeyError: - - print("KeyError in weight parameters: the key 'weight' is not in the keys of weight parameter dictionary.") + print( + "KeyError in weight parameters: the key 'weight' is not in the keys of weight parameter dictionary." + ) error_counter += 1 try: - - test_syn_comp_field = weight_params[weight_param]['synComp'] + test_syn_comp_field = weight_params[weight_param]["synComp"] if not isinstance(test_syn_comp_field, str): - - print("TypeError in weight parameters: the value of the key 'synComp' must be of type 'str'. The current type is '%s'." % (type(test_syn_comp_field))) + print( + "TypeError in weight parameters: the value of the key 'synComp' must be of type 'str'. The current type is '%s'." + % (type(test_syn_comp_field)) + ) error_counter += 1 else: - - if test_syn_comp_field != 'all': - + if test_syn_comp_field != "all": try: - - test_syn_ends_with_field = weight_params[weight_param]['synEndsWith'] + test_syn_ends_with_field = weight_params[weight_param][ + "synEndsWith" + ] if not isinstance(test_syn_ends_with_field, list): - - print("TypeError in weight parameters: the value of the key 'synEndsWith' must be of type 'list'.") - print("The current type is '%s'." % (type(test_syn_ends_with_field))) + print( + "TypeError in weight parameters: the value of the key 'synEndsWith' must be of type 'list'." + ) + print( + "The current type is '%s'." + % (type(test_syn_ends_with_field)) + ) error_counter += 1 except KeyError: - - print("KeyError in weight parameters: the key 'synEndsWith' is not in the keys of weight parameter dictionary.") + print( + "KeyError in weight parameters: the key 'synEndsWith' is not in the keys of weight parameter dictionary." + ) error_counter += 1 try: - - test_target_cell_group = weight_params[weight_param]['targetCellGroup'] + test_target_cell_group = weight_params[weight_param][ + "targetCellGroup" + ] if not isinstance(test_target_cell_group, list): - - print("TypeError in weight parameters: the value of the key 'targetCellGroup' must be of type 'list'.") - print("The current type is '%s'." % (type(test_target_cell_group))) + print( + "TypeError in weight parameters: the value of the key 'targetCellGroup' must be of type 'list'." + ) + print( + "The current type is '%s'." + % (type(test_target_cell_group)) + ) error_counter += 1 except KeyError: - - print("KeyError in weight parameters: the key 'targetCellGroup' is not in the keys of weight parameter dictionary.") + print( + "KeyError in weight parameters: the key 'targetCellGroup' is not in the keys of weight parameter dictionary." + ) error_counter += 1 except KeyError: - - print("KeyError in weight parameters: the key 'synComp' is not in the keys of weight parameter dictionary.") + print( + "KeyError in weight parameters: the key 'synComp' is not in the keys of weight parameter dictionary." + ) error_counter += 1 if error_counter == 0: - return True else: - - return False + return False ############################################################################################## -def check_delay_params(delay_params): +def check_delay_params(delay_params): error_counter = 0 if not isinstance(delay_params, list): - - print("TypeError in delay parameters: delay parameters must be of type 'list'. The current type is '%s'." % (type(delay_params))) + print( + "TypeError in delay parameters: delay parameters must be of type 'list'. The current type is '%s'." + % (type(delay_params)) + ) error_counter += 1 else: - for delay_param in range(0, len(delay_params)): - if not isinstance(delay_params[delay_param], dict): - - print("TypeError in delay parameters: list elements in delay parameters must be of type 'dict'. The current type is '%s'." % (type(delay_params[delay_param]))) + print( + "TypeError in delay parameters: list elements in delay parameters must be of type 'dict'. The current type is '%s'." + % (type(delay_params[delay_param])) + ) error_counter += 1 else: - try: - - test_weight_field = delay_params[delay_param]['delay'] + test_weight_field = delay_params[delay_param]["delay"] except KeyError: - - print("KeyError in delay parameters: the key 'delay' is not in the keys of delay parameter dictionary.") + print( + "KeyError in delay parameters: the key 'delay' is not in the keys of delay parameter dictionary." + ) error_counter += 1 try: - - test_syn_comp_field = delay_params[delay_param]['synComp'] + test_syn_comp_field = delay_params[delay_param]["synComp"] if not isinstance(test_syn_comp_field, str): - - print("TypeError in delay parameters: the value of the key 'synComp' must be of type 'str'. The current type is '%s'." % (type(test_syn_comp_field))) + print( + "TypeError in delay parameters: the value of the key 'synComp' must be of type 'str'. The current type is '%s'." + % (type(test_syn_comp_field)) + ) error_counter += 1 else: - - if test_syn_comp_field != 'all': - + if test_syn_comp_field != "all": try: - - test_syn_ends_with_field = delay_params[delay_param]['synEndsWith'] + test_syn_ends_with_field = delay_params[delay_param][ + "synEndsWith" + ] if not isinstance(test_syn_ends_with_field, list): - - print("TypeError in delay parameters: the value of the key 'synEndsWith' must be of type 'list'.") - print("The current type is '%s'." % (type(test_syn_ends_with_field))) + print( + "TypeError in delay parameters: the value of the key 'synEndsWith' must be of type 'list'." + ) + print( + "The current type is '%s'." + % (type(test_syn_ends_with_field)) + ) error_counter += 1 except KeyError: - - print("KeyError in delay parameters: the key 'synEndsWith' is not in the keys of delay parameter dictionary.") + print( + "KeyError in delay parameters: the key 'synEndsWith' is not in the keys of delay parameter dictionary." + ) error_counter += 1 try: - - test_target_cell_group = delay_params[delay_param]['targetCellGroup'] + test_target_cell_group = delay_params[delay_param][ + "targetCellGroup" + ] if not isinstance(test_target_cell_group, list): - - print("TypeError in delay parameters: the value of the key 'targetCellGroup' must be of type 'list'.") - print("The current type is '%s'." % (type(test_target_cell_group))) + print( + "TypeError in delay parameters: the value of the key 'targetCellGroup' must be of type 'list'." + ) + print( + "The current type is '%s'." + % (type(test_target_cell_group)) + ) error_counter += 1 except KeyError: - - print("KeyError in delay parameters: the key 'targetCellGroup' is not in the keys of delay parameter dictionary.") + print( + "KeyError in delay parameters: the key 'targetCellGroup' is not in the keys of delay parameter dictionary." + ) error_counter += 1 except KeyError: - - print("KeyError in delay parameters: the key 'synComp' is not in the keys of delay parameter dictionary.") + print( + "KeyError in delay parameters: the key 'synComp' is not in the keys of delay parameter dictionary." + ) error_counter += 1 if error_counter == 0: - return True else: - - return False + return False ############################################################################################## -def check_inputs(input_params, popDict, path_to_cells, path_to_synapses=None): +def check_inputs(input_params, popDict, path_to_cells, path_to_synapses=None): error_counter = 0 for cell_receiver in input_params.keys(): - found_target_pop = False for pop_id in popDict.keys(): - if cell_receiver in pop_id: - test_cell_component = popDict[pop_id] - if test_cell_component['Compartments'] == 'single': - + if test_cell_component["Compartments"] == "single": cell_type = None - if test_cell_component['Compartments'] == 'multi': + if test_cell_component["Compartments"] == "multi": + segment_groups = get_segment_groups( + test_cell_component["PopObj"].component, path_to_cells + ) - segment_groups = get_segment_groups(test_cell_component['PopObj'].component, path_to_cells) - - cell_type = test_cell_component['PopObj'].component + cell_type = test_cell_component["PopObj"].component found_target_pop = True break if not found_target_pop: - - opencortex.print_comment_v("KeyError in input parameters: cell population id '%s' is not in the keys of population dictionary" % cell_receiver) + opencortex.print_comment_v( + "KeyError in input parameters: cell population id '%s' is not in the keys of population dictionary" + % cell_receiver + ) error_counter += 1 cell_type = None if not isinstance(input_params[cell_receiver], list): - - opencortex.print_comment_v("TypeError in input parameters: the dictionary value for '%s' must be a list." - " The current type is %s" % (cell_receiver, type(input_params[cell_receiver]))) + opencortex.print_comment_v( + "TypeError in input parameters: the dictionary value for '%s' must be a list." + " The current type is %s" + % (cell_receiver, type(input_params[cell_receiver])) + ) error_counter += 1 else: - for input_group_ind in range(0, len(input_params[cell_receiver])): - input_group_params = input_params[cell_receiver][input_group_ind] try: - - test_key = input_group_params['InputType'] + test_key = input_group_params["InputType"] if not isinstance(test_key, str): + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'InputType' must be of type 'string'. The current type is %s" + % type(test_key) + ) - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'InputType' must be of type 'string'. The current type is %s" % type(test_key)) - - error_counter += 1 - - if test_key not in ['GeneratePoissonTrains', 'PulseGenerators', 'GenerateSpikeSourcePoisson']: + error_counter += 1 - opencortex.print_comment_v("ValueError in input parameters: the value of the key 'InputType' must be one of the following: " - "'GeneratePoissonTrains','PulseGenerators', 'GenerateSpikeSourcePoisson'") + if test_key not in [ + "GeneratePoissonTrains", + "PulseGenerators", + "GenerateSpikeSourcePoisson", + ]: + opencortex.print_comment_v( + "ValueError in input parameters: the value of the key 'InputType' must be one of the following: " + "'GeneratePoissonTrains','PulseGenerators', 'GenerateSpikeSourcePoisson'" + ) error_counter += 1 else: - if test_key == "GeneratePoissonTrains": - try: - test_train_type = input_group_params['TrainType'] + test_train_type = input_group_params["TrainType"] if not isinstance(test_train_type, str): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'TrainType' must be of type 'string'. " - "The current type is %s" % type(test_train_type)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'TrainType' must be of type 'string'. " + "The current type is %s" % type(test_train_type) + ) error_counter += 1 else: - - if test_train_type not in ['persistent', 'transient']: - - opencortex.print_comment_v("ValueError in input parameters: the value of the key 'TrainType' when 'InputType' is 'GeneratePoissonTrains' must be" - " one of the following: 'persistent' or 'transient'") + if test_train_type not in [ + "persistent", + "transient", + ]: + opencortex.print_comment_v( + "ValueError in input parameters: the value of the key 'TrainType' when 'InputType' is 'GeneratePoissonTrains' must be" + " one of the following: 'persistent' or 'transient'" + ) error_counter += 1 else: - if test_train_type == "persistent": - try: - - test_rates = input_group_params['AverageRateList'] + test_rates = input_group_params[ + "AverageRateList" + ] if not isinstance(test_rates, list): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'AverageRateList' must be of type 'list'." - " The current type is %s" % type(test_rates)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'AverageRateList' must be of type 'list'." + " The current type is %s" + % type(test_rates) + ) error_counter += 1 else: for r in range(0, len(test_rates)): - - if not isinstance(test_rates[r], float): - - opencortex.print_comment_v("TypeError in input parameters: the list values of the key 'AverageRateList' must be of type 'float'." - " The current type is %s" % type(test_rates[r])) + if not isinstance( + test_rates[r], float + ): + opencortex.print_comment_v( + "TypeError in input parameters: the list values of the key 'AverageRateList' must be of type 'float'." + " The current type is %s" + % type(test_rates[r]) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'AverageRateList' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'AverageRateList' is not in the keys of input parameters." + ) error_counter += 1 if test_train_type == "transient": - try: - - test_time_units = input_group_params['TimeUnits'] + test_time_units = input_group_params[ + "TimeUnits" + ] if not isinstance(test_time_units, str): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'TimeUnits' must be of type 'str'." - " The current type is %s." % type(test_time_units)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'TimeUnits' must be of type 'str'." + " The current type is %s." + % type(test_time_units) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'TimeUnits' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'TimeUnits' is not in the keys of input parameters." + ) error_counter += 1 - try: - - test_rates = input_group_params['AverageRateList'] + test_rates = input_group_params[ + "AverageRateList" + ] if not isinstance(test_rates, list): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'AverageRateList' must be of type 'list'." - " The current type is %s." % type(test_rates)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'AverageRateList' must be of type 'list'." + " The current type is %s." + % type(test_rates) + ) error_counter += 1 else: - for r in range(0, len(test_rates)): - - if not isinstance(test_rates[r], float): - - opencortex.print_comment_v("TypeError in input parameters: the list values of the key 'AverageRateList' must be of type 'float'." - " The current type is %s." % type(test_rates[r])) + if not isinstance( + test_rates[r], float + ): + opencortex.print_comment_v( + "TypeError in input parameters: the list values of the key 'AverageRateList' must be of type 'float'." + " The current type is %s." + % type(test_rates[r]) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'AverageRateList' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'AverageRateList' is not in the keys of input parameters." + ) error_counter += 1 try: - - test_rates = input_group_params['DelayList'] + test_rates = input_group_params[ + "DelayList" + ] if not isinstance(test_rates, list): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'DelayList' must be of type 'list'." - " The current type is %s." % type(test_rates)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'DelayList' must be of type 'list'." + " The current type is %s." + % type(test_rates) + ) error_counter += 1 else: - for r in range(0, len(test_rates)): - - if not isinstance(test_rates[r], float): - - opencortex.print_comment_v("TypeError in input parameters: the list values of the key 'DelayList' must be of type 'float'." - " The current type is %s." % type(test_rates[r])) + if not isinstance( + test_rates[r], float + ): + opencortex.print_comment_v( + "TypeError in input parameters: the list values of the key 'DelayList' must be of type 'float'." + " The current type is %s." + % type(test_rates[r]) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'DelayList' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'DelayList' is not in the keys of input parameters." + ) error_counter += 1 try: - - test_rates = input_group_params['DurationList'] + test_rates = input_group_params[ + "DurationList" + ] if not isinstance(test_rates, list): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'DurationList' must be of type 'list'." - " The current type is %s." % type(test_rates)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'DurationList' must be of type 'list'." + " The current type is %s." + % type(test_rates) + ) error_counter += 1 else: - for r in range(0, len(test_rates)): - - if not isinstance(test_rates[r], float): - - opencortex.print_comment_v("TypeError in input parameters: the list values of the key 'DurationList' must be of type 'float'." - " The current type is %s." % type(test_rates[r])) + if not isinstance( + test_rates[r], float + ): + opencortex.print_comment_v( + "TypeError in input parameters: the list values of the key 'DurationList' must be of type 'float'." + " The current type is %s." + % type(test_rates[r]) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'DurationList' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'DurationList' is not in the keys of input parameters." + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'TrainType' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'TrainType' is not in the keys of input parameters." + ) error_counter += 1 try: - - test_rate_units = input_group_params['RateUnits'] + test_rate_units = input_group_params["RateUnits"] if not isinstance(test_rate_units, str): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'RateUnits' must be of type 'str'." - "The current type is %s." % type(test_rate_units)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'RateUnits' must be of type 'str'." + "The current type is %s." + % type(test_rate_units) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parametres: the key 'RateUnits' is not in the keys of inputs parameters.") + opencortex.print_comment_v( + "KeyError in input parametres: the key 'RateUnits' is not in the keys of inputs parameters." + ) error_counter += 1 try: - - test_synapse = input_group_params['Synapse'] + test_synapse = input_group_params["Synapse"] if not isinstance(test_synapse, str): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'Synapse' must be of type 'str'." - " The current type is %s." % type(test_synapse)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'Synapse' must be of type 'str'." + " The current type is %s." % type(test_synapse) + ) error_counter += 1 else: - if path_to_synapses != None: - - found = check_synapse_location(test_synapse, path_to_synapses) + found = check_synapse_location( + test_synapse, path_to_synapses + ) if not found: - - opencortex.print_comment_v("ValueError in input parameters: the value '%s' of the key 'Synapse' is not found in %s" % (test_synapse, path_to_synapses)) + opencortex.print_comment_v( + "ValueError in input parameters: the value '%s' of the key 'Synapse' is not found in %s" + % (test_synapse, path_to_synapses) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'Synapse' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'Synapse' is not in the keys of input parameters." + ) error_counter += 1 - if test_key == 'GenerateSpikeSourcePoisson': - + if test_key == "GenerateSpikeSourcePoisson": try: - - test_time_units = input_group_params['TimeUnits'] + test_time_units = input_group_params["TimeUnits"] if not isinstance(test_time_units, str): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'TimeUnits' must be of type 'str'." - " The current type is %s." % type(test_time_units)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'TimeUnits' must be of type 'str'." + " The current type is %s." + % type(test_time_units) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'TimeUnits' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'TimeUnits' is not in the keys of input parameters." + ) error_counter += 1 try: - - test_rates = input_group_params['AverageRateList'] + test_rates = input_group_params["AverageRateList"] if not isinstance(test_rates, list): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'AverageRateList' must be of type 'list'." - " The current type is %s." % type(test_rates)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'AverageRateList' must be of type 'list'." + " The current type is %s." % type(test_rates) + ) error_counter += 1 else: - for r in range(0, len(test_rates)): - if not isinstance(test_rates[r], float): - - opencortex.print_comment_v("TypeError in input parameters: the list values of the key 'AverageRateList' must be of type 'float'." - " The current type is %s." % type(test_rates[r])) + opencortex.print_comment_v( + "TypeError in input parameters: the list values of the key 'AverageRateList' must be of type 'float'." + " The current type is %s." + % type(test_rates[r]) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'AverageRateList' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'AverageRateList' is not in the keys of input parameters." + ) error_counter += 1 try: - - test_rates = input_group_params['DelayList'] + test_rates = input_group_params["DelayList"] if not isinstance(test_rates, list): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'DelayList' must be of type 'list'." - " The current type is %s." % type(test_rates)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'DelayList' must be of type 'list'." + " The current type is %s." % type(test_rates) + ) error_counter += 1 else: - for r in range(0, len(test_rates)): - if not isinstance(test_rates[r], float): - - opencortex.print_comment_v("TypeError in input parameters: the list values of the key 'DelayList' must be of type 'float'." - " The current type is %s." % type(test_rates[r])) + opencortex.print_comment_v( + "TypeError in input parameters: the list values of the key 'DelayList' must be of type 'float'." + " The current type is %s." + % type(test_rates[r]) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'DelayList' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'DelayList' is not in the keys of input parameters." + ) error_counter += 1 try: - - test_rates = input_group_params['DurationList'] + test_rates = input_group_params["DurationList"] if not isinstance(test_rates, list): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'DurationList' must be of type 'list'." - " The current type is %s." % type(test_rates)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'DurationList' must be of type 'list'." + " The current type is %s." % type(test_rates) + ) error_counter += 1 else: - for r in range(0, len(test_rates)): - if not isinstance(test_rates[r], float): - - opencortex.print_comment_v("TypeError in input parameters: the list values of the key 'DurationList' must be of type 'float'." - " The current type is %s." % type(test_rates[r])) + opencortex.print_comment_v( + "TypeError in input parameters: the list values of the key 'DurationList' must be of type 'float'." + " The current type is %s." + % type(test_rates[r]) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'DurationList' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'DurationList' is not in the keys of input parameters." + ) error_counter += 1 try: - - test_weights = input_group_params['WeightList'] + test_weights = input_group_params["WeightList"] if not isinstance(test_weights, list): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'WeightList' must be of type 'list'." - " The current type is %s." % type(test_weights)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'WeightList' must be of type 'list'." + " The current type is %s." % type(test_weights) + ) error_counter += 1 else: - for r in range(0, len(test_weights)): - if not isinstance(test_weights[r], float): - - opencortex.print_comment_v("TypeError in input parameters: the list values of the key 'WeightList' must be of type 'float'." - " The current type is %s." % type(test_weights[r])) + opencortex.print_comment_v( + "TypeError in input parameters: the list values of the key 'WeightList' must be of type 'float'." + " The current type is %s." + % type(test_weights[r]) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'WeightList' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'WeightList' is not in the keys of input parameters." + ) error_counter += 1 try: - - test_rate_units = input_group_params['RateUnits'] + test_rate_units = input_group_params["RateUnits"] if not isinstance(test_rate_units, str): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'RateUnits' must be of type 'str'." - "The current type is %s." % type(test_rate_units)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'RateUnits' must be of type 'str'." + "The current type is %s." + % type(test_rate_units) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parametres: the key 'RateUnits' is not in the keys of inputs parameters.") + opencortex.print_comment_v( + "KeyError in input parametres: the key 'RateUnits' is not in the keys of inputs parameters." + ) error_counter += 1 try: - - test_synapse = input_group_params['Synapse'] + test_synapse = input_group_params["Synapse"] if not isinstance(test_synapse, str): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'Synapse' must be of type 'str'." - " The current type is %s." % type(test_synapse)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'Synapse' must be of type 'str'." + " The current type is %s." % type(test_synapse) + ) error_counter += 1 else: - if path_to_synapses != None: - - found = check_synapse_location(test_synapse, path_to_synapses) + found = check_synapse_location( + test_synapse, path_to_synapses + ) if not found: - - opencortex.print_comment_v("ValueError in input parameters: the value '%s' of the key 'Synapse' is not found in %s" % (test_synapse, path_to_synapses)) + opencortex.print_comment_v( + "ValueError in input parameters: the value '%s' of the key 'Synapse' is not found in %s" + % (test_synapse, path_to_synapses) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'Synapse' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'Synapse' is not in the keys of input parameters." + ) error_counter += 1 - if test_key == 'PulseGenerators': - + if test_key == "PulseGenerators": try: - - test_time_units = input_group_params['TimeUnits'] + test_time_units = input_group_params["TimeUnits"] if not isinstance(test_time_units, str): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'TimeUnits' must be of type 'str'." - " The current type is %s." % type(test_time_units)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'TimeUnits' must be of type 'str'." + " The current type is %s." + % type(test_time_units) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'TimeUnits' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'TimeUnits' is not in the keys of input parameters." + ) error_counter += 1 try: - - test_amplitude_units = input_group_params['AmplitudeUnits'] + test_amplitude_units = input_group_params[ + "AmplitudeUnits" + ] if not isinstance(test_amplitude_units, str): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'AmplitudeUnits' must be of type 'str'." - " The current type is %s." % type(test_amplitude_units)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'AmplitudeUnits' must be of type 'str'." + " The current type is %s." + % type(test_amplitude_units) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parametres: the key 'AmplitudeUnits' is not in the keys of inputs parameters.") + opencortex.print_comment_v( + "KeyError in input parametres: the key 'AmplitudeUnits' is not in the keys of inputs parameters." + ) error_counter += 1 try: - - test_noise = input_group_params['Noise'] + test_noise = input_group_params["Noise"] if not isinstance(test_noise, bool): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'Noise' must be of type 'bool'." - " The current type is %s." % type(test_noise)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'Noise' must be of type 'bool'." + " The current type is %s." % type(test_noise) + ) error_counter += 1 else: - if test_noise: - try: - - test_smallest_amplitudes = input_group_params['SmallestAmplitudeList'] - - if not isinstance(test_smallest_amplitudes, list): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'SmallestAmplitudeList' must be of type 'list'." - " The current type is %s." % type(test_smallest_amplitudes)) + test_smallest_amplitudes = ( + input_group_params[ + "SmallestAmplitudeList" + ] + ) + + if not isinstance( + test_smallest_amplitudes, list + ): + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'SmallestAmplitudeList' must be of type 'list'." + " The current type is %s." + % type(test_smallest_amplitudes) + ) error_counter += 1 except KeyError: + opencortex.print_comment_v( + "KeyError in input parameters: the key 'SmallestAmplitudeList' is not in the keys of input parameters when " + "'Noise' is set to True." + ) - opencortex.print_comment_v("KeyError in input parameters: the key 'SmallestAmplitudeList' is not in the keys of input parameters when " - "'Noise' is set to True.") - - error_counter += 1 + error_counter += 1 try: - - test_largest_amplitudes = input_group_params['LargestAmplitudeList'] - - if not isinstance(test_largest_amplitudes, list): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'LargestAmplitudeList' must be of type 'list'." - " The current type is %s." % type(test_largest_amplitudes)) + test_largest_amplitudes = ( + input_group_params[ + "LargestAmplitudeList" + ] + ) + + if not isinstance( + test_largest_amplitudes, list + ): + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'LargestAmplitudeList' must be of type 'list'." + " The current type is %s." + % type(test_largest_amplitudes) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'LargestAmplitudeList' is not in the keys of input parameters when " - "'Noise' is set to True.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'LargestAmplitudeList' is not in the keys of input parameters when " + "'Noise' is set to True." + ) error_counter += 1 else: - try: - - test_amplitudes = input_group_params['AmplitudeList'] + test_amplitudes = input_group_params[ + "AmplitudeList" + ] if not isinstance(test_amplitudes, list): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'AmplitudeList' must be of type 'list'." - " The current type is %s." % type(test_amplitudes)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'AmplitudeList' must be of type 'list'." + " The current type is %s." + % type(test_amplitudes) + ) error_counter += 1 else: - for r in range(0, len(test_amplitudes)): - - if not isinstance(test_amplitudes[r], float): - - opencortex.print_comment_v("TypeError in input parameters: the list values of the key 'AverageRateList' must be of type 'float'." - " The current type is %s." % type(test_amplitudes[r])) + if not isinstance( + test_amplitudes[r], float + ): + opencortex.print_comment_v( + "TypeError in input parameters: the list values of the key 'AverageRateList' must be of type 'float'." + " The current type is %s." + % type(test_amplitudes[r]) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'AmplitudeList' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'AmplitudeList' is not in the keys of input parameters." + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'Noise' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'Noise' is not in the keys of input parameters." + ) error_counter += 1 try: - test_delays = input_group_params['DelayList'] + test_delays = input_group_params["DelayList"] if not isinstance(test_delays, list): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'DelayList' must be of type 'list'." - " The current type is %s." % type(test_delays)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'DelayList' must be of type 'list'." + " The current type is %s." % type(test_delays) + ) error_counter += 1 else: - for r in range(0, len(test_delays)): - if not isinstance(test_delays[r], float): - - opencortex.print_comment_v("TypeError in input parameters: the list values of the key 'DelayList' must be of type 'float'." - " The current type is %s." % type(test_delays[r])) + opencortex.print_comment_v( + "TypeError in input parameters: the list values of the key 'DelayList' must be of type 'float'." + " The current type is %s." + % type(test_delays[r]) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'DelayList' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'DelayList' is not in the keys of input parameters." + ) error_counter += 1 try: - - test_durations = input_group_params['DurationList'] + test_durations = input_group_params["DurationList"] if not isinstance(test_durations, list): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'DurationList' must be of type 'list'." - " The current type is %s." % type(test_durations)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'DurationList' must be of type 'list'." + " The current type is %s." + % type(test_durations) + ) error_counter += 1 else: - for r in range(0, len(test_durations)): - if not isinstance(test_durations[r], float): - - opencortex.print_comment_v("TypeError in input parameters: the list values of the key 'DurationList' must be of type 'float'." - " The current type is %s." % type(test_durations[r])) + opencortex.print_comment_v( + "TypeError in input parameters: the list values of the key 'DurationList' must be of type 'float'." + " The current type is %s." + % type(test_durations[r]) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'DurationList' is not in the keys of input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'DurationList' is not in the keys of input parameters." + ) error_counter += 1 - except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'InputType' is not in input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'InputType' is not in input parameters." + ) error_counter += 1 try: - - test_input_name = input_group_params['InputName'] + test_input_name = input_group_params["InputName"] if not isinstance(test_input_name, str): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'InputName' must be of type 'str'." - - "The current type is %s." % type(test_input_name)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'InputName' must be of type 'str'." + "The current type is %s." % type(test_input_name) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'InputName' is not in input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'InputName' is not in input parameters." + ) error_counter += 1 - if ('UniversalTargetSegmentID' not in input_group_params.keys()) and ('UniversalFractionAlong' not in input_group_params.keys()): - + if ("UniversalTargetSegmentID" not in input_group_params.keys()) and ( + "UniversalFractionAlong" not in input_group_params.keys() + ): try: - - test_key = input_group_params['TargetDict'] + test_key = input_group_params["TargetDict"] if not isinstance(test_key, dict): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'TargetDict' in input parameters must be of type 'dict'." - " The current type is %s." % type(test_key)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'TargetDict' in input parameters must be of type 'dict'." + " The current type is %s." % type(test_key) + ) error_counter += 1 else: - if cell_type != None: - for target_segment_group in test_key.keys(): - - if not check_segment_group(segment_groups, target_segment_group): - - opencortex.print_comment_v("ValueError in input parameters: '%s' is not a segment group of the cell type '%s'" % (target_segment_group, cell_receiver)) + if not check_segment_group( + segment_groups, target_segment_group + ): + opencortex.print_comment_v( + "ValueError in input parameters: '%s' is not a segment group of the cell type '%s'" + % (target_segment_group, cell_receiver) + ) error_counter += 1 else: - - if not isinstance(test_key[target_segment_group], int): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key '%s' must be of type 'int'." - " The current type is %s" % (target_segment_group, type(test_key[target_segment_group]))) + if not isinstance( + test_key[target_segment_group], int + ): + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key '%s' must be of type 'int'." + " The current type is %s" + % ( + target_segment_group, + type( + test_key[target_segment_group] + ), + ) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'TargetDict' is not in input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'TargetDict' is not in input parameters." + ) error_counter += 1 - if 'TargetDict' in input_group_params.keys(): - - if 'UniversalTargetSegmentID' in input_group_params.keys(): - - opencortex.print_comment_v("KeyError in input parameters: the key 'UniversalTargetSegmentID' cannot be specified together with the key 'TargetDict'.") + if "TargetDict" in input_group_params.keys(): + if "UniversalTargetSegmentID" in input_group_params.keys(): + opencortex.print_comment_v( + "KeyError in input parameters: the key 'UniversalTargetSegmentID' cannot be specified together with the key 'TargetDict'." + ) error_counter += 1 - if 'UniversalFractionAlong' in input_group_params.keys(): - - opencortex.print_comment_v("KeyError in input parameters: the key 'UniversalFractionAlong' cannot be specified together with the key 'TargetDict'.") + if "UniversalFractionAlong" in input_group_params.keys(): + opencortex.print_comment_v( + "KeyError in input parameters: the key 'UniversalFractionAlong' cannot be specified together with the key 'TargetDict'." + ) error_counter += 1 else: - try: - - test_target_seg_id = input_group_params['UniversalTargetSegmentID'] + test_target_seg_id = input_group_params[ + "UniversalTargetSegmentID" + ] except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'UniversalTargetSegmentID' must be specified when the key 'TargetDict' is not in " - "input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'UniversalTargetSegmentID' must be specified when the key 'TargetDict' is not in " + "input parameters." + ) error_counter += 1 try: - - test_fraction_along = input_group_params['UniversalFractionAlong'] + test_fraction_along = input_group_params[ + "UniversalFractionAlong" + ] except KeyError: - - opencortex.print_comment_v("KeyError in input parameters: the key 'UniversalFractionAlong' must be specified when the key 'TargetDict' is not in " - "input parameters.") + opencortex.print_comment_v( + "KeyError in input parameters: the key 'UniversalFractionAlong' must be specified when the key 'TargetDict' is not in " + "input parameters." + ) error_counter += 1 try: - - test_key = input_group_params['FractionToTarget'] + test_key = input_group_params["FractionToTarget"] if not isinstance(test_key, float): - - opencortex.print_comment_v("TypeError: the value of the key 'FractionToTarget' must be of type 'float'. The current type is %s." % type(test_key)) + opencortex.print_comment_v( + "TypeError: the value of the key 'FractionToTarget' must be of type 'float'. The current type is %s." + % type(test_key) + ) error_counter += 1 except KeyError: - - opencortex.print_comment_v("KeyError: the key 'FractionToTarget' is not in input parameters.") + opencortex.print_comment_v( + "KeyError: the key 'FractionToTarget' is not in input parameters." + ) error_counter += 1 - try: - - test_key = input_group_params['LocationSpecific'] - + test_key = input_group_params["LocationSpecific"] if not isinstance(test_key, bool): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'LocationSpecific' must be of the type 'bool'." - " The current type is %s." % type(test_key)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'LocationSpecific' must be of the type 'bool'." + " The current type is %s." % type(test_key) + ) error_counter += 1 else: - if test_key: - try: - - test_region_key = input_group_params['TargetRegions'] + test_region_key = input_group_params["TargetRegions"] if not isinstance(test_region_key, list): - - opencortex.print_comment_v("TypeError in input parameters: the value of the key 'TargetRegions' must be of the type 'list'." - " The current type is %s." % type(test_region_key)) + opencortex.print_comment_v( + "TypeError in input parameters: the value of the key 'TargetRegions' must be of the type 'list'." + " The current type is %s." + % type(test_region_key) + ) error_counter += 1 else: - for region in range(0, len(test_region_key)): - - if not isinstance(test_region_key[region], dict): - - opencortex.print_comment_v("TypeError in input parameters: the list values of the key 'TargetRegions' must be of the type 'dict'." - " The current type is %s." % type(test_region_key[region])) + if not isinstance( + test_region_key[region], dict + ): + opencortex.print_comment_v( + "TypeError in input parameters: the list values of the key 'TargetRegions' must be of the type 'dict'." + " The current type is %s." + % type(test_region_key[region]) + ) error_counter += 1 else: + for dim_key in [ + "XVector", + "YVector", + "ZVector", + ]: + if ( + dim_key + not in test_region_key[ + region + ].keys() + ): + opencortex.print_comment_v( + "ValueError in input parameters: the list values of the key 'TargetRegions' must be dictionaries " + "with the following keys: 'XVector', 'YVector', 'ZVector'." + ) - for dim_key in ['XVector', 'YVector', 'ZVector']: - - if dim_key not in test_region_key[region].keys(): - - opencortex.print_comment_v("ValueError in input parameters: the list values of the key 'TargetRegions' must be dictionaries " - "with the following keys: 'XVector', 'YVector', 'ZVector'.") - - error_counter += 1 + error_counter += 1 else: - - if not isinstance(test_region_key[region][dim_key], list): - - opencortex.print_comment_v("TypeError in input parameters: the 'X/Y/ZVector' must store the value of type 'list'." - " The current type is %s." % type(test_region_key[region][dim_key])) + if not isinstance( + test_region_key[region][ + dim_key + ], + list, + ): + opencortex.print_comment_v( + "TypeError in input parameters: the 'X/Y/ZVector' must store the value of type 'list'." + " The current type is %s." + % type( + test_region_key[region][ + dim_key + ] + ) + ) error_counter += 1 else: - - if len(test_region_key[region][dim_key]) != 2: - - opencortex.print_comment_v("ValueError in input parameters: the lists stored by 'XVector', 'YVector' and 'ZVector'" - " must contain two values.") + if ( + len( + test_region_key[region][ + dim_key + ] + ) + != 2 + ): + opencortex.print_comment_v( + "ValueError in input parameters: the lists stored by 'XVector', 'YVector' and 'ZVector'" + " must contain two values." + ) error_counter += 1 else: - - if (test_region_key[region][dim_key][0]-test_region_key[region][dim_key][1]) == 0: - - opencortex.print_comment_v("ValueError in input parameters: the lists stored by 'XVector', 'YVector' and 'ZVector'" - " must contain two different values.") - - error_counter += 1 + if ( + test_region_key[region][ + dim_key + ][0] + - test_region_key[ + region + ][dim_key][1] + ) == 0: + opencortex.print_comment_v( + "ValueError in input parameters: the lists stored by 'XVector', 'YVector' and 'ZVector'" + " must contain two different values." + ) + + error_counter += 1 except KeyError: + opencortex.print_comment_v( + "KeyError in input parameters: 'LocationSpecific' is True but the key 'TargetRegions' is not in input parameters." + ) - opencortex.print_comment_v("KeyError in input parameters: 'LocationSpecific' is True but the key 'TargetRegions' is not in input parameters.") - - error_counter += 1 - - + error_counter += 1 except KeyError: + opencortex.print_comment_v( + "KeyError in input parameters: the key 'LocationSpecific' is not in input parameters." + ) - opencortex.print_comment_v("KeyError in input parameters: the key 'LocationSpecific' is not in input parameters.") - - error_counter += 1 + error_counter += 1 if error_counter == 0: - - return True + return True else: + return False - return False - -############################################################################################## +############################################################################################## diff --git a/opencortex/utils/color.py b/opencortex/utils/color.py index 9651fed..7b9db72 100644 --- a/opencortex/utils/color.py +++ b/opencortex/utils/color.py @@ -1,10 +1,10 @@ ############################################################### -### +### ### Note: OpenCortex is under active development, the API is subject to change without notice!! -### +### ### Authors: Padraig Gleeson, Rokas Stanislovas ### -### This software has been funded by the Wellcome Trust, as well as a GSoC 2016 project +### This software has been funded by the Wellcome Trust, as well as a GSoC 2016 project ### on Cortical Network develoment ### ############################################################## @@ -12,30 +12,29 @@ # Colors to use across different networks to ease visual comparison # Reds -L1_PRINCIPAL_CELL = '0.4 0.6 0.6' # rgb(95,158,160) -L1_INTERNEURON = '0.5 0.9 0.9' # rgb(175,238,238) +L1_PRINCIPAL_CELL = "0.4 0.6 0.6" # rgb(95,158,160) +L1_INTERNEURON = "0.5 0.9 0.9" # rgb(175,238,238) # Reds -L23_PRINCIPAL_CELL = '0.6 0 0' -L23_PRINCIPAL_CELL_2 = '1 0.2 0.2' -L23_INTERNEURON = '1 0.4 0.4' -L23_INTERNEURON_2 = '1 0.6 0.6' +L23_PRINCIPAL_CELL = "0.6 0 0" +L23_PRINCIPAL_CELL_2 = "1 0.2 0.2" +L23_INTERNEURON = "1 0.4 0.4" +L23_INTERNEURON_2 = "1 0.6 0.6" # Blues -L4_PRINCIPAL_CELL = '0 0.25 0.5' -L4_INTERNEURON = '0.8 0.7 1' - -#Greens -L5_PRINCIPAL_CELL = '0 0.4 0' -L5_PRINCIPAL_CELL_2 = '0 0.8 0.4' -L5_INTERNEURON = '0.8 1 0.8' -L5_INTERNEURON_2 = '0.8 1 0.6' +L4_PRINCIPAL_CELL = "0 0.25 0.5" +L4_INTERNEURON = "0.8 0.7 1" -#Oranges -L6_PRINCIPAL_CELL = '1 0.6 0.2' -L6_INTERNEURON = '1 0.8 0.8' +# Greens +L5_PRINCIPAL_CELL = "0 0.4 0" +L5_PRINCIPAL_CELL_2 = "0 0.8 0.4" +L5_INTERNEURON = "0.8 1 0.8" +L5_INTERNEURON_2 = "0.8 1 0.6" +# Oranges +L6_PRINCIPAL_CELL = "1 0.6 0.2" +L6_INTERNEURON = "1 0.8 0.8" -THALAMUS_1 = '0 0.6 0.6' #Cyan -THALAMUS_2 = '1 0.6 0.6' #Olive +THALAMUS_1 = "0 0.6 0.6" # Cyan +THALAMUS_2 = "1 0.6 0.6" # Olive diff --git a/examples/redo.sh b/regenerateAndTest.sh similarity index 74% rename from examples/redo.sh rename to regenerateAndTest.sh index 5fe5a37..f990b15 100755 --- a/examples/redo.sh +++ b/regenerateAndTest.sh @@ -1,6 +1,8 @@ #!/bin/bash set -ex -cd .. + +ruff format *.py */*.py */*/*.py */*/*/*.py */*/*/*/*.py + pip install . cd opencortex/test pytest -vs diff --git a/setup.py b/setup.py index 624997b..672d56d 100644 --- a/setup.py +++ b/setup.py @@ -1,46 +1,53 @@ from setuptools import setup import opencortex + version = opencortex.__version__ setup( - name='OpenCortex', + name="OpenCortex", version=version, - author='Rokas Stanislovas and Padraig Gleeson', - author_email='p.gleeson@gmail.com', - packages = ['opencortex', - 'opencortex.core', - 'opencortex.build', - 'opencortex.test', - 'opencortex.utils'], + author="Rokas Stanislovas and Padraig Gleeson", + author_email="p.gleeson@gmail.com", + packages=[ + "opencortex", + "opencortex.core", + "opencortex.build", + "opencortex.test", + "opencortex.utils", + ], package_data={ - 'opencortex': [ - '../NeuroML2/prototypes/iaf/*', - '../NeuroML2/prototypes/izhikevich/*', - '../NeuroML2/prototypes/Thalamocortical/*', - '../NeuroML2/prototypes/BlueBrainProject_NMC/*', - '../NeuroML2/prototypes/AllenInstituteCellTypesDB_HH/*', - '../NeuroML2/prototypes/L23Pyr_SmithEtAl2013/*', - '../NeuroML2/prototypes/acnet2/*']}, - - url='https://github.com/OpenSourceBrain/OpenCortex', - license='LICENSE.lesser', - description='A framework for building cortical network models', - long_description=open('README.md').read(), + "opencortex": [ + "../NeuroML2/prototypes/iaf/*", + "../NeuroML2/prototypes/izhikevich/*", + "../NeuroML2/prototypes/Thalamocortical/*", + "../NeuroML2/prototypes/BlueBrainProject_NMC/*", + "../NeuroML2/prototypes/AllenInstituteCellTypesDB_HH/*", + "../NeuroML2/prototypes/L23Pyr_SmithEtAl2013/*", + "../NeuroML2/prototypes/acnet2/*", + ] + }, + url="https://github.com/OpenSourceBrain/OpenCortex", + license="LICENSE.lesser", + description="A framework for building cortical network models", + long_description=open("README.md").read(), install_requires=[ - 'pyNeuroML>=0.3.18', # sets dependencies for other neuroml libs - 'matplotlib', - 'tables'], + "pyNeuroML>=0.3.18", # sets dependencies for other neuroml libs + "matplotlib", + "tables", + ], dependency_links=[ - 'git+https://github.com/NeuralEnsemble/libNeuroML.git@development#egg=libNeuroML-0.2.10' + "git+https://github.com/NeuralEnsemble/libNeuroML.git@development#egg=libNeuroML-0.2.10" + ], + classifiers=[ + "Intended Audience :: Science/Research", + "License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)", + "Natural Language :: English", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Topic :: Scientific/Engineering", ], - classifiers = [ - 'Intended Audience :: Science/Research', - 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)', - 'Natural Language :: English', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 2.6', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3.2', - 'Topic :: Scientific/Engineering'] )