예제 #1
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
예제 #2
0
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)
예제 #3
0
def convert_string_to_quantity(s):
    if isinstance(s, basestring):
        return NeuroUnitParser.QuantitySimple(s).as_quantities_quantity()
    else:
        return s
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