def create_object(name, color, x=0, y=0, z=0):

    obj = Cell()
    obj.name = name
    obj.id = name
    nml_doc.cells.append(obj)
    morphology = Morphology(id='mm')
    obj.morphology = morphology

    pop = Population(id="Pop_%s" % name,
                     component=obj.id,
                     type="populationList",
                     size=0)
    net.populations.append(pop)
    populations[name] = pop
    pop.properties.append(Property(tag="color", value=color))
    add_instance(name, x, y, z)

    sg = SegmentGroup(id='all')
    obj.morphology.segment_groups.append(sg)

    return obj
Beispiel #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
                                amplitude=args.ie0,
                                period='25ms')
        nml_doc.sine_generator_dls.append(pulse)
    else:
        pulse = SineGenerator(id='mod_%s' % pop,
                              phase='0',
                              delay='0ms',
                              duration='%sms' % duration,
                              amplitude='%snA' % args.ie0,
                              period='25ms')
        nml_doc.sine_generators.append(pulse)

# Create the network
net = Network(id='net1')

net.properties.append(Property('recommended_dt_ms', dt))
net.properties.append(Property('recommended_duration_ms', duration))

nml_doc.networks.append(net)

nml_doc.includes.append(IncludeType('WC_Parameters%s.xml' % dl_str))

colours = ['1 0 0', '0 0 1']
for pop_idx, pop in enumerate(pops):
    population = Population(id='%sPop' % pop,
                            component=(pops[pop_idx]),
                            size=n_pops[pop_idx],
                            type='populationList')
    net.populations.append(population)
    population.properties.append(Property(tag='color', value=colours[pop_idx]))
    population.properties.append(Property(tag='radius', value='10'))
Beispiel #4
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 = -75,
             vmax = 20,
             seed = 1234,
             validate=True, test=False):

    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
    info += "\n%s\n"%(bioparameter_info("    "))

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

    nml_doc.iaf_cells.append(params.generic_cell)

    net = Network(id=net_id)


    nml_doc.networks.append(net)

    nml_doc.pulse_generators.append(params.offset_current)

    # Use the spreadsheet reader to give a list of all cells and a list of all connections
    # This could be replaced with a call to "DatabaseReader" or "OpenWormNeuroLexReader" in future...
    # If called from unittest folder ammend path to "../../../../"
    spreadsheet_location = "../../../../" if test else "../../../"

    cell_names, conns = SpreadsheetDataReader.readDataFromSpreadsheet(spreadsheet_location, include_nonconnected_cells=True)

    cell_names.sort()

    # 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_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 hasattr(params.generic_cell, 'custom_component_type_definition'):
        lems_info["includes"].append(params.generic_cell.custom_component_type_definition)

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

    populations_without_location = 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_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_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 = "../../../" if test else "../../" #if running test
            cell_file = cell_file_path+'generatedNeuroML2/%s.nml'%cell
            doc = loaders.NeuroMLLoader.load(cell_file)
            all_cells[cell] = doc.cells[0]
            location = doc.cells[0].morphology.segments[0].proximal
            print("Loaded morphology file from: %s, with id: %s, location: (%s, %s, %s)"%(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_cell.id)
            if populations_without_location:
                target = "%s[0]" % (cell)

            exp_input = ExplicitInput(target=target, input=params.offset_current.id)

            if cells_to_stimulate is None or cell in cells_to_stimulate:
                net.explicit_inputs.append(exp_input)

            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_cell.id)
                if populations_without_location:
                    plot["quantity"] = "%s[0]/v" % (cell)
                lems_info["plots"].append(plot)

                if hasattr(params.generic_cell, 'custom_component_type_definition'):
                    plot = {}

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

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

            if hasattr(params.generic_cell, 'custom_component_type_definition'):
                save = {}
                save["cell"] = cell
                save["quantity"] = "%s/0/%s/activity" % (cell, params.generic_cell.id)
                if populations_without_location:
                    save["quantity"] = "%s[0]/activity" % (cell)
                lems_info["activity_to_save"].append(save)

            lems_info["cells"].append(cell)

            count+=1

    print("Finished loading %i cells"%count)

    mneurons, all_muscles, muscle_conns = SpreadsheetDataReader.readMuscleDataFromSpreadsheet(spreadsheet_location)

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

            inst.location = Location(100, 10*muscle_count, 100)

            target = "%s/0/%s"%(pop0.id, params.generic_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_cell.id)
            if populations_without_location:
                plot["quantity"] = "%s[0]/v" % (muscle)
            lems_info["muscle_plots"].append(plot)

            if hasattr(params.generic_cell, 'custom_component_type_definition'):
                plot = {}

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

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

            if hasattr(params.generic_cell, 'custom_component_type_definition'):
                save = {}
                save["cell"] = muscle
                save["quantity"] = "%s/0/%s/activity" % (muscle, params.generic_cell.id)
                if populations_without_location:
                    save["quantity"] = "%s[0]/activity" % (muscle)
                lems_info["muscles_activity_to_save"].append(save)

            lems_info["muscles"].append(muscle)

            muscle_count+=1

        print("Finished creating %i muscles"%muscle_count)

    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
            syn0 = params.exc_syn
            if 'GABA' in conn.synclass:
                syn0 = params.inh_syn
            if '_GJ' in conn.synclass:
                syn0 = params.elec_syn
                elect_conn = isinstance(params.elec_syn, GapJunction)

            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 = split_neuroml_quantity(syn0.gbase)
                cond0 = "%s%s"%(magnitude*conn.number, unit)
                cond1 = "%s%s"%(magnitude*number_syns, unit)
                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)

            if not elect_conn:

                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_cell.id)
                    post_cell_id="../%s/0/%s"%(conn.post_cell, params.generic_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)


            else:
                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)


    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
            syn0 = params.exc_syn
            if 'GABA' in conn.synclass:
                syn0 = params.inh_syn
            if '_GJ' in conn.synclass:
                syn0 = params.elec_syn
                elect_conn = isinstance(params.elec_syn, GapJunction)

            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 = split_neuroml_quantity(syn0.gbase)
                cond0 = "%s%s"%(magnitude*conn.number, unit)
                cond1 = "%s%s"%(magnitude*number_syns, unit)
                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)

            if not elect_conn:

                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_cell.id)
                    post_cell_id="../%s/0/%s"%(conn.post_cell, params.generic_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)


            else:
                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)

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


    return nml_doc
pop1 = Population(id="IafPop1", component=IafCell1.id, size=size1)

net.populations.append(pop1)

size2 = int(5 * scale)
pop2 = Population(id="IzhPop", component=iz0.id, size=size2)

net.populations.append(pop2)

cell_num = int(4 * scale)
pop = Population(id="Pop_x",
                 component=IafCell0.id,
                 type="populationList",
                 size=cell_num)
net.populations.append(pop)
pop.properties.append(Property(tag="color", value="1 0 0"))

x_size = 500
y_size = 500
z_size = 500

for i in range(cell_num):
    inst = Instance(id=i)
    pop.instances.append(inst)

    inst.location = Location(x=str(x_size * random.random()),
                             y=str(y_size * random.random()),
                             z=str(z_size * random.random()))

prob_connection = 0.5
proj_count = 0
Beispiel #6
0
def run():

    cell_num = 10
    x_size = 500
    y_size = 500
    z_size = 500

    nml_doc = NeuroMLDocument(id="Net3DExample")

    syn0 = ExpOneSynapse(id="syn0", gbase="65nS", erev="0mV", tau_decay="3ms")
    nml_doc.exp_one_synapses.append(syn0)

    net = Network(id="Net3D")
    nml_doc.networks.append(net)

    proj_count = 0
    #conn_count = 0

    for cell_id in range(0, cell_num):

        cell = Cell(id="Cell_%i" % cell_id)

        cell.morphology = generateRandomMorphology()

        nml_doc.cells.append(cell)

        pop = Population(id="Pop_%i" % cell_id,
                         component=cell.id,
                         type="populationList")
        net.populations.append(pop)
        pop.properties.append(Property(tag="color", value="1 0 0"))

        inst = Instance(id="0")
        pop.instances.append(inst)

        inst.location = Location(x=str(x_size * random()),
                                 y=str(y_size * random()),
                                 z=str(z_size * random()))

        prob_connection = 0.5
        for post in range(0, cell_num):
            if post is not cell_id and random() <= prob_connection:

                from_pop = "Pop_%i" % cell_id
                to_pop = "Pop_%i" % post

                pre_seg_id = 0
                post_seg_id = 1

                projection = Projection(id="Proj_%i" % proj_count,
                                        presynaptic_population=from_pop,
                                        postsynaptic_population=to_pop,
                                        synapse=syn0.id)
                net.projections.append(projection)
                connection = Connection(id=proj_count, \
                                        pre_cell_id="%s[%i]"%(from_pop,0), \
                                        pre_segment_id=pre_seg_id, \
                                        pre_fraction_along=random(),
                                        post_cell_id="%s[%i]"%(to_pop,0), \
                                        post_segment_id=post_seg_id,
                                        post_fraction_along=random())

                projection.connections.append(connection)
                proj_count += 1
                #net.synaptic_connections.append(SynapticConnection(from_="%s[%i]"%(from_pop,0),  to="%s[%i]"%(to_pop,0)))

    #######   Write to file  ######

    nml_file = 'tmp/net3d.nml'
    writers.NeuroMLWriter.write(nml_doc, nml_file)

    print("Written network file to: " + nml_file)

    ###### Validate the NeuroML ######

    from neuroml.utils import validate_neuroml2

    validate_neuroml2(nml_file)
Beispiel #7
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
Beispiel #8
0
                         a="0.03per_ms",
                         b="-2nS",
                         c="-50.0mV",
                         d="100pA")
nml_doc.izhikevich2007_cells.append(iz0)

syn0 = ExpOneSynapse(id="syn0", gbase="65nS", erev="0mV", tau_decay="3ms")
nml_doc.exp_one_synapses.append(syn0)

net = Network(id="IzNet")
nml_doc.networks.append(net)

size0 = 5
pop0 = Population(id="IzPop0", component=iz0.id, size=size0)
# Set optional color property. Note: used later when generating graphs etc.
pop0.properties.append(Property(tag='color', value='0 0 .8'))
net.populations.append(pop0)

size1 = 5
pop1 = Population(id="IzPop1", component=iz0.id, size=size1)
pop1.properties.append(Property(tag='color', value='.8 0 0'))
net.populations.append(pop1)

proj = Projection(id='proj',
                  presynaptic_population=pop0.id,
                  postsynaptic_population=pop1.id,
                  synapse=syn0.id)
net.projections.append(proj)

random.seed(123)
prob_connection = 0.8
Beispiel #9
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)
Beispiel #10
0
def generate(
        scale_populations=1,
        percentage_exc_detailed=0,
        #exc2_cell = 'SmithEtAl2013/L23_Retuned_477127614',
        exc2_cell='SmithEtAl2013/L23_NoHotSpot',
        #exc2_cell = 'BBP/cADpyr229_L23_PC_5ecbf9b163_0_0',
        #exc2_cell = 'BBP/cNAC187_L23_NBC_9d37c4b1f8_0_0',
        #exc2_cell = 'Thalamocortical/L23PyrRS',
        percentage_inh_detailed=0,
        scalex=1,
        scaley=1,
        scalez=1,
        exc_exc_conn_prob=0.25,
        exc_inh_conn_prob=0.25,
        inh_exc_conn_prob=0.75,
        inh_inh_conn_prob=0.75,
        ee2_conn_prob=0,
        ie2_conn_prob=0,
        Bee=.1,
        Bei=.1,
        Bie=-.2,
        Bii=-.2,
        Bee2=1,
        Bie2=-2,
        Be_bkg=.1,
        Be_stim=.1,
        r_bkg=0,
        r_bkg_ExtExc=0,
        r_bkg_ExtInh=0,
        r_bkg_ExtExc2=0,
        r_stim=0,
        fraction_inh_pert=0.75,
        Ttrans=500,  # transitent time to discard the data (ms)
        Tblank=1500,  # simulation time before perturbation (ms)
        Tstim=1500,  # simulation time of perturbation (ms)
        Tpost=500,  # simulation time after perturbation (ms)
        connections=True,
        connections2=False,
        exc_target_dendrites=False,
        inh_target_dendrites=False,
        duration=1000,
        dt=0.025,
        global_delay=.1,
        max_in_pop_to_plot_and_save=10,
        format='xml',
        suffix='',
        run_in_simulator=None,
        num_processors=1,
        target_dir='./temp/',
        v_clamp=False,
        simulation_seed=11111):

    reference = ("ISN_net%s" % (suffix)).replace('.', '_')

    ks = open('kernelseed', 'w')
    ks.write('%i' % simulation_seed)
    ks.close()

    info = ('  Generating ISN network: %s\n' % reference)
    info += (
        '    Duration: %s; dt: %s; scale: %s; simulator: %s (num proc. %s)\n' %
        (duration, dt, scale_populations, run_in_simulator, num_processors))
    info += ('    Bee: %s; Bei: %s; Bie: %s; Bii: %s\n' % (Bee, Bei, Bie, Bii))
    info += ('    Bkg exc at %sHz\n' % (r_bkg_ExtExc))
    info += ('    Bkg inh at %sHz\n' % (r_bkg_ExtInh))
    info += ('    Be_stim: %s at %sHz (i.e. %sHz for %s perturbed I cells)\n' %
             (Be_stim, r_stim, r_bkg_ExtInh + r_stim, fraction_inh_pert))
    info += ('    Exc detailed: %s%% - Inh detailed %s%%\n' %
             (percentage_exc_detailed, percentage_inh_detailed))
    info += ('    Seed: %s' % (simulation_seed))

    print('-------------------------------------------------')
    print(info)
    print('-------------------------------------------------')

    num_exc = scale_pop_size(np.round(100 * exc_inh_fraction),
                             scale_populations)
    num_exc2 = int(math.ceil(num_exc * percentage_exc_detailed / 100.0))
    num_exc -= num_exc2

    num_inh = scale_pop_size(np.round(100 * (1 - exc_inh_fraction)),
                             scale_populations)
    num_inh2 = int(math.ceil(num_inh * percentage_inh_detailed / 100.0))
    num_inh -= num_inh2

    nml_doc, network = oc.generate_network(reference,
                                           network_seed=simulation_seed)
    nml_doc.notes = info
    network.notes = info

    #exc_cell_id = 'AllenHH_480351780'
    #exc_cell_id = 'AllenHH_477127614'
    #exc_cell_id = 'HH_477127614'
    exc_cell_id = 'HH2_477127614'
    exc_type = exc_cell_id.split('_')[0]
    oc.include_neuroml2_cell_and_channels(
        nml_doc, 'cells/%s/%s.cell.nml' % (exc_type, exc_cell_id), exc_cell_id)

    #inh_cell_id = 'AllenHH_485058595'
    #inh_cell_id = 'AllenHH_476686112'
    #inh_cell_id = 'AllenHH_477127614'
    #inh_cell_id = 'HH_476686112'
    inh_cell_id = 'HH2_476686112'
    inh_type = exc_cell_id.split('_')[0]
    oc.include_neuroml2_cell_and_channels(
        nml_doc, 'cells/%s/%s.cell.nml' % (inh_type, inh_cell_id), inh_cell_id)

    if percentage_exc_detailed > 0:
        exc2_cell_id = exc2_cell.split('/')[1]
        exc2_cell_dir = exc2_cell.split('/')[0]
        oc.include_neuroml2_cell_and_channels(
            nml_doc, 'cells/%s/%s.cell.nml' % (exc2_cell_dir, exc2_cell_id),
            exc2_cell_id)

    if percentage_inh_detailed > 0:
        inh2_cell_id = 'cNAC187_L23_NBC_9d37c4b1f8_0_0'
        oc.include_neuroml2_cell_and_channels(
            nml_doc, 'cells/BBP/%s.cell.nml' % inh2_cell_id, inh2_cell_id)

    xDim = 700 * scalex
    yDim = 100 * scaley
    yDimExc2 = 50 * scaley
    zDim = 700 * scalez

    xs = -1 * xDim / 2
    ys = -1 * yDim / 2
    zs = -1 * zDim / 2

    #####   Synapses

    synAmpaEE = oc.add_exp_one_syn(nml_doc,
                                   id="ampaEE",
                                   gbase="%snS" % Bee,
                                   erev="0mV",
                                   tau_decay="1ms")
    synAmpaEI = oc.add_exp_one_syn(nml_doc,
                                   id="ampaEI",
                                   gbase="%snS" % Bei,
                                   erev="0mV",
                                   tau_decay="1ms")

    synGabaIE = oc.add_exp_one_syn(nml_doc,
                                   id="gabaIE",
                                   gbase="%snS" % abs(Bie),
                                   erev="-80mV",
                                   tau_decay="2ms")
    synGabaII = oc.add_exp_one_syn(nml_doc,
                                   id="gabaII",
                                   gbase="%snS" % abs(Bii),
                                   erev="-80mV",
                                   tau_decay="2ms")

    synAmpaBkg = oc.add_exp_one_syn(nml_doc,
                                    id="ampaBkg",
                                    gbase="%snS" % Be_bkg,
                                    erev="0mV",
                                    tau_decay="1ms")
    #synAmpaStim = oc.add_exp_one_syn(nml_doc, id="ampaStim", gbase="%snS"%Be_stim,
    #                         erev="0mV", tau_decay="1ms")

    synAmpaEE2 = oc.add_exp_one_syn(nml_doc,
                                    id="ampaEE2",
                                    gbase="%snS" % Bee2,
                                    erev="0mV",
                                    tau_decay="10ms")
    synGabaIE2 = oc.add_exp_one_syn(nml_doc,
                                    id="gabaIE2",
                                    gbase="%snS" % abs(Bie2),
                                    erev="-80mV",
                                    tau_decay="10ms")

    #####   Input types
    '''tpfsA = oc.add_transient_poisson_firing_synapse(nml_doc,
                                       id="tpsfA",
                                       average_rate="%s Hz"%r_bkg,
                                       delay = '0ms', 
                                       duration = '%sms'%(Ttrans+Tblank),
                                       synapse_id=synAmpaBkg.id)

    tpfsB = oc.add_transient_poisson_firing_synapse(nml_doc,
                                       id="tpsfB",
                                       average_rate="%s Hz"%r_bkg,
                                       delay = '%sms'%(Ttrans+Tblank),
                                       duration = '%sms'%(Tstim),
                                       synapse_id=synAmpaBkg.id)

    tpfsC = oc.add_transient_poisson_firing_synapse(nml_doc,
                                       id="tpsfC",
                                       average_rate="%s Hz"%(r_bkg+r_stim),
                                       delay = '%sms'%(Ttrans+Tblank),
                                       duration = '%sms'%(Tstim),
                                       synapse_id=synAmpaStim.id)'''

    tpfsExtExc = oc.add_transient_poisson_firing_synapse(
        nml_doc,
        id="tpfsExtExc",
        average_rate="%s Hz" % r_bkg_ExtExc,
        delay='0ms',
        duration='%sms' % (Ttrans + Tblank + Tstim + Tpost),
        synapse_id=synAmpaBkg.id)

    tpfsExtExc2 = oc.add_transient_poisson_firing_synapse(
        nml_doc,
        id="tpfsExtExc2",
        average_rate="%s Hz" % r_bkg_ExtExc2,
        delay='0ms',
        duration='%sms' % (Ttrans + Tblank + Tstim + Tpost),
        synapse_id=synAmpaBkg.id)

    tpfsExtInh = oc.add_transient_poisson_firing_synapse(
        nml_doc,
        id="tpfsExtInh",
        average_rate="%s Hz" % r_bkg_ExtInh,
        delay='0ms',
        duration='%sms' % (Ttrans + Tblank + Tstim + Tpost),
        synapse_id=synAmpaBkg.id)

    tpfsPertInh_before = oc.add_transient_poisson_firing_synapse(
        nml_doc,
        id="tpfsPertInh_before",
        average_rate="%s Hz" % r_bkg_ExtInh,
        delay='0ms',
        duration='%sms' % (Ttrans + Tblank),
        synapse_id=synAmpaBkg.id)
    tpfsPertInh_during = oc.add_transient_poisson_firing_synapse(
        nml_doc,
        id="tpfsPertInh_during",
        average_rate="%s Hz" % (r_bkg_ExtInh + r_stim),
        delay='%sms' % (Ttrans + Tblank),
        duration='%sms' % (Tstim),
        synapse_id=synAmpaBkg.id)
    tpfsPertInh_after = oc.add_transient_poisson_firing_synapse(
        nml_doc,
        id="tpfsPertInh_after",
        average_rate="%s Hz" % r_bkg_ExtInh,
        delay='%sms' % (Ttrans + Tblank + Tstim),
        duration='%sms' % (Tpost),
        synapse_id=synAmpaBkg.id)

    #####   Populations

    popExc = oc.add_population_in_rectangular_region(network,
                                                     'popExc',
                                                     exc_cell_id,
                                                     num_exc,
                                                     xs,
                                                     ys,
                                                     zs,
                                                     xDim,
                                                     yDim,
                                                     zDim,
                                                     color=exc_color)
    from neuroml import Property
    popExc.properties.append(Property('type', 'E'))
    allExc = [popExc]

    if num_exc2 > 0:
        popExc2 = oc.add_population_in_rectangular_region(network,
                                                          'popExc2',
                                                          exc2_cell_id,
                                                          num_exc2,
                                                          xs,
                                                          yDim / 2,
                                                          zs,
                                                          xDim,
                                                          yDimExc2,
                                                          zDim,
                                                          color=exc2_color)
        popExc2.properties.append(Property('type', 'E'))

        allExc.append(popExc2)

    popInh = oc.add_population_in_rectangular_region(network,
                                                     'popInh',
                                                     inh_cell_id,
                                                     num_inh,
                                                     xs,
                                                     ys,
                                                     zs,
                                                     xDim,
                                                     yDim,
                                                     zDim,
                                                     color=inh_color)
    popInh.properties.append(Property('type', 'I'))
    allInh = [popInh]

    if num_inh2 > 0:
        popInh2 = oc.add_population_in_rectangular_region(network,
                                                          'popInh2',
                                                          inh2_cell_id,
                                                          num_inh2,
                                                          xs,
                                                          ys,
                                                          zs,
                                                          xDim,
                                                          yDim,
                                                          zDim,
                                                          color=inh2_color)

        allInh.append(popInh2)

    #####   Projections

    if connections:

        weight_expr = 'abs(normal(1,0.5))'

        for popEpr in allExc:

            for popEpo in allExc:
                proj = add_projection(network, "projEE", popEpr, popEpo,
                                      synAmpaEE.id, exc_exc_conn_prob,
                                      global_delay, exc_target_dendrites,
                                      weight_expr)

            for popIpo in allInh:
                proj = add_projection(network, "projEI", popEpr, popIpo,
                                      synAmpaEI.id, exc_inh_conn_prob,
                                      global_delay, exc_target_dendrites,
                                      weight_expr)

        for popIpr in allInh:

            for popEpo in allExc:
                proj = add_projection(network, "projIE", popIpr, popEpo,
                                      synGabaIE.id, inh_exc_conn_prob,
                                      global_delay, inh_target_dendrites,
                                      weight_expr)

            for popIpo in allInh:
                proj = add_projection(network, "projII", popIpr, popIpo,
                                      synGabaII.id, inh_inh_conn_prob,
                                      global_delay, inh_target_dendrites,
                                      weight_expr)

    elif connections2:

        weight_expr = 'abs(normal(1,0.5))'

        proj = add_projection(network, "projEE", popExc, popExc, synAmpaEE.id,
                              exc_exc_conn_prob, global_delay,
                              exc_target_dendrites, weight_expr)
        proj = add_projection(network, "projEI", popExc, popInh, synAmpaEI.id,
                              exc_inh_conn_prob, global_delay,
                              exc_target_dendrites, weight_expr)
        proj = add_projection(network, "projIE", popInh, popExc, synGabaIE.id,
                              inh_exc_conn_prob, global_delay,
                              inh_target_dendrites, weight_expr)
        proj = add_projection(network, "projII", popInh, popInh, synGabaII.id,
                              inh_inh_conn_prob, global_delay,
                              inh_target_dendrites, weight_expr)

        proj = add_projection(network, "projEE2", popExc, popExc2,
                              synAmpaEE2.id, ee2_conn_prob, global_delay,
                              exc_target_dendrites, weight_expr)
        proj = add_projection(network, "projIE2", popInh, popExc2,
                              synGabaIE2.id, ie2_conn_prob, global_delay,
                              inh_target_dendrites, weight_expr)

    #####   Inputs

    oc.add_inputs_to_population(network,
                                "Stim_E",
                                popExc,
                                tpfsExtExc.id,
                                all_cells=True)

    if num_exc2 > 0:
        oc.add_inputs_to_population(network,
                                    "Stim_E2",
                                    popExc2,
                                    tpfsExtExc2.id,
                                    all_cells=True)

    num_inh_pert = int(popInh.get_size() * fraction_inh_pert)

    oc.add_inputs_to_population(network,
                                "Stim_I_nonpert",
                                popInh,
                                tpfsExtInh.id,
                                all_cells=False,
                                only_cells=range(num_inh_pert,
                                                 popInh.get_size()))

    oc.add_inputs_to_population(network,
                                "Stim_I_pert_before",
                                popInh,
                                tpfsPertInh_before.id,
                                all_cells=False,
                                only_cells=range(0, num_inh_pert))
    oc.add_inputs_to_population(network,
                                "Stim_I_pert_during",
                                popInh,
                                tpfsPertInh_during.id,
                                all_cells=False,
                                only_cells=range(0, num_inh_pert))
    oc.add_inputs_to_population(network,
                                "Stim_I_pert_after",
                                popInh,
                                tpfsPertInh_after.id,
                                all_cells=False,
                                only_cells=range(0, num_inh_pert))

    # injecting noise in the soma of detailed neurons to insert some variability
    '''oc.add_targeted_inputs_to_population(network, 
                                         "PG_noise",
                                         popExc2, 
                                         'noisyCurrentSource1',             # from ../../../NoisyCurrentSource.xml
                                         segment_group='soma_group',
                                         number_per_cell = 1,
                                         all_cells=True)
    
    
    oc.add_inputs_to_population(network, "Stim_pre_ExtExc_%s"%popExc.id,
                                    popExc, tpfsExtExc.id,
                                    all_cells=True)

    for pop in allExc:
        #oc.add_inputs_to_population(network, "Stim_pre_ExtExc_%s"%pop.id,
        #                            pop, tpfsExtExc.id,
        #                            all_cells=True)

        oc.add_inputs_to_population(network, "Stim_pre_%s"%pop.id,
                                    pop, tpfsA.id,
                                    all_cells=True)
        
        oc.add_inputs_to_population(network, "Stim_E_%s"%pop.id,
                                    pop, tpfsB.id,
                                    all_cells=True) 

    for pop in allInh:
        num_inh_pert = int(pop.get_size()*fraction_inh_pert)

        oc.add_inputs_to_population(network, "Stim_pre_ExtInh_%s"%pop.id,
                                    pop, tpfsExtInh.id,
                                    all_cells=True)

        oc.add_inputs_to_population(network, "Stim_pre_%s"%pop.id,
                                    pop, tpfsA.id,
                                    all_cells=True)
        
        oc.add_inputs_to_population(network, "Stim_I_pert_%s"%pop.id,
                                    pop, tpfsC.id,
                                    all_cells=False,
                                    only_cells=range(0,num_inh_pert))   
                                    
        oc.add_inputs_to_population(network, "Stim_I_nonpert_%s"%pop.id,
                                    pop, tpfsB.id,
                                    all_cells=False,
                                    only_cells=range(num_inh_pert,pop.get_size()))  '''

    save_v = {}
    plot_v = {}

    # Work in progress...
    # General idea: clamp one (or more) exc cell at rev pot of inh syn and see only exc inputs
    #
    if v_clamp:

        levels = {'IPSC': synAmpaEE.erev, 'EPSC': synGabaIE.erev}

        for l in levels:
            cell_index = levels.keys().index(l)

            pop = 'popExc2'
            plot = 'IClamp_i_%s' % (l)

            for seg_id in [0, 2953,
                           1406]:  # 2953: end of axon; 1406 on dendrite

                clamp_id = "vclamp_cell%s_seg%s_%s" % (cell_index, seg_id, l)
                v_clamped = levels[l]

                vc = oc.add_voltage_clamp_triple(
                    nml_doc,
                    id=clamp_id,
                    delay='0ms',
                    duration='%sms' % duration,
                    conditioning_voltage=v_clamped,
                    testing_voltage=v_clamped,
                    return_voltage=v_clamped,
                    simple_series_resistance="1e2ohm",
                    active="1")

                vc_dat_file = 'v_clamps_i_seg%s_%s.%s.dat' % (seg_id, l,
                                                              simulation_seed)

                seg_file = '%s_seg%s_%s_v.dat' % (pop, seg_id, l)

                save_v[vc_dat_file] = []
                plot_v[plot] = []

                oc.add_inputs_to_population(network,
                                            "vclamp_seg%s_%s" % (seg_id, l),
                                            network.get_by_id(pop),
                                            vc.id,
                                            all_cells=False,
                                            only_cells=[cell_index],
                                            segment_ids=[seg_id])

                # record at seg
                q = '%s/%s/%s/%s/%s/i' % (pop, cell_index,
                                          network.get_by_id(pop).component,
                                          seg_id, clamp_id)

                save_v[vc_dat_file].append(q)
                plot_v[plot].append(q)

                if seg_id != 0:
                    save_v[seg_file] = []
                    q = '%s/%s/%s/%s/v' % (pop, cell_index,
                                           network.get_by_id(pop).component,
                                           seg_id)
                    save_v[seg_file].append(q)

    #####   Save NeuroML and LEMS Simulation files

    nml_file_name = '%s.net.%s' % (network.id,
                                   'nml.h5' if format == 'hdf5' else 'nml')
    oc.save_network(nml_doc,
                    nml_file_name,
                    validate=(format == 'xml'),
                    format=format,
                    target_dir=target_dir)

    print("Saved to: %s" % nml_file_name)

    if num_exc > 0:
        exc_traces = '%s_%s_v.dat' % (network.id, popExc.id)
        save_v[exc_traces] = []
        plot_v[popExc.id] = []

    if num_inh > 0:
        inh_traces = '%s_%s_v.dat' % (network.id, popInh.id)
        save_v[inh_traces] = []
        plot_v[popInh.id] = []

    if num_exc2 > 0:
        exc2_traces = '%s_%s_v.dat' % (network.id, popExc2.id)
        save_v[exc2_traces] = []
        plot_v[popExc2.id] = []

    if num_inh2 > 0:
        inh2_traces = '%s_%s_v.dat' % (network.id, popInh2.id)
        save_v[inh2_traces] = []
        plot_v[popInh2.id] = []

    for i in range(min(max_in_pop_to_plot_and_save, num_exc)):
        plot_v[popExc.id].append("%s/%i/%s/v" %
                                 (popExc.id, i, popExc.component))
        save_v[exc_traces].append("%s/%i/%s/v" %
                                  (popExc.id, i, popExc.component))

    for i in range(min(max_in_pop_to_plot_and_save, num_exc2)):
        plot_v[popExc2.id].append("%s/%i/%s/v" %
                                  (popExc2.id, i, popExc2.component))
        save_v[exc2_traces].append("%s/%i/%s/v" %
                                   (popExc2.id, i, popExc2.component))

    for i in range(min(max_in_pop_to_plot_and_save, num_inh)):
        plot_v[popInh.id].append("%s/%i/%s/v" %
                                 (popInh.id, i, popInh.component))
        save_v[inh_traces].append("%s/%i/%s/v" %
                                  (popInh.id, i, popInh.component))

    for i in range(min(max_in_pop_to_plot_and_save, num_inh2)):
        plot_v[popInh2.id].append("%s/%i/%s/v" %
                                  (popInh2.id, i, popInh2.component))
        save_v[inh2_traces].append("%s/%i/%s/v" %
                                   (popInh2.id, i, popInh2.component))

    gen_spike_saves_for_all_somas = True

    lems_file_name, lems_sim = oc.generate_lems_simulation(
        nml_doc,
        network,
        target_dir + nml_file_name,
        duration=duration,
        dt=dt,
        gen_plots_for_all_v=False,
        gen_plots_for_quantities=plot_v,
        gen_saves_for_all_v=False,
        gen_saves_for_quantities=save_v,
        gen_spike_saves_for_all_somas=gen_spike_saves_for_all_somas,
        target_dir=target_dir,
        include_extra_lems_files=['./NoisyCurrentSource.xml'],
        report_file_name='report.txt',
        simulation_seed=simulation_seed)

    if run_in_simulator:

        print("Running %s for %sms in %s" %
              (lems_file_name, duration, run_in_simulator))

        traces, events = oc.simulate_network(lems_file_name,
                                             run_in_simulator,
                                             max_memory='4000M',
                                             nogui=True,
                                             load_saved_data=True,
                                             reload_events=True,
                                             plot=False,
                                             verbose=True,
                                             num_processors=num_processors)

        print("Reloaded traces: %s" % traces.keys())
        #print("Reloaded events: %s"%events.keys())

        use_events_for_rates = False

        exc_rate = 0
        inh_rate = 0

        if use_events_for_rates:
            if (run_in_simulator == 'jNeuroML_NetPyNE'):
                raise (
                    'Saving of spikes (and so calculation of rates) not yet supported in jNeuroML_NetPyNE'
                )
            for ek in events.keys():
                rate = 1000 * len(events[ek]) / float(duration)
                print("Cell %s has a rate %s Hz" % (ek, rate))
                if 'popExc' in ek:
                    exc_rate += rate / num_exc
                if 'popInh' in ek:
                    inh_rate += rate / num_inh

        else:
            tot_exc_rate = 0
            exc_cells = 0
            tot_inh_rate = 0
            inh_cells = 0
            tt = [t * 1000 for t in traces['t']]
            for tk in traces.keys():
                if tk != 't':
                    rate = get_rate_from_trace(tt,
                                               [v * 1000 for v in traces[tk]])
                    print("Cell %s has rate %s Hz" % (tk, rate))
                    if 'popExc' in tk:
                        tot_exc_rate += rate
                        exc_cells += 1
                    if 'popInh' in tk:
                        tot_inh_rate += rate
                        inh_cells += 1

            exc_rate = tot_exc_rate / exc_cells
            inh_rate = tot_inh_rate / inh_cells

        print("Run %s: Exc rate: %s Hz; Inh rate %s Hz" %
              (reference, exc_rate, inh_rate))

        return exc_rate, inh_rate, traces

    return nml_doc, nml_file_name, lems_file_name
Beispiel #11
0
def create_olm_cell():
    """Create the complete cell.

    :returns: cell object
    """
    nml_cell_doc = NeuroMLDocument(id="oml_cell")
    cell = create_cell("olm")
    nml_cell_file = cell.id + ".cell.nml"

    # Add two soma segments
    diam = 10.0
    soma_0 = add_segment(cell,
                         prox=[0.0, 0.0, 0.0, diam],
                         dist=[0.0, 10., 0.0, diam],
                         name="Seg0_soma_0",
                         group="soma_0")

    soma_1 = add_segment(cell,
                         prox=None,
                         dist=[0.0, 10. + 10., 0.0, diam],
                         name="Seg1_soma_0",
                         parent=soma_0,
                         group="soma_0")

    # Add axon segments
    diam = 1.5
    axon_0 = add_segment(cell,
                         prox=[0.0, 0.0, 0.0, diam],
                         dist=[0.0, -75, 0.0, diam],
                         name="Seg0_axon_0",
                         parent=soma_0,
                         fraction_along=0.0,
                         group="axon_0")
    axon_1 = add_segment(cell,
                         prox=None,
                         dist=[0.0, -150, 0.0, diam],
                         name="Seg1_axon_0",
                         parent=axon_0,
                         group="axon_0")

    # Add 2 dendrite segments

    diam = 3.0
    dend_0_0 = add_segment(cell,
                           prox=[0.0, 20, 0.0, diam],
                           dist=[100, 120, 0.0, diam],
                           name="Seg0_dend_0",
                           parent=soma_1,
                           fraction_along=1,
                           group="dend_0")

    dend_1_0 = add_segment(cell,
                           prox=None,
                           dist=[177, 197, 0.0, diam],
                           name="Seg1_dend_0",
                           parent=dend_0_0,
                           fraction_along=1,
                           group="dend_0")

    dend_0_1 = add_segment(cell,
                           prox=[0.0, 20, 0.0, diam],
                           dist=[-100, 120, 0.0, diam],
                           name="Seg0_dend_1",
                           parent=soma_1,
                           fraction_along=1,
                           group="dend_1")
    dend_1_1 = add_segment(cell,
                           prox=None,
                           dist=[-177, 197, 0.0, diam],
                           name="Seg1_dend_1",
                           parent=dend_0_1,
                           fraction_along=1,
                           group="dend_1")

    # XXX: For segment groups to be correctly mapped to sections in NEURON,
    # they must include the correct neurolex ID
    for section_name in ["soma_0", "axon_0", "dend_0", "dend_1"]:
        section_group = get_seg_group_by_id(section_name, cell)
        section_group.neuro_lex_id = 'sao864921383'

    den_seg_group = get_seg_group_by_id("dendrite_group", cell)
    den_seg_group.includes.append(Include(segment_groups="dend_0"))
    den_seg_group.includes.append(Include(segment_groups="dend_1"))
    den_seg_group.properties.append(Property(tag="color", value="0.8 0 0"))

    ax_seg_group = get_seg_group_by_id("axon_group", cell)
    ax_seg_group.includes.append(Include(segment_groups="axon_0"))
    ax_seg_group.properties.append(Property(tag="color", value="0 0.8 0"))

    soma_seg_group = get_seg_group_by_id("soma_group", cell)
    soma_seg_group.includes.append(Include(segment_groups="soma_0"))

    soma_seg_group.properties.append(Property(tag="color", value="0 0 0.8"))

    # Other cell properties
    set_init_memb_potential(cell, "-67mV")
    set_resistivity(cell, "0.15 kohm_cm")
    set_specific_capacitance(cell, "1.3 uF_per_cm2")

    # channels
    # leak
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="leak_all",
                        cond_density="0.01 mS_per_cm2",
                        ion_channel="leak_chan",
                        ion_chan_def_file="olm-example/leak_chan.channel.nml",
                        erev="-67mV",
                        ion="non_specific")
    # HCNolm_soma
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="HCNolm_soma",
                        cond_density="0.5 mS_per_cm2",
                        ion_channel="HCNolm",
                        ion_chan_def_file="olm-example/HCNolm.channel.nml",
                        erev="-32.9mV",
                        ion="h",
                        group="soma_group")
    # Kdrfast_soma
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="Kdrfast_soma",
                        cond_density="73.37 mS_per_cm2",
                        ion_channel="Kdrfast",
                        ion_chan_def_file="olm-example/Kdrfast.channel.nml",
                        erev="-77mV",
                        ion="k",
                        group="soma_group")
    # Kdrfast_dendrite
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="Kdrfast_dendrite",
                        cond_density="105.8 mS_per_cm2",
                        ion_channel="Kdrfast",
                        ion_chan_def_file="olm-example/Kdrfast.channel.nml",
                        erev="-77mV",
                        ion="k",
                        group="dendrite_group")
    # Kdrfast_axon
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="Kdrfast_axon",
                        cond_density="117.392 mS_per_cm2",
                        ion_channel="Kdrfast",
                        ion_chan_def_file="olm-example/Kdrfast.channel.nml",
                        erev="-77mV",
                        ion="k",
                        group="axon_group")
    # KvAolm_soma
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="KvAolm_soma",
                        cond_density="4.95 mS_per_cm2",
                        ion_channel="KvAolm",
                        ion_chan_def_file="olm-example/KvAolm.channel.nml",
                        erev="-77mV",
                        ion="k",
                        group="soma_group")
    # KvAolm_dendrite
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="KvAolm_dendrite",
                        cond_density="2.8 mS_per_cm2",
                        ion_channel="KvAolm",
                        ion_chan_def_file="olm-example/KvAolm.channel.nml",
                        erev="-77mV",
                        ion="k",
                        group="dendrite_group")
    # Nav_soma
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="Nav_soma",
                        cond_density="10.7 mS_per_cm2",
                        ion_channel="Nav",
                        ion_chan_def_file="olm-example/Nav.channel.nml",
                        erev="50mV",
                        ion="na",
                        group="soma_group")
    # Nav_dendrite
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="Nav_dendrite",
                        cond_density="23.4 mS_per_cm2",
                        ion_channel="Nav",
                        ion_chan_def_file="olm-example/Nav.channel.nml",
                        erev="50mV",
                        ion="na",
                        group="dendrite_group")
    # Nav_axon
    add_channel_density(cell,
                        nml_cell_doc,
                        cd_id="Nav_axon",
                        cond_density="17.12 mS_per_cm2",
                        ion_channel="Nav",
                        ion_chan_def_file="olm-example/Nav.channel.nml",
                        erev="50mV",
                        ion="na",
                        group="axon_group")

    nml_cell_doc.cells.append(cell)
    pynml.write_neuroml2_file(nml_cell_doc, nml_cell_file, True, True)
    return nml_cell_file