Ejemplo n.º 1
0
def generateLEMS(population, n_units, max_amplitude, min_amplitude):
    def generatePulse(population, idx, amplitude):
        pulse = PulseGenerator(id='baseline_%s%d' % (population, idx),
                               delay='0ms',
                               duration='200ms',
                               amplitude='%.02f pA' % amplitude)
        nml_doc.pulse_generators.append(pulse)

    def generatePopulation(population, n_units, net):
        population_uc = population.upper()
        pop = Population(id='%sPop' % population,
                         component='%s' % population_uc,
                         size=n_units)
        net.populations.append(pop)

    def generateExmplicitInput(population, idx, net):
        exp_input = ExplicitInput(target='%sPop[%d]' % (population, idx),
                                  input='baseline_%s%d' % (population, idx),
                                  destination='synapses')
        net.explicit_inputs.append(exp_input)

    nml_doc = NeuroMLDocument(id='fI_%s' % population)

    # Add silent synapsis
    silent_syn = SilentSynapse(id='silent1_%s' % population)
    nml_doc.silent_synapses.append(silent_syn)

    step = (max_amplitude - min_amplitude) / n_units
    amplitudes = np.arange(min_amplitude, max_amplitude, step)

    net = Network(id='net_%s' % population)
    nml_doc.networks.append(net)
    generatePopulation('%s' % population, n_units, net)

    for idx, amplitude in enumerate(amplitudes):
        generatePulse('%s' % population, idx, amplitude)

        generateExmplicitInput('%s' % population, idx, net)

    # Write to file
    nml_file = 'fI_%s.nml' % population
    writers.NeuroMLWriter.write(nml_doc, nml_file)
    print('Written network file to: %s' % nml_file)

    # Validate the NeuroML
    from neuroml.utils import validate_neuroml2
    validate_neuroml2(nml_file)
Ejemplo n.º 2
0
def generate(net_id,
             params,
             cells=None,
             cells_to_plot=None,
             cells_to_stimulate=None,
             include_muscles=False,
             conn_number_override=None,
             conn_number_scaling=None,
             duration=500,
             dt=0.01,
             vmin=None,
             vmax=None,
             seed=1234,
             validate=True,
             test=False,
             verbose=True,
             target_directory='./'):

    root_dir = os.path.dirname(os.path.abspath(__file__))

    params.create_models()

    if vmin == None:
        if params.level == 'A':
            vmin = -72
        elif params.level == 'B':
            vmin = -52
        elif params.level == 'C':
            vmin = -60
        else:
            vmin = -52

    if vmax == None:
        if params.level == 'A':
            vmax = -48
        elif params.level == 'B':
            vmax = -28
        elif params.level == 'C':
            vmax = 25
        else:
            vmax = -28

    random.seed(seed)

    info = "\n\nParameters and setting used to generate this network:\n\n"+\
           "    Cells:                         %s\n" % (cells if cells is not None else "All cells")+\
           "    Cell stimulated:               %s\n" % (cells_to_stimulate if cells_to_stimulate is not None else "All cells")+\
           "    Connection numbers overridden: %s\n" % (conn_number_override if conn_number_override is not None else "None")+\
           "    Connection numbers scaled:     %s\n" % (conn_number_scaling if conn_number_scaling is not None else "None")+\
           "    Include muscles:               %s\n" % include_muscles
    print_(info)
    info += "\n%s\n" % (params.bioparameter_info("    "))

    nml_doc = NeuroMLDocument(id=net_id, notes=info)

    if params.level == "A" or params.level == "B" or params.level == "BC1":
        nml_doc.iaf_cells.append(params.generic_muscle_cell)
        nml_doc.iaf_cells.append(params.generic_neuron_cell)
    elif params.level == "C":
        nml_doc.cells.append(params.generic_muscle_cell)
        nml_doc.cells.append(params.generic_neuron_cell)

    net = Network(id=net_id)

    nml_doc.networks.append(net)

    nml_doc.pulse_generators.append(params.offset_current)

    if params.level == "C" or params.level == "C1":
        nml_doc.fixed_factor_concentration_models.append(
            params.concentration_model)

    cell_names, conns = get_cell_names_and_connection()

    # To hold all Cell NeuroML objects vs. names
    all_cells = {}

    # lems_file = ""
    lems_info = {
        "comment": info,
        "reference": net_id,
        "duration": duration,
        "dt": dt,
        "vmin": vmin,
        "vmax": vmax,
        "cell_component": params.generic_neuron_cell.id
    }

    lems_info["plots"] = []
    lems_info["activity_plots"] = []
    lems_info["muscle_plots"] = []
    lems_info["muscle_activity_plots"] = []

    lems_info["to_save"] = []
    lems_info["activity_to_save"] = []
    lems_info["muscles_to_save"] = []
    lems_info["muscles_activity_to_save"] = []
    lems_info["cells"] = []
    lems_info["muscles"] = []
    lems_info["includes"] = []

    if params.custom_component_types_definitions:
        lems_info["includes"].append(params.custom_component_types_definitions)
        if target_directory != './':
            def_file = "%s/%s" % (os.path.dirname(os.path.abspath(__file__)),
                                  params.custom_component_types_definitions)
            shutil.copy(def_file, target_directory)
        nml_doc.includes.append(
            IncludeType(href=params.custom_component_types_definitions))

    backers_dir = root_dir + "/../../../../OpenWormBackers/" if test else root_dir + "/../../../OpenWormBackers/"
    sys.path.append(backers_dir)
    import backers
    cells_vs_name = backers.get_adopted_cell_names(backers_dir)

    populations_without_location = False  # isinstance(params.elec_syn, GapJunction)

    count = 0
    for cell in cell_names:

        if cells is None or cell in cells:

            inst = Instance(id="0")

            if not populations_without_location:
                # build a Population data structure out of the cell name
                pop0 = Population(id=cell,
                                  component=params.generic_neuron_cell.id,
                                  type="populationList")
                pop0.instances.append(inst)

            else:
                # build a Population data structure out of the cell name
                pop0 = Population(id=cell,
                                  component=params.generic_neuron_cell.id,
                                  size="1")

            # put that Population into the Network data structure from above
            net.populations.append(pop0)

            if cells_vs_name.has_key(cell):
                p = Property(tag="OpenWormBackerAssignedName",
                             value=cells_vs_name[cell])
                pop0.properties.append(p)

            # also use the cell name to grab the morphology file, as a NeuroML data structure
            #  into the 'all_cells' dict
            cell_file_path = root_dir + "/../../../" if test else root_dir + "/../../"  #if running test
            cell_file = cell_file_path + 'generatedNeuroML2/%s.cell.nml' % cell
            doc = loaders.NeuroMLLoader.load(cell_file)
            all_cells[cell] = doc.cells[0]
            location = doc.cells[0].morphology.segments[0].proximal
            if verbose:
                print_(
                    "Loaded morphology: %s; id: %s; location: (%s, %s, %s)" %
                    (os.path.realpath(cell_file), all_cells[cell].id,
                     location.x, location.y, location.z))

            inst.location = Location(float(location.x), float(location.y),
                                     float(location.z))

            target = "../%s/0/%s" % (pop0.id, params.generic_neuron_cell.id)
            if populations_without_location:
                target = "../%s[0]" % (cell)

            if cells_to_stimulate is None or cell in cells_to_stimulate:
                input_list = InputList(id="Input_%s_%s" %
                                       (cell, params.offset_current.id),
                                       component=params.offset_current.id,
                                       populations='%s' % cell)

                input_list.input.append(
                    Input(id=0, target=target, destination="synapses"))

                net.input_lists.append(input_list)

            if cells_to_plot is None or cell in cells_to_plot:
                plot = {}

                plot["cell"] = cell
                plot["colour"] = get_random_colour_hex()
                plot["quantity"] = "%s/0/%s/v" % (
                    cell, params.generic_neuron_cell.id)
                if populations_without_location:
                    plot["quantity"] = "%s[0]/v" % (cell)
                lems_info["plots"].append(plot)

                if params.generic_neuron_cell.__class__.__name__ == 'IafActivityCell':
                    plot = {}

                    plot["cell"] = cell
                    plot["colour"] = get_random_colour_hex()
                    plot["quantity"] = "%s/0/%s/activity" % (
                        cell, params.generic_neuron_cell.id)
                    if populations_without_location:
                        plot["quantity"] = "%s[0]/activity" % (cell)
                    lems_info["activity_plots"].append(plot)

                if params.generic_neuron_cell.__class__.__name__ == 'Cell':
                    plot = {}

                    plot["cell"] = cell
                    plot["colour"] = get_random_colour_hex()
                    plot["quantity"] = "%s/0/%s/caConc" % (
                        cell, params.generic_neuron_cell.id)
                    if populations_without_location:
                        plot["quantity"] = "%s[0]/caConc" % (cell)
                    lems_info["activity_plots"].append(plot)

            save = {}
            save["cell"] = cell
            save["quantity"] = "%s/0/%s/v" % (cell,
                                              params.generic_neuron_cell.id)
            if populations_without_location:
                save["quantity"] = "%s[0]/v" % (cell)
            lems_info["to_save"].append(save)

            if params.generic_neuron_cell.__class__.__name__ == 'IafActivityCell':
                save = {}
                save["cell"] = cell
                save["quantity"] = "%s/0/%s/activity" % (
                    cell, params.generic_neuron_cell.id)
                if populations_without_location:
                    save["quantity"] = "%s[0]/activity" % (cell)
                lems_info["activity_to_save"].append(save)
            if params.generic_neuron_cell.__class__.__name__ == 'Cell':
                save = {}
                save["cell"] = cell
                save["quantity"] = "%s/0/%s/caConc" % (
                    cell, params.generic_neuron_cell.id)
                if populations_without_location:
                    save["quantity"] = "%s[0]/caConc" % (cell)
                lems_info["activity_to_save"].append(save)

            lems_info["cells"].append(cell)

            count += 1

    if verbose:
        print_("Finished loading %i cells" % count)

    mneurons, all_muscles, muscle_conns = get_cell_muscle_names_and_connection(
    )

    muscles = get_muscle_names()

    if include_muscles:

        muscle_count = 0
        for muscle in muscles:

            inst = Instance(id="0")

            if not populations_without_location:
                # build a Population data structure out of the cell name
                pop0 = Population(id=muscle,
                                  component=params.generic_muscle_cell.id,
                                  type="populationList")
                pop0.instances.append(inst)

            else:
                # build a Population data structure out of the cell name
                pop0 = Population(id=muscle,
                                  component=params.generic_muscle_cell.id,
                                  size="1")

            # put that Population into the Network data structure from above
            net.populations.append(pop0)

            if cells_vs_name.has_key(muscle):
                # No muscles adopted yet, but just in case they are in future...
                p = Property(tag="OpenWormBackerAssignedName",
                             value=cells_vs_name[muscle])
                pop0.properties.append(p)

            x = 80 * (-1 if muscle[1] == 'V' else 1)
            z = 80 * (-1 if muscle[2] == 'L' else 1)
            y = -300 + 30 * int(muscle[3:5])
            print_('Positioning muscle: %s at (%s,%s,%s)' % (muscle, x, y, z))
            inst.location = Location(x, y, z)

            target = "%s/0/%s" % (pop0.id, params.generic_muscle_cell.id)
            if populations_without_location:
                target = "%s[0]" % (muscle)

            plot = {}

            plot["cell"] = muscle
            plot["colour"] = get_random_colour_hex()
            plot["quantity"] = "%s/0/%s/v" % (muscle,
                                              params.generic_muscle_cell.id)
            if populations_without_location:
                plot["quantity"] = "%s[0]/v" % (muscle)
            lems_info["muscle_plots"].append(plot)

            if params.generic_muscle_cell.__class__.__name__ == 'IafActivityCell':
                plot = {}

                plot["cell"] = muscle
                plot["colour"] = get_random_colour_hex()
                plot["quantity"] = "%s/0/%s/activity" % (
                    muscle, params.generic_muscle_cell.id)
                if populations_without_location:
                    plot["quantity"] = "%s[0]/activity" % (muscle)
                lems_info["muscle_activity_plots"].append(plot)

            if params.generic_muscle_cell.__class__.__name__ == 'Cell':
                plot = {}

                plot["cell"] = muscle
                plot["colour"] = get_random_colour_hex()
                plot["quantity"] = "%s/0/%s/caConc" % (
                    muscle, params.generic_muscle_cell.id)
                if populations_without_location:
                    plot["quantity"] = "%s[0]/caConc" % (muscle)
                lems_info["muscle_activity_plots"].append(plot)

            save = {}
            save["cell"] = muscle
            save["quantity"] = "%s/0/%s/v" % (muscle,
                                              params.generic_muscle_cell.id)
            if populations_without_location:
                save["quantity"] = "%s[0]/v" % (muscle)
            lems_info["muscles_to_save"].append(save)

            if params.generic_muscle_cell.__class__.__name__ == 'IafActivityCell':
                save = {}
                save["cell"] = muscle
                save["quantity"] = "%s/0/%s/activity" % (
                    muscle, params.generic_muscle_cell.id)
                if populations_without_location:
                    save["quantity"] = "%s[0]/activity" % (muscle)
                lems_info["muscles_activity_to_save"].append(save)
            if params.generic_muscle_cell.__class__.__name__ == 'Cell':
                save = {}
                save["cell"] = muscle
                save["quantity"] = "%s/0/%s/caConc" % (
                    muscle, params.generic_muscle_cell.id)
                if populations_without_location:
                    save["quantity"] = "%s[0]/caConc" % (muscle)
                lems_info["muscles_activity_to_save"].append(save)

            lems_info["muscles"].append(muscle)

            muscle_count += 1

        if verbose:
            print_("Finished creating %i muscles" % muscle_count)

    existing_synapses = {}

    for conn in conns:

        if conn.pre_cell in lems_info["cells"] and conn.post_cell in lems_info[
                "cells"]:
            # take information about each connection and package it into a
            # NeuroML Projection data structure
            proj_id = get_projection_id(conn.pre_cell, conn.post_cell,
                                        conn.synclass, conn.syntype)

            elect_conn = False
            analog_conn = False
            syn0 = params.neuron_to_neuron_exc_syn
            if 'GABA' in conn.synclass:
                syn0 = params.neuron_to_neuron_inh_syn
            if '_GJ' in conn.synclass:
                syn0 = params.neuron_to_neuron_elec_syn
                elect_conn = isinstance(params.neuron_to_neuron_elec_syn,
                                        GapJunction)

            if isinstance(syn0, GradedSynapse):
                analog_conn = True
                if len(nml_doc.silent_synapses) == 0:
                    silent = SilentSynapse(id="silent")
                    nml_doc.silent_synapses.append(silent)

            number_syns = conn.number
            conn_shorthand = "%s-%s" % (conn.pre_cell, conn.post_cell)

            if conn_number_override is not None and (
                    conn_number_override.has_key(conn_shorthand)):
                number_syns = conn_number_override[conn_shorthand]
            elif conn_number_scaling is not None and (
                    conn_number_scaling.has_key(conn_shorthand)):
                number_syns = conn.number * conn_number_scaling[conn_shorthand]
            '''
            else:
                print conn_shorthand
                print conn_number_override
                print conn_number_scaling'''

            if number_syns != conn.number:
                magnitude, unit = bioparameters.split_neuroml_quantity(
                    syn0.gbase)
                cond0 = "%s%s" % (magnitude * conn.number, unit)
                cond1 = "%s%s" % (magnitude * number_syns, unit)
                if verbose:
                    print_(">> Changing number of effective synapses connection %s -> %s: was: %s (total cond: %s), becomes %s (total cond: %s)" % \
                     (conn.pre_cell, conn.post_cell, conn.number, cond0, number_syns, cond1))

            syn_new = create_n_connection_synapse(syn0, number_syns, nml_doc,
                                                  existing_synapses)

            if elect_conn:

                if populations_without_location:
                    proj0 = ElectricalProjection(id=proj_id, \
                                       presynaptic_population=conn.pre_cell,
                                       postsynaptic_population=conn.post_cell)

                    net.electrical_projections.append(proj0)

                    # Add a Connection with the closest locations
                    conn0 = ElectricalConnection(id="0", \
                               pre_cell="0",
                               post_cell="0",
                               synapse=syn_new.id)

                    proj0.electrical_connections.append(conn0)
                else:
                    proj0 = ElectricalProjection(id=proj_id, \
                                       presynaptic_population=conn.pre_cell,
                                       postsynaptic_population=conn.post_cell)

                    net.electrical_projections.append(proj0)

                    pre_cell_id = "../%s/0/%s" % (
                        conn.pre_cell, params.generic_neuron_cell.id)
                    post_cell_id = "../%s/0/%s" % (
                        conn.post_cell, params.generic_neuron_cell.id)

                    #print_("Conn %s -> %s"%(pre_cell_id,post_cell_id))

                    # Add a Connection with the closest locations
                    conn0 = ElectricalConnectionInstance(id="0", \
                               pre_cell=pre_cell_id,
                               post_cell=post_cell_id,
                               synapse=syn_new.id)

                    proj0.electrical_connection_instances.append(conn0)

            elif analog_conn:

                proj0 = ContinuousProjection(id=proj_id, \
                                   presynaptic_population=conn.pre_cell,
                                   postsynaptic_population=conn.post_cell)

                net.continuous_projections.append(proj0)

                pre_cell_id = "../%s/0/%s" % (conn.pre_cell,
                                              params.generic_neuron_cell.id)
                post_cell_id = "../%s/0/%s" % (conn.post_cell,
                                               params.generic_neuron_cell.id)

                conn0 = ContinuousConnectionInstance(id="0", \
                           pre_cell=pre_cell_id,
                           post_cell=post_cell_id,
                           pre_component="silent",
                           post_component=syn_new.id)

                proj0.continuous_connection_instances.append(conn0)

            else:

                if not populations_without_location:
                    proj0 = Projection(id=proj_id, \
                                       presynaptic_population=conn.pre_cell,
                                       postsynaptic_population=conn.post_cell,
                                       synapse=syn_new.id)

                    net.projections.append(proj0)

                    pre_cell_id = "../%s/0/%s" % (
                        conn.pre_cell, params.generic_neuron_cell.id)
                    post_cell_id = "../%s/0/%s" % (
                        conn.post_cell, params.generic_neuron_cell.id)

                    conn0 = ConnectionWD(id="0", \
                               pre_cell_id=pre_cell_id,
                               post_cell_id=post_cell_id,
                               weight = number_syns,
                               delay = '0ms')

                    proj0.connection_wds.append(conn0)

                if populations_without_location:
                    raise NotImplementedError
                    '''
                    #         <synapticConnection from="hh1pop[0]" to="hh2pop[0]" synapse="syn1exp" destination="synapses"/>
                    pre_cell_id="%s[0]"%(conn.pre_cell)
                    post_cell_id="%s[0]"%(conn.post_cell)

                    conn0 = SynapticConnection(from_=pre_cell_id,
                               to=post_cell_id,
                               synapse=syn_new.id,
                               destination="synapses")

                    net.synaptic_connections.append(conn0)'''

    if include_muscles:
        for conn in muscle_conns:

            if conn.pre_cell in lems_info[
                    "cells"] and conn.post_cell in muscles:
                # take information about each connection and package it into a
                # NeuroML Projection data structure
                proj_id = get_projection_id(conn.pre_cell, conn.post_cell,
                                            conn.synclass, conn.syntype)

                elect_conn = False
                analog_conn = False
                syn0 = params.neuron_to_muscle_exc_syn
                if 'GABA' in conn.synclass:
                    syn0 = params.neuron_to_muscle_inh_syn
                if '_GJ' in conn.synclass:
                    syn0 = params.neuron_to_muscle_elec_syn
                    elect_conn = isinstance(params.neuron_to_muscle_elec_syn,
                                            GapJunction)

                if isinstance(syn0, GradedSynapse):
                    analog_conn = True
                    if len(nml_doc.silent_synapses) == 0:
                        silent = SilentSynapse(id="silent")
                        nml_doc.silent_synapses.append(silent)

                number_syns = conn.number
                conn_shorthand = "%s-%s" % (conn.pre_cell, conn.post_cell)

                if conn_number_override is not None and (
                        conn_number_override.has_key(conn_shorthand)):
                    number_syns = conn_number_override[conn_shorthand]
                elif conn_number_scaling is not None and (
                        conn_number_scaling.has_key(conn_shorthand)):
                    number_syns = conn.number * conn_number_scaling[
                        conn_shorthand]
                '''
            else:
                print conn_shorthand
                print conn_number_override
                print conn_number_scaling'''

                if number_syns != conn.number:
                    magnitude, unit = bioparameters.split_neuroml_quantity(
                        syn0.gbase)
                    cond0 = "%s%s" % (magnitude * conn.number, unit)
                    cond1 = "%s%s" % (magnitude * number_syns, unit)
                    if verbose:
                        print_(">> Changing number of effective synapses connection %s -> %s: was: %s (total cond: %s), becomes %s (total cond: %s)" % \
                         (conn.pre_cell, conn.post_cell, conn.number, cond0, number_syns, cond1))

                syn_new = create_n_connection_synapse(syn0, number_syns,
                                                      nml_doc,
                                                      existing_synapses)

                if elect_conn:

                    if populations_without_location:
                        proj0 = ElectricalProjection(id=proj_id, \
                                           presynaptic_population=conn.pre_cell,
                                           postsynaptic_population=conn.post_cell)

                        net.electrical_projections.append(proj0)

                        # Add a Connection with the closest locations
                        conn0 = ElectricalConnection(id="0", \
                                   pre_cell="0",
                                   post_cell="0",
                                   synapse=syn_new.id)

                        proj0.electrical_connections.append(conn0)
                    else:
                        proj0 = ElectricalProjection(id=proj_id, \
                                           presynaptic_population=conn.pre_cell,
                                           postsynaptic_population=conn.post_cell)

                        net.electrical_projections.append(proj0)

                        pre_cell_id = "../%s/0/%s" % (
                            conn.pre_cell, params.generic_neuron_cell.id)
                        post_cell_id = "../%s/0/%s" % (
                            conn.post_cell, params.generic_muscle_cell.id)

                        #print_("Conn %s -> %s"%(pre_cell_id,post_cell_id))

                        # Add a Connection with the closest locations
                        conn0 = ElectricalConnectionInstance(id="0", \
                                   pre_cell=pre_cell_id,
                                   post_cell=post_cell_id,
                                   synapse=syn_new.id)

                        proj0.electrical_connection_instances.append(conn0)

                elif analog_conn:

                    proj0 = ContinuousProjection(id=proj_id, \
                                       presynaptic_population=conn.pre_cell,
                                       postsynaptic_population=conn.post_cell)

                    net.continuous_projections.append(proj0)

                    pre_cell_id = "../%s/0/%s" % (
                        conn.pre_cell, params.generic_neuron_cell.id)
                    post_cell_id = "../%s/0/%s" % (
                        conn.post_cell, params.generic_muscle_cell.id)

                    conn0 = ContinuousConnectionInstance(id="0", \
                               pre_cell=pre_cell_id,
                               post_cell=post_cell_id,
                               pre_component="silent",
                               post_component=syn_new.id)

                    proj0.continuous_connection_instances.append(conn0)

                else:

                    if not populations_without_location:
                        proj0 = Projection(id=proj_id, \
                                           presynaptic_population=conn.pre_cell,
                                           postsynaptic_population=conn.post_cell,
                                           synapse=syn_new.id)

                        net.projections.append(proj0)

                        # Add a Connection with the closest locations

                        pre_cell_id = "../%s/0/%s" % (
                            conn.pre_cell, params.generic_neuron_cell.id)
                        post_cell_id = "../%s/0/%s" % (
                            conn.post_cell, params.generic_muscle_cell.id)

                        conn0 = Connection(id="0", \
                                   pre_cell_id=pre_cell_id,
                                   post_cell_id=post_cell_id)

                        proj0.connections.append(conn0)

                    if populations_without_location:
                        #         <synapticConnection from="hh1pop[0]" to="hh2pop[0]" synapse="syn1exp" destination="synapses"/>
                        pre_cell_id = "%s[0]" % (conn.pre_cell)
                        post_cell_id = "%s[0]" % (conn.post_cell)

                        conn0 = SynapticConnection(from_=pre_cell_id,
                                                   to=post_cell_id,
                                                   synapse=syn_new.id,
                                                   destination="synapses")

                        net.synaptic_connections.append(conn0)

    # import pprint
    # pprint.pprint(lems_info)
    template_path = root_dir + '/../' if test else root_dir + '/'  # if running test
    write_to_file(nml_doc,
                  lems_info,
                  net_id,
                  template_path,
                  validate=validate,
                  verbose=verbose,
                  target_directory=target_directory)

    return nml_doc
Ejemplo n.º 3
0
nml_doc.exp_one_synapses.append(syn0)

syn1 = ExpTwoSynapse(id="syn1",
                     gbase="2nS",
                     erev="0mV",
                     tau_rise="1ms",
                     tau_decay="3ms")

nml_doc.exp_two_synapses.append(syn1)

gj = GapJunction(id="gj1", conductance="10pS")

nml_doc.gap_junctions.append(gj)

sil_syn = SilentSynapse(id="silent1")
nml_doc.silent_synapses.append(sil_syn)

grad_syn = GradedSynapse(id="gs1",
                         conductance="0.5pS",
                         delta="5mV",
                         Vth="-55mV",
                         k="0.025per_ms",
                         erev="0mV")
nml_doc.graded_synapses.append(grad_syn)

pfs = PoissonFiringSynapse(id='pfs',
                           average_rate='150Hz',
                           synapse=syn0.id,
                           spike_target="./%s" % syn0.id)
Ejemplo n.º 4
0
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)

    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")
    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)

    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)
                                
        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)
                                
        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)
        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)
                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:
                    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)
    else:
        lems_file_name = None

    return nml_doc, nml_file_name, lems_file_name
Ejemplo n.º 5
0
def generate(net_id,
             params,
             data_reader = "SpreadsheetDataReader",
             cells = None,
             cells_to_plot = None,
             cells_to_stimulate = None,
             muscles_to_include=[],
             conns_to_include=[],
             conn_number_override = None,
             conn_number_scaling = None,
             conn_polarity_override = None,
             duration = 500,
             dt = 0.01,
             vmin = None,
             vmax = None,
             seed = 1234,
             test=False,
             verbose=True,
             param_overrides={},
             target_directory='./'):
                 
    validate = not (params.is_level_B() or params.is_level_C0())
                
    root_dir = os.path.dirname(os.path.abspath(__file__))
    for k in param_overrides.keys():
        v = param_overrides[k]
        print_("Setting parameter %s = %s"%(k,v))
        params.set_bioparameter(k, v, "Set with param_overrides", 0)
    

    params.create_models()
    
    if vmin==None:
        if params.is_level_A():
            vmin=-72
        elif params.is_level_B():
            vmin=-52 
        elif params.is_level_C():
            vmin=-60
        elif params.is_level_D():
            vmin=-60
        else:
            vmin=-52 
            
    
    if vmax==None:
        if params.is_level_A():
            vmax=-48
        elif params.is_level_B():
            vmax=-28
        elif params.is_level_C():
            vmax=25
        elif params.is_level_D():
            vmax=25
        else:
            vmax=-28
    
    random.seed(seed)

    info = "\n\nParameters and setting used to generate this network:\n\n"+\
           "    Data reader:                    %s\n" % data_reader+\
           "    Cells:                          %s\n" % (cells if cells is not None else "All cells")+\
           "    Cell stimulated:                %s\n" % (cells_to_stimulate if cells_to_stimulate is not None else "All neurons")+\
           "    Connection:                     %s\n" % (conns_to_include if conns_to_include is not None else "All connections") + \
           "    Connection numbers overridden:  %s\n" % (conn_number_override if conn_number_override is not None else "None")+\
           "    Connection numbers scaled:      %s\n" % (conn_number_scaling if conn_number_scaling is not None else "None")+ \
           "    Connection polarities override: %s\n" % conn_polarity_override + \
           "    Muscles:                        %s\n" % (muscles_to_include if muscles_to_include is not None else "All muscles")
    if verbose: print_(info)
    info += "\n%s\n"%(params.bioparameter_info("    "))

    nml_doc = NeuroMLDocument(id=net_id, notes=info)

    if params.is_level_A() or params.is_level_B() or params.level == "BC1":
        nml_doc.iaf_cells.append(params.generic_muscle_cell) 
        nml_doc.iaf_cells.append(params.generic_neuron_cell) 
    elif params.is_level_C():
        nml_doc.cells.append(params.generic_muscle_cell)
        nml_doc.cells.append(params.generic_neuron_cell)
    elif params.is_level_D():
        nml_doc.cells.append(params.generic_muscle_cell)
         

    net = Network(id=net_id)


    nml_doc.networks.append(net)

    nml_doc.pulse_generators.append(params.offset_current)

    if is_cond_based_cell(params):
        nml_doc.fixed_factor_concentration_models.append(params.concentration_model)

    cell_names, conns = get_cell_names_and_connection(data_reader)

    # To hold all Cell NeuroML objects vs. names
    all_cells = {}

    # lems_file = ""
    lems_info = {"comment":    info,
                 "reference":  net_id,
                 "duration":   duration,
                 "dt":         dt,
                 "vmin":       vmin,
                 "vmax":       vmax}

    lems_info["plots"] = []
    lems_info["activity_plots"] = []
    lems_info["muscle_plots"] = []
    lems_info["muscle_activity_plots"] = []

    lems_info["to_save"] = []
    lems_info["activity_to_save"] = []
    lems_info["muscles_to_save"] = []
    lems_info["muscles_activity_to_save"] = []
    lems_info["cells"] = []
    lems_info["muscles"] = []
    lems_info["includes"] = []

    if params.custom_component_types_definitions:
        if isinstance(params.custom_component_types_definitions, str):
            params.custom_component_types_definitions = [params.custom_component_types_definitions]
        for ctd in params.custom_component_types_definitions:
            lems_info["includes"].append(ctd)
            if target_directory != './':
                def_file = "%s/%s"%(os.path.dirname(os.path.abspath(__file__)), ctd)
                shutil.copy(def_file, target_directory)
            nml_doc.includes.append(IncludeType(href=ctd))
    
    
    backers_dir = root_dir+"/../../../../OpenWormBackers/" if test else root_dir+"/../../../OpenWormBackers/"
    sys.path.append(backers_dir)
    import backers
    cells_vs_name = backers.get_adopted_cell_names(backers_dir)


    count = 0
    for cell in cell_names:

        if cells is None or cell in cells:

            inst = Instance(id="0")

            if not params.is_level_D():
                # build a Population data structure out of the cell name
                pop0 = Population(id=cell,
                                  component=params.generic_neuron_cell.id,
                                  type="populationList")
                cell_id = params.generic_neuron_cell.id
            else:
                # build a Population data structure out of the cell name
                pop0 = Population(id=cell,
                                  component=cell,
                                  type="populationList")
                cell_id = cell
                                  
            pop0.instances.append(inst)



            # put that Population into the Network data structure from above
            net.populations.append(pop0)
            
            if cells_vs_name.has_key(cell):
                p = Property(tag="OpenWormBackerAssignedName", value=cells_vs_name[cell])
                pop0.properties.append(p)

            # also use the cell name to grab the morphology file, as a NeuroML data structure
            #  into the 'all_cells' dict
            cell_file_path = root_dir+"/../../../" if test else root_dir+"/../../" #if running test
            cell_file = cell_file_path+'generatedNeuroML2/%s.cell.nml'%cell
            doc = loaders.NeuroMLLoader.load(cell_file)
            all_cells[cell] = doc.cells[0]
            
            
            if params.is_level_D():
                new_cell = params.create_neuron_cell(cell, doc.cells[0].morphology)
                
                nml_cell_doc = NeuroMLDocument(id=cell)
                nml_cell_doc.cells.append(new_cell)
                new_cell_file = 'cells/'+cell+'_D.cell.nml'
                nml_file = target_directory+'/'+new_cell_file
                print_("Writing new cell to: %s"%os.path.realpath(nml_file))
                writers.NeuroMLWriter.write(nml_cell_doc, nml_file)
                
                nml_doc.includes.append(IncludeType(href=new_cell_file))
                lems_info["includes"].append(new_cell_file)
                
                inst.location = Location(0,0,0)
            else:
                location = doc.cells[0].morphology.segments[0].proximal
            
                inst.location = Location(float(location.x), float(location.y), float(location.z))
            
            if verbose: 
                print_("Loaded morphology: %s; id: %s; placing at location: (%s, %s, %s)"%(os.path.realpath(cell_file), all_cells[cell].id, inst.location.x, inst.location.y, inst.location.z))


                
            if cells_to_stimulate is None or cell in cells_to_stimulate:

                target = "../%s/0/%s"%(pop0.id, cell_id)
                if params.is_level_D():
                    target+="/0"
                
                input_list = InputList(id="Input_%s_%s"%(cell,params.offset_current.id),
                                     component=params.offset_current.id,
                                     populations='%s'%cell)

                input_list.input.append(Input(id=0, 
                              target=target, 
                              destination="synapses"))

                net.input_lists.append(input_list)


            if cells_to_plot is None or cell in cells_to_plot:
                plot = {}

                plot["cell"] = cell
                plot["colour"] = get_random_colour_hex()
                plot["quantity"] = "%s/0/%s/v" % (cell, cell_id)
                lems_info["plots"].append(plot)

                if params.is_level_B():
                    plot = {}

                    plot["cell"] = cell
                    plot["colour"] = get_random_colour_hex()
                    plot["quantity"] = "%s/0/%s/activity" % (cell, cell_id)
                    lems_info["activity_plots"].append(plot)

                if is_cond_based_cell(params):
                    plot = {}

                    plot["cell"] = cell
                    plot["colour"] = get_random_colour_hex()
                    plot["quantity"] = "%s/0/%s/caConc" % (cell, cell_id)
                    lems_info["activity_plots"].append(plot)

            save = {}
            save["cell"] = cell
            save["quantity"] = "%s/0/%s/v" % (cell, cell_id)
            lems_info["to_save"].append(save)

            if params.is_level_B():
                save = {}
                save["cell"] = cell
                save["quantity"] = "%s/0/%s/activity" % (cell, cell_id)
                lems_info["activity_to_save"].append(save)
            if is_cond_based_cell(params):
                save = {}
                save["cell"] = cell
                save["quantity"] = "%s/0/%s/caConc" % (cell, cell_id)
                lems_info["activity_to_save"].append(save)

            lems_info["cells"].append(cell)

            count+=1

    if verbose: 
        print_("Finished loading %i cells"%count)

    
    mneurons, all_muscles, muscle_conns = get_cell_muscle_names_and_connection(data_reader)

    #if data_reader == "SpreadsheetDataReader":
    #    all_muscles = get_muscle_names()
        
    if muscles_to_include == None or muscles_to_include == True:
        muscles_to_include = all_muscles
    elif muscles_to_include == False:
        muscles_to_include = []
        
    for m in muscles_to_include:
        assert m in all_muscles

    if len(muscles_to_include)>0:

        muscle_count = 0
        for muscle in muscles_to_include:

            inst = Instance(id="0")

            # build a Population data structure out of the cell name
            pop0 = Population(id=muscle,
                              component=params.generic_muscle_cell.id,
                              type="populationList")
            pop0.instances.append(inst)


            # put that Population into the Network data structure from above
            net.populations.append(pop0)

            if cells_vs_name.has_key(muscle):
                # No muscles adopted yet, but just in case they are in future...
                p = Property(tag="OpenWormBackerAssignedName", value=cells_vs_name[muscle])
                pop0.properties.append(p)

            x, y, z = get_muscle_position(muscle, data_reader)
            print_('Positioning muscle: %s at (%s,%s,%s)'%(muscle,x,y,z))
            inst.location = Location(x,y,z)

            #target = "%s/0/%s"%(pop0.id, params.generic_muscle_cell.id) # unused

            plot = {}

            plot["cell"] = muscle
            plot["colour"] = get_random_colour_hex()
            plot["quantity"] = "%s/0/%s/v" % (muscle, params.generic_muscle_cell.id)
            lems_info["muscle_plots"].append(plot)

            if params.generic_muscle_cell.__class__.__name__ == 'IafActivityCell':
                plot = {}

                plot["cell"] = muscle
                plot["colour"] = get_random_colour_hex()
                plot["quantity"] = "%s/0/%s/activity" % (muscle, params.generic_muscle_cell.id)
                lems_info["muscle_activity_plots"].append(plot)
                
            if params.generic_muscle_cell.__class__.__name__ == 'Cell':
                plot = {}

                plot["cell"] = muscle
                plot["colour"] = get_random_colour_hex()
                plot["quantity"] = "%s/0/%s/caConc" % (muscle, params.generic_muscle_cell.id)
                lems_info["muscle_activity_plots"].append(plot)

            save = {}
            save["cell"] = muscle
            save["quantity"] = "%s/0/%s/v" % (muscle, params.generic_muscle_cell.id)
            lems_info["muscles_to_save"].append(save)

            if params.generic_muscle_cell.__class__.__name__ == 'IafActivityCell':
                save = {}
                save["cell"] = muscle
                save["quantity"] = "%s/0/%s/activity" % (muscle, params.generic_muscle_cell.id)
                lems_info["muscles_activity_to_save"].append(save)
            if params.generic_muscle_cell.__class__.__name__ == 'Cell':
                save = {}
                save["cell"] = muscle
                save["quantity"] = "%s/0/%s/caConc" % (muscle, params.generic_muscle_cell.id)
                lems_info["muscles_activity_to_save"].append(save)

            lems_info["muscles"].append(muscle)

            muscle_count+=1
            
            if muscle in cells_to_stimulate:

                target = "../%s/0/%s"%(pop0.id, params.generic_muscle_cell.id)
                if params.is_level_D():
                    target+="/0"
                
                input_list = InputList(id="Input_%s_%s"%(muscle,params.offset_current.id),
                                     component=params.offset_current.id,
                                     populations='%s'%pop0.id)

                input_list.input.append(Input(id=0, 
                              target=target, 
                              destination="synapses"))

                net.input_lists.append(input_list)

        if verbose: 
            print_("Finished creating %i muscles"%muscle_count)
        
    
    existing_synapses = {}

    for conn in conns:

        if conn.pre_cell in lems_info["cells"] and conn.post_cell in lems_info["cells"]:
            # take information about each connection and package it into a
            # NeuroML Projection data structure
            proj_id = get_projection_id(conn.pre_cell, conn.post_cell, conn.synclass, conn.syntype)
            conn_shorthand = "%s-%s" % (conn.pre_cell, conn.post_cell)

            elect_conn = False
            analog_conn = False
            syn0 = params.neuron_to_neuron_exc_syn
            orig_pol = "exc"
            
            if 'GABA' in conn.synclass:
                syn0 = params.neuron_to_neuron_inh_syn
                orig_pol = "inh"
            if '_GJ' in conn.synclass:
                syn0 = params.neuron_to_neuron_elec_syn
                elect_conn = isinstance(params.neuron_to_neuron_elec_syn, GapJunction)
                conn_shorthand = "%s-%s_GJ" % (conn.pre_cell, conn.post_cell)

            if conns_to_include and conn_shorthand not in conns_to_include:
                continue

            print conn_shorthand + " " + str(conn.number) + " " + orig_pol + " " + conn.synclass

            polarity = None
            if conn_polarity_override and conn_polarity_override.has_key(conn_shorthand):
                polarity = conn_polarity_override[conn_shorthand]

            if polarity and not elect_conn:
                if polarity == 'inh':
                    syn0 = params.neuron_to_neuron_inh_syn
                else:
                    syn0 = params.neuron_to_neuron_exc_syn
                if verbose and polarity != orig_pol:
                    print_(">> Changing polarity of connection %s -> %s: was: %s, becomes %s " % \
                       (conn.pre_cell, conn.post_cell, orig_pol, polarity))
                
                
                
            if isinstance(syn0, GradedSynapse) or isinstance(syn0, GradedSynapse2):
                analog_conn = True
                if len(nml_doc.silent_synapses)==0:
                    silent = SilentSynapse(id="silent")
                    nml_doc.silent_synapses.append(silent)

            number_syns = conn.number

            if conn_number_override is not None and (conn_number_override.has_key(conn_shorthand)):
                number_syns = conn_number_override[conn_shorthand]
            elif conn_number_scaling is not None and (conn_number_scaling.has_key(conn_shorthand)):
                number_syns = conn.number*conn_number_scaling[conn_shorthand]
            '''
            else:
                print conn_shorthand
                print conn_number_override
                print conn_number_scaling'''
            """if polarity:
                print "%s %s num:%s" % (conn_shorthand, polarity, number_syns)
            elif elect_conn:
                print "%s num:%s" % (conn_shorthand, number_syns)
            else:
                print "%s %s num:%s" % (conn_shorthand, orig_pol, number_syns)"""
            
            if number_syns != conn.number:
                if analog_conn or elect_conn:
                    magnitude, unit = bioparameters.split_neuroml_quantity(syn0.conductance)
                else:
                    magnitude, unit = bioparameters.split_neuroml_quantity(syn0.gbase)
                cond0 = "%s%s"%(magnitude*conn.number, unit)
                cond1 = "%s%s" % (get_str_from_expnotation(magnitude * number_syns), unit)
                gj = "" if not elect_conn else " GapJunction"
                if verbose: 
                    print_(">> Changing number of effective synapses connection %s -> %s%s: was: %s (total cond: %s), becomes %s (total cond: %s)" % \
                     (conn.pre_cell, conn.post_cell, gj, conn.number, cond0, number_syns, cond1))

            #print "######## %s-%s %s %s" % (conn.pre_cell, conn.post_cell, conn.synclass, number_syns)
            #known_motor_prefixes = ["VA"]
            #if conn.pre_cell.startswith(tuple(known_motor_prefixes)) or conn.post_cell.startswith(tuple(known_motor_prefixes)):
            #    print "######### %s-%s %s %s" % (conn.pre_cell, conn.post_cell, number_syns, conn.synclass)

            syn_new = create_n_connection_synapse(syn0, number_syns, nml_doc, existing_synapses)

            if elect_conn:

                proj0 = ElectricalProjection(id=proj_id, \
                                   presynaptic_population=conn.pre_cell,
                                   postsynaptic_population=conn.post_cell)

                net.electrical_projections.append(proj0)

                pre_cell_id=get_cell_id_string(conn.pre_cell, params)
                post_cell_id= get_cell_id_string(conn.post_cell, params)

                #print_("Conn %s -> %s"%(pre_cell_id,post_cell_id))

                # Add a Connection with the closest locations
                conn0 = ElectricalConnectionInstance(id="0", \
                           pre_cell=pre_cell_id,
                           post_cell=post_cell_id,
                           synapse=syn_new.id)

                proj0.electrical_connection_instances.append(conn0)
                
            elif analog_conn:
        
                proj0 = ContinuousProjection(id=proj_id, \
                                   presynaptic_population=conn.pre_cell,
                                   postsynaptic_population=conn.post_cell)

                net.continuous_projections.append(proj0)

                pre_cell_id= get_cell_id_string(conn.pre_cell, params)
                post_cell_id= get_cell_id_string(conn.post_cell, params)

                conn0 = ContinuousConnectionInstance(id="0", \
                           pre_cell=pre_cell_id,
                           post_cell=post_cell_id,
                           pre_component="silent",
                           post_component=syn_new.id)

                proj0.continuous_connection_instances.append(conn0)
                
                
            else:

                proj0 = Projection(id=proj_id, \
                                   presynaptic_population=conn.pre_cell,
                                   postsynaptic_population=conn.post_cell,
                                   synapse=syn_new.id)

                net.projections.append(proj0)

                pre_cell_id= get_cell_id_string(conn.pre_cell, params)
                post_cell_id= get_cell_id_string(conn.post_cell, params)

                conn0 = ConnectionWD(id="0", \
                           pre_cell_id=pre_cell_id,
                           post_cell_id=post_cell_id,
                           weight = number_syns,
                           delay = '0ms')

                proj0.connection_wds.append(conn0)



    if len(muscles_to_include)>0:
        for conn in muscle_conns:
            if not conn.post_cell in muscles_to_include:
                continue
            if not conn.pre_cell in lems_info["cells"] and not conn.pre_cell in muscles_to_include:
                continue

            # take information about each connection and package it into a
            # NeuroML Projection data structure
            proj_id = get_projection_id(conn.pre_cell, conn.post_cell, conn.synclass, conn.syntype)
            conn_shorthand = "%s-%s" % (conn.pre_cell, conn.post_cell)

            elect_conn = False
            analog_conn = False
            syn0 = params.neuron_to_muscle_exc_syn
            orig_pol = "exc"
            if 'GABA' in conn.synclass:
                syn0 = params.neuron_to_muscle_inh_syn
                orig_pol = "inh"
            
            if '_GJ' in conn.synclass :
                elect_conn = isinstance(params.neuron_to_muscle_elec_syn, GapJunction)
                conn_shorthand = "%s-%s_GJ" % (conn.pre_cell, conn.post_cell)
                if conn.pre_cell in lems_info["cells"]:
                    syn0 = params.neuron_to_muscle_elec_syn
                elif conn.pre_cell in muscles_to_include:
                    try:
                        syn0 = params.muscle_to_muscle_elec_syn
                    except:
                        syn0 = params.neuron_to_muscle_elec_syn

            if conns_to_include and conn_shorthand not in conns_to_include:
                continue
                
            print conn_shorthand + " " + str(conn.number) + " " + orig_pol + " " + conn.synclass

            polarity = None
            if conn_polarity_override and conn_polarity_override.has_key(conn_shorthand):
                polarity = conn_polarity_override[conn_shorthand]

            if polarity and not elect_conn:
                if polarity == 'inh':
                    syn0 = params.neuron_to_neuron_inh_syn
                else:
                    syn0 = params.neuron_to_neuron_exc_syn
                if verbose and polarity != orig_pol:
                    print_(">> Changing polarity of connection %s -> %s: was: %s, becomes %s " % \
                       (conn.pre_cell, conn.post_cell, orig_pol, polarity))

            if isinstance(syn0, GradedSynapse) or isinstance(syn0, GradedSynapse2):
                analog_conn = True
                if len(nml_doc.silent_synapses)==0:
                    silent = SilentSynapse(id="silent")
                    nml_doc.silent_synapses.append(silent)
                    
            number_syns = conn.number
            
            if conn_number_override is not None and (conn_number_override.has_key(conn_shorthand)):
                number_syns = conn_number_override[conn_shorthand]
            elif conn_number_scaling is not None and (conn_number_scaling.has_key(conn_shorthand)):
                number_syns = conn.number*conn_number_scaling[conn_shorthand]
            '''
            else:
                print conn_shorthand
                print conn_number_override
                print conn_number_scaling'''
            """if polarity:
                print "%s %s num:%s" % (conn_shorthand, polarity, number_syns)
            elif elect_conn:
                print "%s num:%s" % (conn_shorthand, number_syns)
            else:
                print "%s %s num:%s" % (conn_shorthand, orig_pol, number_syns)"""

            if number_syns != conn.number:
                
                if analog_conn or elect_conn:
                    magnitude, unit = bioparameters.split_neuroml_quantity(syn0.conductance)
                else:
                    magnitude, unit = bioparameters.split_neuroml_quantity(syn0.gbase)
                cond0 = "%s%s"%(magnitude*conn.number, unit)
                cond1 = "%s%s" % (get_str_from_expnotation(magnitude * number_syns), unit)
                gj = "" if not elect_conn else " GapJunction"
                if verbose: 
                    print_(">> Changing number of effective synapses connection %s -> %s%s: was: %s (total cond: %s), becomes %s (total cond: %s)" % \
                     (conn.pre_cell, conn.post_cell, gj, conn.number, cond0, number_syns, cond1))


            syn_new = create_n_connection_synapse(syn0, number_syns, nml_doc, existing_synapses)

            if elect_conn:

                proj0 = ElectricalProjection(id=proj_id, \
                                   presynaptic_population=conn.pre_cell,
                                   postsynaptic_population=conn.post_cell)

                net.electrical_projections.append(proj0)

                pre_cell_id= get_cell_id_string(conn.pre_cell, params)
                post_cell_id= get_cell_id_string(conn.post_cell, params, muscle=True)

                #print_("Conn %s -> %s"%(pre_cell_id,post_cell_id))

                # Add a Connection with the closest locations
                conn0 = ElectricalConnectionInstance(id="0", \
                           pre_cell=pre_cell_id,
                           post_cell=post_cell_id,
                           synapse=syn_new.id)

                proj0.electrical_connection_instances.append(conn0)
                
            elif analog_conn:
        
                proj0 = ContinuousProjection(id=proj_id, \
                                   presynaptic_population=conn.pre_cell,
                                   postsynaptic_population=conn.post_cell)

                net.continuous_projections.append(proj0)

                pre_cell_id= get_cell_id_string(conn.pre_cell, params)
                post_cell_id= get_cell_id_string(conn.post_cell, params, muscle=True)

                conn0 = ContinuousConnectionInstance(id="0", \
                           pre_cell=pre_cell_id,
                           post_cell=post_cell_id,
                           pre_component="silent",
                           post_component=syn_new.id)

                proj0.continuous_connection_instances.append(conn0)

            else:

                proj0 = Projection(id=proj_id, \
                                   presynaptic_population=conn.pre_cell,
                                   postsynaptic_population=conn.post_cell,
                                   synapse=syn_new.id)

                net.projections.append(proj0)

                # Add a Connection with the closest locations

                pre_cell_id= get_cell_id_string(conn.pre_cell, params)
                post_cell_id= get_cell_id_string(conn.post_cell, params, muscle=True)

                conn0 = Connection(id="0", \
                           pre_cell_id=pre_cell_id,
                           post_cell_id=post_cell_id)

                proj0.connections.append(conn0)



    # import pprint
    # pprint.pprint(lems_info)
    template_path = root_dir+'/../' if test else root_dir+'/' # if running test
    write_to_file(nml_doc, lems_info, net_id, template_path, validate=validate, verbose=verbose, target_directory=target_directory)


    return nml_doc
Ejemplo n.º 6
0
def generatePopulationLEMS(pops, n_pops, amplitudes, baseline, sim_length,
                           delay):
    def generatePopulationProjection(from_pop, to_pop, n_from_pop, n_to_pop,
                                     w_to_from_pop, p_to_from_pop, net):
        connection_count = 0
        projection = ContinuousProjection(
            id='%s_%s' % (from_pop, to_pop),
            presynaptic_population='%sPop' % from_pop,
            postsynaptic_population='%sPop' % to_pop)
        for idx_from_pop in range(n_from_pop):
            for idx_to_pop in range(n_to_pop):
                if random.random() <= p_to_from_pop:
                    pre_comp = from_pop.upper()
                    to_comp = to_pop.upper()
                    connection = ContinuousConnectionInstanceW(
                        id=connection_count,
                        pre_cell='../%sPop/%i/%s' %
                        (from_pop, idx_from_pop, pre_comp),
                        post_cell='../%sPop/%i/%s' %
                        (to_pop, idx_to_pop, to_comp),
                        pre_component='silent1',
                        post_component='rs',
                        weight=w_to_from_pop / (p_to_from_pop * n_from_pop))
                    projection.continuous_connection_instance_ws.append(
                        connection)
                    connection_count += 1
        if connection_count > 0:
            net.continuous_projections.append(projection)

    # Connection probabilities for each pop in the population
    w_to_from_pops = np.array([[2.42, -.33, -0.80, 0], [2.97, -3.45, -2.13, 0],
                               [4.64, 0, 0, -2.79], [0.71, 0, -0.16, 0]])

    # p_to_from_pop = np.array([[1, 1,    1,     0],
    #                           [1, 1, 1,     0],
    #                           [1, 0,    0,  1],
    #                           [1, 0,  1,     0]])
    p_to_from_pop = np.array([[0.02, 1, 1, 0], [0.01, 1, 0.85, 0],
                              [0.01, 0, 0, 0.55], [0.01, 0, 0.5, 0]])

    nml_doc = NeuroMLDocument(id='RandomPopulation')

    # Add silent synapsis
    silent_syn = SilentSynapse(id='silent1')
    nml_doc.silent_synapses.append(silent_syn)

    for pop_idx, pop in enumerate(pops):
        pulse = PulseGenerator(id='baseline_%s' % pop,
                               delay='0ms',
                               duration=str(sim_length) + 'ms',
                               amplitude=amplitudes[pop_idx])
        nml_doc.pulse_generators.append(pulse)

        if pop == 'vip':
            # time point when additional current is induced
            pulse_mod = PulseGenerator(id='modVIP',
                                       delay=str(delay) + 'ms',
                                       duration=str(sim_length - delay) + 'ms',
                                       amplitude='10 pA')
            nml_doc.pulse_generators.append(pulse_mod)

    # Create the network and add the 4 different populations
    net = Network(id='net2')
    nml_doc.networks.append(net)

    colours = ['0 0 1', '1 0 0', '.5 0 .5', '0 1 0']
    centres = [(0, 0, 0), (-1200, 0, 0), (-800, 800, 0), (0, 1200, 0)]
    radii = [800, 200, 200, 200]
    # Populate the network with the 4 populations
    for pop_idx, pop in enumerate(pops):
        pop = Population(id='%sPop' % pop,
                         component=(pops[pop_idx]).upper(),
                         size=n_pops[pop_idx],
                         type='populationList')
        net.populations.append(pop)
        pop.properties.append(Property(tag='color', value=colours[pop_idx]))
        pop.properties.append(Property(tag='radius', value=10))

        for n_pop in range(n_pops[pop_idx]):
            inst = Instance(id=n_pop)
            pop.instances.append(inst)
            x, y, z = centres[pop_idx]
            r = (random.random() * radii[pop_idx]**3)**(1. / 3)
            theta = random.random() * math.pi
            phi = random.random() * math.pi * 2

            inst.location = Location(
                x=str(x + r * math.sin(theta) * math.cos(phi)),
                y=str(y + r * math.sin(theta) * math.sin(phi)),
                z=str(z + r * math.cos(theta)))

    for from_idx, from_pop in enumerate(pops):
        for to_idx, to_pop in enumerate(pops):
            generatePopulationProjection(pops[from_idx], pops[to_idx],
                                         n_pops[from_idx], n_pops[to_idx],
                                         w_to_from_pops[to_idx, from_idx],
                                         p_to_from_pop[to_idx, from_idx], net)
    # Add inputs
    for pop_idx, pop in enumerate(pops):

        input_list = InputList(id='baseline_%s' % pop,
                               component='baseline_%s' % pops[pop_idx],
                               populations='%sPop' % pop)
        net.input_lists.append(input_list)

        if pop == 'vip':
            input_list_mod = InputList(id='modulation_%s' % pop,
                                       component='modVIP',
                                       populations='%sPop' % pop)
            net.input_lists.append(input_list_mod)

        for n_idx in range(n_pops[pop_idx]):
            input = Input(id=n_idx,
                          target='../%sPop/%i/%s' % (pop, n_idx, pop.upper()),
                          destination='synapses')
            input_list.input.append(input)

            # if vip add modulatory input
            if pop == 'vip':

                mod_input = Input(id=n_idx,
                                  target='../vipPop/%i/VIP' % n_idx,
                                  destination='synapses')
                input_list_mod.input.append(mod_input)

    nml_file = 'RandomPopulationRate_%s_baseline.nml' % baseline
    writers.NeuroMLWriter.write(nml_doc, nml_file)
    print('Written network file to: %s' % nml_file)

    # Validate the NeuroML
    from neuroml.utils import validate_neuroml2
    validate_neuroml2(nml_file)