Receives a genome and draws a neural network with arbitrary topology.
541669
def draw_net(config, genome, view=False, filename=None, node_names=None, show_disabled=True, prune_unused=False,
             node_colors=None, fmt='svg'):
    
    # Attributes for network nodes.
    if graphviz is None:
        warnings.warn("This display is not available due to a missing optional dependency (graphviz)")
        return

    if node_names is None:
        node_names = {}

    assert type(node_names) is dict

    if node_colors is None:
        node_colors = {}

    assert type(node_colors) is dict

    node_attrs = {
        'shape': 'circle',
        'fontsize': '9',
        'height': '0.2',
        'width': '0.2'}

    dot = graphviz.Digraph(format=fmt, node_attr=node_attrs)

    inputs = set()
    for k in config.genome_config.input_keys:
        inputs.add(k)
        name = node_names.get(k, str(k))
        input_attrs = {'style': 'filled', 'shape': 'box', 'fillcolor': node_colors.get(k, 'lightgray')}
        dot.node(name, _attributes=input_attrs)

    outputs = set()
    for k in config.genome_config.output_keys:
        outputs.add(k)
        name = node_names.get(k, str(k))
        node_attrs = {'style': 'filled', 'fillcolor': node_colors.get(k, 'lightblue')}

        dot.node(name, _attributes=node_attrs)

    if prune_unused:
        connections = set()
        for cg in genome.connections.values():
            if cg.enabled or show_disabled:
                connections.add((cg.in_node_id, cg.out_node_id))

        used_nodes = copy.copy(outputs)
        pending = copy.copy(outputs)
        while pending:
            new_pending = set()
            for a, b in connections:
                if b in pending and a not in used_nodes:
                    new_pending.add(a)
                    used_nodes.add(a)
            pending = new_pending
    else:
        used_nodes = set(genome.nodes.keys())

    for n in used_nodes:
        if n in inputs or n in outputs:
            continue

        attrs = {'style': 'filled',
                 'fillcolor': node_colors.get(n, 'white')}
        dot.node(str(n), _attributes=attrs)

    for cg in genome.connections.values():
        if cg.enabled or show_disabled:
            #if cg.input not in used_nodes or cg.output not in used_nodes:
            #    continue
            input, output = cg.key
            a = node_names.get(input, str(input))
            b = node_names.get(output, str(output))
            style = 'solid' if cg.enabled else 'dotted'
            color = 'green' if cg.weight > 0 else 'red'
            width = str(0.1 + abs(cg.weight / 5.0))
            dot.edge(a, b, _attributes={'style': style, 'color': color, 'penwidth': width})

    dot.render(filename, view=view)

    return dot
729656
function drawGraph (opts) {

    // Clone the options, so the 'options' variable always keeps intact.
    var o = Flotr._.extend(Flotr._.clone(options), opts || {});

    // Return a new graph.
    return Flotr.draw(
      container,
      [ d1, d2, d3 ],
      o
    );
  }
84552
def generate_and_run(simulation, 
                     simulator, 
                     network=None, 
                     return_results=False, 
                     base_dir=None,
                     target_dir=None,
                     num_processors=1):
    

    if network == None:
        network = load_network_json(simulation.network)
    
    print_v("Generating network %s and running in simulator: %s..." % (network.id, simulator))
    
    if simulator == 'NEURON':
        
        _generate_neuron_files_from_neuroml(network, dir_for_mod_files=target_dir)
        
        from neuromllite.NeuronHandler import NeuronHandler
        
        nrn_handler = NeuronHandler()

        for c in network.cells:
            if c.neuroml2_source_file:
                src_dir = os.path.dirname(os.path.abspath(c.neuroml2_source_file))
                nrn_handler.executeHoc('load_file("%s/%s.hoc")' % (src_dir, c.id))
                
        generate_network(network, nrn_handler, generate_network, base_dir)
        if return_results:
            raise NotImplementedError("Reloading results not supported in Neuron yet...")


    elif simulator.lower() == 'sonata': # Will not "run" obviously...
        
        from neuromllite.SonataHandler import SonataHandler
        
        sonata_handler = SonataHandler()
        
        generate_network(network, sonata_handler, always_include_props=True, base_dir=base_dir)
    
        print_v("Done with Sonata...")


    elif simulator.lower().startswith('graph'): # Will not "run" obviously...
                           
        from neuromllite.GraphVizHandler import GraphVizHandler, engines
        

        try:
            if simulator[-1].isalpha():
                print simulator
                print simulator[5:]
                print simulator[5:-1]
                engine = engines[simulator[-1]]
                level = int(simulator[5:-1])
            else:
                engine = 'dot'
                level = int(simulator[5:])
        
        except Exception as e:
            print e
            print_v("Error parsing: %s"%simulator)
            print_v("Graphs of the network structure can be generated at many levels of detail (1-6, required) and laid out using GraphViz engines (d - dot (default); c - circo; n - neato; f - fdp), so use: -graph3c, -graph2, -graph4f etc.")
            return
        
        handler = GraphVizHandler(level, engine=engine, nl_network=network)
        
        generate_network(network, handler, always_include_props=True, base_dir=base_dir)
    
        print_v("Done with GraphViz...")
        
        
    elif simulator.lower().startswith('matrix'): # Will not "run" obviously...
                           
        from neuromllite.MatrixHandler import MatrixHandler
        
        try:
            level = int(simulator[6:])
        except:
            print_v("Error parsing: %s"%simulator)
            print_v("Matrices of the network structure can be generated at many levels of detail (1-n, required), so use: -matrix1, -matrix2, etc.")
            return
        
        handler = MatrixHandler(level, nl_network=network)
        
        generate_network(network, handler, always_include_props=True, base_dir=base_dir)
    
        print_v("Done with MatrixHandler...")
        

    elif simulator.startswith('PyNN'):
        
        #_generate_neuron_files_from_neuroml(network)
        simulator_name = simulator.split('_')[1].lower()
        
        
        from neuromllite.PyNNHandler import PyNNHandler
        
        pynn_handler = PyNNHandler(simulator_name, simulation.dt, network.id)
        
        syn_cell_params = {}
        for proj in network.projections:
            
            synapse = network.get_child(proj.synapse, 'synapses')
            post_pop = network.get_child(proj.postsynaptic, 'populations')
          
            if not post_pop.component in syn_cell_params:
                syn_cell_params[post_pop.component] = {}
            for p in synapse.parameters:
                post = ''
                if synapse.pynn_receptor_type == "excitatory":
                    post = '_E'
                elif synapse.pynn_receptor_type == "inhibitory":
                    post = '_I'
                syn_cell_params[post_pop.component]['%s%s' % (p, post)] = synapse.parameters[p]
                    
        
        cells = {}
        for c in network.cells:
            if c.pynn_cell:
                cell_params = {}
                if c.parameters: 
                    for p in c.parameters:
                        cell_params[p] = evaluate(c.parameters[p], network.parameters)
                
                dont_set_here = ['tau_syn_E', 'e_rev_E', 'tau_syn_I', 'e_rev_I']
                for d in dont_set_here:
                    if d in c.parameters:
                        raise Exception('Synaptic parameters like %s should be set '+
                          'in individual synapses, not in the list of parameters associated with the cell' % d)
                if c.id in syn_cell_params:
                    cell_params.update(syn_cell_params[c.id])
                print_v("Creating cell with params: %s" % cell_params)
                exec('cells["%s"] = pynn_handler.sim.%s(**cell_params)' % (c.id, c.pynn_cell))
                
                if c.pynn_cell != 'SpikeSourcePoisson':
                    exec("cells['%s'].default_initial_values['v'] = cells['%s'].parameter_space['v_rest'].base_value" % (c.id, c.id))
                
        pynn_handler.set_cells(cells)
        
        receptor_types = {}
        for s in network.synapses:
            if s.pynn_receptor_type:
                receptor_types[s.id] = s.pynn_receptor_type
                
        pynn_handler.set_receptor_types(receptor_types)
        
        for input_source in network.input_sources:
            if input_source.pynn_input:
                pynn_handler.add_input_source(input_source)
        
        generate_network(network, pynn_handler, always_include_props=True, base_dir=base_dir)
        
        for pid in pynn_handler.populations:
            pop = pynn_handler.populations[pid]
            if 'all' in simulation.recordTraces or pop.label in simulation.recordTraces:
                if pop.can_record('v'):
                    pop.record('v')
        
        
        pynn_handler.sim.run(simulation.duration)
        pynn_handler.sim.end()
        
        traces = {}
        events = {}
        
        if not 'NeuroML' in simulator:
            from neo.io import PyNNTextIO

            for pid in pynn_handler.populations:
                pop = pynn_handler.populations[pid]

                if 'all' in simulation.recordTraces or pop.label in simulation.recordTraces:
                    
                    filename = "%s.%s.v.dat" % (simulation.id, pop.label)
                    all_columns = []
                    print_v("Writing data for %s to %s" % (pop.label, filename))
                    for i in range(len(pop)):
                        if pop.can_record('v'):
                            ref = '%s[%i]'%(pop.label,i)
                            traces[ref] = []
                            data = pop.get_data('v', gather=False)
                            for segment in data.segments:
                                vm = segment.analogsignals[0].transpose()[i]
                                
                                if len(all_columns) == 0:
                                    tt = np.array([t * simulation.dt / 1000. for t in range(len(vm))])
                                    all_columns.append(tt)
                                vm_si = [float(v / 1000.) for v in vm]
                                traces[ref] = vm_si
                                all_columns.append(vm_si)
                                
                            times_vm = np.array(all_columns).transpose()
                                
                    np.savetxt(filename, times_vm, delimiter='\t', fmt='%s')
          
        
        if return_results:
            _print_result_info(traces, events)
            return traces, events

    elif simulator == 'NetPyNE':
        
        if target_dir==None:
            target_dir='./'
            
        _generate_neuron_files_from_neuroml(network, dir_for_mod_files=target_dir)
        
        from netpyne import specs
        from netpyne import sim
        # Note NetPyNE from this branch is required: https://github.com/Neurosim-lab/netpyne/tree/neuroml_updates
        from netpyne.conversion.neuromlFormat import NetPyNEBuilder
        
        import pprint; pp = pprint.PrettyPrinter(depth=6)
        
        netParams = specs.NetParams()
        simConfig = specs.SimConfig()
        netpyne_handler = NetPyNEBuilder(netParams, simConfig=simConfig, verbose=True)
        
        generate_network(network, netpyne_handler, base_dir=base_dir)
        
        netpyne_handler.finalise()
        
        simConfig = specs.SimConfig() 
        simConfig.tstop = simulation.duration
        simConfig.duration = simulation.duration
        simConfig.dt = simulation.dt
        simConfig.seed = simulation.seed
        simConfig.recordStep = simulation.dt
        
        simConfig.recordCells = ['all'] 
        simConfig.recordTraces = {}
        

        for pop in netpyne_handler.popParams.values():
            if 'all' in simulation.recordTraces or pop.id in simulation.recordTraces:
                for i in pop['cellsList']:
                    id = pop['pop']
                    index = i['cellLabel']
                    simConfig.recordTraces['v_%s_%s' % (id, index)] = {'sec':'soma', 'loc':0.5, 'var':'v', 'conds':{'pop':id, 'cellLabel':index}}

        simConfig.saveDat = True
        
        print_v("NetPyNE netParams: ")
        pp.pprint(netParams.todict())
        #print_v("NetPyNE simConfig: ")
        #pp.pprint(simConfig.todict())
        
        sim.initialize(netParams, simConfig)  # create network object and set cfg and net params

        sim.net.createPops()  
        cells = sim.net.createCells()                 # instantiate network cells based on defined populations  
        
        
        for proj_id in netpyne_handler.projection_infos.keys():
            projName, prePop, postPop, synapse, ptype = netpyne_handler.projection_infos[proj_id]
            print_v("Creating connections for %s (%s): %s->%s via %s" % (projName, ptype, prePop, postPop, synapse))
            
            preComp = netpyne_handler.pop_ids_vs_components[prePop]
            
            for conn in netpyne_handler.connections[projName]:
                
                pre_id, pre_seg, pre_fract, post_id, post_seg, post_fract, delay, weight = conn
                
                #connParam = {'delay':delay,'weight':weight,'synsPerConn':1, 'sec':post_seg, 'loc':post_fract, 'threshold':threshold}
                connParam = {'delay':delay, 'weight':weight, 'synsPerConn':1, 'sec':post_seg, 'loc':post_fract}
                
                if ptype == 'electricalProjection':

                    if weight != 1:
                        raise Exception('Cannot yet support inputs where weight !=1!')
                    connParam = {'synsPerConn': 1, 
                        'sec': post_seg, 
                        'loc': post_fract, 
                        'gapJunction': True, 
                        'weight': weight}
                else:
                    connParam = {'delay': delay,
                        'weight': weight,
                        'synsPerConn': 1, 
                        'sec': post_seg, 
                        'loc': post_fract} 
                        #'threshold': threshold}

                connParam['synMech'] = synapse

                if post_id in sim.net.gid2lid:  # check if postsyn is in this node's list of gids
                    sim.net._addCellConn(connParam, pre_id, post_id)
                    
                    
        stims = sim.net.addStims()                    # add external stimulation to cells (IClamps etc)
        simData = sim.setupRecording()              # setup variables to record for each cell (spikes, V traces, etc)
        sim.runSim()                      # run parallel Neuron simulation  
        sim.gatherData()                  # gather spiking data and cell info from each node
        sim.saveData()                    # save params, cell info and sim output to file (pickle,mat,txt,etc)
        
        if return_results:
            raise NotImplementedError("Reloading results not supported in NetPyNE yet...")
        
    elif simulator == 'jNeuroML' or  simulator == 'jNeuroML_NEURON' or simulator == 'jNeuroML_NetPyNE':

        from pyneuroml.lems import generate_lems_file_for_neuroml
        from pyneuroml import pynml

        lems_file_name = 'LEMS_%s.xml' % simulation.id

        nml_file_name, nml_doc = generate_neuroml2_from_network(network, base_dir=base_dir, target_dir=target_dir)
        included_files = ['PyNN.xml']

        for c in network.cells:        
            if c.lems_source_file:
                included_files.append(c.lems_source_file)
        '''
        if network.cells:
            for c in network.cells:
                included_files.append(c.neuroml2_source_file)
        '''
        if network.synapses:
            for s in network.synapses:  
                if s.lems_source_file:
                    included_files.append(s.lems_source_file)
                
        print_v("Generating LEMS file prior to running in %s" % simulator)
        
        pops_plot_save = []
        pops_spike_save = []
        gen_plots_for_quantities = {}
        gen_saves_for_quantities = {}
        
        for p in network.populations:
            
            if simulation.recordTraces and ('all' in simulation.recordTraces or p.id in simulation.recordTraces):
                pops_plot_save.append(p.id)
                
            if simulation.recordSpikes and ('all' in simulation.recordSpikes or p.id in simulation.recordSpikes):
                pops_spike_save.append(p.id)
                
            if simulation.recordRates and ('all' in simulation.recordRates or p.id in simulation.recordRates):
                size = evaluate(p.size, network.parameters)
                for i in range(size):
                    quantity = '%s/%i/%s/r' % (p.id, i, p.component)
                    gen_plots_for_quantities['%s_%i_r' % (p.id, i)] = [quantity]
                    gen_saves_for_quantities['%s_%i.r.dat' % (p.id, i)] = [quantity]
                
            if simulation.recordVariables:
                for var in simulation.recordVariables:
                    to_rec = simulation.recordVariables[var]
                    if ('all' in to_rec or p.id in to_rec):
                        size = evaluate(p.size, network.parameters)
                        for i in range(size):
                            quantity = '%s/%i/%s/%s' % (p.id, i, p.component,var)
                            gen_plots_for_quantities['%s_%i_%s' % (p.id, i, var)] = [quantity]
                            gen_saves_for_quantities['%s_%i.%s.dat' % (p.id, i, var)] = [quantity]
                
        
        generate_lems_file_for_neuroml(simulation.id, 
                                       nml_file_name, 
                                       network.id, 
                                       simulation.duration, 
                                       simulation.dt, 
                                       lems_file_name,
                                       target_dir=target_dir if target_dir else '.',
                                       nml_doc=nml_doc, # Use this if the nml doc has already been loaded (to avoid delay in reload)
                                       include_extra_files=included_files,
                                       
                                       gen_plots_for_all_v=False,
                                       plot_all_segments=False,
                                       gen_plots_for_quantities=gen_plots_for_quantities, # Dict with displays vs lists of quantity paths
                                       gen_plots_for_only_populations=pops_plot_save, # List of populations, all pops if = []
                                       
                                       gen_saves_for_all_v=False,
                                       save_all_segments=False,
                                       gen_saves_for_only_populations=pops_plot_save, # List of populations, all pops if = []
                                       gen_saves_for_quantities=gen_saves_for_quantities, # Dict with file names vs lists of quantity paths
                                       
                                       gen_spike_saves_for_all_somas=False,
                                       gen_spike_saves_for_only_populations=pops_spike_save, # List of populations, all pops if = []
                                       gen_spike_saves_for_cells={}, # Dict with file names vs lists of quantity paths
                                       spike_time_format='ID_TIME',
                                       
                                       copy_neuroml=True,
                                       lems_file_generate_seed=12345,
                                       report_file_name='report.%s.txt' % simulation.id,
                                       simulation_seed=simulation.seed if simulation.seed else 12345,
                                       verbose=True)
              
        lems_file_name = _locate_file(lems_file_name, target_dir)
        
        if simulator == 'jNeuroML':
            results = pynml.run_lems_with_jneuroml(lems_file_name, 
                                                   nogui=True, 
                                                   load_saved_data=return_results, 
                                                   reload_events=return_results)
        elif simulator == 'jNeuroML_NEURON':
            results = pynml.run_lems_with_jneuroml_neuron(lems_file_name, 
                                                          nogui=True, 
                                                          load_saved_data=return_results, 
                                                          reload_events=return_results)
        elif simulator == 'jNeuroML_NetPyNE':
            results = pynml.run_lems_with_jneuroml_netpyne(lems_file_name, 
                                                           nogui=True, 
                                                           verbose=True, 
                                                           load_saved_data=return_results, 
                                                           reload_events=return_results,
                                                           num_processors=num_processors)

        print_v("Finished running LEMS file %s in %s (returning results: %s)" % (lems_file_name, simulator, return_results))

        if return_results:
            traces, events = results
            _print_result_info(traces, events)
            return results
261661
function draw(){
    
    ctx.clearRect(0,0,WIDTH,HEIGHT);
    
    var netx = new convnetjs.Vol(1,1,2);
    // draw decisions in the grid
    var density= 5.0;
    var gridstep = 2;
    var gridx = [];
    var gridy = [];
    var gridl = []; 
    for(var x=0.0, cx=0; x<=WIDTH; x+= density, cx++) {
      for(var y=0.0, cy=0; y<=HEIGHT; y+= density, cy++) {
        //var dec= svm.marginOne([(x-WIDTH/2)/ss, (y-HEIGHT/2)/ss]);
        netx.w[0] = (x-WIDTH/2)/ss;
        netx.w[1] = (y-HEIGHT/2)/ss;
        var a = net.forward(netx, false);
        
        if(a.w[0] > a.w[1]) ctx.fillStyle = 'rgb(250, 150, 150)';
        else ctx.fillStyle = 'rgb(150, 250, 150)';

        //ctx.fillStyle = 'rgb(150,' + Math.floor(a.w[0]*105)+150 + ',150)';
        //ctx.fillStyle = 'rgb(' + Math.floor(a.w[0]*255) + ',' + Math.floor(a.w[1]*255) + ', 0)';
        ctx.fillRect(x-density/2-1, y-density/2-1, density+2, density+2);

        if(cx%gridstep === 0 && cy%gridstep===0) {
          // record the transformation information
          var xt = net.layers[lix].out_act.w[d0]; // in screen coords
          var yt = net.layers[lix].out_act.w[d1]; // in screen coords
          gridx.push(xt);
          gridy.push(yt);
          gridl.push(a.w[0] > a.w[1]); // remember final label as well
        }
      }
    }

    // draw axes
    ctx.beginPath();
    ctx.strokeStyle = 'rgb(50,50,50)';
    ctx.lineWidth = 1;
    ctx.moveTo(0, HEIGHT/2);
    ctx.lineTo(WIDTH, HEIGHT/2);
    ctx.moveTo(WIDTH/2, 0);
    ctx.lineTo(WIDTH/2, HEIGHT);
    ctx.stroke();

    // draw representation transformation axes for two neurons at some layer
    var mmx = cnnutil.maxmin(gridx);
    var mmy = cnnutil.maxmin(gridy);
    visctx.clearRect(0,0,visWIDTH,visHEIGHT);
    visctx.strokeStyle = 'rgb(0, 0, 0)';
    var n = Math.floor(Math.sqrt(gridx.length)); // size of grid. Should be fine?
    var ng = gridx.length;
    var c = 0; // counter
    visctx.beginPath() 
    for(var x=0;x<n;x++) {
      for(var y=0;y<n;y++) {

        // down
        var ix1 = x*n+y;
        var ix2 = x*n+y+1;
        if(ix1 >= 0 && ix2 >= 0 && ix1 < ng && ix2 < ng && y<n-1) { // check oob
          var xraw = gridx[ix1];
          xraw1 = visWIDTH*(gridx[ix1] - mmx.minv)/mmx.dv;
          yraw1 = visHEIGHT*(gridy[ix1] - mmy.minv)/mmy.dv;
          xraw2 = visWIDTH*(gridx[ix2] - mmx.minv)/mmx.dv;
          yraw2 = visHEIGHT*(gridy[ix2] - mmy.minv)/mmy.dv;
          visctx.moveTo(xraw1, yraw1);
          visctx.lineTo(xraw2, yraw2);
        }

        // and draw its color
        if(gridl[ix1]) visctx.fillStyle = 'rgb(250, 150, 150)';
        else visctx.fillStyle = 'rgb(150, 250, 150)';
        var sz = density * gridstep;
        visctx.fillRect(xraw1-sz/2-1, yraw1-sz/2-1, sz+2, sz+2);

        // right
        var ix1 = (x+1)*n+y;
        var ix2 = x*n+y;
        if(ix1 >= 0 && ix2 >= 0 && ix1 < ng && ix2 < ng && x <n-1) { // check oob
          var xraw = gridx[ix1];
          xraw1 = visWIDTH*(gridx[ix1] - mmx.minv)/mmx.dv;
          yraw1 = visHEIGHT*(gridy[ix1] - mmy.minv)/mmy.dv;
          xraw2 = visWIDTH*(gridx[ix2] - mmx.minv)/mmx.dv;
          yraw2 = visHEIGHT*(gridy[ix2] - mmy.minv)/mmy.dv;
          visctx.moveTo(xraw1, yraw1);
          visctx.lineTo(xraw2, yraw2);
        }
 
      }
    }
    visctx.stroke();

    // draw datapoints.
    ctx.strokeStyle = 'rgb(0,0,0)';
    ctx.lineWidth = 1;
    for(var i=0;i<N;i++) {
      
      if(labels[i]==1) ctx.fillStyle = 'rgb(100,200,100)';
      else ctx.fillStyle = 'rgb(200,100,100)';
      
      drawCircle(data[i][0]*ss+WIDTH/2, data[i][1]*ss+HEIGHT/2, 5.0);

      // also draw transformed data points while we're at it
      netx.w[0] = data[i][0];
      netx.w[1] = data[i][1]
      var a = net.forward(netx, false);
      var xt = visWIDTH * (net.layers[lix].out_act.w[d0] - mmx.minv) / mmx.dv; // in screen coords
      var yt = visHEIGHT * (net.layers[lix].out_act.w[d1] - mmy.minv) / mmy.dv; // in screen coords
      if(labels[i]==1) visctx.fillStyle = 'rgb(100,200,100)';
      else visctx.fillStyle = 'rgb(200,100,100)';
      visctx.beginPath();
      visctx.arc(xt, yt, 5.0, 0, Math.PI*2, true); 
      visctx.closePath();
      visctx.stroke();
      visctx.fill();
    }
}
928675
def generate(self):
        '''
        '''
        offsets = (0., 0.)

        n_previous = 0

        # set recursion limit with respect to
        # the max number of nodes on the trees
        old_depth = sys.getrecursionlimit()
        max_depth = old_depth if old_depth > self._max_rec_depth else self._max_rec_depth
        # TODO: This should be fixed so we don't set sys.setrecursionlimit at all
        sys.setrecursionlimit(max_depth)

        if isinstance(self._obj, Neurite):

            max_diameter = _max_diameter(self._obj.root_node)

            dummy_section = Tree()
            dummy_section.add_child(self._obj.root_node)
            self._generate_dendro(dummy_section, (max_diameter, 0.), offsets)

            self._groups.append((0, self._n))

            self._dims.append(self._max_dims)

        else:

            for neurite in self._obj.neurites:

                neurite = neurite.root_node
                max_diameter = _max_diameter(neurite)
                dummy_section = Tree()

                dummy_section.add_child(neurite)
                self._generate_dendro(dummy_section, (max_diameter, 0.), offsets)

                # store in trees the indices for the slice which corresponds
                # to the current neurite
                self._groups.append((n_previous, self._n))

                # store the max dims per neurite for view positioning
                self._dims.append(self._max_dims)

                # reset the max dimensions for the next tree in line
                self._max_dims = [0., 0.]

                # keep track of the next tree start index in list
                n_previous = self._n

        # set it back to its initial value
        sys.setrecursionlimit(old_depth)
1109677
def configure_new(self, config):
        """"""

        # Create node genes for the output pins.
        for node_key in config.output_keys:
            self.nodes[node_key] = self.create_node(config, node_key)

        # Add hidden nodes if requested.
        if config.num_hidden > 0:
            for i in range(config.num_hidden):
                node_key = config.get_new_node_key(self.nodes)
                assert node_key not in self.nodes
                node = self.create_node(config, node_key)
                self.nodes[node_key] = node

        # Add connections based on initial connectivity type.

        if 'fs_neat' in config.initial_connection:
            if config.initial_connection == 'fs_neat_nohidden':
                self.connect_fs_neat_nohidden(config)
            elif config.initial_connection == 'fs_neat_hidden':
                self.connect_fs_neat_hidden(config)
            else:
                if config.num_hidden > 0:
                    print(
                        "Warning: initial_connection = fs_neat will not connect to hidden nodes;",
                        "\tif this is desired, set initial_connection = fs_neat_nohidden;",
                        "\tif not, set initial_connection = fs_neat_hidden",
                        sep='\n', file=sys.stderr);
                self.connect_fs_neat_nohidden(config)
        elif 'full' in config.initial_connection:
            if config.initial_connection == 'full_nodirect':
                self.connect_full_nodirect(config)
            elif config.initial_connection == 'full_direct':
                self.connect_full_direct(config)
            else:
                if config.num_hidden > 0:
                    print(
                        "Warning: initial_connection = full with hidden nodes will not do direct input-output connections;",
                        "\tif this is desired, set initial_connection = full_nodirect;",
                        "\tif not, set initial_connection = full_direct",
                        sep='\n', file=sys.stderr);
                self.connect_full_nodirect(config)
        elif 'partial' in config.initial_connection:
            if config.initial_connection == 'partial_nodirect':
                self.connect_partial_nodirect(config)
            elif config.initial_connection == 'partial_direct':
                self.connect_partial_direct(config)
            else:
                if config.num_hidden > 0:
                    print(
                        "Warning: initial_connection = partial with hidden nodes will not do direct input-output connections;",
                        "\tif this is desired, set initial_connection = partial_nodirect {0};".format(
                            config.connection_fraction),
                        "\tif not, set initial_connection = partial_direct {0}".format(
                            config.connection_fraction),
                        sep='\n', file=sys.stderr);
                self.connect_partial_nodirect(config)
1151992
def _prep_genome(out_dir, data):
    
    genome_name = utils.splitext_plus(os.path.basename(dd.get_ref_file(data)))[0]
    out_dir = utils.safe_makedir(os.path.join(out_dir, genome_name))
    ref_file = dd.get_ref_file(data)
    utils.symlink_plus(ref_file, os.path.join(out_dir, os.path.basename(ref_file)))
    with open(os.path.join(out_dir, "GenomeSize.xml"), "w") as out_handle:
        out_handle.write('<sequenceSizes genomeName="%s">' % genome_name)
        for c in pysam.AlignmentFile("%s.dict" % utils.splitext_plus(ref_file)[0]).header["SQ"]:
            cur_ploidy = ploidy.get_ploidy([data], region=[c["SN"]])
            out_handle.write('<chromosome fileName="%s" contigName="%s" totalBases="%s" knownBases="%s" '
                             'isCircular="false" ploidy="%s" md5="%s"/>' %
                             (os.path.basename(ref_file), c["SN"], c["LN"], c["LN"], cur_ploidy, c["M5"]))
        out_handle.write('</sequenceSizes>')
    return out_dir
739579
def map_neurons(fun, neurites, neurite_type):
    ''''''
    nrns = _neuronfunc.neuron_population(neurites)
    return [fun(n, neurite_type=neurite_type) for n in nrns]
1138053
def mygenerator(n=5, n_edges=5):
    '''
    
    '''
    G = nx.Graph()

    for i in range(n):
        G.add_node(i)
    
    for i in range(n_edges):
        nodes = list(G.nodes)
        n_in = choice(nodes)
        nodes.remove(n_in)  # Avoid loops
        n_out = choice(nodes)
        G.add_edge(n_in, n_out)
    return G
1240766
def draw(self, name, dname, draw_branches=True):
        
        from pydot import Dot, Edge
        import os

        g = Dot()
        g.set_node_defaults(color='lightgray',
                            style='filled',
                            shape='box',
                            fontname='Courier',
                            fontsize='10')
        for node in sorted(self.nodes, key=lambda x: x.num):
            if draw_branches and node.type.is_cond:
                g.add_edge(Edge(str(node), str(node.true), color='green'))
                g.add_edge(Edge(str(node), str(node.false), color='red'))
            else:
                for suc in self.sucs(node):
                    g.add_edge(Edge(str(node), str(suc), color='blue'))
            for except_node in self.catch_edges.get(node, []):
                g.add_edge(Edge(str(node),
                                str(except_node),
                                color='black',
                                style='dashed'))

        g.write(os.path.join(dname, '%s.png' % name), format='png')
99931
def run(self):
        """"""
        random.seed(self.seed)
        np.random.seed(self.np_seed)
        if not isinstance(self, multiprocessing.Process):
            # Calling mxnet methods in a subprocess will raise an exception if
            # mxnet is built with GPU support
            # https://github.com/apache/incubator-mxnet/issues/4659
            mx.random.seed(self.mx_seed)

        # Startup - Master waits for this
        try:
            stream_iter = iter(self.stream)
            self._errorq.put(None)
        except Exception as e:  # pylint: disable=broad-except
            tb = traceback.format_exc()
            self._errorq.put((e, tb))

        # Async work
        while True:
            try:  # Check control queue
                c = self._controlq.get(False)
                if c is None:
                    break
                else:
                    raise RuntimeError('Got unexpected control code {}'.format(repr(c)))
            except queue.Empty:
                pass
            except RuntimeError as e:
                tb = traceback.format_exc()
                self._errorq.put((e, tb))
                self._dataq.put(None)

            try:
                data = next(stream_iter)
                error = None
            except Exception as e:  # pylint: disable=broad-except
                tb = traceback.format_exc()
                error = (e, tb)
                data = None
            finally:
                self._errorq.put(error)
                self._dataq.put(data)
508951
public static ComputationGraphConfiguration.GraphBuilder inceptionV1ResC(
                    ComputationGraphConfiguration.GraphBuilder graph, String blockName, int scale,
                    double activationScale, String input) {
        // loop and add each subsequent resnet blocks
        String previousBlock = input;
        for (int i = 1; i <= scale; i++) {
            graph
                            // 1x1
                            .addLayer(nameLayer(blockName, "cnn1", i),
                                            new ConvolutionLayer.Builder(new int[] {1, 1})
                                                            .convolutionMode(ConvolutionMode.Same).nIn(1344).nOut(192)
                                                            .cudnnAlgoMode(ConvolutionLayer.AlgoMode.NO_WORKSPACE)
                                                            .build(),
                                            previousBlock)
                            .addLayer(nameLayer(blockName, "batch1", i),
                                            new BatchNormalization.Builder(false).decay(0.995).eps(0.001).nIn(192)
                                                            .nOut(192).build(),
                                            nameLayer(blockName, "cnn1", i))
                            // 1x1 -> 1x3 -> 3x1
                            .addLayer(nameLayer(blockName, "cnn2", i),
                                            new ConvolutionLayer.Builder(new int[] {1, 1})
                                                            .convolutionMode(ConvolutionMode.Same).nIn(1344).nOut(192)
                                                            .cudnnAlgoMode(ConvolutionLayer.AlgoMode.NO_WORKSPACE)
                                                            .build(),
                                            previousBlock)
                            .addLayer(nameLayer(blockName, "batch2", i),
                                            new BatchNormalization.Builder(false).decay(0.995).eps(0.001).nIn(192)
                                                            .nOut(192).build(),
                                            nameLayer(blockName, "cnn2", i))
                            .addLayer(nameLayer(blockName, "cnn3", i),
                                            new ConvolutionLayer.Builder(new int[] {1, 3})
                                                            .convolutionMode(ConvolutionMode.Same).nIn(192).nOut(192)
                                                            .cudnnAlgoMode(ConvolutionLayer.AlgoMode.NO_WORKSPACE)
                                                            .build(),
                                            nameLayer(blockName, "batch2", i))
                            .addLayer(nameLayer(blockName, "batch3", i),
                                            new BatchNormalization.Builder(false).decay(0.995).eps(0.001).nIn(192)
                                                            .nOut(192).build(),
                                            nameLayer(blockName, "cnn3", i))
                            .addLayer(nameLayer(blockName, "cnn4", i),
                                            new ConvolutionLayer.Builder(new int[] {3, 1})
                                                            .convolutionMode(ConvolutionMode.Same).nIn(192).nOut(192)
                                                            .cudnnAlgoMode(ConvolutionLayer.AlgoMode.NO_WORKSPACE)
                                                            .build(),
                                            nameLayer(blockName, "batch3", i))
                            .addLayer(nameLayer(blockName, "batch4", i),
                                            new BatchNormalization.Builder(false).decay(0.995).eps(0.001)
                                                            .activation(Activation.TANH).nIn(192).nOut(192).build(),
                                            nameLayer(blockName, "cnn4", i))
                            // --> 1x1 --> scale -->
                            .addVertex(nameLayer(blockName, "merge1", i), new MergeVertex(),
                                            nameLayer(blockName, "batch1", i), nameLayer(blockName, "batch4", i))
                            .addLayer(nameLayer(blockName, "cnn5", i),
                                            new ConvolutionLayer.Builder(new int[] {1, 1})
                                                            .convolutionMode(ConvolutionMode.Same).nIn(384).nOut(1344)
                                                            .cudnnAlgoMode(ConvolutionLayer.AlgoMode.NO_WORKSPACE)
                                                            .build(),
                                            nameLayer(blockName, "merge1", i))
                            .addLayer(nameLayer(blockName, "batch5", i),
                                            new BatchNormalization.Builder(false).decay(0.995).eps(0.001)
                                                            .activation(Activation.TANH).nIn(1344).nOut(1344).build(),
                                            nameLayer(blockName, "cnn5", i))
                            .addVertex(nameLayer(blockName, "scaling", i), new ScaleVertex(activationScale),
                                            nameLayer(blockName, "batch5", i))
                            // -->
                            .addLayer(nameLayer(blockName, "shortcut-identity", i),
                                            new ActivationLayer.Builder().activation(Activation.IDENTITY).build(),
                                            previousBlock)
                            .addVertex(nameLayer(blockName, "shortcut", i),
                                            new ElementWiseVertex(ElementWiseVertex.Op.Add),
                                            nameLayer(blockName, "scaling", i),
                                            nameLayer(blockName, "shortcut-identity", i));

            // leave the last vertex as the block name for convenience
            if (i == scale)
                graph.addLayer(blockName, new ActivationLayer.Builder().activation(Activation.TANH).build(),
                                nameLayer(blockName, "shortcut", i));
            else
                graph.addLayer(nameLayer(blockName, "activation", i),
                                new ActivationLayer.Builder().activation(Activation.TANH).build(),
                                nameLayer(blockName, "shortcut", i));

            previousBlock = nameLayer(blockName, "activation", i);
        }
        return graph;
    }
796809
def create (netParams=None, simConfig=None, output=False):
    '''  '''
    from .. import sim
    import __main__ as top
    if not netParams: netParams = top.netParams
    if not simConfig: simConfig = top.simConfig

    sim.initialize(netParams, simConfig)  # create network object and set cfg and net params
    pops = sim.net.createPops()                  # instantiate network populations
    cells = sim.net.createCells()                 # instantiate network cells based on defined populations
    conns = sim.net.connectCells()                # create connections between cells based on params
    stims = sim.net.addStims()                    # add external stimulation to cells (IClamps etc)
    rxd = sim.net.addRxD()                    # add reaction-diffusion (RxD)
    simData = sim.setupRecording()             # setup variables to record for each cell (spikes, V traces, etc)

    if output: return (pops, cells, conns, rxd, stims, simData)
1207894
def generate_dummy_graph(network):
    """"""
    
    graph = pypsa.descriptors.OrderedGraph()
    
    graph.add_nodes_from([bus for bus in network.buses.index if bus not in buses_to_split])
    
    #add positions to graph for voronoi cell computation
    for node in graph.nodes():
        graph.node[node]["pos"] = np.array(network.buses.loc[node,["x","y"]],dtype=float)
    
    return graph
1342967
def draw(self):
        '''
        
        '''
        if self.__conditional_flag is True:
            return np.concatenate((self.__create_samples(), self.__create_samples()), axis=1)
        else:
            return self.__create_samples()
1010523
def build_and_train(iterations, log_stride, test=False):
  """"""

  # Test mode settings.
  batch_size = 2 if test else FLAGS.batch_size
  num_mems = 2 if test else FLAGS.num_mems
  num_heads = 1 if test else FLAGS.num_mems
  num_blocks = 1 if test else FLAGS.num_mems
  head_size = 4 if test else FLAGS.head_size
  max_length = 3 if test else FLAGS.max_length
  max_nest = 2 if test else FLAGS.max_nest
  mlp_size = (20,) if test else (256, 256, 256, 256)

  with tf.Graph().as_default():
    t0 = time.time()

    # Initialize the dataset.
    lte_train = learn_to_execute.LearnToExecute(
        batch_size, max_length, max_nest)
    lte_test = learn_to_execute.LearnToExecute(
        batch_size, max_length, max_nest, mode=learn_to_execute.Mode.TEST)
    train_data_iter = lte_train.make_one_shot_iterator().get_next()
    test_data_iter = lte_test.make_one_shot_iterator().get_next()
    output_size = lte_train.state.vocab_size

    # Create the model.
    core = snt.RelationalMemory(
        mem_slots=num_mems,
        head_size=head_size,
        num_heads=num_heads,
        num_blocks=num_blocks,
        gate_style=FLAGS.gate_style)
    final_mlp = snt.nets.MLP(
        output_sizes=mlp_size,
        activate_final=True)
    model = SequenceModel(
        core=core,
        target_size=output_size,
        final_mlp=final_mlp)
    tf.logging.info("Instantiated models ({:3f})".format(time.time() - t0))

    # Define the loss & accuracy.
    def loss_fn(inputs, targets, input_sequence_length, output_sequence_length):
      """Creates the loss and the exports."""
      logits = model(
          inputs, targets, input_sequence_length, output_sequence_length)
      targets = tf.cast(targets, tf.int32)
      sq_sz_out_max = targets.shape[0].value

      # Create a mask to ignore accuracy on buffer characters.
      sequence_sizes = tf.cast(output_sequence_length, tf.float32)
      lengths_transposed = tf.expand_dims(sequence_sizes, 1)
      range_row = tf.expand_dims(
          tf.range(0, sq_sz_out_max, 1, dtype=tf.float32), 0)
      mask = tf.cast(tf.transpose(tf.less(range_row, lengths_transposed)),
                     tf.float32)

      # Compute token accuracy and solved.
      correct = tf.equal(tf.argmax(logits, 2), tf.argmax(targets, 2))
      solved = tf.reduce_all(tf.boolean_mask(correct, tf.squeeze(mask)), axis=0)
      token_acc = tf.reduce_sum(tf.cast(correct, tf.float32) * mask)
      token_acc /= tf.reduce_sum(sequence_sizes)

      # Compute Loss.
      mask = tf.cast(tf.tile(tf.expand_dims(mask, 2), (1, 1, logits.shape[2])),
                     tf.float32)
      masked_logits = logits * mask
      masked_target = tf.cast(targets, tf.float32) * mask
      logits_flat = tf.reshape(masked_logits,
                               [sq_sz_out_max * batch_size, -1])
      target_flat = tf.reshape(masked_target,
                               [sq_sz_out_max * batch_size, -1])
      xent = tf.nn.softmax_cross_entropy_with_logits(logits=logits_flat,
                                                     labels=target_flat)
      loss = tf.reduce_mean(xent)
      return loss, token_acc, solved

    # Get training step counter.
    global_step = tf.train.get_or_create_global_step()

    # Create the optimizer.
    learning_rate_op = tf.reduce_max([
        tf.train.exponential_decay(
            FLAGS.learning_rate,
            global_step,
            decay_steps=FLAGS.epochs // 100,
            decay_rate=0.9,
            staircase=False),
        FLAGS.min_learning_rate
    ])
    optimizer = tf.train.AdamOptimizer(learning_rate_op)

    # Compute loss, accuracy & the step op.
    inputs, targets, _, input_lengths, output_lengths = train_data_iter
    train_loss, train_acc, train_sol = loss_fn(
        inputs, targets, input_lengths, output_lengths)
    step_op = optimizer.minimize(train_loss, global_step=global_step)
    inputs, targets, _, input_lengths, output_lengths = test_data_iter
    _, test_acc, test_sol = loss_fn(
        inputs, targets, input_lengths, output_lengths)
    tf.logging.info("Created losses and optimizers ({:3f})".format(
        time.time() - t0))

    # Begin Training.
    t0 = time.time()
    tf.logging.info("Starting training ({:3f})".format(time.time() - t0))
    with tf.train.SingularMonitoredSession() as sess:
      for it in six.moves.range(iterations):
        sess.run([step_op, learning_rate_op])
        if it % log_stride == 0:
          loss_v, train_acc_v, test_acc_v, train_sol_v, test_sol_v = sess.run([
              train_loss, train_acc, test_acc, train_sol, test_sol])
          elapsed = time.time() - t0
          tf.logging.info(
              "iter: {:2d}, train loss {:3f}; train acc {:3f}; test acc {:3f};"
              " train solved {:3f}; test solved {:3f}; ({:3f})".format(
                  it, loss_v, train_acc_v, test_acc_v, train_sol_v, test_sol_v,
                  elapsed))
903857
def create(genome, config, time_constant):
        
        genome_config = config.genome_config
        required = required_for_output(genome_config.input_keys, genome_config.output_keys, genome.connections)

        # Gather inputs and expressed connections.
        node_inputs = {}
        for cg in itervalues(genome.connections):
            if not cg.enabled:
                continue

            i, o = cg.key
            if o not in required and i not in required:
                continue

            if o not in node_inputs:
                node_inputs[o] = [(i, cg.weight)]
            else:
                node_inputs[o].append((i, cg.weight))

        node_evals = {}
        for node_key, inputs in iteritems(node_inputs):
            node = genome.nodes[node_key]
            activation_function = genome_config.activation_defs.get(node.activation)
            aggregation_function = genome_config.aggregation_function_defs.get(node.aggregation)
            node_evals[node_key] = CTRNNNodeEval(time_constant,
                                                 activation_function,
                                                 aggregation_function,
                                                 node.bias,
                                                 node.response,
                                                 inputs)

        return CTRNN(genome_config.input_keys, genome_config.output_keys, node_evals)