From c83ef5772f5e59e261e22ca9f9af9dec0b0d3ecd Mon Sep 17 00:00:00 2001 From: Gregory Jefferis Date: Thu, 15 Jul 2021 02:00:59 +0100 Subject: [PATCH] WIP read in metadata --- R/neuron-io.R | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/R/neuron-io.R b/R/neuron-io.R index 723379e4..41ab1a5a 100644 --- a/R/neuron-io.R +++ b/R/neuron-io.R @@ -268,6 +268,7 @@ read.neurons<-function(paths, pattern=NULL, neuronnames=NULL, format=NULL, total = length(paths), show_after=2) + mdl=list() for(n in nn){ if(interactive()) pb$tick() @@ -287,6 +288,11 @@ read.neurons<-function(paths, pattern=NULL, neuronnames=NULL, format=NULL, nl=x break } + md <- attr(x, 'metadata') + if(!is.null(md)) { + mdl[[n]]=md + attr(x, 'metadata')=NULL + } nl[[n]]=x } @@ -305,6 +311,10 @@ read.neurons<-function(paths, pattern=NULL, neuronnames=NULL, format=NULL, } # nb only keep dataframe rows for neurons that were successfully read in # Look after the attached dataframe + if(is.null(df) && length(mdl)>0) { + df <- do.call(rbind, mdl) + rownames(df) <- names(mdl) + } if(!is.null(df)){ data.frame(nl)=df } @@ -548,7 +558,11 @@ read.neuron.swc<-function(f, ...){ d=read.swc(f) # multiply by 2 to get diam which is what I work with internally d$W=d$W*2 - as.neuron(d, InputFileName=f, ...) + d=as.neuron(d, InputFileName=f, ...) + metadata=read_swc_meta(f) + if(!is.null(metadata)) + attr(d, 'metadata')=metadata + d } # internal function that just reads a table of SWC format data @@ -566,6 +580,27 @@ read.swc<-function(f){ d } +read_swc_comments <- function(f) { + con=file(f, open='r') + on.exit(close(con)) + header=character() + while(TRUE) { + l=try(readLines(con = con, n=1), silent = T) + if(inherits(l, 'try-error') || nchar(l)<1 || substr(l,1,1)!="#") + break; + header=c(header, l) + } + header +} + +read_swc_meta <- function(f, parse=TRUE) { + h=read_swc_comments(f) + if(!isTRUE(any(nchar(metal <- grep("^# Meta: ", h, value = TRUE))>0))) + return(NULL) + meta=substr(metal, nchar("# Meta: ")+1, nchar(metal)) + if(isTRUE(parse)) jsonlite::fromJSON(meta, simplifyVector = F) else meta +} + #' @rdname read.neuron.swc #' @inheritParams ngraph #' @export