def add_instance(name, x, y, z):

    pop = populations[name]
    inst = Instance(id=len(pop.instances))
    pop.size = pop.size + 1
    pop.instances.append(inst)
    inst.location = Location(x=x, y=y, z=z)
def writeConnections():
    net_id = "MuscleConnections"
    nml_network_doc = NeuroMLDocument(id=net_id)

    # Create a NeuroML Network data structure to hold on to all the neuron-
    # muscle connection info.
    net = Network(id=net_id)
    nml_network_doc.networks.append(net)

    pop0 = Population(id=muscles[0].name, component=muscles[0].name, size=1)
    inst = Instance(id="0")
    inst.location = Location(x="0.0", y="0.0", z="0.0")
    pop0.instances.append(inst)

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

    for (pre_cell, post_cell, close_pairs) in connect_list:

        # take information about each connection and package it into a 
        # NeuroML Projection data structure
        proj_id = "NCXLS_%s_%s"%(pre_cell, post_cell)
        proj0 = Projection(id=proj_id,
                           presynaptic_population=pre_cell,
                           postsynaptic_population=post_cell) 
                           #synapse=conn.synclass)
        for conn0 in close_pairs:
            proj0.connections.append(conn0)

        net.projections.append(proj0)
    nml_file = 'Output/' + net_id+'.nml'
    writers.NeuroMLWriter.write(nml_network_doc, nml_file)
def writeConnections():
    net_id = "MuscleConnections"
    nml_network_doc = NeuroMLDocument(id=net_id)

    # Create a NeuroML Network data structure to hold on to all the neuron-
    # muscle connection info.
    net = Network(id=net_id)
    nml_network_doc.networks.append(net)

    pop0 = Population(id=muscles[0].name, component=muscles[0].name, size=1)
    inst = Instance(id="0")
    inst.location = Location(x="0.0", y="0.0", z="0.0")
    pop0.instances.append(inst)

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

    for (pre_cell, post_cell, close_pairs) in connect_list:

        # take information about each connection and package it into a
        # NeuroML Projection data structure
        proj_id = "NCXLS_%s_%s" % (pre_cell, post_cell)
        proj0 = Projection(id=proj_id,
                           presynaptic_population=pre_cell,
                           postsynaptic_population=post_cell)
        #synapse=conn.synclass)
        for conn0 in close_pairs:
            proj0.connections.append(conn0)

        net.projections.append(proj0)
    nml_file = 'Output/' + net_id + '.nml'
    writers.NeuroMLWriter.write(nml_network_doc, nml_file)
def add_population_in_rectangular_region(net, pop_id, cell_id, size, x_min, y_min, z_min, x_size, y_size, z_size, color=None):
    
        pop = Population(id=pop_id, component=cell_id, type="populationList", size=size)
        if color is not None:
            pop.properties.append(Property("color",color))
        net.populations.append(pop)

        for i in range(0, size) :
                index = i
                inst = Instance(id=index)
                pop.instances.append(inst)
                inst.location = Location(x=str(x_min +(x_size)*random()), y=str(y_min +(y_size)*random()), z=str(z_min+(z_size)*random()))
Beispiel #5
0
def create_olm_network():
    """Create the network

    :returns: name of network nml file
    """
    net_doc = NeuroMLDocument(id="network", notes="OLM cell network")
    net_doc_fn = "olm_example_net.nml"
    net_doc.includes.append(IncludeType(href=create_olm_cell()))
    # Create a population: convenient to create many cells of the same type
    pop = Population(id="pop0",
                     notes="A population for our cell",
                     component="olm",
                     size=1,
                     type="populationList")
    pop.instances.append(Instance(id=1, location=Location(0., 0., 0.)))
    # Input
    pulsegen = PulseGenerator(id="pg_olm",
                              notes="Simple pulse generator",
                              delay="100ms",
                              duration="100ms",
                              amplitude="0.08nA")

    exp_input = ExplicitInput(target="pop0[0]", input="pg_olm")

    net = Network(id="single_olm_cell_network",
                  note="A network with a single population")
    net_doc.pulse_generators.append(pulsegen)
    net.explicit_inputs.append(exp_input)
    net.populations.append(pop)
    net_doc.networks.append(net)

    pynml.write_neuroml2_file(nml2_doc=net_doc,
                              nml2_file_name=net_doc_fn,
                              validate=True)
    return net_doc_fn
def run():

    cell_num = 2
    
    nml_doc = NeuroMLDocument(id="demo_attraction")

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

    for cell_id in range(0,cell_num):

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

        cell.morphology = generate_with_morphology(db_name,cfg_file)
        
        nml_doc.cells.append(cell)

        pop = Population(id="Pop_%i"%cell_id, component=cell.id, type="populationList")
        net.populations.append(pop)
       
        inst = Instance(id="0")
        pop.instances.append(inst)

        inst.location = Location(x=0, y=0, z=0)
    
        
    
    #######   Write to file  ######    
 
     	nml_file = 'demo_attraction/demo_attraction.net.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
                segment.distal.x, segment.distal.y, -1 * theta + math.pi)

        nml_file = new_ref + '.cell.nml'

        writers.NeuroMLWriter.write(doc, nml_file)

        print("Saved modified morphology file to: " + nml_file)

        net_doc.includes.append(IncludeType(nml_file))

        pop = Population(id="Pop_%s" % new_ref,
                         component=new_ref,
                         type="populationList")

        net.populations.append(pop)

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

        width = 6
        X = count % width
        Z = (count - X) / width
        inst.location = Location(x=300 * X, y=0, z=300 * Z)

        count += 1

net_file = net_ref + '.net.nml'
writers.NeuroMLWriter.write(net_doc, net_file)

print("Written network with %i cells in network to: %s" % (count, net_file))
Beispiel #8
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 #9
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 #10
0
    def createModel(self):

        # File names of all components
        pyr_file_name = "../ACnet2_NML2/Cells/pyr_4_sym.cell.nml"
        bask_file_name = "../ACnet2_NML2/Cells/bask.cell.nml"

        exc_exc_syn_names = '../ACnet2_NML2/Synapses/AMPA_syn.synapse.nml'
        exc_inh_syn_names = '../ACnet2_NML2/Synapses/AMPA_syn_inh.synapse.nml'
        inh_exc_syn_names = '../ACnet2_NML2/Synapses/GABA_syn.synapse.nml'
        inh_inh_syn_names = '../ACnet2_NML2/Synapses/GABA_syn_inh.synapse.nml'
        bg_exc_syn_names = '../ACnet2_NML2/Synapses/bg_AMPA_syn.synapse.nml'

        nml_doc = NeuroMLDocument(id=self.filename + '_doc')
        net = Network(id=self.filename + '_net')
        nml_doc.networks.append(net)

        nml_doc.includes.append(IncludeType(pyr_file_name))
        nml_doc.includes.append(IncludeType(bask_file_name))
        nml_doc.includes.append(IncludeType(exc_exc_syn_names))
        nml_doc.includes.append(IncludeType(exc_inh_syn_names))
        nml_doc.includes.append(IncludeType(inh_exc_syn_names))
        nml_doc.includes.append(IncludeType(inh_inh_syn_names))
        nml_doc.includes.append(IncludeType(bg_exc_syn_names))

        # Create a LEMSSimulation to manage creation of LEMS file
        ls = LEMSSimulation(self.filename, self.sim_time, self.dt)

        # Point to network as target of simulation
        ls.assign_simulation_target(net.id)

        # The names of the cell type/component used in the Exc & Inh populations
        exc_group_component = "pyr_4_sym"
        inh_group_component = "bask"

        # The names of the Exc & Inh groups/populations
        exc_group = "pyramidals"  #"pyramidals48x48"
        inh_group = "baskets"  #"baskets24x24"

        # The names of the network connections
        net_conn_exc_exc = "pyr_pyr"
        net_conn_exc_inh = "pyr_bask"
        net_conn_inh_exc = "bask_pyr"
        net_conn_inh_inh = "bask_bask"

        # The names of the synapse types
        exc_exc_syn = "AMPA_syn"
        exc_exc_syn_seg_id = 3  # Middle apical dendrite
        exc_inh_syn = "AMPA_syn_inh"
        exc_inh_syn_seg_id = 1  # Dendrite
        inh_exc_syn = "GABA_syn"
        inh_exc_syn_seg_id = 6  # Basal dendrite
        inh_inh_syn = "GABA_syn_inh"
        inh_inh_syn_seg_id = 0  # Soma

        aff_exc_syn = "AMPA_aff_syn"
        aff_exc_syn_seg_id = 5  # proximal apical dendrite

        bg_exc_syn = "bg_AMPA_syn"
        bg_exc_syn_seg_id = 7  # Basal dendrite

        # Excitatory Parameters
        XSCALE_ex = 24  #48
        ZSCALE_ex = 24  #48
        xSpacing_ex = 40  # 10^-6m
        zSpacing_ex = 40  # 10^-6m

        # Inhibitory Parameters
        XSCALE_inh = 12  #24
        ZSCALE_inh = 12  #24
        xSpacing_inh = 80  # 10^-6m
        zSpacing_inh = 80  # 10^-6m

        numCells_ex = XSCALE_ex * ZSCALE_ex
        numCells_inh = XSCALE_inh * ZSCALE_inh

        # Connection probabilities (initial value)
        connection_probability_ex_ex = 0.15
        connection_probability_ex_inh = 0.45
        connection_probability_inh_ex = 0.6
        connection_probability_inh_inh = 0.6

        # Generate excitatory cells

        exc_pop = Population(id=exc_group,
                             component=exc_group_component,
                             type="populationList",
                             size=XSCALE_ex * ZSCALE_ex)
        net.populations.append(exc_pop)

        exc_pos = np.zeros((XSCALE_ex * ZSCALE_ex, 2))

        for i in range(0, XSCALE_ex):
            for j in range(0, ZSCALE_ex):
                # create cells
                x = i * xSpacing_ex
                z = j * zSpacing_ex
                index = i * ZSCALE_ex + j

                inst = Instance(id=index)
                exc_pop.instances.append(inst)

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

                exc_pos[index, 0] = x
                exc_pos[index, 1] = z

        # Generate inhibitory cells

        inh_pop = Population(id=inh_group,
                             component=inh_group_component,
                             type="populationList",
                             size=XSCALE_inh * ZSCALE_inh)
        net.populations.append(inh_pop)

        inh_pos = np.zeros((XSCALE_inh * ZSCALE_inh, 2))

        for i in range(0, XSCALE_inh):
            for j in range(0, ZSCALE_inh):
                # create cells
                x = i * xSpacing_inh
                z = j * zSpacing_inh
                index = i * ZSCALE_inh + j

                inst = Instance(id=index)
                inh_pop.instances.append(inst)

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

                inh_pos[index, 0] = x
                inh_pos[index, 1] = z

        proj_exc_exc = Projection(id=net_conn_exc_exc,
                                  presynaptic_population=exc_group,
                                  postsynaptic_population=exc_group,
                                  synapse=exc_exc_syn)
        net.projections.append(proj_exc_exc)
        proj_exc_inh = Projection(id=net_conn_exc_inh,
                                  presynaptic_population=exc_group,
                                  postsynaptic_population=inh_group,
                                  synapse=exc_inh_syn)
        net.projections.append(proj_exc_inh)
        proj_inh_exc = Projection(id=net_conn_inh_exc,
                                  presynaptic_population=inh_group,
                                  postsynaptic_population=exc_group,
                                  synapse=inh_exc_syn)
        net.projections.append(proj_inh_exc)
        proj_inh_inh = Projection(id=net_conn_inh_inh,
                                  presynaptic_population=inh_group,
                                  postsynaptic_population=inh_group,
                                  synapse=inh_inh_syn)
        net.projections.append(proj_inh_inh)

        # Generate exc -> *  connections

        exc_exc_conn = np.zeros((numCells_ex, numCells_ex))
        exc_inh_conn = np.zeros((numCells_ex, numCells_inh))

        count_exc_exc = 0
        count_exc_inh = 0
        for i in range(0, XSCALE_ex):
            for j in range(0, ZSCALE_ex):
                x = i * xSpacing_ex
                y = j * zSpacing_ex
                index = i * ZSCALE_ex + j
                #print("Looking at connections for exc cell at (%i, %i)"%(i,j))

                # exc -> exc  connections
                conn_type = net_conn_exc_exc
                for k in range(0, XSCALE_ex):
                    for l in range(0, ZSCALE_ex):

                        # calculate distance from pre- to post-synaptic neuron
                        xk = k * xSpacing_ex
                        yk = l * zSpacing_ex
                        distance = math.sqrt((x - xk)**2 + (y - yk)**2)
                        connection_probability = connection_probability_ex_ex * math.exp(
                            -(distance / (10.0 * xSpacing_ex))**2)

                        # create a random number between 0 and 1, if it is <= connection_probability
                        # accept connection otherwise refuse
                        a = random.random()
                        if 0 < a <= connection_probability:
                            index2 = k * ZSCALE_ex + l
                            count_exc_exc += 1

                            add_connection(proj_exc_exc, count_exc_exc,
                                           exc_group, exc_group_component,
                                           index, 0, exc_group,
                                           exc_group_component, index2,
                                           exc_exc_syn_seg_id)

                            exc_exc_conn[index, index2] = 1

                # exc -> inh  connections
                conn_type = net_conn_exc_inh
                for k in range(0, XSCALE_inh):
                    for l in range(0, ZSCALE_inh):

                        # calculate distance from pre- to post-synaptic neuron
                        xk = k * xSpacing_inh
                        yk = l * zSpacing_inh
                        distance = math.sqrt((x - xk)**2 + (y - yk)**2)
                        connection_probability = connection_probability_ex_inh * math.exp(
                            -(distance / (10.0 * xSpacing_ex))**2)

                        # create a random number between 0 and 1, if it is <= connection_probability
                        # accept connection otherwise refuse
                        a = random.random()
                        if 0 < a <= connection_probability:
                            index2 = k * ZSCALE_inh + l
                            count_exc_inh += 1

                            add_connection(proj_exc_inh, count_exc_inh,
                                           exc_group, exc_group_component,
                                           index, 0, inh_group,
                                           inh_group_component, index2,
                                           exc_inh_syn_seg_id)

                            exc_inh_conn[index, index2] = 1

        inh_exc_conn = np.zeros((numCells_inh, numCells_ex))
        inh_inh_conn = np.zeros((numCells_inh, numCells_inh))

        count_inh_exc = 0
        count_inh_inh = 0
        for i in range(0, XSCALE_inh):
            for j in range(0, ZSCALE_inh):

                x = i * xSpacing_inh
                y = j * zSpacing_inh
                index = i * ZSCALE_inh + j
                #print("Looking at connections for inh cell at (%i, %i)"%(i,j))

                # inh -> exc  connections
                conn_type = net_conn_inh_exc
                for k in range(0, XSCALE_ex):
                    for l in range(0, ZSCALE_ex):

                        # calculate distance from pre- to post-synaptic neuron
                        xk = k * xSpacing_ex
                        yk = l * zSpacing_ex
                        distance = math.sqrt((x - xk)**2 + (y - yk)**2)
                        connection_probability = connection_probability_inh_ex * math.exp(
                            -(distance / (10.0 * xSpacing_ex))**2)

                        # create a random number between 0 and 1, if it is <= connection_probability
                        # accept connection otherwise refuse
                        a = random.random()
                        if 0 < a <= connection_probability:
                            index2 = k * ZSCALE_ex + l
                            count_inh_exc += 1

                            add_connection(proj_inh_exc, count_inh_exc,
                                           inh_group, inh_group_component,
                                           index, 0, exc_group,
                                           exc_group_component, index2,
                                           inh_exc_syn_seg_id)

                            inh_exc_conn[index, index2] = 1

                # inh -> inh  connections
                conn_type = net_conn_inh_inh
                for k in range(0, XSCALE_inh):
                    for l in range(0, ZSCALE_inh):

                        # calculate distance from pre- to post-synaptic neuron
                        xk = k * xSpacing_inh
                        yk = l * zSpacing_inh
                        distance = math.sqrt((x - xk)**2 + (y - yk)**2)
                        connection_probability = connection_probability_inh_inh * math.exp(
                            -(distance / (10.0 * xSpacing_ex))**2)

                        # create a random number between 0 and 1, if it is <= connection_probability
                        # accept connection otherwise refuse
                        a = random.random()
                        if 0 < a <= connection_probability:
                            index2 = k * ZSCALE_inh + l
                            count_inh_inh += 1

                            add_connection(proj_inh_inh, count_inh_inh,
                                           inh_group, inh_group_component,
                                           index, 0, inh_group,
                                           inh_group_component, index2,
                                           inh_inh_syn_seg_id)

                            inh_inh_conn[index, index2] = 1

        print(
            "Generated network with %i exc_exc, %i exc_inh, %i inh_exc, %i inh_inh connections"
            % (count_exc_exc, count_exc_inh, count_inh_exc, count_inh_inh))

        #######   Create Input   ######
        # Create a sine generator
        sgE = SineGenerator(id="sineGen_0",
                            phase="0",
                            delay="0ms",
                            duration=str(self.sim_time) + "ms",
                            amplitude=str(self.Edrive_weight) + "nA",
                            period=str(self.Drive_period) + "ms")
        sgI = SineGenerator(id="sineGen_1",
                            phase="0",
                            delay="0ms",
                            duration=str(self.sim_time) + "ms",
                            amplitude=str(self.Idrive_weight) + "nA",
                            period=str(self.Drive_period) + "ms")

        nml_doc.sine_generators.append(sgE)
        nml_doc.sine_generators.append(sgI)
        # Create an input object for each excitatory cell
        for i in range(0, XSCALE_ex):
            exp_input = ExplicitInput(target="%s[%i]" % (exc_pop.id, i),
                                      input=sgE.id)
            net.explicit_inputs.append(exp_input)

        # Create an input object for a percentage of inhibitory cells
        input_probability = 0.65
        for i in range(0, XSCALE_inh):
            ran = random.random()
            if 0 < ran <= input_probability:
                inh_input = ExplicitInput(target="%s[%i]" % (inh_pop.id, i),
                                          input=sgI.id)
                net.explicit_inputs.append(inh_input)

        # Define Poisson noise input

        # Ex

        #nml_doc.includes.append(IncludeType('Synapses/bg_AMPA_syn.synapse.nml'))

        pfs1 = PoissonFiringSynapse(id="poissonFiringSyn1",
                                    average_rate=str(self.bg_noise_frequency) +
                                    "Hz",
                                    synapse=bg_exc_syn,
                                    spike_target="./%s" % bg_exc_syn)
        nml_doc.poisson_firing_synapses.append(pfs1)

        pfs_input_list1 = InputList(id="pfsInput1",
                                    component=pfs1.id,
                                    populations=exc_pop.id)
        net.input_lists.append(pfs_input_list1)
        for i in range(0, numCells_ex):
            pfs_input_list1.input.append(
                Input(id=i,
                      target='../%s/%i/%s' %
                      (exc_pop.id, i, exc_group_component),
                      segment_id=bg_exc_syn_seg_id,
                      destination="synapses"))

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

        print("Saving to file...")
        nml_file = '../ACnet2_NML2/' + self.filename + '_doc' + '.net.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)
        print "-----------------------------------"

        ###### Output #######

        # Output membrane potential
        # Ex population
        Ex_potentials = 'V_Ex'
        ls.create_output_file(Ex_potentials,
                              "../ACnet2_NML2/Results/v_exc.dat")
        for j in range(numCells_ex):
            quantity = "%s[%i]/v" % (exc_pop.id, j)
            v = 'v' + str(j)
            ls.add_column_to_output_file(Ex_potentials, v, quantity)

        # Inh population
        #Inh_potentials = 'V_Inh'
        #ls.create_output_file(Inh_potentials, "../ACnet2_NML2/Results/v_inh.dat")
        #for j in range(numCells_inh):
        #	quantity = "%s[%i]/v"%(inh_pop.id, j)
        #	v = 'v'+str(j)
        #	ls.add_column_to_output_file(Inh_potentials,v, quantity)

        # include generated network
        ls.include_neuroml2_file(nml_file)

        # Save to LEMS XML file
        lems_file_name = ls.save_to_file(file_name='../ACnet2_NML2/LEMS_' +
                                         self.filename + '.xml')
Beispiel #11
0
def generate(
    net_id, params, cells=None, cells_to_plot=None, cells_to_stimulate=None, duration=500, dt=0.01, vmin=-75, vmax=20
):

    nml_doc = NeuroMLDocument(id=net_id)

    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...
    cell_names, conns = SpreadsheetDataReader.readDataFromSpreadsheet("../../../")

    cell_names.sort()

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

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

    lems_info["plots"] = []
    lems_info["cells"] = []

    for cell in cell_names:

        if cells is None or cell in cells:
            # build a Population data structure out of the cell name
            pop0 = Population(id=cell, component=params.generic_cell.id, type="populationList")

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

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

            # also use the cell name to grab the morphology file, as a NeuroML data structure
            #  into the 'all_cells' dict
            cell_file = "../../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))

            exp_input = ExplicitInput(
                target="%s/0/%s" % (pop0.id, params.generic_cell.id), 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()
                lems_info["plots"].append(plot)

            lems_info["cells"].append(cell)

    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)

            syn0 = params.exc_syn
            if "GABA" in conn.synclass:
                syn0 = params.inh_syn

            syn_new = create_n_connection_synapse(syn0, conn.number, nml_doc)

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

            # Get the corresponding Cell for each
            # pre_cell = all_cells[conn.pre_cell]
            # post_cell = all_cells[conn.post_cell]

            net.projections.append(proj0)

            # Add a Connection with the closest locations
            conn0 = Connection(
                id="0",
                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),
            )

            proj0.connections.append(conn0)

    write_to_file(nml_doc, lems_info, net_id)
net.populations.append(pop1)



cell_num = 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()), y=str(y_size*random()), z=str(z_size*random()))

prob_connection = 0.5
proj_count = 0


from_pop = "Pop_x"
to_pop = "Pop_x"
projection = Projection(id="Proj", presynaptic_population=from_pop, postsynaptic_population=to_pop, synapse=syn0.id)

net.projections.append(projection)

Beispiel #13
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)

        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 #14
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
connection_probability_inh_inh = 0.6


# Generate excitatory cells 

exc_pop = Population(id=exc_group, component=exc_group_component, type="populationList", size=XSCALE_ex*ZSCALE_ex)
net.populations.append(exc_pop)

for i in range(0, XSCALE_ex) :
    for j in range(0, ZSCALE_ex):
        # create cells
        x = i*xSpacing_ex
        z = j*zSpacing_ex
        index = i*ZSCALE_ex + j 

        inst = Instance(id=index)
        exc_pop.instances.append(inst)

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

# Generate inhibitory cells

inh_pop = Population(id=inh_group, component=inh_group_component, type="populationList", size=XSCALE_inh*ZSCALE_inh)
net.populations.append(inh_pop)

for i in range(0, XSCALE_inh) :
    for j in range(0, ZSCALE_inh):
        # create cells
        x = i*xSpacing_inh
        z = j*zSpacing_inh
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

from_pop = pop.id
to_pop = pop.id
projection = Projection(id="Proj",
                        presynaptic_population=from_pop,
                        postsynaptic_population=to_pop,
                        synapse=syn0.id)
def generate_granule_cell_layer(network_id,
                                x_size,     # um
                                y_size,     # um
                                z_size,     # um
                                numCells_mf,
                                numCells_grc,
                                numCells_gol,
                                mf_group_component = "MossyFiber",
                                grc_group_component = "Granule_98",
                                gol_group_component = "Golgi_98",
                                connections = True,
                                connection_probability_grc_gol =   0.2,
                                connection_probability_gol_grc =   0.1,
                                inputs = False,
                                input_firing_rate = 50, # Hz
                                num_inputs_per_mf = 4,
                                validate = True,
                                random_seed = 1234,
                                generate_lems_simulation = False,
                                duration = 500,  # ms
                                dt = 0.005,
                                temperature="32.0 degC"):

    seed(random_seed)

    nml_doc = NeuroMLDocument(id=network_id)

    net = Network(id = network_id, 
                  type = "networkWithTemperature",
                  temperature = temperature)
                  
    net.notes = "Network generated using libNeuroML v%s"%__version__
    nml_doc.networks.append(net)

    if numCells_mf>0:
        nml_doc.includes.append(IncludeType(href='%s.cell.nml'%mf_group_component))
    if numCells_grc>0:
        nml_doc.includes.append(IncludeType(href='%s.cell.nml'%grc_group_component))
    if numCells_gol>0:
        nml_doc.includes.append(IncludeType(href='%s.cell.nml'%gol_group_component))

    # The names of the groups/populations 
    mf_group = "MossyFibers" 
    grc_group = "Grans" 
    gol_group = "Golgis" 


    # The names of the synapse types (should match names at Cell Mechanism/Network tabs in neuroConstruct)=
    mf_grc_syn = "MF_AMPA"
    grc_gol_syn = "AMPA_GranGol"
    gol_grc_syn = "GABAA"

    for syn in [mf_grc_syn, grc_gol_syn, gol_grc_syn]:
        nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%syn))


    # Generate Gran cells 
    if numCells_mf>0:
        mf_pop = Population(id=mf_group, component=mf_group_component, type="populationList", size=numCells_mf)
        mf_pop.properties.append(Property("color","0 0 1"))
        net.populations.append(mf_pop)

        for i in range(0, numCells_mf) :
                index = i
                inst = Instance(id=index)
                mf_pop.instances.append(inst)
                inst.location = Location(x=str(x_size*random()), y=str(y_size*random()), z=str(z_size*random()))

    # Generate Gran cells 
    if numCells_grc>0:
        grc_pop = Population(id=grc_group, component=grc_group_component, type="populationList", size=numCells_grc)
        grc_pop.properties.append(Property("color","1 0 0"))
        net.populations.append(grc_pop)

        for i in range(0, numCells_grc) :
                index = i
                inst = Instance(id=index)
                grc_pop.instances.append(inst)
                inst.location = Location(x=str(x_size*random()), y=str(y_size*random()), z=str(z_size*random()))

    # Generate Golgi cells
    if numCells_gol>0:
        gol_pop = Population(id=gol_group, component=gol_group_component, type="populationList", size=numCells_gol)
        gol_pop.properties.append(Property("color","0 1 0"))
        net.populations.append(gol_pop)

        for i in range(0, numCells_gol) :
                index = i
                inst = Instance(id=index)
                gol_pop.instances.append(inst)
                inst.location = Location(x=str(x_size*random()), y=str(y_size*random()), z=str(z_size*random()))

    if connections:

        add_probabilistic_projection(net, mf_group, mf_group_component, grc_group, grc_group_component, 'NetConn', mf_grc_syn, numCells_mf, numCells_grc, 1)
    
        add_probabilistic_projection(net, grc_group, grc_group_component, gol_group, gol_group_component, 'NetConn', grc_gol_syn, numCells_grc, numCells_gol, connection_probability_grc_gol)
        
        add_probabilistic_projection(net, gol_group, gol_group_component, grc_group, grc_group_component, 'NetConn', gol_grc_syn, numCells_gol, numCells_grc, connection_probability_gol_grc)
    

    if inputs:
        
        mf_input_syn = "MFSpikeSyn"
        nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%mf_input_syn))
        
        rand_spiker_id = "input%sHz"%input_firing_rate
        
        
        #<poissonFiringSynapse id="Input_8" averageRate="50.0 per_s" synapse="MFSpikeSyn" spikeTarget="./MFSpikeSyn"/>
        pfs = PoissonFiringSynapse(id=rand_spiker_id,
                                   average_rate="%s per_s"%input_firing_rate,
                                   synapse=mf_input_syn,
                                   spike_target="./%s"%mf_input_syn)
                                   
        nml_doc.poisson_firing_synapses.append(pfs)
        
        input_list = InputList(id="Input_0",
                             component=rand_spiker_id,
                             populations=mf_group)
                             
        count = 0
        for i in range(0, numCells_mf):
            
            for j in range(num_inputs_per_mf):
                input = Input(id=count, 
                              target="../%s/%i/%s"%(mf_group, i, mf_group_component), 
                              destination="synapses")  
                input_list.input.append(input)
            
            count += 1
                             
        net.input_lists.append(input_list)


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

    print("Saving to file...")
    nml_file = network_id+'.net.nml'
    writers.NeuroMLWriter.write(nml_doc, nml_file)

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


    if validate:

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

        from neuroml.utils import validate_neuroml2
        validate_neuroml2(nml_file) 
        
    if generate_lems_simulation:
        # Create a LEMSSimulation to manage creation of LEMS file
        
        ls = LEMSSimulation("Sim_%s"%network_id, duration, dt)

        # Point to network as target of simulation
        ls.assign_simulation_target(net.id)
        
        # Include generated/existing NeuroML2 files
        ls.include_neuroml2_file('%s.cell.nml'%grc_group_component)
        ls.include_neuroml2_file('%s.cell.nml'%gol_group_component)
        ls.include_neuroml2_file(nml_file)
        

        # Specify Displays and Output Files
        if numCells_mf>0:
            disp_mf = "display_mf"
            ls.create_display(disp_mf, "Voltages Mossy fibers", "-70", "10")

            of_mf = 'Volts_file_mf'
            ls.create_output_file(of_mf, "v_mf.dat")


            for i in range(numCells_mf):
                quantity = "%s/%i/%s/v"%(mf_group, i, mf_group_component)
                ls.add_line_to_display(disp_mf, "MF %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color())
                ls.add_column_to_output_file(of_mf, "v_%i"%i, quantity)

        # Specify Displays and Output Files
        if numCells_grc>0:
            disp_grc = "display_grc"
            ls.create_display(disp_grc, "Voltages Granule cells", "-75", "30")

            of_grc = 'Volts_file_grc'
            ls.create_output_file(of_grc, "v_grc.dat")


            for i in range(numCells_grc):
                quantity = "%s/%i/%s/v"%(grc_group, i, grc_group_component)
                ls.add_line_to_display(disp_grc, "GrC %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color())
                ls.add_column_to_output_file(of_grc, "v_%i"%i, quantity)
        
        if numCells_gol>0:
            disp_gol = "display_gol"
            ls.create_display(disp_gol, "Voltages Golgi cells", "-75", "30")

            of_gol = 'Volts_file_gol'
            ls.create_output_file(of_gol, "v_gol.dat")

            for i in range(numCells_gol):
                quantity = "%s/%i/%s/v"%(gol_group, i, gol_group_component)
                ls.add_line_to_display(disp_gol, "Golgi %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color())
                ls.add_column_to_output_file(of_gol, "v_%i"%i, quantity)

        # Save to LEMS XML file
        lems_file_name = ls.save_to_file()
    else:
        
        ls = None
        
    print "-----------------------------------"
    
    return nml_doc, ls
Beispiel #18
0
def generate(net_id, params, cells=None, cells_to_plot=None, cells_to_stimulate=None, conn_number_override=None, conn_number_scaling=None, duration=500, dt=0.01, vmin=-75, vmax=20):
    
    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")
    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...
    cell_names, conns = SpreadsheetDataReader.readDataFromSpreadsheet("../../../")

    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["cells"] = []

    for cell in cell_names:
        
        if cells is None or cell in cells:
            # build a Population data structure out of the cell name
            pop0 = Population(id=cell, 
                              component=params.generic_cell.id,
                              type="populationList")

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

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

            # also use the cell name to grab the morphology file, as a NeuroML data structure
            #  into the 'all_cells' dict
            cell_file = '../../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))

            exp_input = ExplicitInput(target="%s/0/%s"%(pop0.id, params.generic_cell.id),
                                                     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()
                lems_info["plots"].append(plot)
                
            lems_info["cells"].append(cell)
            
    
    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)

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

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

            # Get the corresponding Cell for each 
            # pre_cell = all_cells[conn.pre_cell]
            # post_cell = all_cells[conn.post_cell]

            net.projections.append(proj0)

            # Add a Connection with the closest locations
            conn0 = Connection(id="0", \
                       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))

            proj0.connections.append(conn0)

    

    write_to_file(nml_doc, lems_info, net_id)
def generate_cerebellar_cortex(network_id,
                                x_size,     # um
                                grc_y_size,     # um
                                purk_y_size,     # um
                                z_size,     # um
                                numCells_mf,
                                numCells_grc,
                                numCells_gol,
                                numCells_purk,
                                grc_group_component = "Granule_98",
                                gol_group_component = "Golgi_98",
                                connections = True,
                                connection_probability_grc_gol =   0.2,
                                connection_probability_gol_grc =   0.1,
                                inputs = False,
                                input_firing_rate = 100, # Hz
                                num_inputs_per_mf = 1,
                                validate = True,
                                random_seed = 1234,
                                generate_lems_simulation = False,
                                duration = 500,  # ms
                                dt = 0.01,
                                temperature="32.0 degC"):

    seed(random_seed)

    nml_doc, ls = generate_granule_cell_layer(network_id,
                                x_size,     # um
                                grc_y_size,     # um
                                z_size,     # um
                                numCells_mf,
                                numCells_grc,
                                numCells_gol,
                                grc_group_component = grc_group_component,
                                gol_group_component = gol_group_component,
                                connections = connections,
                                connection_probability_grc_gol =   connection_probability_grc_gol,
                                connection_probability_gol_grc =   connection_probability_gol_grc,
                                inputs = inputs,
                                input_firing_rate = input_firing_rate, 
                                num_inputs_per_mf = num_inputs_per_mf,
                                validate = validate,
                                random_seed = random_seed,
                                generate_lems_simulation = generate_lems_simulation,
                                duration = duration,  # ms
                                dt = dt,
                                temperature=temperature)
                                
    net = nml_doc.networks[0]
    
    purk_group_component = "purk2"

    purk_group = "Purkinjes" 


    # Generate excitatory cells 

    if numCells_purk>0:
        nml_doc.includes.append(IncludeType(href='%s.cell.nml'%purk_group_component))
        
        purk_pop = Population(id=purk_group, component=purk_group_component, type="populationList", size=numCells_purk)
        purk_pop.properties.append(Property("color","1 1 0"))
        net.populations.append(purk_pop)

        for i in range(0, numCells_purk):
                index = i
                inst = Instance(id=index)
                purk_pop.instances.append(inst)
                inst.location = Location(x=str(x_size*random()), y=str(grc_y_size + purk_y_size*random()), z=str(z_size*random()))


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

    print("Saving to file...")
    nml_file = network_id+'.net.nml'
    writers.NeuroMLWriter.write(nml_doc, nml_file)

    print("Written network file to: "+nml_file)
    
    
    ls.include_neuroml2_file('%s.cell.nml'%purk_group_component)
    
    lems_file_name = ls.save_to_file()
    
    return nml_doc, ls
Beispiel #20
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,
             verbose=True,
             target_directory='./'):
                

    params.create_models()
    
    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"%(params.bioparameter_info("    "))

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

    if params.level == "A" or params.level == "B":
        nml_doc.iaf_cells.append(params.generic_cell) 
    elif params.level == "C":
        nml_doc.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 params.custom_component_types_definitions:
        lems_info["includes"].append(params.custom_component_types_definitions)
        if target_directory != './':
            def_file = "%s/%s"%(os.path.dirname(__file__), params.custom_component_types_definitions)
            shutil.copy(def_file, target_directory)
    

    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.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 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 params.generic_cell.__class__.__name__ == 'IafActivityCell':
                    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)

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

                    plot["cell"] = cell
                    plot["colour"] = get_random_colour_hex()
                    plot["quantity"] = "%s/0/%s/caConc" % (cell, params.generic_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_cell.id)
            if populations_without_location:
                save["quantity"] = "%s[0]/v" % (cell)
            lems_info["to_save"].append(save)

            if params.generic_cell.__class__.__name__ == 'IafActivityCell':
                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

    if verbose: 
        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

        if verbose: 
            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)
                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)

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

            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, verbose=verbose, target_directory=target_directory)


    return nml_doc
            segment.distal.x, segment.distal.y = rotate_z(segment.distal.x, segment.distal.y, -1* theta+math.pi)


        nml_file = new_ref+'.cell.nml'

        writers.NeuroMLWriter.write(doc,nml_file)

        print("Saved modified morphology file to: "+nml_file)

        net_doc.includes.append(IncludeType(nml_file))

        pop = Population(id="Pop_%s"%new_ref, component=new_ref, type="populationList")

        net.populations.append(pop)

        inst = Instance(id="0")
        pop.instances.append(inst)
        
        width = 6
        X = count%width
        Z = (count -X) / width
        inst.location = Location(x=300*X, y=0, z=300*Z)
        
        count+=1


net_file = net_ref+'.net.nml'
writers.NeuroMLWriter.write(net_doc, net_file)

print("Written network with %i cells in network to: %s"%(count,net_file))
def generate_granule_cell_layer(network_id,
                                x_size = 0,     # um
                                y_size = 0,     # um
                                z_size = 0,     # um
                                numCells_grc = 0,
                                numCells_gol = 0,
                                connections = True,
                                connections_method = 'random',
                                connection_probability_grc_gol =   0.2,
                                connection_probability_gol_grc =   0.1,
                                inputs = False,
                                input_firing_rate = 50, # Hz
                                num_inputs_per_grc = 4,
                                validate = True,
                                random_seed = 1234,
                                generate_lems_simulation = False,
                                max_plotted_cells_per_pop = 10,
                                duration = 500,  # ms
                                dt = 0.025,
                                temperature="32.0 degC"):

    seed(random_seed)

    nml_doc = NeuroMLDocument(id=network_id)

    net = Network(id = network_id, 
                  type = "networkWithTemperature",
                  temperature = temperature)
                  
    net.notes = "Network generated using libNeuroML v%s"%__version__
    nml_doc.networks.append(net)

    # The names of the cell type/component used in the populations (Cell Type in neuroConstruct)
    grc_group_component = "Granule_98"
    gol_group_component = "Golgi_98"

    nml_doc.includes.append(IncludeType(href='%s.cell.nml'%grc_group_component))
    nml_doc.includes.append(IncludeType(href='%s.cell.nml'%gol_group_component))

    # The names of the Exc & Inh groups/populations (Cell Group in neuroConstruct)
    grc_group = "Grans" 
    gol_group = "Golgis" 

    # The names of the network connections 
    net_conn_grc_gol = "NetConn_Grans_Golgis"
    net_conn_gol_grc = "NetConn_Golgis_Grans"

    # The names of the synapse types (should match names at Cell Mechanism/Network tabs in neuroConstruct)
    grc_gol_syn = "AMPA_GranGol"
    gol_grc_syn = "GABAA"

    for syn in [grc_gol_syn, gol_grc_syn]:
        nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%syn))

        
    if network_id == 'Solinas2010':
        # Set size and cell numbers for Solinas 2010 network 
        import sys,os
        NEURON_sim_path = '../NEURON'
        sys.path.append(NEURON_sim_path)
        local_path = os.getcwd()
        os.chdir(NEURON_sim_path)
        print os.getcwd()
        import GenerateSolinas2010 as GS2010
        structure = GS2010.GenerateSolinas2010(generate=True)
        os.chdir(local_path)
        goc_data = structure['Golgis']
        grc_data = structure['Granules']
        grc_pos = grc_data['positions']['data']
        goc_pos = goc_data['positions']['data']
        numCells_grc = grc_pos.shape[0]
        numCells_gol = goc_pos.shape[0]
        
    # Generate excitatory cells 

    grc_pop = Population(id=grc_group, component=grc_group_component, type="populationList", size=numCells_grc)
    net.populations.append(grc_pop)

    for i in range(0, numCells_grc) :
            index = i
            inst = Instance(id=index)
            grc_pop.instances.append(inst)
            inst.location = Location(x=str(grc_pos[i,0]), y=str(grc_pos[i,1]), z=str(grc_pos[i,2]))

    # Generate inhibitory cells
    gol_pop = Population(id=gol_group, component=gol_group_component, type="populationList", size=numCells_gol)
    net.populations.append(gol_pop)

    for i in range(0, numCells_gol) :
            index = i
            inst = Instance(id=index)
            gol_pop.instances.append(inst)
            inst.location = Location(x=str(goc_pos[i,0]), y=str(goc_pos[i,1]), z=str(goc_pos[i,2]))
    
    if connections:

        proj_grc_gol = Projection(id=net_conn_grc_gol, presynaptic_population=grc_group, postsynaptic_population=gol_group, synapse=grc_gol_syn)
        net.projections.append(proj_grc_gol)
        proj_gol_grc = Projection(id=net_conn_gol_grc, presynaptic_population=gol_group, postsynaptic_population=grc_group, synapse=gol_grc_syn)
        net.projections.append(proj_gol_grc)

        count_grc_gol = 0
        count_gol_grc = 0

        # Generate exc -> *  connections

        def add_connection(projection, id, pre_pop, pre_component, pre_cell_id, pre_seg_id, post_pop, post_component, post_cell_id, post_seg_id):

            connection = Connection(id=id, \
                                    pre_cell_id="../%s/%i/%s"%(pre_pop, pre_cell_id, pre_component), \
                                    pre_segment_id=pre_seg_id, \
                                    pre_fraction_along=0.5,
                                    post_cell_id="../%s/%i/%s"%(post_pop, post_cell_id, post_component), \
                                    post_segment_id=post_seg_id,
                                    post_fraction_along=0.5)

            projection.connections.append(connection)

        # Connect Granule cells to Golgi cells
        for i in range(0, numCells_grc):
            # get targets for grc[i] from the structure dict
            # print 'Granule ', i , structure['Granules']['divergence_to_goc']['data'][i][1:]
            for j in structure['Granules']['divergence_to_goc']['data'][i][1:]:
                add_connection(proj_grc_gol, count_grc_gol, grc_group, grc_group_component, i, 0, gol_group, gol_group_component, j, 0)
                count_grc_gol+=1

        # Connect Golgi cells to Granule cells
        for i in range(0, numCells_gol):
            # get targets glomeruli for goc[i] from the lol in structure dict
            # print 'Golgi ', i
            # print structure['Golgis']['divergence_to_glom']['data'][i][1:]
            for k in structure['Golgis']['divergence_to_glom']['data'][i][1:]:
                # get target granule cells for glom[k] from the lol in structure dict
                # print 'Glom ', k
                # print structure['Glomeruli']['divergence_to_grc']['data'][k]
                for j in structure['Glomeruli']['divergence_to_grc']['data'][k][1:]:
                    # print 'Granule ', j
                    add_connection(proj_gol_grc, count_gol_grc, gol_group, gol_group_component, i, 0, grc_group, grc_group_component, j, 0)
                    count_gol_grc+=1

    if inputs:
        
        mf_input_syn = "MF_AMPA"
        nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%mf_input_syn))
        
        rand_spiker_id = "input50Hz"
        
        
        #<poissonFiringSynapse id="Input_8" averageRate="50.0 per_s" synapse="MFSpikeSyn" spikeTarget="./MFSpikeSyn"/>
        pfs = PoissonFiringSynapse(id="input50Hz",
                                   average_rate="%s per_s"%input_firing_rate,
                                   synapse=mf_input_syn,
                                   spike_target="./%s"%mf_input_syn)
                                   
        nml_doc.poisson_firing_synapses.append(pfs)
        
        input_list = InputList(id="Input_0",
                             component=rand_spiker_id,
                             populations=grc_group)
                             
        count = 0
        for i in range(0, numCells_grc):
            
            for j in range(num_inputs_per_grc):
                input = Input(id=count, 
                              target="../%s/%i/%s"%(grc_group, i, grc_group_component), 
                              destination="synapses")  
                input_list.input.append(input)
            
            count += 1
                             
        net.input_lists.append(input_list)


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

    print("Saving to file...")
    nml_file = network_id+'.net.nml'
    writers.NeuroMLWriter.write(nml_doc, nml_file)

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


    if validate:

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

        from neuroml.utils import validate_neuroml2
        validate_neuroml2(nml_file) 
        
    if generate_lems_simulation:
        # Create a LEMSSimulation to manage creation of LEMS file
        
        ls = LEMSSimulation("Sim_%s"%network_id, duration, dt)

        # Point to network as target of simulation
        ls.assign_simulation_target(net.id)
        
        # Include generated/existing NeuroML2 files
        ls.include_neuroml2_file('%s.cell.nml'%grc_group_component)
        ls.include_neuroml2_file('%s.cell.nml'%gol_group_component)
        ls.include_neuroml2_file(nml_file)
        

        # Specify Displays and Output Files
        disp_grc = "display_grc"
        ls.create_display(disp_grc, "Voltages Granule cells", "-95", "-38")

        of_grc = 'Volts_file_grc'
        ls.create_output_file(of_grc, "v_grc.dat")
        
        disp_gol = "display_gol"
        ls.create_display(disp_gol, "Voltages Golgi cells", "-95", "-38")

        of_gol = 'Volts_file_gol'
        ls.create_output_file(of_gol, "v_gol.dat")

        for i in range(min(numCells_grc,max_plotted_cells_per_pop)):
            quantity = "%s/%i/%s/v"%(grc_group, i, grc_group_component)
            ls.add_line_to_display(disp_grc, "GrC %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color())
            ls.add_column_to_output_file(of_grc, "v_%i"%i, quantity)
            
        for i in range(min(numCells_gol,max_plotted_cells_per_pop)):
            quantity = "%s/%i/%s/v"%(gol_group, i, gol_group_component)
            ls.add_line_to_display(disp_gol, "Golgi %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color())
            ls.add_column_to_output_file(of_gol, "v_%i"%i, quantity)

        # Save to LEMS XML file
        lems_file_name = ls.save_to_file()
        
    print "-----------------------------------"
Beispiel #23
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
Beispiel #24
0
    net_id = "CElegansConnectome"

    nml_network_doc = NeuroMLDocument(id=net_id)

    # Create a NeuroML Network data structure to hold on to all the connection info.
    net = Network(id=net_id)
    nml_network_doc.networks.append(net)

    # To hold all Cell NeuroML objects vs. names
    all_cells = {}
    
    for cell in cell_names:
    	# build a Population data structure out of the cell name
        pop0 = Population(id=cell, component=cell, size=1)
        inst = Instance(id="0")
        # Each of these cells is at (0,0,0), i.e. segment 3D info in each cell is absolute
        inst.location = Location(x="0.0", y="0.0", z="0.0")
        pop0.instances.append(inst)
        
        # put that Population into the Network data structure from above
        net.populations.append(pop0)
        
        # also use the cell name to grab the morphology file, as a NeuroML data structure
        #  into the 'all_cells' dict
        cell_file = '../generatedNeuroML2/%s.cell.nml'%cell
        doc = loaders.NeuroMLLoader.load(cell_file)
        all_cells[cell] = doc.cells[0]
        print("Loaded morphology file from: %s, with id: %s"%(cell_file, all_cells[cell].id))

    dists = []
Beispiel #25
0
def generate(net_id, params, cells = None, cells_to_plot=None, cells_to_stimulate=None, duration=500, dt=0.01, vmin=-75, vmax=20):
    
    nml_doc = NeuroMLDocument(id=net_id)

    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...
    cell_names, conns = SpreadsheetDataReader.readDataFromSpreadsheet("../../../")

    cell_names.sort()

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

    # lems_file = ""
    lems_info = {"reference":  net_id,
                 "duration":   duration,
                 "dt":         dt,
                 "vmin":       vmin,
                 "vmax":       vmax,
                 "cell_component":    params.generic_cell.id}
    
    lems_info["plots"] = []
    lems_info["cells"] = []

    for cell in cell_names:
        
        if cells is None or cell in cells:
            # build a Population data structure out of the cell name
            pop0 = Population(id=cell, 
                              component=params.generic_cell.id,
                              type="populationList")

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

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

            # also use the cell name to grab the morphology file, as a NeuroML data structure
            #  into the 'all_cells' dict
            cell_file = '../../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))

            exp_input = ExplicitInput(target="%s/0/%s"%(pop0.id, params.generic_cell.id),
                                                     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()
                lems_info["plots"].append(plot)
                
            lems_info["cells"].append(cell)
            
    
    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)

            syn0 = params.exc_syn
            if 'GABA' in conn.synclass:
                syn0 = params.inh_syn
                
            syn_new = create_n_connection_synapse(syn0, conn.number, nml_doc)

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

            # Get the corresponding Cell for each 
            # pre_cell = all_cells[conn.pre_cell]
            # post_cell = all_cells[conn.post_cell]

            net.projections.append(proj0)

            # Add a Connection with the closest locations
            conn0 = Connection(id="0", \
                       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))

            proj0.connections.append(conn0)

    

    write_to_file(nml_doc, lems_info, net_id)
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'))

    for n_pop in range(n_pops[pop_idx]):
        inst = Instance(id=n_pop)
        population.instances.append(inst)
        inst.location = Location(x=-20 if 'E' in pop else 20, y=0, z=0)

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], net)

# Add inputs
for pop_idx, pop in enumerate(pops):
    for n_idx in range(n_pops[pop_idx]):
        exp_input = ExplicitInput(target='%sPop/%i/%s' % (pop, n_idx, pop),
                                  input='mod_%s' % pops[pop_idx],
                                  destination='synapses')
            morphology_file_name = '%d.swc' % dataset_id
            ct.save_reconstruction(dataset_id, morphology_file_name)

            # Requires: https://github.com/pgleeson/Cvapp-NeuroMorpho.org
            command = 'java -cp ../../../Cvapp-NeuroMorpho.org/build/ cvapp.main %s -exportnml2'%morphology_file_name
            print("Executing: %s"%command)
            return_string = subprocess.check_output(command, cwd='.', shell=True)

            nml2_file_name = '%d.cell.nml' % dataset_id

            nml_doc.includes.append(IncludeType(nml2_file_name))

            pop = Population(id="Pop_%i"%dataset_id, component=dataset_id, type="populationList")

            net.populations.append(pop)

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

            inst.location = Location(x=0, y=0, z=0)
        
    else:
        print('Skipping cell: %s'%(dataset_id))
    

nml_file = net_ref+'.net.nml'
writers.NeuroMLWriter.write(nml_doc, nml_file)

print("Written network file to: "+nml_file)
        
def generate_example_network(network_id,
                             numCells_exc,
                             numCells_inh,
                             x_size = 1000,
                             y_size = 100, 
                             z_size = 1000,
                             exc_group_component = "SimpleIaF",
                             inh_group_component = "SimpleIaF_inh",
                             validate = True,
                             random_seed = 1234,
                             generate_lems_simulation = False,
                             connections = True,
                             connection_probability_exc_exc =   0.4,
                             connection_probability_inh_exc =   0.4,
                             connection_probability_exc_inh =   0.4,
                             connection_probability_inh_inh =   0.4,
                             inputs = False,
                             input_firing_rate = 50, # Hz
                             input_offset_min = 0, # nA
                             input_offset_max = 0, # nA
                             num_inputs_per_exc = 4,
                             duration = 500,  # ms
                             dt = 0.05,
                             temperature="32.0 degC"):

    seed(random_seed)

    nml_doc = NeuroMLDocument(id=network_id)

    net = Network(id = network_id, 
                  type = "networkWithTemperature",
                  temperature = temperature)
                  
    net.notes = "Network generated using libNeuroML v%s"%__version__
    nml_doc.networks.append(net)
    
    for cell_comp in set([exc_group_component, inh_group_component]): # removes duplicates
        nml_doc.includes.append(IncludeType(href='%s.cell.nml'%cell_comp))

    # The names of the Exc & Inh groups/populations 
    exc_group = "Exc" 
    inh_group = "Inh" 

    # The names of the network connections 
    net_conn_exc_inh = "NetConn_Exc_Inh"
    net_conn_inh_exc = "NetConn_Inh_Exc"
    net_conn_exc_exc = "NetConn_Exc_Exc"
    net_conn_inh_inh = "NetConn_Inh_Inh"

    # The names of the synapse types (should match names at Cell Mechanism/Network tabs in neuroConstruct)
    exc_inh_syn = "AMPAR"
    inh_exc_syn = "GABAA"
    exc_exc_syn = "AMPAR"
    inh_inh_syn = "GABAA"

    for syn in [exc_inh_syn, inh_exc_syn]:
        nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%syn))


    # Generate excitatory cells 

    exc_pop = Population(id=exc_group, component=exc_group_component, type="populationList", size=numCells_exc)
    net.populations.append(exc_pop)

    for i in range(0, numCells_exc) :
            index = i
            inst = Instance(id=index)
            exc_pop.instances.append(inst)
            inst.location = Location(x=str(x_size*random()), y=str(y_size*random()), z=str(z_size*random()))

    # Generate inhibitory cells
    inh_pop = Population(id=inh_group, component=inh_group_component, type="populationList", size=numCells_inh)
    net.populations.append(inh_pop)

    for i in range(0, numCells_inh) :
            index = i
            inst = Instance(id=index)
            inh_pop.instances.append(inst)
            inst.location = Location(x=str(x_size*random()), y=str(y_size*random()), z=str(z_size*random()))

    if connections:

        proj_exc_exc = Projection(id=net_conn_exc_exc, presynaptic_population=exc_group, postsynaptic_population=exc_group, synapse=exc_exc_syn)
        net.projections.append(proj_exc_exc)
        
        proj_exc_inh = Projection(id=net_conn_exc_inh, presynaptic_population=exc_group, postsynaptic_population=inh_group, synapse=exc_inh_syn)
        net.projections.append(proj_exc_inh)
        
        proj_inh_exc = Projection(id=net_conn_inh_exc, presynaptic_population=inh_group, postsynaptic_population=exc_group, synapse=inh_exc_syn)
        net.projections.append(proj_inh_exc)
        
        proj_inh_inh = Projection(id=net_conn_inh_inh, presynaptic_population=inh_group, postsynaptic_population=inh_group, synapse=inh_inh_syn)
        net.projections.append(proj_inh_inh)

        count_exc_inh = 0
        count_inh_exc = 0
        count_exc_exc = 0
        count_inh_inh = 0


        for i in range(0, numCells_exc):
            for j in range(0, numCells_inh):
                if i != j:
                    if random()<connection_probability_exc_inh:
                        add_connection(proj_exc_inh, count_exc_inh, exc_group, exc_group_component, i, 0, inh_group, inh_group_component, j, 0)
                        count_exc_inh+=1
                        
                    if random()<connection_probability_inh_exc:

                        add_connection(proj_inh_exc, count_inh_exc, inh_group, inh_group_component, j, 0, exc_group, exc_group_component, i, 0)
                        count_inh_exc+=1
                        
        for i in range(0, numCells_exc):
            for j in range(0, numCells_exc):
                if i != j:
                        
                    if random()<connection_probability_exc_exc:

                        add_connection(proj_exc_exc, count_exc_exc, exc_group, exc_group_component, i, 0, exc_group, exc_group_component, j, 0)
                        count_exc_exc+=1
                    

        for i in range(0, numCells_inh):
            for j in range(0, numCells_inh):
                if i != j:

                    if random()<connection_probability_inh_inh:

                        add_connection(proj_inh_inh, count_inh_inh, inh_group, inh_group_component, j, 0, inh_group, inh_group_component, i, 0)
                        count_inh_inh+=1

    if inputs:
        
        
        if input_firing_rate>0:
            mf_input_syn = "AMPAR"
            if mf_input_syn!=exc_inh_syn and mf_input_syn!=inh_exc_syn:
                nml_doc.includes.append(IncludeType(href='%s.synapse.nml'%mf_input_syn))

            rand_spiker_id = "input_%sHz"%input_firing_rate
            
            pfs = PoissonFiringSynapse(id=rand_spiker_id,
                                       average_rate="%s per_s"%input_firing_rate,
                                       synapse=mf_input_syn,
                                       spike_target="./%s"%mf_input_syn)

            nml_doc.poisson_firing_synapses.append(pfs)

            input_list = InputList(id="Input_0",
                                 component=rand_spiker_id,
                                 populations=exc_group)

            count = 0
            for i in range(0, numCells_exc):

                for j in range(num_inputs_per_exc):
                    input = Input(id=count, 
                                  target="../%s/%i/%s"%(exc_group, i, exc_group_component), 
                                  destination="synapses")  
                    input_list.input.append(input)

                count += 1

            net.input_lists.append(input_list)
            
        if input_offset_max != 0 or input_offset_min != 0:
            

            for i in range(0, numCells_exc):

                pg = PulseGenerator(id="PulseGenerator_%i"%i,
                                    delay="0ms",
                                    duration="%sms"%duration,
                                    amplitude="%fnA"%(input_offset_min+(input_offset_max-input_offset_min)*random()))
                nml_doc.pulse_generators.append(pg)

                input_list = InputList(id="Input_Pulse_List_%i"%i,
                                     component=pg.id,
                                     populations=exc_group)

                input = Input(id=0, 
                              target="../%s/%i/%s"%(exc_group, i, exc_group_component), 
                              destination="synapses")  
                input_list.input.append(input)


                net.input_lists.append(input_list)


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

    print("Saving to file...")
    nml_file = network_id+'.net.nml'
    writers.NeuroMLWriter.write(nml_doc, nml_file)

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


    if validate:

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

        from neuroml.utils import validate_neuroml2
        validate_neuroml2(nml_file) 
        
    if generate_lems_simulation:
        # Create a LEMSSimulation to manage creation of LEMS file
        
        ls = LEMSSimulation("Sim_%s"%network_id, duration, dt)

        # Point to network as target of simulation
        ls.assign_simulation_target(net.id)
        
        # Include generated/existing NeuroML2 files
        ls.include_neuroml2_file('%s.cell.nml'%exc_group_component)
        ls.include_neuroml2_file('%s.cell.nml'%inh_group_component)
        ls.include_neuroml2_file(nml_file)
        

        # Specify Displays and Output Files
        disp_exc = "display_exc"
        ls.create_display(disp_exc, "Voltages Exc cells", "-80", "50")

        of_exc = 'Volts_file_exc'
        ls.create_output_file(of_exc, "v_exc.dat")
        
        disp_inh = "display_inh"
        ls.create_display(disp_inh, "Voltages Inh cells", "-80", "50")

        of_inh = 'Volts_file_inh'
        ls.create_output_file(of_inh, "v_inh.dat")

        for i in range(numCells_exc):
            quantity = "%s/%i/%s/v"%(exc_group, i, exc_group_component)
            ls.add_line_to_display(disp_exc, "Exc %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color())
            ls.add_column_to_output_file(of_exc, "v_%i"%i, quantity)
            
        for i in range(numCells_inh):
            quantity = "%s/%i/%s/v"%(inh_group, i, inh_group_component)
            ls.add_line_to_display(disp_inh, "Inh %i: Vm"%i, quantity, "1mV", pynml.get_next_hex_color())
            ls.add_column_to_output_file(of_inh, "v_%i"%i, quantity)

        # Save to LEMS XML file
        lems_file_name = ls.save_to_file()
        
    print "-----------------------------------"
Beispiel #29
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 #30
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_cell) 
    elif params.level == "C":
        nml_doc.cells.append(params.generic_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_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_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 = 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_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_cell.id)
                if populations_without_location:
                    plot["quantity"] = "%s[0]/v" % (cell)
                lems_info["plots"].append(plot)

                if params.generic_cell.__class__.__name__ == 'IafActivityCell':
                    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)

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

                    plot["cell"] = cell
                    plot["colour"] = get_random_colour_hex()
                    plot["quantity"] = "%s/0/%s/caConc" % (cell, params.generic_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_cell.id)
            if populations_without_location:
                save["quantity"] = "%s[0]/v" % (cell)
            lems_info["to_save"].append(save)

            if params.generic_cell.__class__.__name__ == 'IafActivityCell':
                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)
            if params.generic_cell.__class__.__name__ == 'Cell':
                save = {}
                save["cell"] = cell
                save["quantity"] = "%s/0/%s/caConc" % (cell, params.generic_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_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)

            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_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 params.generic_cell.__class__.__name__ == 'IafActivityCell':
                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)
                
            if params.generic_cell.__class__.__name__ == 'Cell':
                plot = {}

                plot["cell"] = muscle
                plot["colour"] = get_random_colour_hex()
                plot["quantity"] = "%s/0/%s/caConc" % (muscle, params.generic_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_cell.id)
            if populations_without_location:
                save["quantity"] = "%s[0]/v" % (muscle)
            lems_info["muscles_to_save"].append(save)

            if params.generic_cell.__class__.__name__ == 'IafActivityCell':
                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)
            if params.generic_cell.__class__.__name__ == 'Cell':
                save = {}
                save["cell"] = muscle
                save["quantity"] = "%s/0/%s/caConc" % (muscle, params.generic_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.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)
                
            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_cell.id)
                    post_cell_id="../%s/0/%s"%(conn.post_cell, params.generic_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_cell.id)
                post_cell_id="../%s/0/%s"%(conn.post_cell, params.generic_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_cell.id)
                    post_cell_id="../%s/0/%s"%(conn.post_cell, params.generic_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.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)

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


    # 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 #31
0
            # Requires: https://github.com/pgleeson/Cvapp-NeuroMorpho.org
            command = 'java -cp ../../../Cvapp-NeuroMorpho.org/build/ cvapp.main %s -exportnml2' % morphology_file_name
            print("Executing: %s" % command)
            return_string = subprocess.check_output(command,
                                                    cwd='.',
                                                    shell=True)

            nml2_file_name = '%d.cell.nml' % dataset_id

            nml_doc.includes.append(IncludeType(nml2_file_name))

            pop = Population(id="Pop_%i" % dataset_id,
                             component=dataset_id,
                             type="populationList")

            net.populations.append(pop)

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

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

    else:
        print('Skipping cell: %s' % (dataset_id))

nml_file = net_ref + '.net.nml'
writers.NeuroMLWriter.write(nml_doc, nml_file)

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