Ejemplo n.º 1
0
    def make_multiinstantiate(self, special_properties, name, parameters):
        """
        Adds ComponentType with MultiInstantiate in order to make
        a population of neurons.

        Parameters
        ----------
        special_properties : dict
            all variables to be defined in MultiInstantiate
        name : str
            MultiInstantiate component name
        parameters : dict
            all extra parameters needed
        """
        PARAM_SUBSCRIPT = "_p"
        self._model_namespace["ct_populationname"] = name+"Multi"
        multi_ct = lems.ComponentType(self._model_namespace["ct_populationname"], extends=BASE_POPULATION)
        structure = lems.Structure()
        multi_ins = lems.MultiInstantiate(component_type=name,
                                          number="N")
        param_dict = {}
        # number of neruons
        multi_ct.add(lems.Parameter(name="N", dimension="none"))
        # other parameters
        for sp in special_properties:
            if special_properties[sp] is None:
                multi_ct.add(lems.Parameter(name=sp+PARAM_SUBSCRIPT, dimension=self._all_params_unit[sp]))
                multi_ins.add(lems.Assign(property=sp, value=sp+PARAM_SUBSCRIPT))
                param_dict[sp] = parameters[sp]
            else:
                # multi_ct.add(lems.Parameter(name=sp, dimension=self._all_params_unit[sp]))
                # check if there are some units in equations
                equation = special_properties[sp]
                # add spaces around brackets to prevent mismatching
                equation = re.sub("\(", " ( ", equation)
                equation = re.sub("\)", " ) ", equation)
                for i in get_identifiers(equation):
                    # iterator is a special case
                    if i == "i":
                        regexp_noletter = "[^a-zA-Z0-9]"
                        equation = re.sub("{re}i{re}".format(re=regexp_noletter),
                                                  " {} ".format(INDEX), equation)
                    # here it's assumed that we don't use Netwton in neuron models
                    elif i in name_to_unit and i != "N":
                        const_i = i+'const'
                        multi_ct.add(lems.Constant(name=const_i, symbol=const_i,
                                     dimension=self._all_params_unit[sp], value="1"+i))
                        equation = re.sub(i, const_i, equation)
                multi_ins.add(lems.Assign(property=sp, value=equation))
        structure.add(multi_ins)
        multi_ct.structure = structure
        self._model.add(multi_ct)
        param_dict = dict([(k+"_p", v) for k, v in param_dict.items()])
        param_dict["N"] = self._nr_of_neurons
        self._model_namespace["populationname"] = self._model_namespace["ct_populationname"] + "pop"
        self._model_namespace["networkname"] = self._model_namespace["ct_populationname"] + "Net"
        self.add_population(self._model_namespace["networkname"],
                            self._model_namespace["populationname"],
                            self._model_namespace["ct_populationname"],
                            **param_dict)
Ejemplo n.º 2
0
 def _determine_parameters(self, paramdict):
     """
     Iterator giving `lems.Parameter` for every parameter from *paramdict*.
     """
     for var in paramdict:
         if is_dimensionless(paramdict[var]):
             self._all_params_unit[var] = "none"
             yield lems.Parameter(var, "none")
         else:
             dim = _determine_dimension(paramdict[var])
             self._all_params_unit[var] = dim
             yield lems.Parameter(var, dim)
def build_lems_for_model(src):
    model = lems.Model()

    model.add(lems.Dimension('time', t=1))
    # model.add(lems.Dimension('au'))

    # primary element of the model is a mass model component
    mass = lems.ComponentType(src.name, extends="baseCellMembPot")
    model.add(mass)
    
    ######### Adding v is required to ease mapping to NEURON...
    mass.dynamics.add(lems.StateVariable(name="v", dimension="voltage", exposure="v"))
    
    mass.add(lems.Attachments(name="synapses",type_="basePointCurrentDL"))
    

    for input in src.input:
        mass.dynamics.add(lems.DerivedVariable(name=input, 
                                               dimension='none',
                                               exposure=input,
                                               select='synapses[*]/I',
                                               reduce='add'))
        mass.add(lems.Exposure(input, 'none'))
        
        
    for key, val in src.const.items():
        mass.add(lems.Parameter(key, 'none'))  # TODO units
        
    
        
    mass.add(lems.Constant(name="MSEC", dimension="time", value="1ms"))
    mass.add(lems.Constant(name="PI", dimension="none", value="3.14159265359"))

    states = []
    der_vars = []
    # for key in src.param:
    #     mass.add(lems.Parameter(key, 'au'))  # TODO units

    for key, val in src.auxex:
        val = val.replace('**', '^')
        mass.dynamics.add(lems.DerivedVariable(key, value=val))

    for key in src.obsrv:
        name_dv = key.replace('(','_').replace(')','').replace(' - ','_min_')
        mass.dynamics.add(lems.DerivedVariable(name_dv, value=key, exposure=name_dv))
        mass.add(lems.Exposure(name_dv, 'none'))

    for src_svar in src.state_space:
        name = src_svar.name
        ddt = src_svar.drift.replace('**', '^')
        mass.dynamics.add(lems.StateVariable(name, 'none', name))
        mass.dynamics.add(lems.TimeDerivative(name, '(%s)/MSEC'%ddt))
        mass.add(lems.Exposure(name, 'none'))
        
    ''' On condition is not need on the model but NeuroML requires its definition -->
            <OnCondition test="r .lt. 0">
                <EventOut port="spike"/>
            </OnCondition>'''
            
    oc = lems.OnCondition(test='v .gt. 0')
    oc.actions.append(lems.EventOut(port='spike'))
    mass.dynamics.add(oc)

    return model
Ejemplo n.º 4
0
import lems.api as lems

model = lems.Model()

model.add(lems.Dimension('voltage', m=1, l=3, t=-3, i=-1))
model.add(lems.Dimension('time', t=1))
model.add(lems.Dimension('capacitance', m=-1, l=-2, t=4, i=2))

model.add(lems.Unit('milliVolt', 'mV', 'voltage', -3))
model.add(lems.Unit('milliSecond', 'ms', 'time', -3))
model.add(lems.Unit('microFarad', 'uF', 'capacitance', -12))

iaf1 = lems.ComponentType('iaf1')
model.add(iaf1)

iaf1.add(lems.Parameter('threshold', 'voltage'))
iaf1.add(lems.Parameter('reset', 'voltage'))
iaf1.add(lems.Parameter('refractoryPeriod', 'time'))
iaf1.add(lems.Parameter('capacitance', 'capacitance'))
iaf1.add(lems.Exposure('vexp', 'voltage'))
dp = lems.DerivedParameter('range', 'threshold - reset', 'voltage')
iaf1.add(dp)

iaf1.dynamics.add(lems.StateVariable('v','voltage', 'vexp')) 
iaf1.dynamics.add(lems.DerivedVariable('v2',dimension='voltage', value='v*2'))
cdv = lems.ConditionalDerivedVariable('v_abs','voltage')
cdv.add(lems.Case('v .geq. 0','v'))
cdv.add(lems.Case('v .lt. 0','-1*v'))
iaf1.dynamics.add(cdv)

Ejemplo n.º 5
0
model.add(lems.Dimension(name="time", t=1))
model.add(lems.Unit(name="second", symbol="s", dimension="time", power=1))
model.add(
    lems.Unit(name="milli second", symbol="ms", dimension="time", power=-3))

lorenz = lems.ComponentType(
    name="lorenz1963",
    description=
    "The Lorenz system is a simplified model for atomspheric convection, derived from the Navier Stokes equations"
)
model.add(lorenz)

lorenz.add(
    lems.Parameter(name="sigma",
                   dimension="none",
                   description="Prandtl Number"))
lorenz.add(
    lems.Parameter(name="beta",
                   dimension="none",
                   description="Also named b elsewhere"))
lorenz.add(
    lems.Parameter(
        name="rho",
        dimension="none",
        description="Related to the Rayleigh number, also named r elsewhere"))

lorenz.add(lems.Parameter(name="x0", dimension="none"))
lorenz.add(lems.Parameter(name="y0", dimension="none"))
lorenz.add(lems.Parameter(name="z0", dimension="none"))
Ejemplo n.º 6
0
def mdf_to_neuroml(graph, save_to=None, format=None, run_duration_sec=2):

    print("Converting graph: %s to NeuroML" % (graph.id))

    net = neuromllite.Network(id=graph.id)
    net.notes = "NeuroMLlite export of {} graph: {}".format(
        format if format else "MDF",
        graph.id,
    )

    model = lems.Model()
    lems_definitions = "%s_lems_definitions.xml" % graph.id

    for node in graph.nodes:
        print("    Node: %s" % node.id)

        node_comp_type = "%s__definition" % node.id
        node_comp = "%s__instance" % node.id

        # Create the ComponentType which defines behaviour of the general class
        ct = lems.ComponentType(node_comp_type, extends="baseCellMembPotDL")
        ct.add(lems.Attachments("only_input_port", "basePointCurrentDL"))
        ct.dynamics.add(
            lems.DerivedVariable(name="V",
                                 dimension="none",
                                 value="0",
                                 exposure="V"))
        model.add(ct)

        # Define the Component - an instance of the ComponentType
        comp = lems.Component(node_comp, node_comp_type)
        model.add(comp)

        cell = neuromllite.Cell(id=node_comp,
                                lems_source_file=lems_definitions)
        net.cells.append(cell)

        pop = neuromllite.Population(
            id=node.id,
            size=1,
            component=cell.id,
            properties={
                "color": "0.2 0.2 0.2",
                "radius": 3
            },
        )
        net.populations.append(pop)

        if len(node.input_ports) > 1:
            raise Exception(
                "Currently only max 1 input port supported in NeuroML...")

        for ip in node.input_ports:
            ct.add(lems.Exposure(ip.id, "none"))
            ct.dynamics.add(
                lems.DerivedVariable(
                    name=ip.id,
                    dimension="none",
                    select="only_input_port[*]/I",
                    reduce="add",
                    exposure=ip.id,
                ))

        on_start = None

        for p in node.parameters:
            print("Converting %s" % p)
            if p.value is not None:
                try:
                    v_num = float(p.value)
                    ct.add(lems.Parameter(p.id, "none"))
                    comp.parameters[p.id] = v_num
                    print(comp.parameters[p.id])
                except Exception as e:

                    ct.add(lems.Exposure(p.id, "none"))
                    dv = lems.DerivedVariable(
                        name=p.id,
                        dimension="none",
                        value="%s" % (p.value),
                        exposure=p.id,
                    )
                    ct.dynamics.add(dv)

            elif p.function is not None:
                ct.add(lems.Exposure(p.id, "none"))
                func_info = mdf_functions[p.function]
                expr = func_info["expression_string"]
                expr2 = substitute_args(expr, p.args)
                for arg in p.args:
                    expr += ";{}={}".format(arg, p.args[arg])
                dv = lems.DerivedVariable(name=p.id,
                                          dimension="none",
                                          value="%s" % (expr2),
                                          exposure=p.id)
                ct.dynamics.add(dv)
            else:
                ct.add(lems.Exposure(p.id, "none"))
                ct.dynamics.add(
                    lems.StateVariable(name=p.id,
                                       dimension="none",
                                       exposure=p.id))
                if p.default_initial_value:
                    if on_start is None:
                        on_start = lems.OnStart()
                        ct.dynamics.add(on_start)
                    sa = lems.StateAssignment(
                        variable=p.id,
                        value=str(evaluate_expr(p.default_initial_value)))
                    on_start.actions.append(sa)

                if p.time_derivative:
                    td = lems.TimeDerivative(variable=p.id,
                                             value=p.time_derivative)
                    ct.dynamics.add(td)

        if len(node.output_ports) > 1:
            raise Exception(
                "Currently only max 1 output port supported in NeuroML...")

        for op in node.output_ports:
            ct.add(lems.Exposure(op.id, "none"))
            ct.dynamics.add(
                lems.DerivedVariable(name=op.id,
                                     dimension="none",
                                     value=op.value,
                                     exposure=op.id))
            only_output_port = "only_output_port"
            ct.add(lems.Exposure(only_output_port, "none"))
            ct.dynamics.add(
                lems.DerivedVariable(
                    name=only_output_port,
                    dimension="none",
                    value=op.id,
                    exposure=only_output_port,
                ))

    if len(graph.edges) > 0:

        model.add(
            lems.Include(
                os.path.join(os.path.dirname(__file__),
                             "syn_definitions.xml")))
        rsDL = neuromllite.Synapse(id="rsDL",
                                   lems_source_file=lems_definitions)
        net.synapses.append(rsDL)
        # syn_id = 'silentSyn'
        # silentSynDL = neuromllite.Synapse(id=syn_id, lems_source_file=lems_definitions)

    for edge in graph.edges:
        print(f"    Edge: {edge.id} connects {edge.sender} to {edge.receiver}")

        ssyn_id = "silentSyn_proj_%s" % edge.id
        ssyn_id = "silentSyn_proj_%s" % edge.id
        # ssyn_id = 'silentSynX'
        silentDLin = neuromllite.Synapse(id=ssyn_id,
                                         lems_source_file=lems_definitions)

        model.add(lems.Component(ssyn_id, "silentRateSynapseDL"))

        net.synapses.append(silentDLin)

        net.projections.append(
            neuromllite.Projection(
                id="proj_%s" % edge.id,
                presynaptic=edge.sender,
                postsynaptic=edge.receiver,
                synapse=rsDL.id,
                pre_synapse=silentDLin.id,
                type="continuousProjection",
                weight=1,
                random_connectivity=neuromllite.RandomConnectivity(
                    probability=1),
            ))

    # Much more todo...
    model.export_to_file(lems_definitions)

    print("Nml net: %s" % net)
    if save_to:
        new_file = net.to_json_file(save_to)
        print("Saved NML to: %s" % save_to)

    ################################################################################
    ###   Build Simulation object & save as JSON

    simtime = 1000 * run_duration_sec
    dt = 0.1
    sim = neuromllite.Simulation(
        id="Sim%s" % net.id,
        network=new_file,
        duration=simtime,
        dt=dt,
        seed=123,
        recordVariables={"OUTPUT": {
            "all": "*"
        }},
    )

    recordVariables = {}
    for node in graph.nodes:
        for ip in node.input_ports:
            if not ip.id in recordVariables:
                recordVariables[ip.id] = {}
            recordVariables[ip.id][node.id] = 0

        for p in node.parameters:
            if p.is_stateful():
                if not p.id in recordVariables:
                    recordVariables[p.id] = {}
                recordVariables[p.id][node.id] = 0

        for op in node.output_ports:
            if not op.id in recordVariables:
                recordVariables[op.id] = {}
            recordVariables[op.id][node.id] = 0

    sim.recordVariables = recordVariables
    if save_to:
        sf = sim.to_json_file()

        print("Saved Simulation to: %s" % sf)

    return net, sim