list of lengths of trunk sections of neurites in a neuron
961415
def trunk_section_lengths(nrn, neurite_type=NeuriteType.all):
    ''''''
    neurite_filter = is_type(neurite_type)
    return [morphmath.section_length(s.root_node.points)
            for s in nrn.neurites if neurite_filter(s)]
146189
def createSynapses(self):
        
        synsoma = h.ExpSyn(self.soma(0.5))
        synsoma.tau = 2
        synsoma.e = 0
        syndend = h.ExpSyn(self.dend(0.5))
        syndend.tau = 2
        syndend.e = 0
        self.synlist.append(synsoma) # synlist is defined in Cell
        self.synlist.append(syndend)
676335
def plot_dendrogram(ax, obj, show_diameters=True):
    '''
    '''
    # create dendrogram and generate rectangle collection
    dnd = Dendrogram(obj, show_diameters=show_diameters)
    dnd.generate()

    # render dendrogram and take into account neurite displacement which
    # starts as zero. It is important to avoid overlapping of neurites
    # and to determine tha limits of the figure.

    _render_dendrogram(dnd, ax, 0.)

    ax.set_title('Morphology Dendrogram')
    ax.set_xlabel('micrometers (um)')
    ax.set_ylabel('micrometers (um)')

    ax.set_aspect('auto')
    ax.legend()
415229
def neurite_root_section_ids(self):
        ''''''
        sec = self.sections
        return [i for i, ss in enumerate(sec)
                if ss.pid > -1 and (sec[ss.pid].ntype == POINT_TYPE.SOMA and
                                    ss.ntype != POINT_TYPE.SOMA)]
249145
def map_sections(fun, neurites, neurite_type=NeuriteType.all, iterator_type=Tree.ipreorder):
    ''''''
    return map(fun, iter_sections(neurites,
                                  iterator_type=iterator_type,
                                  neurite_filter=is_type(neurite_type)))
1060347
def _extract_pynn_components_to_neuroml(nl_model, nml_doc=None):
    
    
    if nml_doc == None:
        from neuroml import NeuroMLDocument
        nml_doc = NeuroMLDocument(id="temp")
    
    for c in nl_model.cells:
        
        if c.pynn_cell:
            
            if nml_doc.get_by_id(c.id) == None:
                import pyNN.neuroml
                cell_params = c.parameters if c.parameters else {}
                #print('------- %s: %s' % (c, cell_params))
                for p in cell_params:
                    cell_params[p] = evaluate(cell_params[p], nl_model.parameters)
                #print('====== %s: %s' % (c, cell_params))
                for proj in nl_model.projections:

                    synapse = nl_model.get_child(proj.synapse, 'synapses')
                    post_pop = nl_model.get_child(proj.postsynaptic, 'populations')
                    if post_pop.component == c.id:
                        #print("--------- Cell %s in post pop %s of %s uses %s"%(c.id,post_pop.id, proj.id, synapse))

                        if synapse.pynn_receptor_type == 'excitatory':
                            post = '_E'
                        elif synapse.pynn_receptor_type == 'inhibitory':
                            post = '_I'
                        for p in synapse.parameters:
                            cell_params['%s%s' % (p, post)] = synapse.parameters[p]

                temp_cell = eval('pyNN.neuroml.%s(**cell_params)' % c.pynn_cell)
                if c.pynn_cell != 'SpikeSourcePoisson':
                    temp_cell.default_initial_values['v'] = temp_cell.parameter_space['v_rest'].base_value

                cell_id = temp_cell.add_to_nml_doc(nml_doc, None)
                cell = nml_doc.get_by_id(cell_id)
                cell.id = c.id
            
    for s in nl_model.synapses:
        if nml_doc.get_by_id(s.id) == None:
            
            if s.pynn_synapse_type and s.pynn_receptor_type:
                import neuroml
                
                if s.pynn_synapse_type == 'cond_exp':
                    syn = neuroml.ExpCondSynapse(id=s.id, tau_syn=s.parameters['tau_syn'], e_rev=s.parameters['e_rev'])
                    nml_doc.exp_cond_synapses.append(syn)
                elif s.pynn_synapse_type == 'cond_alpha':
                    syn = neuroml.AlphaCondSynapse(id=s.id, tau_syn=s.parameters['tau_syn'], e_rev=s.parameters['e_rev'])
                    nml_doc.alpha_cond_synapses.append(syn)
                elif s.pynn_synapse_type == 'curr_exp':
                    syn = neuroml.ExpCurrSynapse(id=s.id, tau_syn=s.parameters['tau_syn'])
                    nml_doc.exp_curr_synapses.append(syn)
                elif s.pynn_synapse_type == 'curr_alpha':
                    syn = neuroml.AlphaCurrSynapse(id=s.id, tau_syn=s.parameters['tau_syn'])
                    nml_doc.alpha_curr_synapses.append(syn)
    
    for i in nl_model.input_sources:
        
        #if nml_doc.get_by_id(i.id) == None:
      
        if i.pynn_input:
            import pyNN.neuroml
            input_params = i.parameters if i.parameters else {}
            exec('input__%s = pyNN.neuroml.%s(**input_params)' % (i.id, i.pynn_input))
            exec('temp_input = input__%s' % i.id)
            pg_id = temp_input.add_to_nml_doc(nml_doc, None)
            #for pp in nml_doc.pulse_generators:
            #    print('PG: %s: %s'%(pp,pp.id))
            pg = nml_doc.get_by_id(pg_id)
            pg.id = i.id
            
    return nml_doc
874105
def quick_summary(nml2_doc):
    '''
    
    '''
    
    info = 'Contents of NeuroML 2 document: %s\n'%nml2_doc.id
    membs = inspect.getmembers(nml2_doc)

    for memb in membs:

        if isinstance(memb[1], list) and len(memb[1])>0 \
                and not memb[0].endswith('_'):
            info+='  %s:\n    ['%memb[0]
            for entry in memb[1]:
                extra = '???'
                extra = entry.name if hasattr(entry,'name') else extra
                extra = entry.href if hasattr(entry,'href') else extra
                extra = entry.id if hasattr(entry,'id') else extra
                
                info+=" %s (%s),"%(entry, extra)
            
            info+=']\n'
    return info
557521
def _rest_make_phenotypes():
    #phenotype sources
    neuroner = Path(devconfig.git_local_base,
                'neuroNER/resources/bluima/neuroner/hbp_morphology_ontology.obo').as_posix()
    neuroner1 = Path(devconfig.git_local_base,
                 'neuroNER/resources/bluima/neuroner/hbp_electrophysiology_ontology.obo').as_posix()
    neuroner2 = Path(devconfig.git_local_base,
                 'neuroNER/resources/bluima/neuroner/hbp_electrophysiology-triggers_ontology.obo').as_posix()
    nif_qual = Path(devconfig.ontology_local_repo,
                    'ttl/NIF-Quality.ttl').as_posix()

    mo = OboFile(os.path.expanduser(neuroner))
    mo1 = OboFile(os.path.expanduser(neuroner1))
    mo2 = OboFile(os.path.expanduser(neuroner2))
    mo_ttl = mo.__ttl__() + mo1.__ttl__() + mo2.__ttl__()

    mo_ttl = """\
    @prefix : <http://FIXME.org/> .
    @prefix nsu: <http://www.FIXME.org/nsupper#> .
    @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
    @prefix owl: <http://www.w3.org/2002/07/owl#> .
    @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
    """ + mo_ttl

    #sio = io.StringIO()
    #sio.write(mo_ttl)

    ng = rdflib.Graph()
    ng.parse(data=mo_ttl, format='turtle')
    ng.parse(os.path.expanduser(nif_qual), format='turtle')
    #ng.namespace_manager.bind('default1', None, override=False, replace=True)
    ng.remove((None, rdflib.OWL.imports, None))

    bad_match = {
        'http://ontology.neuinfo.org/NIF/BiomaterialEntities/NIF-Quality.owl#nlx_qual_20090505',
        'http://ontology.neuinfo.org/NIF/BiomaterialEntities/NIF-Quality.owl#sao1693353776',
        'http://ontology.neuinfo.org/NIF/BiomaterialEntities/NIF-Quality.owl#sao1288413465',
        'http://ontology.neuinfo.org/NIF/BiomaterialEntities/NIF-Quality.owl#sao4459136323',
        'http://ontology.neuinfo.org/NIF/BiomaterialEntities/NIF-Quality.owl#nlx_qual_20090507',
    }

    exact = []
    similar = []
    quals = []
    s2 = {}

    for subject, label in sorted(ng.subject_objects(rdflib.RDFS.label)):

        syns = set([a for a in ng.objects(subject, rdflib.URIRef('http://www.FIXME.org/nsupper#synonym'))])
        syns.update(set([a for a in ng.objects(subject, rdflib.URIRef('http://ontology.neuinfo.org/NIF/Backend/OBO_annotation_properties.owl#synonym'))]))
        #if syns:
            #print(syns)
        #print(subject)
        #print(label.lower())
        if 'quality' in label.lower():
            quals.append((subject, label))
        subpre = ng.namespace_manager.compute_qname(subject)[1]
        llower = rdflib.Literal(label.lower(), lang='en')
        for s in ng.subjects(rdflib.RDFS.label, llower):
            if s != subject:
                exact.append((subject, s, label, llower))
        for s, p, o in sorted(ng.triples((None, rdflib.RDFS.label, None))):
            spre = ng.namespace_manager.compute_qname(s)[1]
            if subject != s and label.lower() in o.lower().split(' ') and spre != subpre:
                if s.toPython() in bad_match or subject.toPython() in bad_match:
                    continue
                #print()
                #print(spre, subpre)
                similar.append((subject, s, label, o))
                if subpre.toPython() == 'http://FIXME.org/':
                    print('YAY')
                    print(label, ',', o)
                    print(subject, s)
                    subject, s = s, subject
                    label, o = o, label

                if subject in s2:
                    #print('YES IT EXISTS')
                    #print(syns, label, [subject, s])
                    s2[subject]['syns'].update(syns)
                    s2[subject]['syns'].add(label)
                    s2[subject]['xrefs'] += [subject, s]
                else:
                    s2[subject] = {'label': label.toPython(), 'o': o.toPython(), 'xrefs':[subject, s], 'syns':syns}  # FIXME overwrites

    pprint(quals)
    

    desired_nif_terms = set() #{
        #'NIFQUAL:sao1959705051',  # dendrite
        #'NIFQUAL:sao2088691397',  # axon
        #'NIFQUAL:sao1057800815',  # morphological
        #'NIFQUAL:sao-1126011106',  # soma
        #'NIFQUAL:',
        #'NIFQUAL:',
    #}
    starts = [
        #"NIFQUAL:sao2088691397",
        #"NIFQUAL:sao1278200674",
        #"NIFQUAL:sao2088691397",
        #"NIFQUAL:sao-1126011106",  # FIXME WTF IS THIS NONSENSE  (scigraph bug?)
        quote("http://ontology.neuinfo.org/NIF/BiomaterialEntities/NIF-Quality.owl#sao1959705051").replace('/','%2F'),
        quote("http://ontology.neuinfo.org/NIF/BiomaterialEntities/NIF-Quality.owl#sao2088691397").replace('/','%2F'),
        quote("http://ontology.neuinfo.org/NIF/BiomaterialEntities/NIF-Quality.owl#sao1278200674").replace('/','%2F'),
        quote("http://ontology.neuinfo.org/NIF/BiomaterialEntities/NIF-Quality.owl#sao2088691397").replace('/','%2F'),
        quote("http://ontology.neuinfo.org/NIF/BiomaterialEntities/NIF-Quality.owl#sao-1126011106").replace('/','%2F'),
    ]

    for id_ in starts:
        want = sgg.getNeighbors(id_, relationshipType='subClassOf', direction='INCOMING', depth=5)
        #print(id_, want)
        desired_nif_terms.update([n['id'] for n in want['nodes']])

    print(desired_nif_terms)


    ilx_start = 50114
    print(ilx_base.format(ilx_start))
    new_terms = {}
    dg = makeGraph('uwotm8', prefixes=PREFIXES)
    xr = makeGraph('xrefs', prefixes=PREFIXES)
    for s, o in sorted(ng.subject_objects(rdflib.RDFS.label))[::-1]:
        spre = ng.namespace_manager.compute_qname(s)[1]
        #if spre.toPython() == g.namespaces['NIFQUAL']:
            #print('skipping', s)
            #continue  # TODO
        if s in new_terms:
            print(s, 'already in as xref probably')
            continue
        #elif spre.toPython() != 'http://uri.interlex.org/base/ilx_' or spre.toPython() != 'http://FIXME.org/' and s.toPython() not in desired_nif_terms:
        #elif spre.toPython() != 'http://FIXME.org/' and s.toPython() not in desired_nif_terms:
            #print('DO NOT WANT', s, spre)
            #continue

        syns = set([s for s in ng.objects(s, dg.namespaces['nsu']['synonym'])])
        #data['syns'] += syns

        data = {}
        id_ = ilx_base.format(ilx_start)
        ilx_start += 1
        if s in s2:
            d = s2[s]
            syns.update(d['syns'])
            new_terms[d['xrefs'][0]] = {'replaced_by':id_}
            xr.add_trip(d['xrefs'][0], 'oboInOwl:replacedBy', id_)
            #dg.add_trip(d['xrefs'][0], 'oboInOwl:replacedBy', id_)
            new_terms[d['xrefs'][1]] = {'replaced_by':id_}
            xr.add_trip(d['xrefs'][1], 'oboInOwl:replacedBy', id_)
            #dg.add_trip(d['xrefs'][1], 'oboInOwl:replacedBy', id_)

            data['labels'] = [d['label'], d['o']]
            #dg.add_trip(id_, rdflib.RDFS.label, d['label'])
            dg.add_trip(id_, rdflib.RDFS.label, d['o'])
            data['xrefs'] = d['xrefs']
            for x in d['xrefs']:  # FIXME... expecting order of evaluation errors here...
                dg.add_trip(id_, 'oboInOwl:hasDbXref', x)  # xr
                xr.add_trip(id_, 'oboInOwl:hasDbXref', x)  # x

        elif spre.toPython() != 'http://ontology.neuinfo.org/NIF/BiomaterialEntities/NIF-Quality.owl#' or ng.namespace_manager.qname(s).replace('default1','NIFQUAL') in desired_nif_terms:  # skip non-xref quals
            #print(ng.namespace_manager.qname(s).replace('default1','NIFQUAL'))
            new_terms[s] = {'replaced_by':id_}
            xr.add_trip(s, 'oboInOwl:replacedBy', id_)
            data['labels'] = [o.toPython()]
            dg.add_trip(id_, rdflib.RDFS.label, o.toPython())
            data['xrefs'] = [s]
            dg.add_trip(id_, 'oboInOwl:hasDbXref', s)  # xr
            xr.add_trip(id_, 'oboInOwl:hasDbXref', s)  # xr
        else:
            ilx_start -= 1
            continue

        new_terms[id_] = data
        dg.add_trip(id_, rdflib.RDF.type, rdflib.OWL.Class)
        xr.add_trip(id_, rdflib.RDF.type, rdflib.OWL.Class)
        for syn in syns:
            if syn.toPython() not in data['labels']:
                if len(syn) > 3:
                    dg.add_trip(id_, 'NIFRID:synonym', syn)
                elif syn:
                    dg.add_trip(id_, 'NIFRID:abbrev', syn)

        if 'EPHYS' in s or any(['EPHYS' in x for x in data['xrefs']]):
            dg.add_trip(id_, rdflib.RDFS.subClassOf, ephys_phenotype)
        elif 'MORPHOLOGY' in s or any(['MORPHOLOGY' in x for x in data['xrefs']]):
            dg.add_trip(id_, rdflib.RDFS.subClassOf, morpho_phenotype)

    #dg.write(convert=False)
    xr.write(convert=False)

    #skip this for now, we can use DG to do lookups later
    #for t in dg.g.triples((None, None, None)):
        #g.add_trip(*t)  # only way to clean prefixes :/
    add_phenotypes(g)
    g.write(convert=False)

    g2 = makeGraph('pheno-comp', PREFIXES)
    for t in ng.triples((None, None, None)):
        g2.add_trip(*t)  # only way to clean prefixes :/

    g2.write(convert=False)

    syn_mappings = {}
    for sub, syn in [_ for _ in g.g.subject_objects(g.expand('NIFRID:synonym'))] + [_ for _ in g.g.subject_objects(rdflib.RDFS.label)]:
        syn = syn.toPython()
        if syn in syn_mappings:
            log.error(f'duplicate synonym! {syn} {sub}')
        syn_mappings[syn] = sub

    #embed()
    return syn_mappings, pedges, ilx_start
382005
def section_areas(neurites, neurite_type=NeuriteType.all):
    ''''''
    return map_sections(sectionfunc.section_area, neurites, neurite_type=neurite_type)
758808
def _initializeTRNToRelayCellConnections(self):
    
    for x in range(self.relayWidth):
      for y in range(self.relayHeight):

        # Create one dendrite for each trn cell that projects to this relay cell
        # This dendrite contains one synapse corresponding to this TRN->relay
        # connection.
        relayCellIndex = self.relayCellIndex((x,y))
        trnCells = self._preSynapticTRNCells(x, y)
        for trnCell in trnCells:
          newSegment = self.relayConnections.createSegments([relayCellIndex])
          self.relayConnections.growSynapses(newSegment,
                                             [self.trnCellIndex(trnCell)], 1.0)
803570
def segment_lengths(neurites, neurite_type=NeuriteType.all):
    ''''''
    def _seg_len(sec):
        '''list of segment lengths of a section'''
        return np.linalg.norm(np.diff(sec.points[:, COLS.XYZ], axis=0), axis=1)

    return map_segments(_seg_len, neurites, neurite_type)
909913
def has_no_dangling_branch(neuron):
    ''''''
    soma_center = neuron.soma.points[:, COLS.XYZ].mean(axis=0)
    recentered_soma = neuron.soma.points[:, COLS.XYZ] - soma_center
    radius = np.linalg.norm(recentered_soma, axis=1)
    soma_max_radius = radius.max()

    def is_dangling(neurite):
        '''Is the neurite dangling ?'''
        starting_point = neurite.points[1][COLS.XYZ]

        if np.linalg.norm(starting_point - soma_center) - soma_max_radius <= 12.:
            return False

        if neurite.type != NeuriteType.axon:
            return True

        all_points = list(chain.from_iterable(n.points[1:]
                                              for n in iter_neurites(neurite)
                                              if n.type != NeuriteType.axon))
        res = [np.linalg.norm(starting_point - p[COLS.XYZ]) >= 2 * p[COLS.R] + 2
               for p in all_points]
        return all(res)

    bad_ids = [(n.root_node.id, [n.root_node.points[1]])
               for n in iter_neurites(neuron) if is_dangling(n)]
    return CheckResult(len(bad_ids) == 0, bad_ids)
1332211
def get_L_yXL(fname, y, x_in_X, L):
    '''
    
    '''
    def _get_L_yXL_per_yXL(fname, x_in_X, X_index,
                                  y, layer):
        # Load data from json dictionary
        f = open(fname, 'r')
        data = json.load(f)
        f.close()
    
        
        # Get number of synapses
        if layer in [str(key) for key in data['data'][y]['syn_dict'].keys()]:
            #init variables
            k_yXL = 0
            k_yX = 0
            
            for x in x_in_X[X_index]:
                p_yxL = data['data'][y]['syn_dict'][layer][x] / 100.
                k_yL = data['data'][y]['syn_dict'][layer]['number of synapses per neuron']
                k_yXL += p_yxL * k_yL
                
            for l in [str(key) for key in data['data'][y]['syn_dict'].keys()]:
                for x in x_in_X[X_index]:
                    p_yxL = data['data'][y]['syn_dict'][l][x] / 100.
                    k_yL = data['data'][y]['syn_dict'][l]['number of synapses per neuron']
                    k_yX +=  p_yxL * k_yL
            
            if k_yXL != 0.:
                return k_yXL / k_yX
            else:
                return 0.
        else:
            return 0.


    #init dict
    L_yXL = {}

    #iterate over postsynaptic cell types
    for y_value in y:
        #container
        data = np.zeros((len(L), len(x_in_X)))
        #iterate over lamina
        for i, Li in enumerate(L):
            #iterate over presynapse population inds
            for j in range(len(x_in_X)):
                data[i][j]= _get_L_yXL_per_yXL(fname, x_in_X,
                                                          X_index=j,
                                                          y=y_value,
                                                          layer=Li)
        L_yXL[y_value] = data

    return L_yXL
426482
def trunk_vectors(nrn, neurite_type=NeuriteType.all):
    '''
    '''
    neurite_filter = is_type(neurite_type)
    nrns = neuron_population(nrn)

    return np.array([morphmath.vector(s.root_node.points[0], n.soma.center)
                     for n in nrns
                     for s in n.neurites if neurite_filter(s)])
859869
def has_axon(neuron, treefun=_read_neurite_type):
    '''
    '''
    return CheckResult(NeuriteType.axon in (treefun(n) for n in neuron.neurites))
192578
def section_strahler_orders(neurites, neurite_type=NeuriteType.all):
    ''''''
    return map_sections(sectionfunc.strahler_order, neurites, neurite_type)
882481
def section_branch_orders(neurites, neurite_type=NeuriteType.all):
    ''''''
    return map_sections(sectionfunc.branch_order, neurites, neurite_type=neurite_type)