forked from tiagodc/TreeLS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathold.R
More file actions
1589 lines (1208 loc) · 51.9 KB
/
Copy pathold.R
File metadata and controls
1589 lines (1208 loc) · 51.9 KB
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
###Data sets
#' Scots Pine point cloud
#' @docType data
#' @name pine
#' @usage pine
NULL
#' Norway Spruce point cloud
#' @docType data
#' @name spruce
#' @usage spruce
NULL
#' Field measurements from sample trees
#' @docType data
#' @name proof
#' @usage proof
NULL
###Data simulation and analysis
#' Angle of a plane with \emph{z}
#' @description Calculates the angle between a plane's normal vector and the \emph{z} axis \code{c(0,0,1)}. The plane here is a point cloud sample.
#' @param XYZplane sample from a point cloud. Matrix n x 3, with columns containing x, y and z coordinates, respectively.
#' @return angle between the plane's normal vector and the \emph{z} axis \code{c(0,0,1)} (in degrees).
#' @export
ang.deg = function(XYZplane){
e = eigen(cov(XYZplane))
ang = ( e$vectors[,3] %*% c(0,0,1) ) / ( sqrt(sum(e$vectors[,3]^2)) * sqrt(sum(c(0,0,1)^2)) )
ang = ang[,,drop=T]
degs = acos(ang)*180/pi
return(degs)
}
#' Angle between two vectors
#' @description Calculates the angle between two vectors.
#' @param a,b numerical vectors of same length
#' @return angle between \emph{a} and \emph{b} (in degrees).
#' @export
angle = function(a,b){
prod = a %*% b
lprod = sqrt(sum(a^2)) * sqrt(sum(b^2))
ang = prod/lprod
cang = acos(ang) * 180/pi
return(cang[,,drop=T])
}
#' Rotates and dislocates a 3D dataset
#' @description Rotates and shifts the coordinates of a 3D point cloud
#' @param xyz.points point cloud, \emph{xyz} matrix object
#' @param rot.mat rotation matrix
#' @param shift dislocation in x, y and z directions, respectively - vector of length 3
#' @return point cloud with new coordinates
#' @seealso \code{\link{xyz.rotation.matrix}}
#' @export
change.coords = function(xyz.points, rot.mat=diag(3), shift=c(0,0,0)){
xyz.points = as.matrix(xyz.points)
rot = xyz.points %*% rot.mat
mrot = t(apply(rot, 1, function(u) u + shift))
return(mrot)
}
#' Random cylinder generation
#' @description Creates a random cylinder with specified paramenters
#' @param n number of points on the cylinder's surface
#' @param len length of the cylinder's axis
#' @param d cylinder diameter
#' @param dev deviation of points from surface, i.e. cylinder wall thickness
#' @param top.bottom if \code{TRUE}, creates only two circles with \code{n} points at bottom and top of the cylinder.
#' @return random cylinder point cloud - \emph{xyz} matrix
#' @export
cyl = function(n=10000, len=100, d=30, dev=NULL, top.bottom = F){
if(is.null(dev)) rad = d/2 else rad = runif(n, d-dev, d+dev)/2
if(top.bottom){
angs = seq(0,2*pi, length.out = n)
x = sin(angs)*rad
y = cos(angs)*rad
z = rep(c(0,len), each=n)
} else {
z=runif(n = n, min = 0, max = len)
angs = runif(n, 0, 2*pi)
x = sin(angs)*rad
y = cos(angs)*rad
}
return(cbind(x,y,z))
}
#' Surface flatness
#' @description calculates the flatness of a point cloud
#' @param XYZplane point cloud - \emph{xyz} matrix
#' @return surface flatness - ranging from 0 (non-flat) to 1 (perfectly flat)
#' @export
FL = function(XYZplane){
e = eigen(cov(XYZplane))
flat = 1 - ( e$values[3] / sum(e$values) )
return(flat)
}
#' Tukey's biweight function
#' @describe calculates weights for a dataset based on Tukey's biweight function
#' @param errors residuals from a fitted model
#' @param b efficiency constant (5 == 95\%)
#' @return list of length 2: \describe{\item{$Y}{residuals / MAD} \item{$weights}{weights}}
#' @export
tukey.estimator = function(errors, b = 5){
s = mad(errors)
Y = errors / s
tue = Y
larger = abs(tue) > b
tue[larger] = 0#b^2 / 6
tue[!larger] = (1-(tue[!larger]/b)^2)^2
#tue[!larger] = (b^2 / 6) * (1-(1-(tue[!larger]/b)^2 )^3 )
return(list(Y = Y, weights = tue))
}
#' Cross product between two vectors
#' @description calculates the cross product between two vectors - not to be confused with \code{crossprod}, which gives the dot product
#' @param a,b numerical vectors of same length
#' @return vector cross product
#' @export
Xprod = function(a,b){
x = c(a[2]*b[3] - a[3]*b[2] ,
a[3]*b[1] - a[1]*b[3] ,
a[1]*b[2] - a[2]*b[1])
return(x)
}
#' 3D rotation matrix
#' @description calculates the 3D rotation matrix for a \emph{xyz} dataset
#' @param ax angle of 1st rotation - around the \emph{x} axis (in degrees)
#' @param az angle of 2nd rotation - around the \emph{z} axis (in degrees)
#' @param ax2 angle of 3rd rotation - around the new \emph{x} axis (in degrees)
#' @return 3 x 3 \emph{xyz} rotation matrix
#' @export
xyz.rotation.matrix = function(ax, az, ax2){
ax = ax * pi/180
Rx = matrix(c(1, 0, 0,
0, cos(ax), sin(ax),
0, -sin(ax), cos(ax)),
ncol=3, byrow = T)
az = az * pi/180
Rz = matrix(c(cos(az), 0, -sin(az),
0, 1, 0,
sin(az), 0, cos(az)),
ncol=3, byrow=T)
ax2 = ax2 * pi/180
Rx2 = matrix(c( cos(ax2), sin(ax2), 0,
-sin(ax2), cos(ax2), 0,
0, 0, 1),
ncol=3, byrow=T)
ro.mat = Rx2 %*% Rz %*% Rx
return(ro.mat)
}
###General point cloud manipulation and visualization
#' Point cloud coloring by height
#' @description colors a point cloud by height intervals
#' @param xyz.cloud point cloud - \emph{xyz} matrix
#' @param pal color pallete - defaults to \code{rainbow}
#' @param n number of height intervals to color differently
#' @param quantile divide point cloud by height quantiles? - If FALSE, divides the point cloud in equal height intervals
#' @import rgl
#' @return plots \emph{xyz.cloud} using \code{rgl} and with the specified color pallete
#' @export
cloud.col = function(xyz.cloud, pal = rainbow, n=10, quantile = F){
if(quantile){
nq = quantile(xyz.cloud[,3], probs = seq(0,1,length.out = n+1))
cl = cut(xyz.cloud[,3], breaks = nq, include.lowest = T)
}else{
rg = range(xyz.cloud[,3])
cl = cut(xyz.cloud[,3], breaks = seq(rg[1], rg[2], by = (rg[2]-rg[1])/n), include.lowest = T)
}
cols = pal(n)[cl]
return(cols)
}
#' Centralize of \emph{xy} to zero
#' @description reassigns the x and y coordinates of a point cloud considering zero as its center
#' @param xyz.cloud point cloud - \emph{xyz} matrix
#' @return point cloud with new coordinates
#' @export
center.zero = function(xyz.cloud){
mn = colMeans(xyz.cloud)
names(mn) = c('x','y','z')
xyz.cloud[,1] = xyz.cloud[,1] - mn[1]
xyz.cloud[,2] = xyz.cloud[,2] - mn[2]
return(list(cloud = xyz.cloud, center = mn[1:2]))
}
#' Circular point cloud clip
#' @description clips a region of a point cloud in circular shape
#' @param cloud point cloud - \emph{xyz} matrix
#' @param rad circle radius
#' @param center x and y center coordinates for the circle
#' @return point cloud of all points inside the specified circle
#' @export
clip.XY = function(cloud, rad = 1.5, center = c(0,0)) {
if (center[1] == 0 & center[2] == 0) {
dists = sqrt(cloud[,1]^2+cloud[,2]^2)
out = cloud[dists <= rad, ]
} else {
dists = sqrt(((cloud[,1]-center[1])^2 + (cloud[,2]-center[2])^2))
out=cloud[dists<=rad, ]
}
return (out)
}
#' Plot 3D axes from the origin
#' @description plots the 3 main axes (\emph{xyz}) starting at \code{c(0,0,0)}
#' @param xyz length of each axis, x, y and z, respectively
#' @param cols color of x, y and z, respectively
#' @param ... further arguments passed to the \code{rgl.lines} function
#' @import rgl
#' @return plots 3D axes over the current rgl environment
#' @export
rglAXES = function(xyz = c(1,1,1), cols = c('red','green','blue'), ...){
rgl.lines(c(0,xyz[1]), c(0,0), c(0,0), col=cols[1], ...)
rgl.lines(c(0,0), c(0,xyz[2]), c(0,0), col=cols[2], ...)
rgl.lines(c(0,0), c(0,0), c(0,xyz[3]), col=cols[3], ...)
}
#' Plotting a stem model
#' @description plots a stem model of stacked cylinders or circles, depending on the \emph{fitting} routine used to calculate the stem segments
#' @param stem.out output from a stem fitting function - \code{\link{fit_RANSAC_circle}}, \code{\link{fit_RANSAC_cylinder}} or \code{\link{fit_IRTLS}}
#' @param cyl.len optional - cylinder length for all stem segments
#' @param col color pallete function or color string name to use to color the cylinders
#' @param bg background color of the rgl environemnt
#' @param alpha alpha value passed on to the \code{\link{ashape3d}} function
#' @examples
#'\dontrun{
#' trunk <- pref_HT(spruce)
#' stem <- fit_RANSAC_circle(trunk)
#' obj3d <- stem.model(stem)
#' rgl.points(spruce, size=1)
#'}
#' @return 3D stem model of stacked cylinders/circles
#' @import alphashape3d
#' @export
stem.model = function(stem.out, cyl.len=NA, col=rainbow, bg='black', alpha=.5){
#require(alphashape3d)
st = stem.out[[1]]
ft = stem.out[[2]]
if(ncol(ft) == 8){
cln = if(is.na(cyl.len)) ft[,2]-ft[,1] else rep(cyl.len, nrow(ft))
cols = if(class(col)=='function') col(nrow(ft)) else rep(col, nrow(ft))
abs = list()
pts = list()
for(i in 1:nrow(ft)){
tp = st[st[,3] <= ft[i,'z2'] & st[,3] >= ft[i,'z1'],]
vcs = cyl.vectors(ft[i,3:7])
d = ft[i,'r']*2
a = vcs$a
#h = if(a[3] < 0) ft[i,'z1'] else ft[i,'z1']
zang = angle(a, c(0,0,1))
xang = angle(c(vcs$n[-3],0), c(1,0,0))
rot = xyz.rotation.matrix(0,zang,xang)
cl = cyl(n=1000, len=cln[i], d=d)
go = change.coords(cl, rot, shift = vcs$Q)
ed = sqrt(sum((colMeans(tp) - colMeans(go))^2))
if(a[3]<0) ed = -ed
go = t(apply(go, 1, function(x) x+a*ed))
#go[,3] = go[,3] + abs(h)-min(go[,3])
acl = ashape3d(go, alpha = alpha)
abs[[i]] = acl
pts[[i]] = tp
}
} else {
if(ncol(ft) == 6){
if(is.na(cyl.len)) cln = .02 else cln = cyl.len
cols = if(class(col)=='function') col(nrow(ft)) else rep(col, nrow(ft))
abs = list()
pts = list()
for(i in 1:nrow(ft)){
tp = st[st[,3] <= ft[i,'z2'] & st[,3] >= ft[i,'z1'],]
xy = ft[i,3:4]
d = ft[i,'r']*2
if(d == 0 | d > 2) next
cl = cyl(n=1000, len=cln, d=d)
h = mean(ft[i,1:2])
go = t(apply(cl, 1, function(u) u + c(xy,h)))
acl = ashape3d(go, alpha = alpha)
abs[[i]] = acl
pts[[i]] = tp
}
}}
nulls = sapply(abs, is.null)
nl2 = sapply(pts, is.null)
bg3d(bg)
lapply(1:length(abs), function(u) if(!nulls[u]) plot.ashape3d(abs[[u]], clear=F, edges=F, vertices=F, col=cols[[u]]))
lapply(1:length(pts), function(u) if(!nl2[u]) rgl.points(pts[[u]], col=cols[[u]]) )
return(abs[!nulls])
}
#' Height-based point cloud filter
#' @description reduces a point cloud's density processing different height intervals individually
#' @param XYZtree point cloud (not necessarily for a whole a tree) - \emph{xyz} matrix
#' @param l.int length of height intervals to split the point cloud into
#' @param thr maximum density threshold - i.e. maximum amount of points tolerated per height interval
#' @return point cloud with reduced density
#' @seealso \code{\link{Vsections}}
#' @export
Vfilter = function(XYZtree, l.int = .3, thr = 10000){
#Description: reduces the point density of a point cloud
#XYZtree == matrix or data frame with 3 columns containing x, y and z coordinates, respectively
#l.int == passed to function Vsections. Length of height intervals
#thr == threshold, maximum number of points to retain in each chunk (radomly selected when n of points > thr)
#output == point cloud with reduced point density according to specified parameters
a = Vsections(XYZtree, l.int = l.int, Plot = F)
a = lapply(a , function(u){ if(nrow(u)>thr) u = u[sample(1:nrow(u), size = thr),] ; return(u) })
a = do.call(rbind, a)
return(a)
}
#' Split point cloud into height intervals
#' @description divides a point cloud in many smaller ones, according to height intervals
#' @param XYZtree point cloud (not necessarily a tree) - \emph{xyz} matrix
#' @param n.int number of height intervals (divided by point quantiles)
#' @param l.int optional - length of height intervals. If not NULL, splits a point cloud by fixed height intervals, instead of using \emph{n.int}
#' @param overlap optional - by how much should the height segments overlap?
#' @param Plot create a plot for every point cloud segment? TRUE or FALSE
#' @param units if \code{Plot == TRUE}, provide the units of measurement for labelling the plots
#' @param ... further arguments passed to \code{plot}
#' @return list with every compartment containing a section of the point cloud in fixed \emph{z} intervals
#' @export
Vsections = function(XYZtree, n.int = 100, l.int = NULL, overlap = NULL, Plot =T, units = 'm', ...){
#Description: subdivides the point cloud in height intervals
#XYZtree == matrix or data frame with 3 columns containing x, y and z coordinates, respectively
#n.int == number of height intervals to subdivide the point cloud
#l.int == if not NULL, n.int is disconsidered and the point cloud is subdivided in equal height invervals of length l.int
#overlap == proportion of point cloud chunks to overlap in z, applied when overlap != NULL
#Plot == if TRUE, plots the x and y coordinates of every chunk
#units == spatial unit, applicable when Plot == TRUE
#... == further 'plot' arguments
#output == object of class 'list', with each compartment containing a slice of the input point cloud
if(class(XYZtree) != 'data.frame') XYZtree = as.data.frame(XYZtree)
rg = range(XYZtree[,3])
if(is.null(l.int)){
ints = seq(rg[1], rg[2], length.out = n.int+1)
} else {
ints = seq(rg[1]-(l.int/2), rg[2]+l.int, by = l.int)
}
classes = cut(XYZtree[,3], breaks = ints)
section.list = split(XYZtree, f = classes)
section.list = section.list[sapply(section.list,nrow)>0]
if(!is.null(overlap) && length(section.list)>1){
add = ints - l.int*overlap
for(i in 2:length(section.list)){
extra = section.list[[i-1]]
extra = extra[extra[,3]>=add[i],]
section.list[[i]] = rbind(section.list[[i]], extra)
names(section.list)[i] = paste('(',add[i],',',ints[i+1],']', sep = '')
}
}
if(Plot){
lapply(section.list, function(u) plot(u[,2] ~ u[,1], pch=20, cex=.5,
main = paste(round(range(u[,3]),digits = 2), units ,collapse = ' - ', sep=' '),
xlab='x', ylab='y', ...))
}
return(section.list)
}
###Hough transformation
#' Tree base Hough transformation filter
#' @description identification of reference cylinder at the tree's base for filtering outliers using the Hough transformation
#' @param XYZmat single tree point cloud - \emph{xyz} matrix
#' @param z.int optional - height interval to take the reference cylinder. If not specified, the height interval adopted is from 5\% to 10\% of the tree's total height
#' @param rad.inf inflation factor to multuply the radius. All points (in the entire point cloud) outside a range of \emph{rad.inf * radius} from the reference cylinder's center will be deleted
#' @param cell.size pixel size for the Hough transformation
#' @param min.val passed on to \code{\link{hough}}
#' @param Plot plot the reference tree segment? TRUE or FALSE
#' @return vector of length 5, containing the upper and lower height limits of the reference cylinder, xy coordinates of circle center and its radius
#' @seealso \code{\link{hough}}
#' @export
HT_base_filter = function(XYZmat, z.int = NULL, rad.inf = 2, cell.size = .025, min.val=.3, Plot=F){
#Description:
#XYZmat == matrix or data frame with 3 columns containing x, y and z coordinates, respectively
#z.int == lower and upper height limits for extracting the reference cylinder
#rad.inf == inflation factor to apply over the cylinder radius
#Plot == if TRUE plots the xy coordinates of the extracted section of the input point cloud
#output == vector of length 5, containing the upper and lower height limits of the reference cylinder,
#xy coordinates of circle center and its radius
if(is.null(z.int)) z.int = min(XYZmat[,3]) + c(.05,.1)*(max(XYZmat[,3]) - min(XYZmat[,3])) else z.int = min(XYZmat[,3]) + z.int
chunk = XYZmat[XYZmat[,3] >= z.int[1] & XYZmat[,3] <= z.int[2],]
ras = makeRaster(chunk, cell.size = cell.size, image = F)
rad = hough(ras, pixel_size = cell.size, Plot = F, min.val = min.val)
top = which(rad$centers[,4] == max(rad$centers[,4]))
if(nrow(rad$centers[top,,drop=F]) > 1) goal = apply(rad$centers[top,], 2, mean) else goal = rad$centers[top,]
if(Plot){
angs = seq(0, 2*pi, length.out = 360)
plot(chunk[,2] ~ chunk[,1], xlab='x', ylab='y', pch=20, cex=.5, main = paste(round(z.int,2), collapse = ' - '))
points(x=goal[1], y=goal[2], col='blue', pch=3)
lines(x = goal[1] + cos(angs)*rad.inf*goal[3], y = goal[2] + sin(angs)*rad.inf*goal[3], lwd=2, col='blue')
}
return(c(z = z.int, xy = goal[1:2], radius = rad.inf*goal[3]))
}
#' Circle hough transformation for a single circle
#' @description estimates the circle parameters for a point cloud using the Hough transformation
#' @param raster output from \code{\link{makeRaster}}
#' @param rad lower and upper limits of radii to survey
#' @param pixel_size pixel side length, in meters
#' @param min.val minimum pixel density or frequency that applies for testing
#' @param Plot if TRUE, saves a .png file showing all sample points generated for the input raster
#' @param img.prefix file name for \emph{Plot}
#' @param ... further arguments passed on to \code{\link[graphics]{plot}}
#' @seealso \code{\link{makeRaster}}
#' @return object of class 'list' with 3 compartments: \describe{\item{$centers}{
#' matrix with 4 columns, each row contains the x and y center coordinates,circle radius and number of 'votes' (overlapping peripheral circles)}
#' \item{$images}{list of arrays, each one containing the votes per raster cell for one iterated radius}
#' \item{$circles}{list of xy coordinates of all peripheral circles tested, each compartment contains a matrix with xy point coordinates from circles with same radius (the ones used in 'images')
#' }}
#' @export
hough = function(raster, rad = c(.025,.5), pixel_size = .025, min.val = .1, Plot = F, img.prefix = '', ...){
rads = seq(rad[1],rad[2], pixel_size)
angs = seq(0, 2*pi, pixel_size / rad[2])
nRad = length(rads)
nAng = length(angs)
combs = expand.grid(rads, angs)
x = sin(combs[,2]) * combs[,1]
y = cos(combs[,2]) * combs[,1]
coords = cbind(x,y)
index = rep(1:nRad, times = nAng)
circles = split(as.data.frame(coords), index)
survey = raster[[3]]
survey[survey < min.val] = 0
means.x = ( raster[[1]][-1] + raster[[1]][-length(raster[[1]])] ) / 2
means.y = ( raster[[2]][-1] + raster[[2]][-length(raster[[2]])] ) / 2
where = which(survey > 0, arr.ind = T)
triang = cbind(means.x[where[,1]], means.y[where[,2]])
circs=matrix(ncol=2,nrow=0)
main.base = matrix(ncol = ncol(survey),nrow=0)
base.index = c()
rad.index = c()
centers = matrix(ncol=4,nrow=0)
for(i in 1:nRad){
base = survey
base[base>=0] = 0
for(j in 1:nrow(triang)){
temp = t(apply(circles[[i]], 1, function(u) u + triang[j,] ))
cx = cut(temp[,1], breaks = raster[[1]])
cy = cut(temp[,2], breaks = raster[[2]])
tab.temp = table(cx,cy)
tab.temp[tab.temp > 0] = 1
base = base + tab.temp
circs = rbind(circs, temp)
rad.index = c(rad.index, rep(i, nrow(temp)))
}
if(Plot){
png(filename = paste(img.prefix, i, '.png', sep = ''), width = 10, height = 10, units = 'cm',res = 200)
par(mar=rep(2,4))
plot(circs[rad.index == i,], main= round(rads[i], 2), pch=20, cex=.3, ...)
dev.off()
}
main.base = rbind(main.base, base)
base.index = c(base.index, rep(i, nrow(base)))
if(sum(base) == 0) next
bullseye = which(base == max(base), arr.ind = T)
votes = max(base)
if(nrow(bullseye) == 1){
x.cen = means.x[bullseye[1]]
y.cen = means.y[bullseye[2]]
xy.cen = c(x.cen, y.cen)
radii = rads[i]
append = c(xy.cen, radii, votes)
}else{
x.cen = means.x[bullseye[,1]]
y.cen = means.y[bullseye[,2]]
xy.cen = cbind(x.cen, y.cen)
votes = rep(votes, nrow(xy.cen))
radii = rep(rads[i], nrow(xy.cen))
append = cbind(xy.cen, radii, votes)
}
centers = rbind(centers, append)
split.base = split(main.base, base.index)
split.base = lapply(split.base, function(u) matrix(u, ncol=ncol(main.base), byrow = F))
split.circs = split(circs, rad.index)
split.circs = lapply(split.circs, function(u) matrix(u, ncol=2, byrow=F))
}
#main.base = split(main.base, base.index)
#circs = split(circs, rad.index)
return(list(centers = centers, images = split.base, circles = split.circs))
}
#' Create raster from a point cloud
#' @description extracts a raster (\emph{xy}) containing density or frequency information from a xyz a point cloud
#' @param XYZmat point cloud - \emph{xyz} matrix
#' @param cell.size pixel size
#' @param density if \code{TRUE}, each pixel will display point density values, if \code{FALSE}, frequency values will be used
#' @param image if \code{TRUE}, plots the raster as an image
#' @return object of clas 'list' with 4 compartments: \describe{\item{$x}{cell breaks in x}
#' \item{$y}{cell breaks in y}
#' \item{$z}{matrix representing each individual raster cell with their respective density or frequency values}
#' \item{$classes}{x and y intervals explicitly identified according to the values in the z compartment}}
#' @export
makeRaster = function(XYZmat, cell.size = .01, density = T, image = T){
rgX = range(XYZmat[,1])
rgY = range(XYZmat[,2])
lx = rgX[2] - rgX[1]
ly = rgY[2] - rgY[1]
clx = seq(rgX[1]-(cell.size/2), rgX[2]+cell.size, by=cell.size)
cly = seq(rgY[1]-(cell.size/2), rgY[2]+cell.size, by=cell.size)
cutx = cut(x = XYZmat[,1], breaks = clx)
cuty = cut(x = XYZmat[,2], breaks = cly)
counts = table(cutx, cuty)
densities = counts/max(counts)
if(density){
raster = matrix(densities, length(clx)-1, length(cly)-1)
}else{
raster = matrix(counts, length(clx)-1, length(cly)-1)
}
lst = list(x = clx, y = cly, z = as.matrix(raster), classes = if(density) densities else counts)
if(image) image(lst, col=grey.colors(length(unique(as.vector(raster)))))
return(lst)
}
###Circle fit
#' Least squares circle fit
#' @description Fits a circle to a set of points - adapted from the \code{pracma} package.
#' @param xp x coordinates
#' @param yp y coordinates
#' @param fast if \code{TRUE} skips the optimization step
#' @param c0 if \code{TRUE}, centers x and y to zero
#' @return vector object containing x, y center coordinates, circle radius and sum of squared errors
#' @export
circlefit = function (xp, yp, fast = FALSE, c0=T){
if (!is.vector(xp, mode = "numeric") || !is.vector(yp, mode = "numeric"))
stop("Arguments 'xp' and 'yp' must be numeric vectors.")
if (length(xp) != length(yp))
stop("Vectors 'xp' and 'yp' must be of the same length.")
if(c0){
cen = c(x=mean(xp), y=mean(yp))
xp = xp-cen[1]
yp = yp-cen[2]
}
n <- length(xp)
p <- qr.solve(cbind(xp, yp, 1), matrix(xp^2 + yp^2, ncol = 1))
r <- c(p[1]/2, p[2]/2, sqrt((p[1]^2 + p[2]^2)/4 + p[3]))
cerr <- function(v) sqrt(sum((sqrt((xp - v[1])^2 + (yp -
v[2])^2) - v[3])^2)/n)
if (fast) {
cat("RMS error:", cerr(r), "\n")
}
else {
q <- optim(p, cerr)
#cat("RMS error:", q$value, "\n")
r <- q$par
}
out = unlist(q[1:2])
if(c0) out[1:2] = out[1:2]+cen
return(out)
}
#' RAndom SAmple Consensus circle fit
#' @description returns the best circle parameters using the RANSAC algorithm
#' @param stem.sec stem section, \emph{xyz} matrix
#' @param n number of points to sample on every RANSAC iteration
#' @param p estimated proportion of inliers in the dataset
#' @param P level of confidence desired
#' @return vector object containing x, y center coordinates, circle radius and sum of squared errors
#' @export
RANSAC.circle = function(stem.sec, n=15, p=.8, P=.99){
slc = stem.sec
if(nrow(stem.sec) < n) n = nrow(stem.sec)
N = log(1 - P) / log(1 - p^n)
data = matrix(ncol=4, nrow=0)
for(j in 1:(5*N)){
a = sample(1:nrow(slc), size = n)
b = tryCatch(circlefit(slc[a,1], slc[a,2]),
error = function(con){ return('next') },
warning = function(con) return('next'))
if(b == 'next') next
#if(class(try(circlefit(slc[a,1], slc[a,2]), silent = T)) == "try-error") next
#b = circlefit(slc[a,1], slc[a,2])
data = rbind(data, b)
}
if(nrow(data) == 0){ dt = NULL }else{
c = which(data[,4] == min(data[,4]))
dt = if(length(c) > 1) data[sample(c, size = 1),] else data[c,]
}
return(dt)
}
###Spectral decomposition filter
#' Spectral Decomposition point cloud filter
#' @description Removes points from the provided point cloud whose neighborhoods don't follow the specified criteria
#' @param sec tree section, \emph{xyz} matrix
#' @param k number of closest points in a neighborhood over which spectral decomposition is performed
#' @param flat.min minimum flatness accepted to keep points in the dataset
#' @param ang.tol angle tolerance (in degrees) between \code{sec}'s normal vector and \emph{z}
#' @return filtered tree section
#' @export
SD.prefilt = function(sec, k, flat.min, ang.tol){
if(nrow(sec) < k) k = nrow(sec)
dists = as.matrix(dist(sec))
srr = apply(dists, 2, function(u){ a = sort(u, index.return=T)[[2]] ; b = a[1:k] ; return(b) })
cld = apply(srr, 2, function(u){sec[u,]})
fln = sapply(cld, FL)
angs = sapply(cld, ang.deg)
out = sec[fln > flat.min & (abs(angs-90) < ang.tol | abs(angs-270) < ang.tol),]
return(out)
}
###Rough noise removal
#' Rough noise removal based on 3D spheres
#' @description removes isolated points from a point cloud
#' @param xyz.tree tree point cloud, \emph{xyz} matrix
#' @param ball.rad spheres radii for first cleaning
#' @param np.min minimum number of points per sphere - spheres with less points will be considered noise and thus removed
#' @param sec.filt apply noise filter a second time?
#' @param lball.rad spheres radii for second cleaning (should be larger than ball.rad) - only used if \code{sec.filt == TRUE}
#' @param min.ncov minimum number of points per sphere for the second cleaning - only used if \code{sec.filt == TRUE}
#' @return tree point cloud without rough noise
#' @export
balls = function(xyz.tree, ball.rad = .025, np.min = 2, sec.filt = T, lball.rad = .05, min.ncov = 3){
tree.list = Vsections(xyz.tree, l.int = 3*ball.rad, Plot = F)
#first filtering step
for(i in 1:length(tree.list)){
chk = tree.list[[i]]
xz = chk[,1]
zx = chk[,3]
chk[,1] = zx
chk[,3] = xz
tmp.ls = Vsections(chk, l.int = ball.rad*3, overlap = 1/3, Plot = F)
dists = lapply(tmp.ls, function(u){ as.matrix(dist(u)) })
counts = lapply(dists, function(u) apply(u,1, function(v) length(v[v < ball.rad])) )
chk = do.call(rbind, tmp.ls)
counts = unlist(counts)
chk = chk[counts > np.min,]
chk = unique(chk)
zx = chk[,3]
xz = chk[,1]
chk[,1] = zx
chk[,3] = xz
tree.list[[i]] = chk
}
#first tree output
tree = do.call(rbind,tree.list)
tree.list = Vsections(tree, l.int = 3*lball.rad, Plot=F)
#second filtering step
if(sec.filt){
for(i in 1:length(tree.list)){
chk = tree.list[[i]]
xz = chk[,1]
zx = chk[,3]
chk[,1] = zx
chk[,3] = xz
tmp.ls = Vsections(chk, l.int = lball.rad*3, overlap = 1/3, Plot = F)
dists = lapply(tmp.ls, function(u){ as.matrix(dist(u)) })
counts = lapply(dists, function(u) apply(u,1, function(v) length(v[v < (ball.rad + lball.rad)])) )
chk = do.call(rbind, tmp.ls)
counts = unlist(counts)
chk = chk[counts > min.ncov,]
chk = unique(chk)
zx = chk[,3]
xz = chk[,1]
chk[,1] = zx
chk[,3] = xz
tree.list[[i]] = chk
}
}
#second tree output
tree = do.call(rbind, tree.list)
return(tree)
}
###Voxel space and 3D neighborhoods
#' 3D sample points cloud construction
#' @description creates sample points in the 3D space randomly or systematically distributed
#' @param xyz.tree tree point cloud, \emph{xyz} matrix
#' @param l minimum distance between sample points
#' @param systematic distribute the points systematically as a voxel grid? TRUE or FALSE
#' @param n,iterate only used if \code{systematic == FALSE}. The higher those values are, the "denser" is the resuling sample points point cloud
#' @return 3D point cloud of sample points - \emph{xyz} matrix
#' @export
cube.space = function(xyz.tree, l=.03, systematic = T, n=3 , iterate=1){
#tree cloud processing
rx = range(xyz.tree[,1])
ry = range(xyz.tree[,2])
rz = range(xyz.tree[,3])
intx = seq(rx[1]-l, rx[2]+l, l)
inty = seq(ry[1]-l, ry[2]+l, l)
intz = seq(rz[1]-l, rz[2]+l, l)
if(systematic){
#systematic 3D sample points
xx = (intx[-length(intx)] + intx[-1]) / 2
yy = (inty[-length(inty)] + inty[-1]) / 2
zz = (intz[-length(intz)] + intz[-1]) / 2
dummy = cbind(NA,NA,zz)
unsplit= xyz.tree#do.call(rbind,split)
colnames(dummy) = colnames(unsplit)
comb = rbind(unsplit,dummy)
split2 = Vsections(comb, l.int = 10*l, Plot = F)
z.smps = lapply(split2, function(u) u[is.na(u[,1]),3])
zobs = sapply(z.smps, length)
split2 = split2[zobs > 0]
z.smps = z.smps[zobs > 0]
smps = lapply(1:length(z.smps), function(u){
a = split2[[u]]
a = a[!is.na(a[,1]),]
if(nrow(a) == 0) smps = NULL else{
cax = cut(a[,1], breaks = intx)
cay = cut(a[,2], breaks = inty)
caz = cut(a[,3], breaks = intz)
cl.a = cbind(cax,cay,caz)
cl.a = unique(cl.a)
rx = range(a[,1])
ry = range(a[,2])
sx = xx[xx >= rx[1] & xx <= rx[2]]
sy = yy[yy >= ry[1] & yy <= ry[2]]
sz = z.smps[[u]]
xy = expand.grid(sx,sy)
z = rep(sz, each=nrow(xy))
smps = cbind(xy,z)
clsx = cut(smps[,1], breaks = intx)
clsy = cut(smps[,2], breaks = inty)
clsz = cut(smps[,3], breaks = intz)
cl.smps = cbind(clsx,clsy,clsz)
vec.a = apply(cl.a, 1, paste, collapse=':')
vec.smps = apply(cl.smps, 1, paste, collapse=':')
log = vec.smps %in% vec.a
smps = smps[log,]
}
return(smps)
})
samples = do.call(rbind,smps)
}else{
#random 3D sample points
rd.gen = function(u, n){
x = runif(n, intx[u[1]], intx[u[1]+1])
y = runif(n, inty[u[2]], inty[u[2]+1])
z = runif(n, intz[u[3]], intz[u[3]+1])
out = c(x,y,z)
return(out)
}
d.rm = function(chk){
dst = as.matrix(dist(chk))
dst[upper.tri(dst, diag = T)] = 100
a = all(dst >= l)
while(a == F){
wch = which(dst < l, arr.ind = T)
wch = unique(wch[,2])
wch = wch[1:ceiling(length(wch)/2)]
chk = chk[-wch,]
dst = as.matrix(dist(chk))
dst[upper.tri(dst, diag = T)] = 100
a = all(dst >= l)
}
return(chk)
}
Ssamples = matrix(ncol=3,nrow=0)
for(i in 1:iterate){
spp = apply(u.ind, 1, rd.gen, n=n)
nr =nrow(spp)/3
sppx = c(spp[1:nr,])
sppy = c(spp[(nr+1):(2*nr),])
sppz = c(spp[(2*nr+1):(3*nr),])
spp = cbind(sppx,sppy,sppz)
spp.list = Vsections(spp, l.int = l*3, overlap = 1/3, Plot = F)
spp.list = lapply(spp.list, d.rm)
samples = do.call(rbind,spp.list)
samples = as.matrix(unique(samples))
Ssamples = rbind(Ssamples,samples)
}
tr.sp = apply(Ssamples, 1, function(u){ x = u[1] + runif(1,l/2,l)
y = u[2] + runif(1,l/2,l)
z = u[3] + l
return(c(x,y,z)) })
tr.sp2 = apply(Ssamples, 1, function(u){ x = u[1] - runif(1,l/2,l)
y = u[2] - runif(1,l/2,l)
z = u[3] - l
return(c(x,y,z)) })
Ssamples = rbind(Ssamples, t(tr.sp), t(tr.sp2))
S.lst = Vsections(Ssamples, l.int = 3*l, overlap = 1/3, Plot = F)
S.lst = lapply(S.lst, d.rm)
samples = do.call(rbind, S.lst)
samples = as.matrix(unique(samples))
}
return(samples)
}
#' Cover sets neghborhoods assignment
#' @description Defines cover set spherical neighborhoods for a 3D point cloud based on euclidian distances
#' @param xyz.tree tree point cloud, \emph{xyz} matrix
#' @param samples3d output point cloud from \code{\link{cube.space}} built for \code{xyz.tree}
#' @param d radius of spherical neighborhoods
#' @param neighborhood order of neighborhoods to include - 1 means only the direct neighbours, 2 includes the neighbours of first neighbours and so on
#' @return list object in which every compartment contains a cover set neighborhood
neighbours = function(xyz.tree, samples3d, d=.03, neighborhood=2){
requireNamespace('foreach', quietly = T)
xyz.tree = xyz.tree[order(xyz.tree[,3],xyz.tree[,2],xyz.tree[,1]),]
samples3d = samples3d[order(samples3d[,3],samples3d[,2],samples3d[,1]),]