def test_quantityexpr():
    data = []

    for (a, b, check_with_gnu) in valid_quantity_exprs:
        print 'a:', a
        print 'b:', b
        A = NeuroUnitParser.QuantityExpr(a)
        print 'LOADING B'
        B = NeuroUnitParser.QuantityExpr(b)

        if check_with_gnu:
            verify_equivalence_with_gnuunits(a, b)
        print "typeA:", type(A)
        print "typeB:", type(B)

        pcA = ((A - B) / A).dimensionless()
        pcB = ((A - B) / B).dimensionless()
        data.append([
            a, b,
            "$%s$" % (A.FormatLatex()),
            "$%s$" % (B.FormatLatex()),
            str(pcA),
            str(pcB)
        ])

    header = "A|B|Parsed(A)|Parsed(B)|PC(A)|PC(B)".split("|")
    return Table(header=header, data=data)
示例#2
0
def cmdline_simulate(args):

    print 'Simulating'
    for arg, arg_value in vars(args).items():
        print arg, arg_value

    from neurounits import NeuroUnitParser, MQ1
    from neurounits.nineml_fe.nineml_fe_utils import get_src_9ml_files

    # Load from all the include directories, but only add files once
    # to prevent duplicate entries in the library_manager
    #src_files = []
    #for incl_path in args.include:
    #    assert os.path.exists(incl_path)
    #    # Add all the files in a directory:
    #    if os.path.isdir(incl_path):
    #        new_files = sorted([ os.path.abspath(fname)  for fname in glob.glob(incl_path+'/*.9ml') ] )
    #        for fname in new_files:
    #            if not fname in src_files:
    #                src_files.append(fname)
    #    # Add an individual file:
    #    elif os.path.isfile(incl_path):
    #        if not incl_path in src_files:
    #            src_files.append(incl_path)

    src_files = get_src_9ml_files(args)

    # Read all the input files:
    library_manager = NeuroUnitParser.Parse9MLFiles(filenames=src_files)

    # Get the component:
    component = library_manager.get(args.component)

    component.summarise()

    # Get the start and end times:
    t_end = NeuroUnitParser.QuantitySimple(args.endt)
    assert t_end.is_compatible(MQ1('1s').units)
    t_end = t_end.float_in_si()
    dt = NeuroUnitParser.QuantitySimple(args.dt)
    assert dt.is_compatible(MQ1('1s').units)
    dt = dt.float_in_si()

    # OK lets simulate!
    res = component.simulate(times=np.arange(0, t_end, dt), )

    print 'Simulating'
    for arg, arg_value in vars(args).items():
        print arg, arg_value

    # and plot:
    res.auto_plot()

    # Shall we pop up?
    if args.show_plot:
        pylab.show()

    print 'Simulating'
    for arg, arg_value in vars(args).items():
        print arg, arg_value
示例#3
0
class NEURONMappings(object):

    current_units = {
        MechanismType.Distributed: NeuroUnitParser.Unit("mA/cm2"),
        MechanismType.Point: NeuroUnitParser.Unit("nA"),
    }

    supplied_value_names = {
        NeuronSuppliedValues.MembraneVoltage: 'v',
        NeuronSuppliedValues.Time: 't',
        NeuronSuppliedValues.Temperature: 'celsius'
    }

    supplied_value_units = {
        NeuronSuppliedValues.MembraneVoltage: NeuroUnitParser.Unit("mV"),
        NeuronSuppliedValues.Time: NeuroUnitParser.Unit("ms"),
        NeuronSuppliedValues.Temperature: NeuroUnitParser.Unit("K")
    }
def test_quantitysimple():
    data = []

    for (a, b, check_with_gnu) in valid_quantitysimple:
        A = NeuroUnitParser.QuantitySimple(a)
        B = NeuroUnitParser.QuantitySimple(b)

        if check_with_gnu:
            verify_equivalence_with_gnuunits(a, b)

        pcA = ((A - B) / A).dimensionless()
        pcB = ((A - B) / B).dimensionless()
        assert pcA == 0
        assert pcB == 0
        data.append([a, b, str(A), str(B), str(pcA), str(pcB)])

    header = "A|B|Parsed(A)|Parsed(B)|PC(A)|PC(B)".split("|")
    return Table(header=header, data=data)
示例#5
0
def test5():

    library_manager = NeuroUnitParser.Parse9MLFile("""
        define_component van_de_pol {
                x' = mu * (x-(x*x*x)/3 - y)  * {10ms-1}
                #x' = mu * (x-(x**3)/3 - y)  * {10ms-1}
                
                y' = x/mu * {10ms-1}
                #mu = 6.0
                
                initial {
                    x=1.0
                    y=6.0
                }
             <=> PARAMETER mu
            }
            """)

    res = library_manager.get('van_de_pol').simulate(times=np.linspace(
        0.0, 0.0200, 10000),
                                                     parameters={'mu': "4.0"})

    res.auto_plot()
示例#6
0
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#-------------------------------------------------------------------------------

from neurounits import NeuroUnitParser
import quantities as pq
from neurounits.writers.writer_ast_to_simulatable_object import EqnSimulator

es = NeuroUnitParser.EqnSet("""
        EQNSET lorenz {
            x' = (sigma*(y-x)) * {1s-1}
            y' = (x*( rho-z)-y) * {1s-1}
            z' = (x*y-beta*z) * {1s-1}
            sigma = 1000
            beta = 8/3
            rho= 28

         <=> OUTPUT x:(), y:(), z:()
         <=> INITIAL x:1.0
         <=> INITIAL y:1.0
         <=> INITIAL z:1.0
        }
        """)

#SimulateEquations(es)

#es.to_redoc().to_pdf(filename="/home/michael/Desktop//out1.pdf")

import numpy as np

evaluator = EqnSimulator(es, )
示例#7
0
def run_scenario_filename(fname, code_path_mode='reduced', only_first_paramtuple=False, plot_results=False, short_run=False):
    
    if short_run is True:
        only_first_paramtuple = True
        
    
    print 'Reading from file', fname
    conf = configobj.ConfigObj(fname)


    units_dict = dict( [(k,NeuroUnitParser.Unit(v).as_quantities_unit() ) for (k,v) in conf['Units'].iteritems() ] )
    param_syms = conf['Parameter Values'].keys()
    param_vals = [ conf['Parameter Values'][sym] for sym in param_syms]


    #description_lines = [ l.strip() for l in conf['description'].split('\n')]    
    #description_lines = [ l for l in description_lines if l]
    
    description_lines = []
    for line in conf['description'].split('\n'):
        
        # Skip blank lines:
        if not line.strip():
            continue
            
        # If it starts with whitespace, then add it to the previous line
        if re.match(r"""^[\s]+""", line):
            description_lines[-1] = description_lines[-1] + ' ' + line.strip()
            continue
        
        # Otherwise, just add it
        description_lines.append(line)
        
    description_lines = [ l.strip() for l in description_lines]
    description_lines = [ re.sub(r"\s+", " ", l) for l in description_lines]
    
    
    

    code_paths = handler_lib.build_code_paths(description_lines, mode=code_path_mode)

    for param_index, param_vals_inst in enumerate(itertools.product(*param_vals)) :


        if only_first_paramtuple and param_index != 0:
            break

        # For each code_path
        for code_path_index, code_path in enumerate(code_paths):

            # Build the base context:
            parameter_values_float = {}
            for (param_index,k) in enumerate(param_syms):
                parameter_values_float[k] = float(param_vals_inst[param_index])

            parameter_values = {}
            for (param_index,k) in enumerate(param_syms):
                parameter_values[k] = float(param_vals_inst[param_index]) * units_dict[k]
            ctx = ActionContext(parameter_values = parameter_values)

            # Execute the code-path:
            code_path.execute(ctx=ctx)

            #Extract the relevant columns and save them to a file:
            column_names = conf['Output Format']['columns']
            basename = conf['Output Format']['base_filename']

            # Get trace data, except time:
            data_col_names = column_names[1:]
            traces = [ctx.res.get_trace(ctx.records[col])for col in data_col_names]
            # Use the time record of the first trace
            time = traces[0].time_pts_ms
            trace_data = [ tr.data_pts/units_dict[col] for col,tr in zip(data_col_names,traces) ]
            trace_data = [tr.rescale(pq.dimensionless).magnitude for tr in trace_data]

            data = [time] + trace_data
            data_matrix = np.vstack(( data) ).T

            opfile = basename.replace('<','{').replace('>','}').format( **parameter_values_float)
            opfile = opfile + 'mfcuke_%d' % code_path_index
            opdir = os.path.join( simtest_utils.Locations.output_root(), conf['scenario_short'])
            opfile = os.path.join(opdir, opfile)

            np.savetxt(opfile, data_matrix)

            if plot_results:
                mf.TagViewer(ctx.res, show=False)
示例#8
0
def convert_string_to_quantity(s):
    if isinstance(s, basestring):
        return NeuroUnitParser.QuantitySimple(s).as_quantities_quantity()
    else:
        return s
示例#9
0
def parse_io_line(line):
    from neurounits import NeuroUnitParser
    from neurounits.unit_errors import ParsingError
    assert isinstance(line, basestring)
    print 'Line', line

    metadata = {}
    if 'METADATA' in line:
        (line, metadata) = line.split('METADATA')
        metadata = read_json(metadata)


    #r = re.compile( r"""<=> \s* (?P<MODE>[a-zA-Z]+) \s* (?P<SYMBOL>[a-zA-Z][a-zA-Z0-9_]*) \s* ([:] \s* (?P<UNIT>[a-zA-Z0-9/()]*) )? """, re.VERBOSE)
    r = re.compile( r"""<=> \s* (?P<MODE>[a-zA-Z]+) \s* (?P<DEFS>.*) $""", re.VERBOSE)
    m = r.match(line)

    if not m:
        raise ParsingError('Unable to parse line: "%s"'%line)
    g = m.groupdict()

    mode = g['MODE']


    if mode in ('INPUT', 'OUTPUT', 'PARAMETER'):
        defs = []

        data = g['DEFS']
        for d in data.split(','):
            pDef = d.split(':')
            if len(pDef) == 1:
                (symbol, dimension_str) = (pDef[0], None)
            elif len(pDef) == 2:
                (symbol, dimension_str) = pDef
            else:
                raise ParsingError("Can't interpret line: %s" % line)

            symbol = symbol.strip()
            dimension_str = (dimension_str.strip() if dimension_str else dimension_str)

            # Allow units to be specified in '{' '}' too. This is hacky and should be better
            # integrated.
            if dimension_str:
                if dimension_str[0] == '{' and dimension_str[-1] == '}':
                    dimension_str = '(' + dimension_str[1:-1] + ')'

            dimension = NeuroUnitParser.Unit(dimension_str) if dimension_str is not None else None
            dimension = dimension.with_no_powerten() if dimension is not None else dimension

            io_data = IODataDimensionSpec(symbol=symbol.strip(),
                    iotype=IOType.LUT[mode], dimension=dimension,
                    metadata=metadata)
            defs.append(io_data)
        return defs

    elif mode == "INITIAL":
        defs = []
        data = g['DEFS']
        for d in data.split(','):
            pDef = d.split(':')

            ic = IODataInitialCondition(symbol=pDef[0], value=pDef[1])
            defs.append(ic)
        return defs
    else:
        raise ParsingError('Unexpected Mode: %s' % mode)
示例#10
0
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#-------------------------------------------------------------------------------

from neurounits import NeuroUnitParser
import quantities as pq
from neurounits.writers.writer_ast_to_simulatable_object import EqnSimulator

es = NeuroUnitParser.EqnSet("""
        EQNSET van_de_pol {
            x' = mu * (x-(x**3)/3 - y)  * {10ms-1}
            y' = x/mu * {10ms-1}
            #mu = 6.0
         <=> PARAMETER mu
         <=> INITIAL x:0
         <=> INITIAL y:0
        }
        """)

#SimulateEquations(es)

#es.to_redoc().to_pdf(filename="/home/michael/Desktop//out1.pdf")

import numpy as np
evaluator = EqnSimulator(es, )

one = es.library_manager.backend.Quantity(1.0,
                                          es.library_manager.backend.Unit())
six = es.library_manager.backend.Quantity(6.0,
library_manager = neurounits.NeuroUnitParser.File(neuron_def)
from neurounits import NeuroUnitParser as P


print library_manager



evaluator = EqnSimulator( library_manager.eqnsets[0] )
res = evaluator(
        time_data = np.linspace(0.0, 0.100, 1000),
        params={
            },
        state0In={
            'V':P.QuantityExpr('-52mV'),
            'm':P.QuantityExpr('0'),
            'h':P.QuantityExpr('0'),
            'kf':P.QuantityExpr('0'),
            'ks':P.QuantityExpr('0'),
            'ca_m':P.QuantityExpr('0'),
            }
        )

print 'Done Simulating'
print res
print res.keys()


#pylab.figure()
#pylab.plot(res['x'], res['y'])
def build_eqnset(chlmlinfo, eqnsetname=None):

    assert type(chlmlinfo) == ChannelMLInfo

    if not eqnsetname:
        eqnsetname = chlmlinfo.name

    unit_mode = {
        'Physiological Units': NeuroMLUnitsMode.Physiological,
        "SI Units": NeuroMLUnitsMode.SI
    }[chlmlinfo.units]

    # Some sanity checks on what is supported:
    # ------------------------------------------
    # Check we are dealing with an IV law, not an IAF type mechanism:
    if chlmlinfo.iv_cond_law and chlmlinfo.iv_cond_law != 'ohmic':
        raise NeuroUnitsImportNeuroMLNotImplementedException(
            "Non-IV Cond law-type Channels")

    if chlmlinfo.iv_default_gmax is None or chlmlinfo.iv_default_erev is None:
        raise NeuroUnitsImportNeuroMLNotImplementedException(
            "Can't find default reversal potentials/conductances")

    if chlmlinfo.unsupported_tags is not None:
        raise NeuroUnitsImportNeuroMLNotImplementedException(
            chlmlinfo.unsupported_tags)

    if chlmlinfo.parameters:
        raise NeuroUnitsImportNeuroMLNotImplementedException(
            "Can't deal with parameters")

    neuroml_dt = {
        NeuroMLUnitsMode.Physiological: "{1ms}",
        NeuroMLUnitsMode.SI: "{1s}",
    }[unit_mode]

    neuroml_v_unit = {
        NeuroMLUnitsMode.Physiological: "{1mV}",
        NeuroMLUnitsMode.SI: "{1V}",
    }[unit_mode]

    eqns = []

    # Build the Q10 Info:
    q10gateadjustments, q10_eqns = build_gate_q10_settings_dict(chlmlinfo)
    eqns.extend(q10_eqns)

    # Build the conductance and current equations:
    eqns.append('%s =  %s * %s' %
                (Name.Conductance, Name.OpenConductance, Name.PropGatesOpen))
    eqns.append('%s =  %s * ( (%s) - (%s) ) ' %
                (Name.MembraneCurrent, Name.Conductance, Name.Voltage,
                 Name.ReversalPotential))

    gate_prop_names = dict([(gate, '%s' % gate.name)
                            for gate in chlmlinfo.gates])
    gate_prop_terms = dict([
        (gate, '*'.join([gate_prop_names[gate]] * gate.instances))
        for gate in chlmlinfo.gates
    ])

    if gate_prop_terms:
        eqns.append('%s = %s' %
                    (Name.PropGatesOpen, '*'.join(gate_prop_terms.values())))
    else:
        eqns.append('%s = 1.0' % (Name.PropGatesOpen))

    # Build Eqns for individual gates:
    for g in chlmlinfo.gates:

        q10tempadjustmentName = q10gateadjustments.get(
            g.name, q10gateadjustments[None])

        # Gate with alpha/beta rate variables specified:
        if g.transitions:
            gate_eqns = _build_gate_alphabetainftau(
                g=g,
                q10tempadjustmentName=q10tempadjustmentName,
                neuroml_dt=neuroml_dt)
            eqns.extend(gate_eqns)

        # Gate specified as an inf-tau value:
        elif len(g.time_courses) == 1 and len(g.steady_states) == 1:
            gate_eqns = _build_gate_inftau(
                g=g,
                q10tempadjustmentName=q10tempadjustmentName,
                neuroml_dt=neuroml_dt)
            eqns.extend(gate_eqns)

        else:
            raise NeuroUnitsImportNeuroMLNotImplementedException(
                'Non-Standard Gate/Transtions')

    #Voltage Offsets:
    vOffset = None
    if chlmlinfo.offset:
        vOffset = "( %f * %s )" % (chlmlinfo.offset, neuroml_v_unit)
    vOffsetTerm = "-%s" % vOffset if vOffset is not None else ""

    # OK, use regular expressions to remap variables
    # to the variable with the unit:
    remaps = [
        lambda e: re.sub(r"""\bcelsius\b""", "(celsius/{1K})", e),
        lambda e: re.sub(r"""\b__VGate__\b""", "((V %s)/%s)" %
                         (vOffsetTerm, neuroml_v_unit), e),
        lambda e: re.sub(r"""\b__V__\b""", "(V)", e),
    ]

    # Apply the remappings:
    for r in remaps:
        eqns = [r(e) for e in eqns]

    io_string = Template("""
    <=> PARAMETER    $OpenConductance : (S/m2)
    <=> PARAMETER    $ReversalPotential : (mV)
    <=> OUTPUT       $MembraneCurrent :(A/m2)    METADATA {"mf":{"role":"TRANSMEMBRANECURRENT"} }
    <=> INPUT        V:(V)       METADATA {"mf":{"role":"MEMBRANEVOLTAGE"} }
    <=> INPUT        $Temperature :(K) METADATA {"mf":{"role":"TEMPERATURE"} } """
                         ).substitute(**Name.__dict__)

    import_string = """
        from std.math import exp
        from std.math import pow
        from std.math import fabs """

    neuroEqn = """
    eqnset %s{
        %s
        %s
        %s
    }""" % (eqnsetname, import_string, "\n\t\t".join(eqns), io_string)

    neuroEqn = "\n".join([l for l in neuroEqn.split("\n") if l.strip()])

    options = NeuroUnitParserOptions(
        allow_unused_parameter_declarations=True,
        allow_unused_suppliedvalue_declarations=True)
    eqnset = NeuroUnitParser.NineMLComponent(text=neuroEqn, options=options)

    default_params = {
        NeuroMLUnitsMode.Physiological: {
            "GMAX":
            NeuroUnitParser.QuantitySimple("%s mS/cm2" %
                                           (chlmlinfo.iv_default_gmax)),
            "VREV":
            NeuroUnitParser.QuantitySimple("%s mV" %
                                           (chlmlinfo.iv_default_erev)),
        },
        NeuroMLUnitsMode.SI: {
            "GMAX":
            NeuroUnitParser.QuantitySimple("%s S/m2" %
                                           (chlmlinfo.iv_default_gmax)),
            "VREV":
            NeuroUnitParser.QuantitySimple("%s V" %
                                           (chlmlinfo.iv_default_erev)),
        },
    }[unit_mode]

    return eqnset, default_params



def cmdline_summarise(args):
	import mredoc
    print 'Summarise'

    
    from neurounits import NeuroUnitParser, MQ1
    from neurounits.nineml_fe.nineml_fe_utils import get_src_9ml_files
    
    src_files = get_src_9ml_files(args)

    # Read all the input files:
    library_manager = NeuroUnitParser.Parse9MLFiles(filenames=src_files)


    print args.what
    if not args.what:
        objs = list(library_manager.objects)
    else:
        objs = [ library_manager.get(name) for name in args.what ]

    summaries = []
    for o in objs:
        print 'Summarising:', repr(o)
        summaries.append( o.to_redoc() )


    summary_obj = mredoc.Section(