-
Notifications
You must be signed in to change notification settings - Fork 28
/
neuron.R
1726 lines (1577 loc) · 66.9 KB
/
neuron.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#' neuron: class to represent traced neurons
#'
#' neuron objects consist of a list containing multiple fields describing the 3D
#' location and connectivity of points in a traced neuron. The critical fields
#' of a neuron, n, are n$d which contains a dataframe in SWC format and
#' n$SegList which contains a representation of the neuron's topology used for
#' most internal calculations. For historical reasons, n$SegList is limited to a
#' \emph{single fully-connected} tree. If the tree contains multiple unconnected
#' subtrees, then these are stored in n$SubTrees and nTrees will be >1; the
#' "master" subtree (typically the one with the most points) will then be stored
#' in n$SegList and n$NumPoints will refer to the number of points in that
#' subtree, not the whole neuron.
#' @description \code{neuron} makes a neuron object from appropriate variables.
#' @details StartPoint, BranchPoints, EndPoints are indices matching the rows of
#' the vertices in \code{d} \strong{not} arbitrary point numbers typically
#' encoded in \code{d$PointNo}.
#' @rdname neuron
#' @export
#' @family neuron
#' @seealso \code{\link{neuronlist}}
#' @param d matrix of vertices and associated data in SWC format
#' @param NumPoints Number of points in master subtree
#' @param StartPoint,BranchPoints,EndPoints Nodes of the neuron
#' @param SegList List where each element contains the vertex indices for a
#' single segments of the neuron, starting at root.
#' @param SubTrees List of SegLists where a neuron has multiple unconnected
#' trees (e.g. because the soma is not part of the graph, or because the
#' neuronal arbour has been cut.)
#' @param ... Additional fields to be included in neuron. Note that if these
#' include CreatedAt, NodeName, InputFileStat or InputFileMD5, they will
#' override fields of that name that are calculated automatically.
#' @param InputFileName Character vector with path to input file
#' @param NeuronName Character vector containing name of neuron or a function
#' with one argument (the full path) which returns the name. The default
#' (\code{NULL}) sets NeuronName to the file name without the file extension.
#' @param MD5 Logical indicating whether to calculate MD5 hash of input
#' @importFrom tools md5sum
#' @examples
#' ## See help for functions listed in See Also for more detailed examples
#' ## Basic properties
#' # a sample neuron
#' n = Cell07PNs[[1]]
#'
#' # summarise it
#' n
#'
#' # inspect its internal structure
#' str(n)
#' # summary of 3D points
#' summary(xyzmatrix(n))
#' # identify 3d location of endpoints
#' xyzmatrix(n)[endpoints(n),]
#'
#' ## Other methods
#' # plot
#' plot(n)
#' # all methods for neuron objects
#' methods(class = 'neuron')
#'
#' ## Neurons as graphs
#' # convert to graph and find longest paths by number of nodes
#' ng=as.ngraph(n)
#' hist(igraph::distances(ng))
#' # ... or in distances microns
#' ngw=as.ngraph(n, weights=TRUE)
#' hist(igraph::distances(ngw))
#'
#' # converting back and forth between neurons and graphs
#' g=as.ngraph(Cell07PNs[[1]])
#' gstem=igraph::induced.subgraph(g, 1:10)
#' # this is fine
#' plot(gstem)
#' plot(as.neuron(gstem))
#'
#' # but if you had an undirected graph
#' ug=igraph::as.undirected(gstem)
#' # you get a warning because there is no explicit origin for the graph
#' as.neuron(ug)
#'
#' # If you need finer control of the conversion process
#' gstem2=as.ngraph(ug, root = 10)
#' plot(gstem2)
#' plot(as.neuron(gstem2))
neuron<-function(d, NumPoints=nrow(d), StartPoint, BranchPoints=integer(), EndPoints,
SegList, SubTrees=NULL, InputFileName=NULL, NeuronName=NULL, ...,
MD5=TRUE){get
coreFieldOrder=c("NumPoints", "StartPoint", "BranchPoints",
"EndPoints", "nTrees", "NumSegs", "SegList", "SubTrees","d" )
mcl<-as.list(match.call())
n=c(mcl,list(NumPoints=NumPoints,
nTrees=ifelse(is.null(SubTrees),1,length(SubTrees)),
NumSegs=length(SegList)))
n=n[intersect(coreFieldOrder,names(n))]
n=lapply(n, eval)
if(is.null(InputFileName)){
n$NeuronName=NeuronName
} else {
if(is.null(NeuronName)) NeuronName=sub("\\.[^.]+$","",basename(InputFileName))
else if(is.function(NeuronName)) NeuronName=NeuronName(InputFileName)
neuron_extra=list(NeuronName=NeuronName,
InputFileName=InputFileName,
CreatedAt=Sys.time(),
NodeName=Sys.info()["nodename"])
if(file.exists(InputFileName)) {
neuron_extra$InputFileStat=file.info(InputFileName)[1,]
if(MD5) neuron_extra$InputFileMD5=md5sum(InputFileName)
}
n=c(neuron_extra,n)
}
dots=list(...)
if(length(dots)) {
n[names(dots)]=dots
}
as.neuron(n)
}
#' @param x A neuron or other object to test/convert
#' @description \code{is.neuron} will check if an object looks like a neuron.
#' @param Strict Whether to check class of neuron or use a more relaxed
#' definition based on object being a list with a SegList component.
#' @export
#' @rdname neuron
is.neuron<-function(x,Strict=FALSE) {
inherits(x,"neuron") ||
(!Strict && is.list(x) && !is.null(x[["SegList"]]))
}
#' @description \code{as.neuron} will convert a suitable object to a neuron
#' @export
#' @rdname neuron
as.neuron<-function(x, ...) UseMethod('as.neuron')
#' @export
as.neuron.neuron<-function(x, ...) x
#' @rdname neuron
#' @export
#' @details Columns will be ordered c('PointNo','Label','X','Y','Z','W','Parent')
#' @description \code{as.neuron.data.frame} expects a block of SWC format data
as.neuron.data.frame<-function(x, ...) {
x=normalise_swc(x)
as.neuron(as.ngraph(x), vertexData=x, ...)
}
#' Normalise an SWC format block of neuron morphology data
#' @param x A data.frame containing neuron morphology data
#' @param requiredColumns Character vector naming columns we should have
#' @param ifMissing What to do if \code{x} is missing a required column
#' @param includeExtraCols Whether to include any extra columns include in
#' code{x}
#' @param defaultValue A list containing default values to use for any missing
#' columns
#' @return A data.frame containing the normalised block of SWC data with
#' standard columns in standard order.
#' @seealso \code{\link{as.neuron.data.frame}}, \code{\link{seglist2swc}}
#' @details Note that row.names of the resultant data.frame will be set to NULL
#' so that they have completely standard values.
#' @export
normalise_swc<-function(x, requiredColumns=c('PointNo','Label','X','Y','Z','W','Parent'),
ifMissing=c('usedefaults','warning','stop'),
includeExtraCols=TRUE,
defaultValue=list(PointNo=seq.int(nrow(x)),Label=2L,
X=NA_real_,Y=NA_real_,Z=NA_real_,
W=NA_real_,Parent=NA_integer_)
){
cnx=colnames(x)
ifMissing=match.arg(ifMissing)
if(ifMissing!='usedefaults') ifMissing=match.fun(ifMissing)
missingColumns=setdiff(requiredColumns, cnx)
if(length(missingColumns)){
if(is.character(ifMissing)){
x[,missingColumns]=defaultValue[missingColumns]
} else {
ifMissing("Columns ", paste(missingColumns, collapse=","), " are missing from x")
}
}
# if only giving a warning for missing columns we may may be missing some
selectedCols=intersect(requiredColumns, colnames(x))
if(includeExtraCols)
selectedCols=c(selectedCols, setdiff(cnx, requiredColumns))
row.names(x)=NULL
x[,selectedCols]
}
#' Make SegList (and other core fields) from full graph of all nodes and origin
#'
#' @description \code{as.neuron.ngraph} converts a graph (typically an
#' \code{ngraph} object) to a neuron
#' @details Uses a depth first search on the tree to reorder using the given
#' origin.
#' @details When the graph contains multiple subgraphs, only one will be chosen
#' as the master tree and used to construct the SegList of the resultant
#' neuron. However all subgraphs will be listed in the SubTrees element of the
#' neuron and nTrees will be set appropriately.
#' @details When the graph vertices have a label attribute derived from PointNo,
#' the origin is assumed to be specified with respect to the vertex labels
#' rather than the raw vertex ids.
#' @param vertexData A dataframe with SWC fields especially X,Y,Z,W,PointNo,
#' Parent.
#' @param origin Root vertex, matched against names (aka PointNo) when
#' available (see details)
#' @param Verbose Whether to be verbose (default: FALSE)
#' @return A list with elements:
#' (NumPoints,StartPoint,BranchPoints,EndPoints,nTrees,NumSegs,SegList,
#' [SubTrees]) NB SubTrees will only be present when nTrees>1.
#' @export
#' @importFrom igraph V V<- vcount decompose.graph
#' @rdname neuron
#' @seealso \code{\link{graph.dfs}, \link{as.seglist}}
as.neuron.ngraph<-function(x, vertexData=NULL, origin=NULL, Verbose=FALSE, ...){
# translate origin into raw vertex id if necessary
if(length(origin)){
vertex_names=igraph::V(x)$name
if(!is.null(vertex_names)){
origin=match(origin, vertex_names)
if(is.na(origin)) stop("Invalid origin")
}
}
# save original vertex ids
igraph::V(x)$vid=seq.int(igraph::vcount(x))
# check if we have multiple subgraphs
if(igraph::no.clusters(x)>1){
if(!length(origin)){
# no origin specified, will pick the biggest subtree
# decompose into list of subgraphs
gg=igraph::decompose.graph(x)
# reorder by descending number of vertices
gg=gg[order(sapply(gg,igraph::vcount), decreasing=TRUE)]
subtrees=lapply(gg, as.seglist, Verbose=Verbose)
sl=subtrees[[1]]
masterg=gg[[1]]
} else {
# origin specified, subtree containing origin will be the master
cg=igraph::clusters(x)
master_tree_num=cg$membership[origin]
# make a master graph with the vertices from subgraph including origin
masterg=igraph::induced.subgraph(x, which(cg$membership==master_tree_num))
# ... and then corresponding seglist
sl=as.seglist(masterg, origin=origin)
# now deal with remaining vertices
remainderg=igraph::induced.subgraph(x, which(cg$membership!=master_tree_num))
gg=igraph::decompose.graph(remainderg)
# reorder by descending number of vertices
gg=gg[order(sapply(gg,igraph::vcount), decreasing=TRUE)]
subtrees=c(list(sl),lapply(gg, as.seglist, Verbose=Verbose))
}
nTrees=length(subtrees)
} else {
# this is a well-behaved graph that is immediately ready to be master graph
# of neuron
sl=as.seglist(masterg<-x, origin=origin, Verbose=Verbose)
subtrees=list(sl)
nTrees=1
}
if(length(sl)==0 || length(sl[[1]])<2)
stop("Invalid neuron! Must contain at least one segment with 2 points")
# Finalise StartPoint - should always be head point of first segment
StartPoint=sl[[1]][1]
# sort out the vertex information
# TODO refactor this into a separate function e.g. normalise.swc since
# we need to do something similar in as.neuron.dataframe and seglist2swc etc
d=data.frame(PointNo=get.vertex.attribute(x,'name'))
if(is.null(vertexData)){
# get vertex information from graph object
xyz=xyzmatrix(x)
if(!is.null(xyz)) d[,c("X","Y","Z")]=xyz[igraph::V(x),]
diam=V(x)$diam
if(!is.null(diam)) d[, "W"]=diam[igraph::V(x)]
} else {
# we were given a block of vertexData
if("PointNo"%in%colnames(vertexData)){
# to be on the safe side, let's reorder the vertex data so that PointNos
# matches PointNos stored in graph as vertex attributes
ids=match(d$PointNo, vertexData$PointNo)
if(any(is.na(ids)))
stop("Mismatch between PointNos stored in graph and those in vertexData")
d=cbind(d, vertexData[ids,colnames(vertexData)!='PointNo'])
} else {
# the datablock doesn't have a PointNo field so just assume that it
# is ordered according to the vertex indices
if(nrow(d)!=nrow(vertexData))
stop("vertexData does not have PointNo column and does not have as",
"many rows as there are points in the graph.")
d=cbind(d, vertexData)
}
}
d=seglist2swc(x=subtrees,d=d)
d=normalise_swc(d)
n=list(d=d,NumPoints=igraph::vcount(masterg),
StartPoint=StartPoint,
BranchPoints=branchpoints(masterg, original.ids='vid'),
EndPoints=endpoints(masterg, original.ids='vid'),
nTrees=nTrees,
NumSegs=length(sl),
SegList=sl)
if(nTrees>1) n=c(n,list(SubTrees=subtrees))
# NB unname is a guard against named fields coming in.
# The name would otherwise turn into a suffix in the neuron that would cause
# trouble when constructing the neuron
# e.g. InputFileName->InputFileName.XT23L1
if(!missing(...)) n=c(n, lapply(pairlist(...), unname))
do.call(neuron, n)
}
#' @description \code{as.neuron.igraph} will convert an \code{ngraph} compatible
#' \code{\link[igraph]{igraph}} object into a \code{neuron}.
#' @export
#' @rdname neuron
as.neuron.igraph <- function(x, ...) {
must_have=c("X","Y","Z","diam")
if(!all(must_have %in% igraph::vertex_attr_names(x)))
stop("Sorry this does not look like an ngraph! Missing XYZ/diam data!")
as.neuron.ngraph(x, ...)
}
#' @description \code{as.neuron.default} will add class "neuron" to a neuron-like
#' object.
#' @rdname neuron
#' @export
as.neuron.default<-function(x, ...){
if(is.null(x)) return (NULL)
if(is.neuron(x,Strict=FALSE)) class(x)=c("neuron",class(x))
x
}
#' Arithmetic for neuron coordinates
#'
#' If x is a 1-vector or a 3-vector, operate on xyz only
#' If x is a 4-vector, apply operation to xyz and diameter
#' @param e1 a neuron
#' @param e2 (a numeric vector to multiply neuron coords in neuron)
#' @return modified neuron
#' @export
#' @rdname neuron-arithmetic
#' @seealso neuron
#' @examples
#' n1<-Cell07PNs[[1]]*2
#' n2<-Cell07PNs[[1]]*c(2,2,2,1)
#' stopifnot(all.equal(n1,n2))
#' n3<-Cell07PNs[[1]]*c(2,2,4)
Ops.neuron <- function(e1, e2=NULL) {
ok <-
switch(
.Generic,
`-` = ,
`*` = ,
`/` = ,
`+` = ,
`^` = ,
'>' = ,
'<' = ,
'>=' = ,
'<=' = TRUE,
FALSE
)
if (!ok) {
stop(gettextf("%s not meaningful for neurons", sQuote(.Generic)))
}
r=e1
lx=length(e2)
e1 <- if(lx==3) {
t(xyzmatrix(e1))
} else if(lx==4) {
t(cbind(xyzmatrix(e1), e1$d$W))
} else if(lx>1) {
stop("second operand must be a numeric vector of length 0, 1, 3 or 4")
} else {
e1=xyzmatrix(r)
}
# I don't exactly know why it is necessary to change this directly, but if not
# NextMethod dispatches on original class of e1 even when I specify object=
.Class=class(e1)
res <- NextMethod(generic=.Generic)
if(lx==4) {
r$d$W=res[4,]
res=t(res[-4,])
} else if(lx==3){
res=t(res)
}
xyzmatrix(r)=res
r
}
#' Scale and centre neuron 3D coordinates
#'
#' @details If \code{scale=TRUE}, the neuron will be rescaled to unit sd in each
#' axis. If \code{center=TRUE}, the neuron will be centred around the axis
#' means. See \code{base::\link{scale.default}} for additional details.
#' @param x A neuron
#' @param center 3-vector to subtract from x,y,z coords
#' @param scale 3-vector used to divide x,y,z coords
#' @return neuron with scaled coordinates
#' @export
#' @seealso \code{\link{scale.default}}, \code{\link{Ops.neuron}}
#' @aliases scale
#' @examples
#' n1.scaledown=scale(Cell07PNs[[1]],scale=c(2,2,3))
#' n1.scaleup=scale(Cell07PNs[[1]],scale=1/c(2,2,3))
scale.neuron<-function(x, center=TRUE, scale=TRUE){
xyzmatrix(x)<-scale(xyzmatrix(x),scale=scale,center=center)
x
}
#' Check equality on key fields of neuron object
#'
#' @inheritParams base::all.equal.default
#' @param fieldsToCheck Which fields in the neuron are always checked. The
#' special value of \code{NA} indicates that \bold{all} fields in the neurons
#' will be compared.
#' @param fieldsToCheckIfPresent These fields are only checked if they are
#' present
#' @param fieldsToExclude Character vector of fields to exclude from check
#' @param CheckSharedFieldsOnly Logical whether to check shared fields only
#' (default: FALSE)
#' @param ... additional arguments passed to \code{all.equal}
#' @export
#' @seealso \code{\link[base]{all.equal}}
#' @examples
#' x=Cell07PNs[[1]]
#' y=x
#' y$NeuronName='rhubarb'
#' # NOT TRUE
#' all.equal(x, y)
#' # TRUE
#' all.equal(x, y, fieldsToExclude='NeuronName')
all.equal.neuron<-function(target,current,tolerance=1e-6,check.attributes=FALSE,
fieldsToCheck=c("NumPoints", "StartPoint", "BranchPoints",
"EndPoints", "NumSegs", "SegList", "d"),
fieldsToCheckIfPresent=c("NeuronName","nTrees","SubTrees"),
fieldsToExclude=character(),
CheckSharedFieldsOnly=FALSE, ...){
if(length(fieldsToCheck)==1 && is.na(fieldsToCheck))
fieldsToCheck=union(names(current), names(target))
if(!is.neuron(target) || !is.neuron(current))
return ("target and current must both be neurons")
fieldsInCommon=intersect(names(target),names(current))
# figure out which of the optional fields to check are present
fieldsToCheckIfPresent=intersect(fieldsInCommon,fieldsToCheckIfPresent)
# and add those to the fields to check
fieldsToCheck=unique(c(fieldsToCheck,fieldsToCheckIfPresent))
if(CheckSharedFieldsOnly){
fieldsToCheck=intersect(fieldsInCommon,fieldsToCheck)
} else{
# check all core fields
missingfields=setdiff(fieldsToCheck,names(current))
if(length(missingfields)>0)
return(paste("Current missing fields: ",missingfields))
missingfields=setdiff(fieldsToCheck,names(target))
if(length(missingfields)>0)
return(paste("Target missing fields: ",missingfields))
}
fieldsToCheck=setdiff(fieldsToCheck,fieldsToExclude)
all.equal(target[fieldsToCheck],current[fieldsToCheck],
tolerance=tolerance, check.attributes=check.attributes, ...)
}
#' Calculate length of all segments in neuron
#'
#' @param x A neuron
#' @param all Whether to calculate lengths for all segments when there are
#' multiple subtrees (default: \code{FALSE})
#' @param flatten Whether to flatten the lists of lists into a single list when
#' \code{all=TRUE}
#' @param sumsegment Whether to return the length of each segment (when
#' {sumsegment=TRUE}, the default) or a list of vectors of lengths of each
#' individual edge in the segment.
#' @details A segment is an unbranched portion of neurite consisting of at least
#' one vertex joined by edges.Only segments in x$SegList will be calculated
#' unless \code{all=TRUE}. Segments containing only one point will have 0
#' length.
#' @return A \code{vector} of lengths for each segment or when
#' \code{sumsegment=FALSE} a \code{list} of vectors
#' @export
#' @seealso \code{\link{as.seglist.neuron}}
#' @examples
#' summary(seglengths(Cell07PNs[[1]]))
#' hist(unlist(seglengths(Cell07PNs[[1]], sumsegment = FALSE)),
#' br=20, main='histogram of edge lengths', xlab='edge lengths /microns')
seglengths=function(x, all=FALSE, flatten=TRUE, sumsegment=TRUE){
# convert to numeric matrix without row names
sts<-as.seglist(x, all=all, flatten=flatten)
d=data.matrix(x$d[, c("X", "Y", "Z")])
if(all && !flatten) {
lapply(sts, function(st) sapply(st,
function(s) seglength(d[s, , drop=FALSE], sum=sumsegment),
simplify=sumsegment, USE.NAMES = FALSE ))
} else sapply(sts, function(s) seglength(d[s, , drop=FALSE], sum=sumsegment),
simplify=sumsegment, USE.NAMES = FALSE)
}
# Calculate length of single segment in neuron
seglength=function(ThisSeg, sum=TRUE){
#ThisSeg is an array of x,y and z data points
#In order to calculate the length
#Need to find dx,dy,dz
#Then find sqrt(dx^2+...)
#Then sum over the path
if(nrow(ThisSeg)==1) return(0)
ds=diff(ThisSeg)
edgelengths=sqrt(rowSums(ds*ds))
if(sum) sum(edgelengths) else unname(edgelengths)
}
#' Resample an object with a new spacing
#' @param x An object to resample
#' @param ... Additional arguments passed to methods
#' @export
resample<-function(x, ...) UseMethod("resample")
#' resample a neuron with a new spacing
#'
#' @param stepsize The new spacing along the tracing
#' @details \code{resample.neuron} Floating point columns including X,Y,Z,W will
#' be interpolated using linear interpolation, while integer or factor columns
#' will be interpolated using constant interpolation. See \code{\link{approx}}
#' for details.
#' @export
#' @rdname resample
#' @seealso \code{\link{approx}}, \code{\link{seglengths}}
#' @family neuron
resample.neuron<-function(x, stepsize, ...) {
# extract original vertex array before resampling
cols=c("X","Y","Z")
if(!is.null(x$d$W)) cols=c(cols, 'W')
# if(!is.null(x$d$Label)) cols=c(cols, 'Label')
d=data.matrix(x$d[, cols, drop=FALSE])
# if(!is.null(d$Label)) d$Label=as.integer(d$Label)
if(any(is.na(d[,1:3])))
stop("Unable to resample neurons with NA points")
# fetch all segments and process each segment in turn
sl=as.seglist(x, all = T, flatten = T)
npoints=nrow(d)
dl=list(d)
for (i in seq_along(sl)){
s=sl[[i]]
# interpolate this segment
dold=d[s, , drop=FALSE]
dnew=resample_segment(dold, stepsize=stepsize, ...)
if(is.null(dnew)) next
dl[[length(dl)+1]]=dnew
# if we've got here, we need to do something
# add new points to the end of the swc block
# and give them sequential point numbers
newids=seq.int(from = npoints+1, length.out = nrow(dnew))
npoints=npoints+nrow(dnew)
# replace internal ids in segment so that proximal point is connected to head
# and distal point is connected to tail
sl[[i]]=c(s[1], newids, s[length(s)])
}
d=do.call(rbind, dl)
d=as.data.frame(d)
rownames(d)=NULL
# let's deal with the label column which was dropped - assume that always the
# same within a segment
head_idxs=sapply(sl, "[", 1)
seglabels=x$d$Label[head_idxs]
# in order to avoid re-ordering the segments when as.neuron.ngraph is called
# we can renumber the raw indices in the seglist (and therefore the vertices)
# in a strictly ascending sequence based on the seglist
# it is *much* more efficient to compute this on a single vector rather than
# separately on each segment in the seglist. However this does involve some
# gymnastics
usl=unlist(sl)
old_ids=unique(usl)
# reorder vertex information to match this
d=d[old_ids,]
node_per_seg=sapply(sl, length)
df=data.frame(id=usl, seg=rep(seq_along(sl), node_per_seg))
df$newid=match(df$id, old_ids)
sl=split(df$newid, df$seg)
labels_by_seg=rep(seglabels, node_per_seg)
# but there will be some duplicated ids (branch points) that we must remove
d$Label=labels_by_seg[!duplicated(df$newid)]
swc=seglist2swc(sl, d)
as.neuron(swc, origin=match(x$StartPoint, old_ids))
}
#' @export
#' @rdname resample
resample.neuronlist<-function(x, stepsize, ...){
nlapply(x, resample, stepsize=stepsize, ...)
}
# Interpolate ordered 3D points (optionally w diameter)
# NB returns NULL if unchanged (when too short or <=2 points)
# and only returns _internal_ points, omitting the head and tail of a segment
#' @importFrom stats approx
resample_segment<-function(d, stepsize, ...) {
# we must have at least 2 points to resample
if(nrow(d) < 2) return(NULL)
dxyz=xyzmatrix(d)
# we should only resample if the segment is longer than the new stepsize
l=seglength(dxyz)
if(l<=stepsize) return(NULL)
# figure out linear position of new internal points
internalPoints=seq(stepsize, l, by=stepsize)
nInternalPoints=length(internalPoints)
# if the last internal point is actually in exactly the same place
# as the endpoint then discard it
if(internalPoints[nInternalPoints]==l) {
internalPoints=internalPoints[-length(internalPoints)]
nInternalPoints=length(internalPoints)
}
# find cumulative length stopping at each original point on the segment
diffs=diff(dxyz)
cumlength=c(0,cumsum(sqrt(rowSums(diffs*diffs))))
# find 3D position of new internal points
# using linear approximation on existing segments
# make an emty object for results
# will have same type (matrix/data.frame as input)
dnew=matrix(nrow=nInternalPoints, ncol=ncol(d))
colnames(dnew)=colnames(d)
if(is.data.frame(d)){
dnew=as.data.frame(dnew)
}
for(n in seq.int(ncol(dnew))) {
dnew[,n] <- if(!all(is.finite(d[,n]))) {
rep(NA, nInternalPoints)
} else {
approx(cumlength, d[,n], internalPoints,
method = ifelse(is.double(d[,n]), "linear", "constant"),
ties="ordered")$y
}
}
dnew
}
#' Smooth the 3D coordinates of a neuron skeleton
#'
#' \code{smooth_neuron} smooths a neuron.
#' @param n Neuron to smooth
#' @param method Smoothing method
#' @param ... Additional parameters passed to segment smoothing functions
#'
#' @return A new neuron with smoothed 3d coordinates
#' @export
#'
#' @examples
#' ns=smooth_neuron(Cell07PNs[[1]], sigma=2)
#' # plot in 2D zooming in on axon terminals
#' plot(Cell07PNs[[1]], col='grey', xlim=c(260,290), ylim=c(115,90))
#' plot(ns, col='red', add=TRUE)
#' \donttest{
#' # 3D plot
#' plot3d(Cell07PNs[[1]], col='grey')
#' plot3d(ns, col='red')
#' }
smooth_neuron <- function(n, method=c("gauss", "spline"), ...) {
method=match.arg(method)
FUN=get(paste0('smooth_segment_', method), mode='function')
# iterate over segments
d=xyzmatrix(n)
if(any(is.na(d[,1:3])))
stop("Unable to resample neurons with NA points")
# fetch all segments and process each segment in turn
sl=as.seglist(n, all = T, flatten = T)
for (i in seq_along(sl)){
s=sl[[i]]
# interpolate this segment
d[s,]=FUN(d[s, , drop=FALSE], ...)
}
xyzmatrix(n) <- d
n
}
#' @rdname smooth_neuron
#' @param xyz A block of 3D coordinates defining an unbranched segment
#' @param sigma The standard deviation of the Gaussian smoothing kernel (which
#' has the same spatial units as the object being smoothed)
#' @importFrom stats dnorm
smooth_segment_gauss <- function(xyz, sigma, ...){
if(nrow(xyz)<2) return(xyz)
# make variable t as the cumulative position along segment
t=c(0,cumsum(seglength(xyz, sum = F)))
xyzt=xyz
for(i in 2:(nrow(xyz)-1)){
weights=dnorm(abs(t-t[i]), sd = sigma)
weights=weights/sum(weights)
xyzt[i,]=colSums(xyz*weights)
}
xyzt
}
#' @importFrom stats smooth.spline
smooth_segment_spline <- function(xyz, ...) {
if(nrow(xyz)<4) return(xyz)
# make variable t as the cumulative position along segment
t=c(0,cumsum(seglength(xyz, sum = F)))
# ensure that ends are fixed
w=rep(1,nrow(xyz))
w[1]=1e6
w[length(w)]=w[1]
fittedxyz=apply(xyz, 2, function(u) smooth.spline(t, u, w=w, ...)$y)
fittedxyz
}
#' Subset neuron by keeping only vertices that match given conditions
#'
#' @details \code{subset} defines which vertices of the neuron to keep and is
#' one of \itemize{
#'
#' \item logical or numeric indices, in which case these are simply used to
#' index the vertices in the order of the data.frame \code{x$d}. Note that any
#' NA values are ignored.
#'
#' \item a function (which is called with the 3D points array and returns T/F
#' vector)
#'
#' \item an expression evaluated in the context of the \code{x$d} data.frame
#' containing the SWC specification of the points and connectivity of the
#' neuron. This can therefore refer e.g. to the X,Y,Z location of vertices in
#' the neuron.
#'
#' }
#'
#' Note that due to its use of
#' \href{http://adv-r.had.co.nz/Computing-on-the-language.html}{non-standard
#' evaluation} \code{subset.neuron}, which is convenient interactive use but
#' can be fragile when used inside other functions. If you run into trouble it
#' is recommended to use the underlying \code{\link{prune_vertices}} function.
#' @param x A neuron object
#' @param subset A subset of points defined by indices, an expression, or a
#' function (see Details)
#' @param invert Whether to invert the subset criteria - a convenience when
#' selecting by function or indices.
#' @param ... Additional parameters (passed on to \code{\link{prune_vertices}})
#' @return subsetted neuron
#' @export
#' @seealso \code{\link{prune.neuron}}, \code{\link{prune_vertices}},
#' \code{\link{subset.dotprops}}
#' @examples
#' n=Cell07PNs[[1]]
#' # keep vertices if their X location is > 2000
#' n1=subset(n, X>200)
#' # diameter of neurite >1
#' n2=subset(n, W>1)
#' # first 50 nodes
#' n3=subset(n, 1:50)
#' # everything but first 50 nodes
#' n4=subset(n, 1:50, invert=TRUE)
#'
#' ## subset neuron by graph structure
#' # first plot neuron and show the point that we will use to divide the neuron
#' n=Cell07PNs[[1]]
#' plot(n)
#' # this neuron has a tag defining a point at which the neuron enters a brain
#' # region (AxonLHEP = Axon Lateral Horn Entry Point)
#' points(t(xyzmatrix(n)[n$AxonLHEP, 1:2]), pch=19, cex=2.5)
#'
#' # now find the points downstream (distal) of that with respect to the root
#' ng=as.ngraph(n)
#' # use a depth first search
#' distal_points=igraph::graph.dfs(ng, root=n$AxonLHEP, unreachable=FALSE,
#' neimode='out')$order
#' distal_tree=subset(n, distal_points)
#' plot(distal_tree, add=TRUE, col='red', lwd=2)
#'
#' # Find proximal tree as well
#' # nb this does not include the AxonLHEP itself as defined here
#' proximal_points=setdiff(igraph::V(ng), distal_points)
#' proximal_tree=subset(n, proximal_points)
#' plot(proximal_tree, add=TRUE, col='blue', lwd=2)
#'
#' \dontrun{
#' ## subset using interactively defined spatial regions
#' plot3d(n)
#' # nb you can save this select3d object using save or saveRDS functions
#' # for future non-interactive use
#' s3d=select3d()
#' n4=subset(n, s3d(xyzmatrix(n)))
#' # special case of previous version
#' n5=subset(n, s3d)
#' stopifnot(all.equal(n4,n5))
#' # keep the points that were removed from n1
#' n4.not=subset(n,Negate(s3d))
#' # vertices with x position > 100 and inside the selector function
#' n6=subset(n,X>100 & s3d(X,Y,Z))
#'
#' ## subset each neuron object in a whole neuronlist
#' n10=Cell07PNs[1:10]
#' plot3d(n10, lwd=0.5, col='grey')
#' n10.crop = nlapply(n10, subset, X>250)
#' plot3d(n10.crop, col='red')
#'
#' ## subset a neuron using a surface
#' library(nat.flybrains)
#' # extract left lateral horn surface and convert to mesh3d
#' lh=as.mesh3d(subset(IS2NP.surf, "LH_L"))
#' # subset neuron with this surface
#' x=subset(Cell07PNs[[1]], function(x) pointsinside(x, lh))
#' shade3d(lh, alpha=0.3)
#' plot3d(x, lwd=3, col='blue')
#' # Now find the parts of the neuron outside the surface
#' y=subset(Cell07PNs[[1]], function(x) Negate(pointsinside)(x, lh))
#' plot3d(y, col='red', lwd=2)
#' }
#' @family neuron
subset.neuron<-function(x, subset, invert=FALSE, ...){
e <- substitute(subset)
r <- eval(e, x$d, parent.frame())
if (!is.logical(r) && !is.numeric(r)) {
# a function that tells us whether a point is in or out
if(is.function(r)) r=subset(x$d[,c("X","Y","Z")])
else stop("Cannot evaluate subset")
}
if(is.logical(r)) {
r <- r & !is.na(r)
r <- which(r)
} else if(is.numeric(r)) {
r=r[!is.na(r)]
} else stop("Subset must evaluate to a logical or numeric index")
# nb !invert since prune_vertices drops vertices whereas subset.neuron keeps vertices
prune_vertices(x, r, invert=!invert, ...)
}
#' Simplify a neuron to the longest tree with n branch points
#'
#' @details If the neuron already contains fewer than or exactly the requested
#' number of branches, then the original neuron is returned. The approach is
#' to build up the new neuron starting from the longest tree including no
#' branches all the way up to the longest tree containing n branches. The
#' distance calculations are only carried out once so it should be reasonably
#' efficient. Nevertheless at each iteration, the longest path from the tree
#' so far to the newly selected leaf is calculated and it is likely that this
#' step could be avoided. Furthermore for large values of n, pruning excess
#' branches rather than building would presumably be more efficient.
#'
#' @param x A \code{\link[nat]{neuron}} to simplify
#' @param n Required number of branch points (default=1, minimum 0)
#' @param invert Whether to keep the simplified backbone (when
#' \code{invert=FALSE}, the default) or its inverse.
#' @param ... Additional arguments (currently ignored)
#'
#' @return The simplified \code{neuron} or the untouched original neuron for
#' neurons that have <=n branch points.
#' @author Gregory Jefferis \email{jefferis@gmail.com}
#' @export
#' @seealso \code{\link[nat]{spine}}
#' @examples
#' \donttest{
#' n=Cell07PNs[['ECA34L']]
#' n.simp=simplify_neuron(n)
#' n.simp4=simplify_neuron(n, n=4)
#'
#' plot(n, col='green', WithNodes = FALSE)
#' plot(n.simp, col='red', add = TRUE)
#' plot(n.simp4, col='blue', add = TRUE)
#'
#' # calculate the inverse as well
#' n.simp4.inv=simplify_neuron(n, n=4, invert=TRUE)
#' plot(n.simp4, col='blue')
#' plot(n.simp4.inv, col='red', add = TRUE)
#' }
#'
#' # 3D plots
#' \dontrun{
#' nclear3d()
#' plot3d(n.simp, col='red', add = TRUE)
#' plot3d(n.simp4, col='blue', add = TRUE)
#' plot3d(n, col='green', WithNodes = FALSE)
#' }
#'
#' # or with plotly where transparency works
#' \dontrun{
#' op <- options(nat.plotengine = 'plotly')
#' nclear3d()
#' plot3d(n.simp, col='red', alpha = 0.5, add = TRUE)
#' plot3d(n.simp4, col='blue', alpha = 0.5, add = TRUE)
#' plot3d(n, col='green', alpha = 0.5, WithNodes = FALSE)
#' }
#'
simplify_neuron <- function(x, n=1, invert=FALSE, ...) {
#Step 1a:Get the number of branch points in the neuron..
nbps=length(branchpoints(x))
#Step 1b:Compare with the actual branch points requested..
if (nbps <= n)
return(x)
if (n < 0)
stop("Must request >=0 branch points!")
#Step 2:Convert to ngraph object..
ng = as.ngraph(x, weights = T)
if (!igraph::is_dag(ng)) {
stop("I can't simplify neurons with cycles!")
}
# Step 3a: Compute all the leaf nodes..
leaves=setdiff(endpoints(ng, original.ids=FALSE), rootpoints(ng, original.ids=FALSE))
# Step 3b: Compute all the branch nodes..
bps=branchpoints(ng, original.ids=FALSE)
# Step 3c: Compute the distance from all the branch nodes to the leaf nodes let's call
# it distance table.. Rows are branch nodes and Columns are leaf nodes..
dd=igraph::distances(ng, v=bps, to=leaves, mode = 'out')
# Step 3d: Compute the decendant paths for all the branch nodes (to get the possibilities
# of different paths from a particular branch point)..
bpdesccount=igraph::ego_size(ng, order = 1, nodes = bps, mode='out', mindist = 1)
names(bpdesccount)=bps
bpsused=rep(0L, length(bps))
names(bpsused)=bps
lp_verts=list()
# The approach is to find the longest tree (lets call it spine) from the root to the
# farthest leaf node first..
# Then additional branches are added to the spine such that they are longest that can be
# added.
for (i in 0:n) {
if (i == 0) {
# Step 4a: Compute the spine, so for that compute the farthest leaf node
# with the distance table..
start = rootpoints(ng, original.ids=FALSE)
# Step 4b: Find out the leaf node which is farthest
furthest_leaf_idx = which.max(apply(dd, 2, robust_max))
} else {
# Step 7a: Find out the leaf node which is farthest Select only the branch nodes
# that are currently in our selected spine
# Also, choose only those who still have some unused descendent paths..
bps_available = bpsused > 0 & bpsused < bpdesccount
# find the length we could add for each leaf
# nb this will be the smallest value that can be added to
# currently selected nodes
# Step 7b: Now choose the shortest path to all the leaf nodes from the available
# branch nodes..
additional_length = apply(dd[bps_available, , drop=FALSE], 2, min, na.rm = T)
# remove any infinite values
additional_length[!is.finite(additional_length)] = 0
# Step 7c: Now choose the leaf nodes that is the farthest of distance among all the
# shortest path to the leaf nodes..
furthest_leaf_idx = which.max(additional_length)
start_idx = which.min(dd[bps_available, furthest_leaf_idx])
# Step 7d: Get the vertex index in the original graph
start = bps[which(bps_available)[start_idx]]
}
# Step 5 or 8: Avoid the choosen leaf from distance computations in next iteration
furthest_leaf = leaves[furthest_leaf_idx]
# strike off selected leaf
dd[, furthest_leaf_idx] = Inf
# Step 6 or 9: Find the path to that chosen leaf from the start point..
path = leafpath(ng, start, furthest_leaf)
lp_verts[[i+1]]=path
# add one to count of any bps used
bpsused[bps %in% path] = bpsused[bps %in% path] + 1
}
# Step 10: Find the edgelist from the path(start to farthest leaf)..
el=EdgeListFromSegList(lp_verts)
# Step 11: Prune the edgelist and choose to retain the pruned one (based on the invert flag)..
prune_edges(ng, el, invert = !invert)
}
leafpath <- function(ng, from, to) {
res=igraph::get.shortest.paths(ng,from = from,to = to,mode = "out")
as.integer(res$vpath[[1]])
}
robust_max=function(x) {
x=x[is.finite(x)]
if(length(x)) max(x) else {
warning("Some points in neuron cannot be reached! Multiple trees?")
-Inf
}
}
# Simplify a neuron to the longest tree with n branch points
#
# @details If the neuron already contains fewer than or exactly the requested
# number of branches, then the original neuron is returned. The approach is
# basically to compute the longest path in the neuron and then collect that path,
# further delete that path and recompute the longest path and then collect that new
# path again. Perform this approach until you reach the requested number of branchpoints.
#
# @inheritParams simplify_neuron
# @author Sridhar Jagannathan \email{j.sridharrajan@gmail.com}
# @export
# @seealso \code{\link[nat]{simplify_neuron}}