Skip to content
Snippets Groups Projects
Commit d0e1cee1 authored by Dilawar Singh's avatar Dilawar Singh
Browse files

Squashed 'moose-core/' changes from ba97d4c..d1130b7

d1130b7 Merge branch 'master' of github.com:BhallaLab/moose-core
967ac3b Added VERSION info moose.version( ) or moose.__version__ returns the version. It was lost somewhere in rrefactoring the code.
457850e Added version( ) and __version__ string.
2625fd0 Added `moose.test` to test `moose-examples` online (#189)
2a822a2 Added assertion in test case and remove import of matplotlib. BhallaLab/moose#221.
2484214 absolute imports are forced with python2 as well.
6c92901 All tests passes locally with python3.
bd78e14 Fixes to import statements.
5c3811e Print time information as well.
a7e715c Inbuilt moose.test( ) functions to run moose-examples. BhallaLab/moose-core#184.
c424e0d Fixes to chemUtil import.
f29e35e Merge branch 'master' of github.com:BhallaLab/moose-core
087aad0 moose.Compartment -> moose.element( ) in couple of more place. One more (#187)
d618fe6 Merge branch 'master' into master
4aca08a Merge branch 'master' of github.com:BhallaLab/moose-core
b8266b3 Fixes to test failure. Not sure if it is correct.  BhallaLab/moose#218 .
56870e8 Merge branch 'master' of github.com:BhallaLab/moose-core
d1e37cb Changed the assert statement. Not sure if this is correct to do BhallaLab/moose-core#218. Need to ask developer for confirmation.
cf44570 We are no longer testing Makefile base flow. Only cmake will be tested from now on.
cf7ff18 moose.Compartment -> moose.element( ) in couple of more place. One more scripts passes the test now.

git-subtree-dir: moose-core
git-subtree-split: d1130b78bd744e01d045459adb20d5bcebdb34a0
parent 77fddf7e
No related branches found
No related tags found
No related merge requests found
......@@ -247,7 +247,6 @@ void HSolve::addConc( Id id, double conc )
{
unsigned int index = localIndex( id );
assert( index < externalCalcium_.size() );
externalCalcium_[ index ] = conc;
}
......
"""
How to use the documentation
----------------------------
from __future__ import absolute_import, division, print_function
MOOSE documentation is split into Python documentation and builtin
documentation. The functions and classes that are only part of the
Python interface can be viewed via Python's builtin ``help``
function::
# Bring moose.py functions into global namespace.
>>> help(moose.connect)
from moose.moose import *
The documentation built into main C++ code of MOOSE can be accessed
via the module function ``doc``::
>>> moose.doc('Neutral')
To get documentation about a particular field::
>>> moose.doc('Neutral.childMsg')
Builtin functions and classes in moose module (Python only)
-----------------------------------------------------------
"""
from .moose import *
# Wrapper to get moose version information.
__version__ = moose._moose.__version__
VERSION = moose._moose.VERSION
# NOTE: No module should be imported here. Use moose.py to write imports.
__version__ = moose.moose.version( )
# moose.py ---
# This is the primary moose module. It wraps _moose.so and adds some
# utility functions.
from __future__ import print_function, division, absolute_import
# Filename: moose.py
# Author: Subhasis Ray
# Maintainer: Dilawar Singh, Harsha Rani, Upi Bhalla
from __future__ import print_function
from contextlib import closing
import warnings
import platform
import pydoc
import os
from io import StringIO
from collections import defaultdict
from . import _moose
from ._moose import *
import __main__ as main
from .genesis import writeKkit
from . import SBML
import moose.SBML.readSBML as _readSBML
import moose.SBML.writeSBML as _writeSBML
import moose.genesis.writeKkit as _writeKkit
import moose.chemUtil as _chemUtil
# Import function from C++ module into moose namespace.
from moose._moose import *
def version( ):
return VERSION
# Tests
from moose.moose_test import test
sequence_types = ['vector<double>',
'vector<int>',
'vector<long>',
......@@ -43,8 +48,6 @@ known_types = ['void',
'melement'] + sequence_types
# SBML related functions.
def mooseReadSBML(filepath, loadpath, solver='ee'):
"""Load SBML model.
......@@ -55,7 +58,7 @@ def mooseReadSBML(filepath, loadpath, solver='ee'):
solver -- Solver to use (default 'ee' ) \n
"""
return SBML.readSBML.mooseReadSBML( filepath, loadpath, solver )
return _readSBML.mooseReadSBML( filepath, loadpath, solver )
def mooseWriteSBML(modelpath, filepath, sceneitems={}):
......@@ -74,7 +77,7 @@ def mooseWriteSBML(modelpath, filepath, sceneitems={}):
--- else, auto-coordinates is used for layout position and passed
"""
return SBML.writeSBML.mooseWriteSBML(modelpath, filepath, sceneitems)
return _writeSBML.mooseWriteSBML(modelpath, filepath, sceneitems)
def mooseWriteKkit(modelpath, filepath,sceneitems={}):
......@@ -85,7 +88,7 @@ def mooseWriteKkit(modelpath, filepath,sceneitems={}):
modelpath -- model path in moose \n
filepath -- Path of output file.
"""
return writeKkit.mooseWriteKkit(modelpath, filepath,sceneitems)
return _writeKkit.mooseWriteKkit(modelpath, filepath,sceneitems)
def moosedeleteChemSolver(modelpath):
......@@ -94,7 +97,7 @@ def moosedeleteChemSolver(modelpath):
this should be followed by mooseaddChemSolver for add solvers on to compartment to simulate else
default is Exponential Euler (ee)
"""
return chemUtil.add_Delete_ChemicalSolver.moosedeleteChemSolver(modelpath)
return _chemUtil.add_Delete_ChemicalSolver.moosedeleteChemSolver(modelpath)
def mooseaddChemSolver(modelpath, solver):
......@@ -108,7 +111,7 @@ def mooseaddChemSolver(modelpath, solver):
"Runge Kutta" ("gsl")
"""
return chemUtil.add_Delete_ChemicalSolver.mooseaddChemSolver(modelpath, solver)
return _chemUtil.add_Delete_ChemicalSolver.mooseaddChemSolver(modelpath, solver)
################################################################
# Wrappers for global functions
......
"""
Test MOOSE installation with moose-examples.
"""
from __future__ import print_function
__author__ = "Dilawar Singh"
__copyright__ = "Copyright 2016, Dilawar Singh"
__credits__ = ["NCBS Bangalore"]
__license__ = "GNU GPL"
__version__ = "1.0.0"
__maintainer__ = "Dilawar Singh"
__email__ = "dilawars@ncbs.res.in"
__status__ = "Development"
import sys
import os
import tempfile
import re
import subprocess
import threading
import signal
import logging
from collections import defaultdict
import time
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename='tests.log',
filemode='w'
)
console = logging.StreamHandler()
console.setLevel(logging.WARNING)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
_logger = logging.getLogger('moose.test')
_logger.addHandler(console)
test_data_url_ = 'https://github.com/BhallaLab/moose-examples/archive/master.zip'
test_repo_url_ = 'https://github.com/BhallaLab/moose-examples'
test_dir_ = os.path.join( tempfile.gettempdir( ), 'moose-examples' )
ignored_dict_ = defaultdict( list )
test_status_ = defaultdict( list )
total_ = 0
matplotlibrc_ = '''
backend : agg
interactive : True
'''
# Handle CTRL+C
def signal_handler(signal, frame):
print( 'You pressed Ctrl+C!' )
print_test_stat( )
quit(-1)
signal.signal(signal.SIGINT, signal_handler)
# Credit: https://stackoverflow.com/a/4825933/1805129
class Command(object):
def __init__(self, cmd):
self.cmd = cmd
self.process = None
self.fnull = open( os.devnull, 'w' )
def __repr__( self ):
return ' '.join( self.cmd )
def run(self, timeout):
def target():
_logger.info( "Running %s" % self )
self.process = subprocess.Popen(
self.cmd, shell=False
, stdout = self.fnull, stderr = subprocess.STDOUT
)
self.process.communicate()
thread = threading.Thread( target = target )
thread.start()
thread.join(timeout)
if thread.is_alive():
self.process.terminate()
thread.join()
return self.process.returncode
def init_test_dir( ):
global test_dir_
global test_url_
if( not os.path.exists( test_dir_ ) ):
os.makedirs( test_dir_ )
_logger.info( "Donwloading test repository" )
subprocess.call(
[ 'git', 'clone', '--depth=10', test_repo_url_, test_dir_ ]
)
os.chdir( test_dir_ )
def suitable_for_testing( script ):
with open( script ) as f:
txt = f.read( )
if not re.search( r'main\(\s*\)', txt ):
_logger.debug( 'Script %s does not contain main( )' % script )
return False, 'main( ) not found'
if re.search( r'raw_input\(\s*\)', txt ):
_logger.debug( 'Script %s requires user input' % script )
return False, 'waits for user input'
return True, 'OK'
def run_test( index, testfile ):
"""Run a given test
"""
global test_status_
global total_
pyExec = os.environ.get( 'PYTHON_EXECUTABLE', '/usr/bin/python' )
cmd = Command( [ pyExec, testfile ] )
ti = time.time( )
status = cmd.run( timeout = 60 )
name = os.path.basename( testfile )
t = time.time( ) - ti
cwd = os.path.dirname( testfile )
os.chdir( cwd )
with open( os.path.join( cwd, 'matplotlibrc' ), 'w' ) as f:
_logger.debug( 'Writing matplotlibrc to %s' % cwd )
f.write( matplotlibrc_ )
out = (name + '.' * 50)[:50]
print( '[TEST %3d/%d] %50s %.2f sec ' % (index, total_, out, t), end='' )
sys.stdout.flush( )
if status != 0:
if status == -15:
msg = '%2d TIMEOUT' % status
test_status_[ 'TIMED-OUT' ].append( testfile )
else:
msg = '%2d FAILED' % status
test_status_[ 'FAILED' ].append( testfile )
print( msg )
else:
print( '%2d PASSED' % status )
test_status_[ 'PASSED' ].append( testfile )
sys.stdout.flush( )
def print_test_stat( ):
global test_status_
for status in test_status_:
print( 'Total %d tests %s' % (len( test_status_[status] ), status ) )
def test_all( ):
global test_dir_
global total_
scripts = [ ]
for d, ds, fs in os.walk( test_dir_ ):
for f in fs:
if not re.match( r'.+\.py$', f):
continue
filepath = os.path.join( d, f )
isOK, msg = suitable_for_testing( filepath )
if isOK:
scripts.append( filepath )
else:
ignored_dict_[ msg ].append( filepath )
for k in ignored_dict_:
_logger.debug( '[INFO] Ignored due to %s' % k )
_logger.debug( '\n\t'.join( ignored_dict_[ k ] ) )
_logger.info( 'Total %d valid tests found' % len( scripts ) )
total_ = len( scripts )
for i, s in enumerate( scripts ):
_logger.info( 'Running test : %s' % s )
run_test(i, s )
def test( ):
"""Download and run tests.
"""
try:
init_test_dir( )
except Exception as e:
print( '[INFO] Failed to clone moose-examples. Error was %s' % e )
quit( )
test_all( )
print_test_stat( )
if __name__ == '__main__':
test( )
......@@ -156,7 +156,7 @@ class NetworkML():
cell_name = self.populationDict[population][0]
segment_path = self.populationDict[population][1][int(cell_id)].path+'/'+\
self.cellSegmentDict[cell_name][0][segment_id][0]
compartment = moose.Compartment(segment_path)
compartment = moose.element(segment_path)
_logger.debug("Adding pulse at {0}: {1}".format(
segment_path, pulsegen.firstLevel )
)
......@@ -226,7 +226,7 @@ class NetworkML():
if childobj.className in ['Compartment','SymCompartment']:
## SymCompartment inherits from Compartment,
## so below wrapping by Compartment() is fine for both Compartment and SymCompartment
child = moose.Compartment(childId)
child = moose.element(childId)
x0 = child.x0
y0 = child.y0
x0new = x0*cos(ztheta)-y0*sin(ztheta)
......@@ -316,7 +316,7 @@ class NetworkML():
weight_override, threshold, delay_override)
def connect(self, syn_name, pre_path, post_path, weight, threshold, delay):
postcomp = moose.Compartment(post_path)
postcomp = moose.element(post_path)
## We usually try to reuse an existing SynChan & SynHandler -
## event based SynHandlers have an array of weights and delays and can represent multiple synapses,
## so a new element of the weights and delays array is created
......@@ -349,7 +349,7 @@ class NetworkML():
if gradedchild is not None and gradedchild.value=='True': # graded synapse
interpol = moose.element(syn.path+"/graded_table")
#### always connect source to input - else 'cannot create message' error.
precomp = moose.Compartment(pre_path)
precomp = moose.element(pre_path)
moose.connect(precomp,"VmOut",interpol,"input")
try:
tau_table = moose.element(syn.path+'/tau_table')
......
"""plot_utils.py: Some utility function for plotting data in moose.
Last modified: Sun Jan 10, 2016 04:04PM
......@@ -15,10 +13,11 @@ __maintainer__ = "Dilawar Singh"
__email__ = "dilawars@ncbs.res.in"
__status__ = "Development"
import matplotlib.pyplot as plt
from . import _moose as moose
from . import print_utils as pu
import numpy as np
import moose
import print_utils as pu
import matplotlib.pyplot as plt
def plotAscii(yvec, xvec = None, file=None):
"""Plot two list-like object in terminal using gnuplot.
......@@ -135,7 +134,7 @@ def plotTables(tables, outfile=None, **kwargs):
subplot = kwargs.get('subplot', True)
for i, tname in enumerate(tables):
if subplot:
plt.subplot(len(tables), 1, i)
plt.subplot(len(tables), 1, i+1)
yvec = tables[tname].vector
xvec = np.linspace(0, moose.Clock('/clock').currentTime, len(yvec))
plt.plot(xvec, yvec, label=tname)
......@@ -233,11 +232,7 @@ def saveRecords(records, xvec = None, **kwargs):
pu.info("Done writing data to %s" % outfile)
def plotRecords(records, xvec = None, **kwargs):
"""plotRecords Plot given records in dictionary.
:param records:
:param xvec: If None, use moose.Clock to generate xvec.
:param **kwargs:
"""Wrapper
"""
dataDict = {}
try:
......@@ -267,7 +262,7 @@ def plotRecords(records, xvec = None, **kwargs):
yvec = dataDict[k].vector
plotVector(yvec, xvec, label=k, **kwargs)
else:
plt.subplot(len(dataDict), 1, i)
plt.subplot(len(dataDict), 1, i+1)
yvec = dataDict[k].vector
plotVector(yvec, xvec, label=k, **kwargs)
......@@ -285,47 +280,15 @@ def plotRecords(records, xvec = None, **kwargs):
plt.savefig("%s" % outfile, transparent=True)
else:
plt.show()
plt.close( )
def plot_records(data_dict, xvec = None, **kwargs):
"""plot_records Plot given dictionary.
def plotTables( records, xvec = None, **kwargs ):
"""Plot dictionary of moose.Table/moose.Table2
:param data_dict:
:param xvec: If None, use moose.Clock to generate xvec.
:param records: A dictionary of moose.Table. All tables must have same
length.
:param xvec: If None, moose.Clock is used to generate time-vector.
:param **kwargs:
"""
legend = kwargs.get('legend', True)
outfile = kwargs.get('outfile', None)
subplot = kwargs.get('subplot', False)
filters = [ x.lower() for x in kwargs.get('filter', [])]
plt.figure(figsize=(10, 1.5*len(data_dict)))
for i, k in enumerate(data_dict):
pu.info("+ Plotting for %s" % k)
plotThis = False
if not filters: plotThis = True
for accept in filters:
if accept in k.lower():
plotThis = True
break
if plotThis:
if not subplot:
yvec = data_dict[k]
plotVector(yvec, xvec, label=k, **kwargs)
else:
plt.subplot(len(data_dict), 1, i)
yvec = data_dict[k]
plotVector(yvec, xvec, label=k, **kwargs)
if subplot:
try:
plt.tight_layout()
except: pass
if outfile:
pu.info("Writing plot to %s" % outfile)
plt.savefig("%s" % outfile, transparent=True)
else:
plt.show()
return plotRecords( records, xvec, **kwargs )
"""sim_utils.py:
Helper function related with simulation.
Last modified: Sat Jan 18, 2014 05:01PM
"""
__author__ = "Dilawar Singh"
__copyright__ = "Copyright 2013, NCBS Bangalore"
__credits__ = ["NCBS Bangalore", "Bhalla Lab"]
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Dilawar Singh"
__email__ = "dilawars@ncbs.res.in"
__status__ = "Development"
from . import _moose
from . import print_utils
from . import verification_utils
def recordTarget(tablePath, target, field = 'vm', **kwargs):
"""Setup a table to record at given path.
Make sure that all root paths in tablePath exists.
Returns a table.
"""
# If target is not an moose object but a string representing intended path
# then we need to fetch the object first.
if type( target) == str:
if not _moose.exists(target):
msg = "Given target `{}` does not exists. ".format( target )
raise RuntimeError( msg )
else:
target = _moose.Neutral( target )
assert target.path, "Target must have a valid moose path."
table = _moose.Table( tablePath )
assert table
# Sanities field.
if field == "output":
pass
elif 'get' not in field:
field = 'get'+field[0].upper()+field[1:]
else:
field = field[:2]+field[3].upper()+field[4:]
try:
print_utils.dump("TABLE"
, "Connecting table {} to target {} field {}".format(
table.path
, target.path
, field
)
)
table.connect( 'requestOut', target, field )
except Exception as e:
debug.dump("ERROR"
, [ "Failed to connect table to target"
, e
]
)
raise e
assert table, "Moose is not able to create a recording table"
return table
def run(simTime, verify=False):
if verify:
verification_utils.verify()
_moose.start(simTime)
This diff is collapsed.
"""verification_utils.py:
IT contains a class which runs tests on moose internal data-structures to
check if it is good for simulation.
Last modified: Sun Feb 15, 2015 12:21PM
"""
from __future__ import print_function
__author__ = "Dilawar Singh"
__copyright__ = "Copyright 2013, NCBS Bangalore"
__credits__ = ["NCBS Bangalore", "Bhalla Lab"]
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Dilawar Singh"
__email__ = "dilawars@ncbs.res.in"
__status__ = "Development"
import sys
import sys
from . import _moose as moose
import unittest
import inspect
from . import print_utils as debug
import numpy as np
from .backend import backend
class MooseTestCase( unittest.TestCase ):
def dump(self, msg, end=''):
''' Dump the messages in test functions '''
caller = inspect.stack()[1][3]
if type(msg) == list:
msg = '\n\t|- '.join(msg)
print(('[VERIFY] {:80s}[{}]'.format(msg, caller)))
def setUp(self):
'''Initialize storehouse
'''
if not backend.moose_elems.filled:
backend.moose_elems.populateStoreHouse()
self.mooseElems = backend.moose_elems
self.nonZeroClockIds = None
def test_disconnected_compartments(self):
'''Test if any comparment is not connected '''
self.dump("Checking if any compartment is not connected ...")
for c in self.mooseElems.compartments:
if (c.neighbors['axial'] or c.neighbors['raxial']):
continue
elif c.neighbors['injectMsg']:
continue
else:
msg = '%s is not connected with any other compartment' % c.path
debug.dump('FAIL'
, [ msg
, 'Did you forget to use `moose.connect`?'
]
)
def test_isolated_pulse_gen(self):
''' Test if any pulse-generator is not injecting current to a
compartment
'''
self.dump('Checking if any pulse-generator is floating')
for pg in self.mooseElems.pulseGens:
if pg.neighbors['output']:
continue
else:
debug.dump(
'FAIL'
, [ 'Current source {} is floating'.format(pg.path)
, 'It is not injecting current to any compartment'
, 'Perhaps you forgot to use `moose.connect`?'
]
)
def test_synchans(self):
self.dump("Checking if any synapse is dead")
for synchan in self.mooseElems.synchans:
if synchan.Gbar <= 0.0:
debug.dump("WARN"
, [ synchan.path
, "Gbar value is zero or negative: %s" % synchan.Gbar
, "Not cool!"
]
)
# Check the output of synchan.
if not synchan.neighbors['channel']:
debug.dump("FAIL"
, [ "SynChan %s is not connected to post-compartment" % synchan.path
, " No connected 'channel'. "
" Did you forget to connect compartment e.g."
"moose.connect(synchan, 'channel', comp, 'channel')"
" where synchan is 'moose.SynChan' and comp is "
" 'moose.Compartment'?"
]
)
else:
pass
# Check if anyone is activating this synchan.
synhandlers = synchan.neighbors['activation']
if not synhandlers:
debug.dump("FAIL"
, [ "No SynHandler is activating SynChan %s" % synchan.path
, " Did you forget to connect a SynHandler e.g. "
"moose.connect(synHandler, 'activationOut', synchan, 'activation'"
" where synchan is 'moose.SynChan' and synHandler is"
" moose.SynHandler."
]
)
else: [self.test_synhandler(x) for x in synhandlers]
def test_synhandler(self, synhandlers):
"""A SynHandler object does not have incoming connections to itself.
Rather it keeps an array of moose.Synapse inside it which recieves input
of moose.SpikeGen.
"""
if type(synhandlers) == moose.vec:
if len(synhandlers) == 1:
synhandler = synhandlers[0]
else:
[self.test_synhandler(x) for x in synhandlers]
else:
synhandler = synhandlers
for synapses in synhandler.synapse:
self.test_synapse(synapses)
def test_synapse(self, synapses):
if type(synapses) == moose.Synapse:
synapse = synapses
elif type(synapses) == moose.vec:
if len(synapses) == 1:
synapse = synapses[0]
else:
[ self.test_synapse(x) for x in synapses ]
spikeGens = synapse.neighbors['addSpike']
if not spikeGens:
debug.dump('FAIL'
, [" Synapse %s has no incoming spikes" % synapse.path
, " Did you forget to connect a moose.SpikeGen e.g."
" moose.connect(spikegen, 'spikeOut', synapse, 'addSpike')"
]
)
else:
[self.test_spikegen(x) for x in spikeGens]
def test_spikegen(self, spikegens):
spikeGen = None
if len(spikegens) > 1:
[self.test_spikegen(x) for x in spikegens]
elif len(spikegens) == 1:
spikeGen = spikegens[0]
elif type(spikegens) == moose.SpikeGen:
spikeGen = spikegens
pre = spikeGen.neighbors['Vm']
if not pre:
debug.dump('FAIL',
[ "SpikeGen %s is not reading Vm of any compartment " % spikeGen.path
, "Did you forget to connect Vm of a "
"compartment to this SpikeGen? "
" e.g. moose.connect(comp, 'VmOut', spikeGen, 'Vm')"
]
)
else: pass
def test_unused_tables(self):
'''Tests if any table is not reading data. Such tables remain empty.
'''
self.dump('Checking if any table is not connected')
for table in self.mooseElems.tables:
if table.neighbors['requestOut']:
continue
else:
debug.dump(
'FAIL'
, [ 'Table {} is not reading data.'.format(table.path)
, ' Did you forget to use `moose.connect`?'
]
)
def test_clocks(self):
"""Tests if clocks are missing. """
self.dump("Checking if clocks are available")
try:
clock = self.mooseElems.clocks[0]
except:
debug.dump("WARN", "Could not find any clock")
return
clockDtList = clock.dts
if np.count_nonzero(clockDtList) < 1:
debug.dump("FATAL"
, [ "No clock is found with non-zero dt size. "
, "Did you forget to use `moose.setClock` function?"
, "Quitting..."
]
)
sys.exit(0)
else:
self.nonZeroClockIds = np.nonzero(self.mooseElems.clocks)
def test_methods_sensitivity(self):
"""Test if each compartment has process connected to a non-zero clock"""
self.dump("Checking for insensitive processes")
[ self.checkSentitivity( m, objs)
for m in ['process', 'init']
for objs in [self.mooseElems.compartments]
]
[self.checkSentitivity('process', objs)
for objs in [self.mooseElems.tables, self.mooseElems.pulseGens]
]
def checkSentitivity( self, methodName, objectList):
"""Check if a given method is sensitive to any non-zero clock
"""
assert type(methodName) == str
insensitiveObjectList = []
for obj in objectList:
if not obj.neighbors[methodName]:
insensitiveObjectList.append(obj)
else:
# Here we must check if method is made sensitive to a
# zero-clock. Currently there is no way to test it in python.
pass
if len(insensitiveObjectList) > 0:
msgList = [
"Method `%s` is insensitive to all clocks. " % methodName
, "Total {} out of {} object ({}) fails this test".format(
len(insensitiveObjectList)
, len(objectList)
, type(insensitiveObjectList[0])
)
]
debug.dump("FAIL", msgList)
def verify( *args, **kwargs):
'''Verify the current moose setup. Emit errors and warnings
'''
connectivitySuite = unittest.TestSuite()
connectivitySuite.addTest(MooseTestCase('test_disconnected_compartments'))
connectivitySuite.addTest(MooseTestCase('test_isolated_pulse_gen'))
connectivitySuite.addTest(MooseTestCase('test_unused_tables'))
connectivitySuite.addTest(MooseTestCase('test_synchans'))
simulationSuite = unittest.TestSuite()
simulationSuite.addTest(MooseTestCase('test_clocks'))
simulationSuite.addTest(MooseTestCase('test_methods_sensitivity'))
# We can replace self with run also and collect the result into a result
# object.
connectivitySuite.debug()
simulationSuite.debug()
......@@ -4,11 +4,11 @@ import os
import sys
import numpy as np
import time
import moose
import matplotlib.pyplot as plt
import test_difshells as td
import chan_proto
import param_chan
import moose
print('Using moose from %s' % moose.__file__ )
difshell_no = 3
......@@ -20,6 +20,13 @@ p_file = os.path.join( script_dir_, "soma.p" )
cond = {'CaL12':30*0.35e-5, 'SK':0.5*0.35e-6}
def assert_stat( vec, expected ):
min_, max_ = np.min( vec ), np.max( vec )
mean, std = np.mean( vec ), np.std( vec )
computed = [ min_, max_, mean, std ]
assert np.allclose( computed, expected ), \
"Got %s expected %s" % (computed, expected)
if __name__ =='__main__':
for tick in range(0, 7):
moose.setClock(tick,10e-6)
......@@ -66,9 +73,10 @@ if __name__ =='__main__':
t_stop = 10.
moose.reinit()
moose.start(t_stop)
print( sktab.vector )
print( shelltab.vector )
print(len(np.where(sktab.vector<1e-19)[0]),
len(np.where(shelltab.vector>50e-6)[0])
)
vec1 = sktab.vector
vec2 = shelltab.vector
assert_stat( vec1, [ 0.0, 5.102834e-22, 4.79066e-22, 2.08408e-23 ] )
assert_stat( vec2, [ 5.0e-5, 5.075007e-5, 5.036985e-5, 2.1950117e-7] )
assert len(np.where(sktab.vector<1e-19)[0]) == 2001
assert len(np.where(shelltab.vector>50e-6)[0]) == 2000
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment