[docs]deffile_schematic(file_like:Union["str","os.PathLike",TextIO],definitions:Optional["Definition"]=None,fname:str=None,*,name=None,morphio_options:Option=Option.no_modifier,)->Schematic:ifhasattr(file_like,"read"):ifnotfile_like.nameandnotfname:raiseOSError("The file-driver MorphIO requires a file name to parse files. ""Use a file-like object that provides a `name` attribute, ""or pass the `fname` keyword argument, ""with a suffix matching the file format.")base=os.path.basename(file_like.nameorfname)handle,abspath=tempfile.mkstemp(suffix=base)os.close(handle)try:withopen(abspath,"w")asf:iffile_like.seekable():file_like.seek(0)f.write(file_like.read())returnfile_schematic(abspath,definitions)finally:os.unlink(abspath)morpho=Morphology(os.fspath(file_like),options=morphio_options)schematic=Schematic(name=name)branches=[morpho.soma,*itertools.chain.from_iterable(s.iter()forsinmorpho.root_sections),]endpoints=[]forbid,branchinenumerate(branches):mid=getattr(branch,"id",-1)+1ifbid!=mid:raiseAssertionError("MorphIO deviated from depth-first order.")parent=_get_parent(morpho,branch)ifnotlen(branch.points):true_parent=NonewhileTrue:ifparentisNone:breakeliflen(parent.points):true_parent=endpoints[getattr(parent,"id",-1)+1]breakparent=Noneifbranch.is_rootelsebranch.parentschematic.create_empty()endpoints.append(true_parent)else:ifparentisnotNone:endpoint=endpoints[getattr(parent,"id",-1)+1]else:endpoint=Noneifisinstance(branch.type,SomaType):branch_type="soma"elif"custom"instr(branch.type):num=re.search(r"\d+$",str(branch.type)).group()branch_type=f"tag_{num}"else:branch_type=str(branch.type).split(".")[-1]forpid,coords,diaminzip(itertools.count(),branch.points,branch.diameters):endpoint=endpointifpid==0elseNoneschematic.create_location((bid,pid),coords,diam/2,[branch_type],endpoint)endpoints.append((bid,pid))ifdefinitionsisnotNone:schematic.definition=definitionsreturnschematic
def_get_parent(morpho:Morphology,branch):# Does the morphology have a soma? If so, the roots are connected to it.root_parent=morpho.somaifmorpho.somaelseNoneifhasattr(branch,"is_root"):returnroot_parentifbranch.is_rootelsebranch.parentelse:# The soma never has a parentreturnNone