├── .Rbuildignore ├── .gitignore ├── DemoWorkflow ├── Demo_Data_1ha_Traunstein.rda └── Demo_Workflow_MeanShiftR.R ├── NAMESPACE ├── man ├── hello.Rd ├── rcpp_hello.Rd ├── split_BufferedPointCloud.Rd ├── calc_SpatialIndex.Rd ├── MeanShift_Classical.Rd ├── match_CrownsStems.Rd ├── MeanShift_Voxels.Rd ├── make_CrownPolygons.Rd ├── filter_OverlappingCrowns.Rd ├── filter_OverlappingCrowns2.Rd ├── filter_StemReturns.Rd ├── parallel_MeanShift.Rd └── apply_MeanShift.Rd ├── MeanShiftR.Rproj ├── DESCRIPTION ├── src ├── LittleFunctionsCollection.h ├── RcppExports.cpp ├── LittleFunctionsCollection.cpp ├── MeanShift_Classical.cpp └── MeanShift_Voxels.cpp ├── R ├── calc_SpatialIndex_function.R ├── RcppExports.R ├── filter_StemReturns.R ├── filter_OverlappingCrowns_function.R ├── filter_OverlappingCrowns2_function.R ├── match_CrownsStems_function.R ├── parallel_MeanShift_function.R ├── apply_MeanShift_function.R ├── split_BufferedPointCloud_function.R └── make_CrownPolygons_function.R ├── LICENSE └── COPYING /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^.*\.Rproj$ 2 | ^\.Rproj\.user$ 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | .RData 4 | .Ruserdata 5 | src/*.o 6 | src/*.so 7 | src/*.dll 8 | -------------------------------------------------------------------------------- /DemoWorkflow/Demo_Data_1ha_Traunstein.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikoknapp/MeanShiftR/HEAD/DemoWorkflow/Demo_Data_1ha_Traunstein.rda -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | export(MeanShift_Classical) 4 | export(MeanShift_Voxels) 5 | 6 | useDynLib(MeanShiftR) 7 | exportPattern("^[[:alpha:]]+") 8 | -------------------------------------------------------------------------------- /man/hello.Rd: -------------------------------------------------------------------------------- 1 | \name{hello} 2 | \alias{hello} 3 | \title{Hello, World!} 4 | \usage{ 5 | hello() 6 | } 7 | \description{ 8 | Prints 'Hello, world!'. 9 | } 10 | \examples{ 11 | hello() 12 | } 13 | -------------------------------------------------------------------------------- /man/rcpp_hello.Rd: -------------------------------------------------------------------------------- 1 | \name{rcpp_hello} 2 | \alias{rcpp_hello} 3 | \title{Hello, Rcpp!} 4 | \usage{ 5 | rcpp_hello() 6 | } 7 | \description{ 8 | Returns an \R \code{list} containing the character vector 9 | \code{c("foo", "bar")} and the numeric vector \code{c(0, 1)}. 10 | } 11 | \examples{ 12 | rcpp_hello() 13 | } 14 | -------------------------------------------------------------------------------- /MeanShiftR.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | 15 | AutoAppendNewline: Yes 16 | StripTrailingWhitespace: Yes 17 | 18 | BuildType: Package 19 | PackageUseDevtools: Yes 20 | PackageInstallArgs: --no-multiarch --with-keep.source 21 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: MeanShiftR 2 | Type: Package 3 | Title: Tree delineation from lidar using mean shift clustering 4 | Version: 0.1.1 5 | Author: Nikolai Knapp 6 | Maintainer: Nikolai Knapp 7 | Description: The package allows individual tree crown delineation (ITCD) from 8 | airborne laser scanning point clouds (lidar) using the Adaptive Mean Shift 9 | 3D (AMS3D) clustering algorithm described by Ferraz et al. (2016). It 10 | further contains functions for parallelization of the clustering and post- 11 | processing such as fitting polygons around tree crowns and matching 12 | detected crowns with stem positions on the ground. 13 | Reference: Ferraz, A., Saatchi, S., Mallet, C. and Meyer, V. (2016). 14 | Lidar detection of individual tree size in tropical forests. 15 | Remote Sensing of Environment. [Online]. 183. p.pp. 318-333. 16 | License: GPL-3 17 | LazyData: TRUE 18 | Depends: 19 | data.table 20 | Imports: 21 | cluster, 22 | pbapply, 23 | plyr, 24 | Rcpp (>= 0.12.9), 25 | rgeos, 26 | sp, 27 | tripack, 28 | raster 29 | LinkingTo: Rcpp 30 | RoxygenNote: 7.1.0 31 | -------------------------------------------------------------------------------- /man/split_BufferedPointCloud.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/split_BufferedPointCloud_function.R 3 | \name{split_BufferedPointCloud} 4 | \alias{split_BufferedPointCloud} 5 | \title{Split point cloud into smaller point clouds with buffer area around} 6 | \usage{ 7 | split_BufferedPointCloud(pc.dt, plot.width, buffer.width) 8 | } 9 | \arguments{ 10 | \item{pc.dt}{Point cloud in data.table format containing columns X, Y and Z} 11 | 12 | \item{plot.width}{Width of the core area in meters} 13 | 14 | \item{buffer.width}{Width of the buffer around the core area in meters} 15 | } 16 | \value{ 17 | List of sub point clouds and buffer and core points labeled in boolean column "Buffer" 18 | } 19 | \description{ 20 | The function splits one large point cloud into several smaller point clouds. 21 | It allows to specify a buffer width around the core area where points are included. 22 | } 23 | \author{ 24 | Nikolai Knapp, nikolai.knapp@ufz.de 25 | } 26 | \keyword{area} 27 | \keyword{buffer} 28 | \keyword{cloud} 29 | \keyword{parallel} 30 | \keyword{plot} 31 | \keyword{point} 32 | \keyword{split} 33 | \keyword{subset} 34 | -------------------------------------------------------------------------------- /man/calc_SpatialIndex.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calc_SpatialIndex_function.R 3 | \name{calc_SpatialIndex} 4 | \alias{calc_SpatialIndex} 5 | \title{Calculate spatial indices for points in 2D space} 6 | \usage{ 7 | calc_SpatialIndex( 8 | xcor, 9 | ycor, 10 | res = 1, 11 | minx = NA, 12 | miny = NA, 13 | maxx = NA, 14 | maxy = NA, 15 | exclude.maxx = T 16 | ) 17 | } 18 | \arguments{ 19 | \item{xcor}{X-coordinate of the point} 20 | 21 | \item{ycor}{Y-coordinate of the point} 22 | 23 | \item{res}{side length of one spatial subunit} 24 | 25 | \item{minx}{minimum X-coordinate} 26 | 27 | \item{miny}{minimum Y-coordinate} 28 | 29 | \item{maxx}{maximum X-coordinate} 30 | 31 | \item{maxy}{maximum Y-coordinate} 32 | 33 | \item{exclude.maxx}{boolean to set whether the given maxx should be excluded or included in the indexing} 34 | } 35 | \value{ 36 | spatial index for the input point 37 | } 38 | \description{ 39 | Function that returns spatial indices (plot numbers) for given coordinate pairs. 40 | E.g. for hectares res = 100 m 41 | } 42 | \author{ 43 | Nikolai Knapp, nikolai.knapp@ufz.de 44 | } 45 | \keyword{index} 46 | \keyword{number} 47 | \keyword{plot} 48 | \keyword{spatial} 49 | -------------------------------------------------------------------------------- /man/MeanShift_Classical.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/RcppExports.R 3 | \name{MeanShift_Classical} 4 | \alias{MeanShift_Classical} 5 | \title{Mean shift clustering} 6 | \usage{ 7 | MeanShift_Classical( 8 | pc, 9 | H2CW_fac, 10 | H2CL_fac, 11 | UniformKernel = FALSE, 12 | MaxIter = 20L 13 | ) 14 | } 15 | \arguments{ 16 | \item{pc}{Point cloud has to be in matrix format with 3-columns representing X, Y and Z and each row representing one point} 17 | 18 | \item{H2CW_fac}{Factor for the ratio of height to crown width. Determines kernel diameter based on its height above ground.} 19 | 20 | \item{H2CL_fac}{Factor for the ratio of height to crown length. Determines kernel height based on its height above ground.} 21 | 22 | \item{UniformKernel}{Boolean to enable the application of a simple uniform kernel without distance weighting (Default False)} 23 | 24 | \item{MaxIter}{Maximum number of iterations, i.e. steps that the kernel can move for each point. If centroid is not found after all iteration, the last position is assigned as centroid and the processing jumps to the next point} 25 | } 26 | \value{ 27 | data.frame with X, Y and Z coordinates of each point in the point cloud and X, Y and Z coordinates of the centroid to which the point belongs 28 | } 29 | \description{ 30 | Adaptive mean shift clustering to delineate tree crowns from lidar point clouds 31 | } 32 | \details{ 33 | Mean shift clustering 34 | } 35 | -------------------------------------------------------------------------------- /src/LittleFunctionsCollection.h: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018 Dr. Nikolai Knapp, UFZ 2 | // 3 | // This file is part of the MeanShiftR R package. 4 | // 5 | // The MeanShiftR R package is free software: you can redistribute 6 | // it and/or modify it under the terms of the GNU General Public License 7 | // as published by the Free Software Foundation, either version 3 of the 8 | // License, or (at your option) any later version. 9 | // 10 | // MeanShiftR is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with MeanShiftR If not, see . 17 | 18 | #include 19 | using namespace Rcpp; 20 | 21 | 22 | // Declarations of all the little functions used by the main functions 23 | 24 | bool InCylinder(double PointX, double PointY, double PointZ, double Radius, double Height, double CtrX, double CtrY, double CtrZ); 25 | double VerticalDistance(double Height, double CtrZ, double PointZ); 26 | double VerticalMask(double Height, double CtrZ, double PointZ); 27 | double EpanechnikovFunction(double Height, double CtrZ, double PointZ); 28 | double GaussFunction(double Width, double CtrX, double CtrY, double PointX, double PointY); 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /man/match_CrownsStems.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/match_CrownsStems_function.R 3 | \name{match_CrownsStems} 4 | \alias{match_CrownsStems} 5 | \title{Match crown projection polygons with tree stem positions} 6 | \usage{ 7 | match_CrownsStems(crowns.spdf, stems.spdf, DBH.min = 0.05) 8 | } 9 | \arguments{ 10 | \item{crowns.spdf}{SpatialPolygonsDataFrame of tree crown projection areas} 11 | 12 | \item{stems.spdf}{SpatialPointsDataFrame of tree stem foot positions (required columns: X, Y, DBH, Species, TreeID)} 13 | 14 | \item{DBH.min}{Minimum stem diameter to be considered} 15 | } 16 | \value{ 17 | SpatialPolygonsDataFrame of tree crown projection areas with additional columns containing the attributes of the assigned stem for each crown 18 | } 19 | \description{ 20 | The function links remote sensing derived crown projection polygons with inventory derived tree stems. 21 | The algorithm sorts all polygons by decreasing area size. Then, starting with the largest crown it checks all 22 | stem positions that fall inside the crown projection area and selects the stem with the largest diameter 23 | and assigns it to the crown. The stem is removed from the set of available stems and the same procedure 24 | is conducted for the next smaller crown and further on until the smallest crown. 25 | } 26 | \author{ 27 | Nikolai Knapp, nikolai.knapp@ufz.de 28 | } 29 | \keyword{DBH} 30 | \keyword{area} 31 | \keyword{crown} 32 | \keyword{diameter} 33 | \keyword{foot} 34 | \keyword{ground} 35 | \keyword{inventory} 36 | \keyword{link} 37 | \keyword{match} 38 | \keyword{point} 39 | \keyword{polygon} 40 | \keyword{position} 41 | \keyword{projection} 42 | \keyword{stem} 43 | \keyword{tree} 44 | \keyword{truth} 45 | -------------------------------------------------------------------------------- /man/MeanShift_Voxels.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/RcppExports.R 3 | \name{MeanShift_Voxels} 4 | \alias{MeanShift_Voxels} 5 | \title{Mean shift clustering using a discrete voxel space} 6 | \usage{ 7 | MeanShift_Voxels( 8 | pc, 9 | H2CW_fac, 10 | H2CL_fac, 11 | UniformKernel = FALSE, 12 | MaxIter = 20L, 13 | maxx = 100L, 14 | maxy = 100L, 15 | maxz = 60L 16 | ) 17 | } 18 | \arguments{ 19 | \item{pc}{Point cloud has to be in matrix format with 3-columns representing X, Y and Z and each row representing one point} 20 | 21 | \item{H2CW_fac}{Factor for the ratio of height to crown width. Determines kernel diameter based on its height above ground.} 22 | 23 | \item{H2CL_fac}{Factor for the ratio of height to crown length. Determines kernel height based on its height above ground.} 24 | 25 | \item{UniformKernel}{Boolean to enable the application of a simple uniform kernel without distance weighting (Default False)} 26 | 27 | \item{MaxIter}{Maximum number of iterations, i.e. steps that the kernel can move for each point. If centroid is not found after all iteration, the last position is assigned as centroid and the processing jumps to the next point} 28 | 29 | \item{maxx}{Maximum X-coordinate} 30 | 31 | \item{maxy}{Maximum Y-coordinate} 32 | 33 | \item{maxz}{Maximum Z-coordinate} 34 | } 35 | \value{ 36 | data.frame with X, Y and Z coordinates of each point in the point cloud and X, Y and Z coordinates of the centroid to which the point belongs 37 | } 38 | \description{ 39 | Adaptive mean shift clustering to delineate tree crowns from lidar point clouds. This is a version using 1-m³ voxels instead of exact point coordinates, to speed up processing. 40 | } 41 | \details{ 42 | Mean shift clustering using a discrete voxel space 43 | } 44 | -------------------------------------------------------------------------------- /man/make_CrownPolygons.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/make_CrownPolygons_function.R 3 | \name{make_CrownPolygons} 4 | \alias{make_CrownPolygons} 5 | \title{Fit polygon hulls around tree crowns in a clustered point cloud to derive crown projection areas} 6 | \usage{ 7 | make_CrownPolygons( 8 | pc.dt, 9 | type = "convexhull", 10 | N.min = 20, 11 | Ext.min = 2, 12 | Ext.max = 50, 13 | proj4string = CRS(as.character(NA)) 14 | ) 15 | } 16 | \arguments{ 17 | \item{pc.dt}{Point cloud in data.table format containing columns X, Y, Z and ID} 18 | 19 | \item{type}{Shape of the desired polygons ("convexhull", "ellipse" or "circle")} 20 | 21 | \item{N.min}{Minimum number of points in a cluster to be considered as a tree crown} 22 | 23 | \item{Ext.min}{Minimum horizontal extent (in meters, in X- and Y-direction) of a cluster to be considered as a tree crown} 24 | 25 | \item{Ext.max}{Maximum horizontal extent (in meters, in X- and Y-direction) of a cluster to be considered as a tree crown} 26 | 27 | \item{proj4string}{Projection string of class CRS-class} 28 | } 29 | \value{ 30 | SpatialPolygonsDataFrame with each feature representing the crown projection area of one tree and columns containing various geometric attributes 31 | } 32 | \description{ 33 | The function creates crown projection area polygons from a clustered point cloud of a forest stand. 34 | The input point cloud needs to have a column containing tree ID / cluster ID of each point. 35 | There are different options for the shape of the polygons. 36 | } 37 | \author{ 38 | Nikolai Knapp, nikolai.knapp@ufz.de 39 | } 40 | \keyword{area} 41 | \keyword{circle} 42 | \keyword{cloud} 43 | \keyword{cluster} 44 | \keyword{convex} 45 | \keyword{crown} 46 | \keyword{ellipse} 47 | \keyword{hull} 48 | \keyword{perimeter} 49 | \keyword{point} 50 | \keyword{polygons} 51 | \keyword{projection} 52 | \keyword{tree} 53 | -------------------------------------------------------------------------------- /man/filter_OverlappingCrowns.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/filter_OverlappingCrowns_function.R 3 | \name{filter_OverlappingCrowns} 4 | \alias{filter_OverlappingCrowns} 5 | \title{Remove crown area polygons based on spatial overlap with other polygons} 6 | \usage{ 7 | filter_OverlappingCrowns(crowns, overlap.threshold) 8 | } 9 | \arguments{ 10 | \item{crowns}{SpatialPolygonsDataFrame of crown projection areas, derived from make_CrownPolygons function} 11 | 12 | \item{overlap.threshold}{Value between 0 and 1 specifying the relative overlap of a pair of crown projection areas (intersection area of two crowns divided by area of a single crown). If the relative overlap is for both crowns larger than this threshold, the crown polygon with the lower tree height value is removed.} 13 | } 14 | \value{ 15 | SpatialPolygonsDataFrame with each feature representing the crown projection area of one tree and columns containing various geometric attributes 16 | } 17 | \description{ 18 | The AMS3D algorithm can lead to clustering artefacts such that a single tree crown may be 19 | assigned to more than one cluster ID and the derived enclosing crown polygons may show very 20 | high spatial overlap. This function enables cleaning of the crown polygon dataset by removing 21 | redundant polygons which most likely represent just one single tree. Of several 22 | overlapping polygons, the polygon with the largest tree height value is kept, while the other 23 | polygons are removed. 24 | The algorithm involves pairwise comparisons of all polygons which are handed over to the 25 | function. Hence, it is recommended to apply it on small tiles (e.g., 1 ha), as processing 26 | time may become very slow for large areas. 27 | } 28 | \author{ 29 | Nikolai Knapp, nikolai.knapp@ufz.de 30 | } 31 | \keyword{area} 32 | \keyword{artefact} 33 | \keyword{clean} 34 | \keyword{cluster} 35 | \keyword{crown} 36 | \keyword{discard} 37 | \keyword{double} 38 | \keyword{drop} 39 | \keyword{error} 40 | \keyword{filter} 41 | \keyword{overlap} 42 | \keyword{polygon} 43 | \keyword{projection} 44 | \keyword{remove} 45 | \keyword{tree} 46 | -------------------------------------------------------------------------------- /man/filter_OverlappingCrowns2.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/filter_OverlappingCrowns2_function.R 3 | \name{filter_OverlappingCrowns2} 4 | \alias{filter_OverlappingCrowns2} 5 | \title{Remove crown area polygons based on spatial overlap with other polygons} 6 | \usage{ 7 | filter_OverlappingCrowns2(crowns, overlap.threshold = 0.9) 8 | } 9 | \arguments{ 10 | \item{crowns}{SpatialPolygonsDataFrame of crown projection areas, derived from make_CrownPolygons function} 11 | 12 | \item{overlap.threshold}{Value between 0 and 1 specifying the relative overlap of a pair of crown projection areas (intersection area of two crowns divided by area of a single crown). If the relative overlap is for both crowns larger than this threshold, the crown polygon with the lower tree height value is removed.} 13 | } 14 | \value{ 15 | SpatialPolygonsDataFrame with each feature representing the crown projection area of one tree and columns containing various geometric attributes 16 | } 17 | \description{ 18 | The AMS3D algorithm can lead to clustering artefacts such that a single tree crown may be 19 | assigned to more than one cluster ID and the derived enclosing crown polygons may show very 20 | high spatial overlap. This function enables cleaning of the crown polygon dataset by removing 21 | redundant polygons which most likely represent just one single tree. Of several 22 | overlapping polygons, the polygon with the largest tree height value is kept, while the other 23 | polygons are removed. 24 | The algorithm involves pairwise comparisons of all polygons which are handed over to the 25 | function. Hence, it is recommended to apply it on small tiles (e.g., 1 ha), as processing 26 | time may become very slow for large areas. 27 | } 28 | \author{ 29 | Nikolai Knapp, nikolai.knapp@ufz.de 30 | } 31 | \keyword{area} 32 | \keyword{artefact} 33 | \keyword{clean} 34 | \keyword{cluster} 35 | \keyword{crown} 36 | \keyword{discard} 37 | \keyword{double} 38 | \keyword{drop} 39 | \keyword{error} 40 | \keyword{filter} 41 | \keyword{overlap} 42 | \keyword{polygon} 43 | \keyword{projection} 44 | \keyword{remove} 45 | \keyword{tree} 46 | -------------------------------------------------------------------------------- /man/filter_StemReturns.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/filter_StemReturns.R 3 | \name{filter_StemReturns} 4 | \alias{filter_StemReturns} 5 | \title{Remove low outlier returns, which originate most probably from tree stems not crowns} 6 | \usage{ 7 | filter_StemReturns(pc.dt, H.quantile = 0.1, filter.factor = 0.9, rm.class = NA) 8 | } 9 | \arguments{ 10 | \item{pc.dt}{Point cloud in data.table format containing columns X, Y, Z and ID} 11 | 12 | \item{H.quantile}{Lower end height quantile on which filter factor is applied} 13 | 14 | \item{filter.factor}{which multiplied with the H.quantile height defines the threshold below which a return will be classified as stem.} 15 | 16 | \item{rm.class}{Switch for automatically removing returns belonging to classes. Should be set to "Stem" to remove stem returns, "Crown" to remove crown returns or NA to keep all returns.} 17 | } 18 | \value{ 19 | SpatialPolygonsDataFrame with each feature representing the crown projection area of one tree and columns containing various geometric attributes 20 | } 21 | \description{ 22 | The AMS3D algorithm can lead to clustering artefacts such that a single tree crown may be 23 | assigned to more than one cluster ID and the derived enclosing crown polygons may show very 24 | high spatial overlap. This function enables cleaning of the crown polygon dataset by removing 25 | redundant polygons which most likely represent just one single tree. Of several 26 | overlapping polygons, the polygon with the largest tree height value is kept, while the other 27 | polygons are removed. 28 | The algorithm involves pairwise comparisons of all polygons which are handed over to the 29 | function. Hence, it is recommended to apply it on small tiles (e.g., 1 ha), as processing 30 | time may become very slow for large areas. 31 | } 32 | \author{ 33 | Nikolai Knapp, nikolai.knapp@ufz.de 34 | } 35 | \keyword{area} 36 | \keyword{artefact} 37 | \keyword{clean} 38 | \keyword{cluster} 39 | \keyword{crown} 40 | \keyword{discard} 41 | \keyword{double} 42 | \keyword{drop} 43 | \keyword{error} 44 | \keyword{filter} 45 | \keyword{overlap} 46 | \keyword{polygon} 47 | \keyword{projection} 48 | \keyword{remove} 49 | \keyword{tree} 50 | -------------------------------------------------------------------------------- /man/parallel_MeanShift.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/parallel_MeanShift_function.R 3 | \name{parallel_MeanShift} 4 | \alias{parallel_MeanShift} 5 | \title{Parallel application of mean shift clustering for individual tree crown delineation} 6 | \usage{ 7 | parallel_MeanShift( 8 | pc.list, 9 | lib.path = NA, 10 | frac.cores = 0.5, 11 | version = "classic", 12 | H2CW = 0.3, 13 | H2CL = 0.4, 14 | max.iter = 20, 15 | buffer.width = 10, 16 | minz = 2, 17 | ctr.ac = 2 18 | ) 19 | } 20 | \arguments{ 21 | \item{pc.list}{List of point clouds in data.table format containing columns X, Y and Z (produced by split_BufferedPointCloud function)} 22 | 23 | \item{lib.path}{String specifying the path from where to load the R packages. Should be set to .libPaths()[1].} 24 | 25 | \item{frac.cores}{Fraction of available cores to use for parallelization} 26 | 27 | \item{version}{of the AMS3D algorithm. Can be set to "classic" (slow but precise also with small trees) or "voxel" (fast but based on rounded coordinates of 1-m precision)} 28 | 29 | \item{H2CW}{Factor for the ratio of height to crown width. Determines kernel diameter based on its height above ground.} 30 | 31 | \item{H2CL}{Factor for the ratio of height to crown length. Determines kernel height based on its height above ground.} 32 | 33 | \item{max.iter}{Maximum number of iterations, i.e. steps that the kernel can move for each point. If centroid is not found after all iteration, the last position is assigned as centroid and the processing jumps to the next point} 34 | 35 | \item{buffer.width}{Width of the buffer around the core area in meters} 36 | 37 | \item{minz}{Minimum height above ground for a point to be considered in the analysis. Has to be > 0.} 38 | 39 | \item{ctr.ac}{Centroid accuracy. Specifies the rounding accuracy for centroid positions. After rounding all centroids with the same coordinates are considered to belong to one tree crown.} 40 | } 41 | \value{ 42 | data.table of point cloud with points labelled with tree IDs 43 | } 44 | \description{ 45 | The function provides the frame work to apply the adaptive mean shift 3D (AMS3D) algorithm on several 46 | sub point clouds of a large investigation area in parallel. It requires a list of sub point clouds as 47 | input and returns one large clustered point cloud as output. The input should have buffer zones around 48 | the focal areas. The buffer width should correspond to at least the maximal possible tree crown radius. 49 | } 50 | \author{ 51 | Nikolai Knapp, nikolai.knapp@ufz.de 52 | } 53 | \keyword{area} 54 | \keyword{buffer} 55 | \keyword{cloud} 56 | \keyword{parallel} 57 | \keyword{plot} 58 | \keyword{point} 59 | \keyword{split} 60 | \keyword{subset} 61 | -------------------------------------------------------------------------------- /src/RcppExports.cpp: -------------------------------------------------------------------------------- 1 | // Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | #include 5 | 6 | using namespace Rcpp; 7 | 8 | // MeanShift_Classical 9 | DataFrame MeanShift_Classical(NumericMatrix pc, double H2CW_fac, double H2CL_fac, bool UniformKernel, int MaxIter); 10 | RcppExport SEXP _MeanShiftR_MeanShift_Classical(SEXP pcSEXP, SEXP H2CW_facSEXP, SEXP H2CL_facSEXP, SEXP UniformKernelSEXP, SEXP MaxIterSEXP) { 11 | BEGIN_RCPP 12 | Rcpp::RObject rcpp_result_gen; 13 | Rcpp::RNGScope rcpp_rngScope_gen; 14 | Rcpp::traits::input_parameter< NumericMatrix >::type pc(pcSEXP); 15 | Rcpp::traits::input_parameter< double >::type H2CW_fac(H2CW_facSEXP); 16 | Rcpp::traits::input_parameter< double >::type H2CL_fac(H2CL_facSEXP); 17 | Rcpp::traits::input_parameter< bool >::type UniformKernel(UniformKernelSEXP); 18 | Rcpp::traits::input_parameter< int >::type MaxIter(MaxIterSEXP); 19 | rcpp_result_gen = Rcpp::wrap(MeanShift_Classical(pc, H2CW_fac, H2CL_fac, UniformKernel, MaxIter)); 20 | return rcpp_result_gen; 21 | END_RCPP 22 | } 23 | // MeanShift_Voxels 24 | DataFrame MeanShift_Voxels(NumericMatrix pc, double H2CW_fac, double H2CL_fac, bool UniformKernel, int MaxIter, int maxx, int maxy, int maxz); 25 | RcppExport SEXP _MeanShiftR_MeanShift_Voxels(SEXP pcSEXP, SEXP H2CW_facSEXP, SEXP H2CL_facSEXP, SEXP UniformKernelSEXP, SEXP MaxIterSEXP, SEXP maxxSEXP, SEXP maxySEXP, SEXP maxzSEXP) { 26 | BEGIN_RCPP 27 | Rcpp::RObject rcpp_result_gen; 28 | Rcpp::RNGScope rcpp_rngScope_gen; 29 | Rcpp::traits::input_parameter< NumericMatrix >::type pc(pcSEXP); 30 | Rcpp::traits::input_parameter< double >::type H2CW_fac(H2CW_facSEXP); 31 | Rcpp::traits::input_parameter< double >::type H2CL_fac(H2CL_facSEXP); 32 | Rcpp::traits::input_parameter< bool >::type UniformKernel(UniformKernelSEXP); 33 | Rcpp::traits::input_parameter< int >::type MaxIter(MaxIterSEXP); 34 | Rcpp::traits::input_parameter< int >::type maxx(maxxSEXP); 35 | Rcpp::traits::input_parameter< int >::type maxy(maxySEXP); 36 | Rcpp::traits::input_parameter< int >::type maxz(maxzSEXP); 37 | rcpp_result_gen = Rcpp::wrap(MeanShift_Voxels(pc, H2CW_fac, H2CL_fac, UniformKernel, MaxIter, maxx, maxy, maxz)); 38 | return rcpp_result_gen; 39 | END_RCPP 40 | } 41 | 42 | static const R_CallMethodDef CallEntries[] = { 43 | {"_MeanShiftR_MeanShift_Classical", (DL_FUNC) &_MeanShiftR_MeanShift_Classical, 5}, 44 | {"_MeanShiftR_MeanShift_Voxels", (DL_FUNC) &_MeanShiftR_MeanShift_Voxels, 8}, 45 | {NULL, NULL, 0} 46 | }; 47 | 48 | RcppExport void R_init_MeanShiftR(DllInfo *dll) { 49 | R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); 50 | R_useDynamicSymbols(dll, FALSE); 51 | } 52 | -------------------------------------------------------------------------------- /R/calc_SpatialIndex_function.R: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2018 Dr. Nikolai Knapp, UFZ 2 | # 3 | # This file is part of the MeanShiftR R package. 4 | # 5 | # The MeanShiftR R package is free software: you can redistribute 6 | # it and/or modify it under the terms of the GNU General Public License 7 | # as published by the Free Software Foundation, either version 3 of the 8 | # License, or (at your option) any later version. 9 | # 10 | # MeanShiftR is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with MeanShiftR If not, see . 17 | 18 | 19 | 20 | #' Calculate spatial indices for points in 2D space 21 | #' 22 | #' Function that returns spatial indices (plot numbers) for given coordinate pairs. 23 | #' E.g. for hectares res = 100 m 24 | #' @param xcor X-coordinate of the point 25 | #' @param ycor Y-coordinate of the point 26 | #' @param res side length of one spatial subunit 27 | #' @param minx minimum X-coordinate 28 | #' @param miny minimum Y-coordinate 29 | #' @param maxx maximum X-coordinate 30 | #' @param maxy maximum Y-coordinate 31 | #' @param exclude.maxx boolean to set whether the given maxx should be excluded or included in the indexing 32 | #' @return spatial index for the input point 33 | #' @keywords spatial index plot number 34 | #' @author Nikolai Knapp, nikolai.knapp@ufz.de 35 | 36 | calc_SpatialIndex <- function(xcor, ycor, res=1, minx=NA, miny=NA, maxx=NA, maxy=NA, exclude.maxx=T){ 37 | # If no coordinate limits are given use the extrema of the data as limits 38 | if(is.na(minx)){ 39 | minx <- floor(min(xcor, na.rm=T)) 40 | } 41 | if(is.na(miny)){ 42 | miny <- floor(min(ycor, na.rm=T)) 43 | } 44 | if(is.na(maxx)){ 45 | maxx <- max(xcor, na.rm=T) 46 | # Convert absolute to relative maxx 47 | rel.maxx <- maxx - minx 48 | } else { 49 | # Convert absolute to relative maxx 50 | rel.maxx <- maxx - minx 51 | if(exclude.maxx==T){ 52 | # Reduce maxx by a tiny number to exclude the upper limit 53 | rel.maxx <- rel.maxx - 1e-10 54 | } 55 | } 56 | if(is.na(maxy)){ 57 | maxy <- max(ycor, na.rm=T) 58 | } 59 | # Convert absolute to relative coordinates 60 | rel.xcor <- xcor - minx 61 | rel.ycor <- ycor - miny 62 | # Count number of cells in X-direction 63 | # %/%: integer division operator 64 | nx <- rel.maxx %/% res + 1 65 | # For each coordinate calculate the cell number in X- and Y-direction 66 | myx <- rel.xcor %/% res + 1 67 | myy <- rel.ycor %/% res + 1 68 | # Calculate the total index 69 | index <- myx + nx * (myy - 1) 70 | # Set index values outside the coordinate limits to NA 71 | index[xcor < minx] <- NA 72 | index[xcor > maxx] <- NA 73 | index[ycor < miny] <- NA 74 | index[ycor > maxy] <- NA 75 | # Return the result 76 | return(index) 77 | } 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /R/RcppExports.R: -------------------------------------------------------------------------------- 1 | # Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | #' Mean shift clustering 5 | #' 6 | #' @title Mean shift clustering 7 | #' @description 8 | #' Adaptive mean shift clustering to delineate tree crowns from lidar point clouds 9 | #' @param pc Point cloud has to be in matrix format with 3-columns representing X, Y and Z and each row representing one point 10 | #' @param H2CW_fac Factor for the ratio of height to crown width. Determines kernel diameter based on its height above ground. 11 | #' @param H2CL_fac Factor for the ratio of height to crown length. Determines kernel height based on its height above ground. 12 | #' @param UniformKernel Boolean to enable the application of a simple uniform kernel without distance weighting (Default False) 13 | #' @param MaxIter Maximum number of iterations, i.e. steps that the kernel can move for each point. If centroid is not found after all iteration, the last position is assigned as centroid and the processing jumps to the next point 14 | #' @return data.frame with X, Y and Z coordinates of each point in the point cloud and X, Y and Z coordinates of the centroid to which the point belongs 15 | #' @export 16 | MeanShift_Classical <- function(pc, H2CW_fac, H2CL_fac, UniformKernel = FALSE, MaxIter = 20L) { 17 | .Call('_MeanShiftR_MeanShift_Classical', PACKAGE = 'MeanShiftR', pc, H2CW_fac, H2CL_fac, UniformKernel, MaxIter) 18 | } 19 | 20 | #' Mean shift clustering using a discrete voxel space 21 | #' 22 | #' @title Mean shift clustering using a discrete voxel space 23 | #' @description 24 | #' Adaptive mean shift clustering to delineate tree crowns from lidar point clouds. This is a version using 1-m³ voxels instead of exact point coordinates, to speed up processing. 25 | #' @param pc Point cloud has to be in matrix format with 3-columns representing X, Y and Z and each row representing one point 26 | #' @param H2CW_fac Factor for the ratio of height to crown width. Determines kernel diameter based on its height above ground. 27 | #' @param H2CL_fac Factor for the ratio of height to crown length. Determines kernel height based on its height above ground. 28 | #' @param UniformKernel Boolean to enable the application of a simple uniform kernel without distance weighting (Default False) 29 | #' @param MaxIter Maximum number of iterations, i.e. steps that the kernel can move for each point. If centroid is not found after all iteration, the last position is assigned as centroid and the processing jumps to the next point 30 | #' @param maxx Maximum X-coordinate 31 | #' @param maxy Maximum Y-coordinate 32 | #' @param maxz Maximum Z-coordinate 33 | #' @return data.frame with X, Y and Z coordinates of each point in the point cloud and X, Y and Z coordinates of the centroid to which the point belongs 34 | #' @export 35 | MeanShift_Voxels <- function(pc, H2CW_fac, H2CL_fac, UniformKernel = FALSE, MaxIter = 20L, maxx = 100L, maxy = 100L, maxz = 60L) { 36 | .Call('_MeanShiftR_MeanShift_Voxels', PACKAGE = 'MeanShiftR', pc, H2CW_fac, H2CL_fac, UniformKernel, MaxIter, maxx, maxy, maxz) 37 | } 38 | 39 | -------------------------------------------------------------------------------- /man/apply_MeanShift.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/apply_MeanShift_function.R 3 | \name{apply_MeanShift} 4 | \alias{apply_MeanShift} 5 | \title{Application of mean shift clustering for individual tree crown delineation with option for parallel processing} 6 | \usage{ 7 | apply_MeanShift( 8 | pc.list, 9 | lib.path = NA, 10 | run.parallel = T, 11 | frac.cores = 0.5, 12 | version = "classic", 13 | H2CW = 0.3, 14 | H2CL = 0.4, 15 | max.iter = 20, 16 | minz = 2, 17 | ctr.ac = 2 18 | ) 19 | } 20 | \arguments{ 21 | \item{pc.list}{List of point clouds in data.table format containing columns X, Y and Z (produced by split_BufferedPointCloud function). Also for single point cloud input (unparallel mode) the input has to be a in list format (one-element list).} 22 | 23 | \item{lib.path}{String specifying the path from where to load the R packages. Should be set to .libPaths()[1].} 24 | 25 | \item{frac.cores}{Fraction of available cores to use for parallelization} 26 | 27 | \item{version}{of the AMS3D algorithm. Can be set to "classic" (slow but precise also with small trees) or "voxel" (fast but based on rounded coordinates of 1-m precision)} 28 | 29 | \item{H2CW}{Factor for the ratio of height to crown width. Determines kernel diameter based on its height above ground.} 30 | 31 | \item{H2CL}{Factor for the ratio of height to crown length. Determines kernel height based on its height above ground.} 32 | 33 | \item{max.iter}{Maximum number of iterations, i.e. steps that the kernel can move for each point. If centroid is not found after all iteration, the last position is assigned as centroid and the processing jumps to the next point} 34 | 35 | \item{minz}{Minimum height above ground for a point to be considered in the analysis. Has to be > 0.} 36 | 37 | \item{ctr.ac}{Centroid accuracy. Specifies the rounding accuracy for centroid positions. After rounding all centroids with the same coordinates are considered to belong to one tree crown.} 38 | } 39 | \value{ 40 | data.table of point cloud with points labelled with tree IDs 41 | } 42 | \description{ 43 | The function provides the framework to apply the adaptive mean shift 3D (AMS3D) algorithm on several 44 | sub point clouds of a large investigation area in parallel. It requires a list of sub point clouds as 45 | input and returns one large clustered point cloud as output. The input should have buffer zones around 46 | the focal areas. The buffer width should correspond to at least the maximal possible tree crown radius. 47 | The function is also recommended for application of AMS3D on single point clouds without parallelization, 48 | because it takes care for point cloud pre- and postprocessing internally (e.g., handling the coordinate extent, 49 | assigning cluster IDs). This functionality is not provided when using the C++ functions (MeanShift_Classical and 50 | MeanShift_Voxels) directly. 51 | } 52 | \author{ 53 | Nikolai Knapp, nikolai.knapp@ufz.de 54 | } 55 | \keyword{area} 56 | \keyword{buffer} 57 | \keyword{cloud} 58 | \keyword{parallel} 59 | \keyword{plot} 60 | \keyword{point} 61 | \keyword{split} 62 | \keyword{subset} 63 | -------------------------------------------------------------------------------- /R/filter_StemReturns.R: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2018 Dr. Nikolai Knapp, UFZ 2 | # 3 | # This file is part of the MeanShiftR R package. 4 | # 5 | # The MeanShiftR R package is free software: you can redistribute 6 | # it and/or modify it under the terms of the GNU General Public License 7 | # as published by the Free Software Foundation, either version 3 of the 8 | # License, or (at your option) any later version. 9 | # 10 | # MeanShiftR is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with MeanShiftR If not, see . 17 | 18 | 19 | 20 | #' Remove low outlier returns, which originate most probably from tree stems not crowns 21 | #' 22 | #' The AMS3D algorithm can lead to clustering artefacts such that a single tree crown may be 23 | #' assigned to more than one cluster ID and the derived enclosing crown polygons may show very 24 | #' high spatial overlap. This function enables cleaning of the crown polygon dataset by removing 25 | #' redundant polygons which most likely represent just one single tree. Of several 26 | #' overlapping polygons, the polygon with the largest tree height value is kept, while the other 27 | #' polygons are removed. 28 | #' The algorithm involves pairwise comparisons of all polygons which are handed over to the 29 | #' function. Hence, it is recommended to apply it on small tiles (e.g., 1 ha), as processing 30 | #' time may become very slow for large areas. 31 | #' @param pc.dt Point cloud in data.table format containing columns X, Y, Z and ID 32 | #' @param H.quantile Lower end height quantile on which filter factor is applied 33 | #' @param filter.factor which multiplied with the H.quantile height defines the threshold below which a return will be classified as stem. 34 | #' @param rm.class Switch for automatically removing returns belonging to classes. Should be set to "Stem" to remove stem returns, "Crown" to remove crown returns or NA to keep all returns. 35 | #' @return SpatialPolygonsDataFrame with each feature representing the crown projection area of one tree and columns containing various geometric attributes 36 | #' @keywords tree crown projection area polygon overlap cluster artefact error double filter clean remove drop discard 37 | #' @author Nikolai Knapp, nikolai.knapp@ufz.de 38 | 39 | filter_StemReturns <- function(pc.dt, H.quantile=0.1, filter.factor=0.9, rm.class=NA){ 40 | 41 | # Package requirements 42 | # require(data.table) 43 | 44 | pc.dt[, LowerQuantileZ := quantile(Z, probs=H.quantile), by=ID] 45 | pc.dt[, FilterZ := filter.factor * LowerQuantileZ] 46 | pc.dt[Z >= FilterZ, ReturnClass := "Crown"] 47 | pc.dt[Z < FilterZ, ReturnClass := "Stem"] 48 | if(rm.class == "Stem"){ 49 | pc.dt <- subset(pc.dt, ReturnClass != "Stem") 50 | }else if(rm.class == "Crown"){ 51 | pc.dt <- subset(pc.dt, ReturnClass != "Crown") 52 | } 53 | return(pc.dt) 54 | } 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /src/LittleFunctionsCollection.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018 Dr. Nikolai Knapp, UFZ 2 | // 3 | // This file is part of the MeanShiftR R package. 4 | // 5 | // The MeanShiftR R package is free software: you can redistribute 6 | // it and/or modify it under the terms of the GNU General Public License 7 | // as published by the Free Software Foundation, either version 3 of the 8 | // License, or (at your option) any later version. 9 | // 10 | // MeanShiftR is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with MeanShiftR If not, see . 17 | 18 | #include 19 | #include 20 | using namespace Rcpp; 21 | 22 | 23 | // Collection of all the little functions used by the main functions 24 | 25 | // Function to check whether a point [PointX, PointY, PointZ] is within a cylider of a given radius 26 | // and height from the center point of the top circle [TopX, TopY, TopZ] 27 | bool InCylinder(double PointX, double PointY, double PointZ, double Radius, double Height, double CtrX, double CtrY, double CtrZ){ 28 | if ((pow((PointX - CtrX), 2.0) + pow((PointY - CtrY), 2.0) <= pow(Radius, 2.0)) && (PointZ >= (CtrZ - (0.5*Height))) && (PointZ <= (CtrZ + (0.5*Height))) == true) { 29 | return true; 30 | } else { 31 | return false; 32 | } 33 | } 34 | 35 | // Help functions for vertical filter 36 | double VerticalDistance(double Height, double CtrZ, double PointZ){ 37 | double BottomDistance = (double) std::abs((CtrZ-Height/4-PointZ)/(3*Height/8)); 38 | double TopDistance = (double) std::abs((CtrZ+Height/2-PointZ)/(3*Height/8)); 39 | double MinDistance = std::min(BottomDistance, TopDistance); 40 | return MinDistance; 41 | } 42 | 43 | //Equivalent R code 44 | //distx <- function(h, CtrZ, PointZ){ 45 | // bottomdist <- abs((CtrZ-h/4-PointZ)/(3*h/8)) 46 | // topdist <- abs((CtrZ+h/2-PointZ)/(3*h/8)) 47 | // mindist <- pmin(bottomdist, topdist) 48 | // return(mindist) 49 | //} 50 | 51 | double VerticalMask(double Height, double CtrZ, double PointZ){ 52 | if((PointZ >= CtrZ-Height/4) && (PointZ <= CtrZ+Height/2)){ 53 | return 1; 54 | } 55 | else 56 | { 57 | return 0; 58 | } 59 | } 60 | 61 | //Equivalent R code 62 | //maskx <- function(h, CtrZ, PointZ){ 63 | // maskvec <- ifelse(PointZ >= CtrZ-h/4 & PointZ <= CtrZ+h/2, 1, 0) 64 | // return(maskvec) 65 | //} 66 | 67 | // Epanechnikov function for vertical filter 68 | double EpanechnikovFunction(double Height, double CtrZ, double PointZ){ 69 | double Result = VerticalMask(Height, CtrZ, PointZ)*(1-(pow((1-VerticalDistance(Height, CtrZ, PointZ)), 2.0))); 70 | return Result; 71 | } 72 | 73 | //Equivalent R code 74 | //Epanechnikov <- function(h, CtrZ, PointZ){ 75 | // output <- maskx(h, CtrZ, PointZ)*(1-(1-distx(h, CtrZ, PointZ))^2) 76 | // return(output) 77 | //} 78 | 79 | // Gauss function for horizontal filter 80 | double GaussFunction(double Width, double CtrX, double CtrY, double PointX, double PointY){ 81 | double Distance = pow((pow((PointX-CtrX), 2.0)+pow((PointY-CtrY), 2.0)), 0.5); 82 | double NormDistance = Distance/Width; 83 | double Result = std::exp(-5.0*pow(NormDistance, 2.0)); 84 | return Result; 85 | } 86 | 87 | //Equivalent R code 88 | //gauss <- function(w, CtrX, CtrY, PointX, PointY){ 89 | // distance <- ((PointX-CtrX)^2+(PointY-CtrY)^2)^0.5 90 | // norm.distance <- distance/w 91 | // output <- exp(-5*norm.distance^2) 92 | // return(output) 93 | //} 94 | -------------------------------------------------------------------------------- /R/filter_OverlappingCrowns_function.R: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2018 Dr. Nikolai Knapp, UFZ 2 | # 3 | # This file is part of the MeanShiftR R package. 4 | # 5 | # The MeanShiftR R package is free software: you can redistribute 6 | # it and/or modify it under the terms of the GNU General Public License 7 | # as published by the Free Software Foundation, either version 3 of the 8 | # License, or (at your option) any later version. 9 | # 10 | # MeanShiftR is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with MeanShiftR If not, see . 17 | 18 | 19 | 20 | #' Remove crown area polygons based on spatial overlap with other polygons 21 | #' 22 | #' The AMS3D algorithm can lead to clustering artefacts such that a single tree crown may be 23 | #' assigned to more than one cluster ID and the derived enclosing crown polygons may show very 24 | #' high spatial overlap. This function enables cleaning of the crown polygon dataset by removing 25 | #' redundant polygons which most likely represent just one single tree. Of several 26 | #' overlapping polygons, the polygon with the largest tree height value is kept, while the other 27 | #' polygons are removed. 28 | #' The algorithm involves pairwise comparisons of all polygons which are handed over to the 29 | #' function. Hence, it is recommended to apply it on small tiles (e.g., 1 ha), as processing 30 | #' time may become very slow for large areas. 31 | #' @param crowns SpatialPolygonsDataFrame of crown projection areas, derived from make_CrownPolygons function 32 | #' @param overlap.threshold Value between 0 and 1 specifying the relative overlap of a pair of crown projection areas (intersection area of two crowns divided by area of a single crown). If the relative overlap is for both crowns larger than this threshold, the crown polygon with the lower tree height value is removed. 33 | #' @return SpatialPolygonsDataFrame with each feature representing the crown projection area of one tree and columns containing various geometric attributes 34 | #' @keywords tree crown projection area polygon overlap cluster artefact error double filter clean remove drop discard 35 | #' @author Nikolai Knapp, nikolai.knapp@ufz.de 36 | 37 | filter_OverlappingCrowns <- function(crowns, overlap.threshold){ 38 | 39 | # Package requirements 40 | # require(rgeos) 41 | 42 | # Create a boolean vector to label which crowns should be kept 43 | n.crowns <- nrow(crowns) 44 | keep.vec <- !logical(n.crowns) 45 | # Store which pairs of polygons intersect 46 | intersection.mx <- rgeos::gIntersects(crowns, byid=T) 47 | for(i in 1:n.crowns){ 48 | for(j in 1:n.crowns){ 49 | if(i != j & intersection.mx[i, j] == T){ 50 | # Derive an intersection polygon and calculate its area as a proportion of either of the two crowns 51 | intersection.polygon <- rgeos::gIntersection(crowns[i,], crowns[j,], byid=T) 52 | rel.intersection.i <- rgeos::gArea(intersection.polygon) / rgeos::gArea(crowns[i,]) 53 | rel.intersection.j <- rgeos::gArea(intersection.polygon) / rgeos::gArea(crowns[j,]) 54 | # Check if threshold is exceeded for both crowns 55 | if(rel.intersection.i > overlap.threshold & rel.intersection.j > overlap.threshold){ 56 | # Label the lower crown for removal 57 | head(crowns) 58 | if(crowns@data[i, "TreeH"] >= crowns@data[j, "TreeH"]){ 59 | keep.vec[j] <- F 60 | }else{ 61 | keep.vec[i] <- F 62 | } 63 | } 64 | } 65 | } 66 | } 67 | crowns <- crowns[keep.vec, ] 68 | return(crowns) 69 | } 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /R/filter_OverlappingCrowns2_function.R: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2018 Dr. Nikolai Knapp, UFZ 2 | # 3 | # This file is part of the MeanShiftR R package. 4 | # 5 | # The MeanShiftR R package is free software: you can redistribute 6 | # it and/or modify it under the terms of the GNU General Public License 7 | # as published by the Free Software Foundation, either version 3 of the 8 | # License, or (at your option) any later version. 9 | # 10 | # MeanShiftR is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with MeanShiftR If not, see . 17 | 18 | 19 | 20 | #' Remove crown area polygons based on spatial overlap with other polygons 21 | #' 22 | #' The AMS3D algorithm can lead to clustering artefacts such that a single tree crown may be 23 | #' assigned to more than one cluster ID and the derived enclosing crown polygons may show very 24 | #' high spatial overlap. This function enables cleaning of the crown polygon dataset by removing 25 | #' redundant polygons which most likely represent just one single tree. Of several 26 | #' overlapping polygons, the polygon with the largest tree height value is kept, while the other 27 | #' polygons are removed. 28 | #' The algorithm involves pairwise comparisons of all polygons which are handed over to the 29 | #' function. Hence, it is recommended to apply it on small tiles (e.g., 1 ha), as processing 30 | #' time may become very slow for large areas. 31 | #' @param crowns SpatialPolygonsDataFrame of crown projection areas, derived from make_CrownPolygons function 32 | #' @param overlap.threshold Value between 0 and 1 specifying the relative overlap of a pair of crown projection areas (intersection area of two crowns divided by area of a single crown). If the relative overlap is for both crowns larger than this threshold, the crown polygon with the lower tree height value is removed. 33 | #' @return SpatialPolygonsDataFrame with each feature representing the crown projection area of one tree and columns containing various geometric attributes 34 | #' @keywords tree crown projection area polygon overlap cluster artefact error double filter clean remove drop discard 35 | #' @author Nikolai Knapp, nikolai.knapp@ufz.de 36 | 37 | filter_OverlappingCrowns2 <- function(crowns, overlap.threshold=0.9){ 38 | 39 | # Package requirements 40 | # require(rgeos) 41 | # require(data.table) 42 | # require(reshape2) 43 | 44 | # Create a boolean vector to label which crowns should be kept 45 | n.crowns <- nrow(crowns) 46 | keep.vec <- !logical(n.crowns) 47 | # Sort crowns by ID 48 | crowns <- crowns[order(crowns$ID),] 49 | # Store which pairs of polygons intersect 50 | intersection.mx <- rgeos::gIntersects(crowns, byid=T) 51 | # Update the row and column names 52 | rownames(intersection.mx) <- 1:nrow(crowns) 53 | colnames(intersection.mx) <- 1:nrow(crowns) 54 | # Melt the matrix into a table and keep only the intersecting pairs 55 | intersection.dt <- data.table::data.table(reshape2::melt(intersection.mx)) 56 | setnames(intersection.dt, old=names(intersection.dt), new=c("Crown.i", "Crown.j", "Overlapping")) 57 | intersection.dt <- subset(intersection.dt, Crown.i != Crown.j & Overlapping == T) 58 | # Loop over all existing pairwise crown overlaps 59 | for(my.row in 1:nrow(intersection.dt)){ 60 | #my.row <- 20 61 | i <- intersection.dt[my.row, Crown.i] 62 | j <- intersection.dt[my.row, Crown.j] 63 | # Derive an intersection polygon and calculate its area as a proportion of either of the two crowns 64 | intersection.polygon <- rgeos::gIntersection(crowns[i,], crowns[j,], byid=T) 65 | rel.intersection.i <- rgeos::gArea(intersection.polygon) / rgeos::gArea(crowns[i,]) 66 | rel.intersection.j <- rgeos::gArea(intersection.polygon) / rgeos::gArea(crowns[j,]) 67 | # Check if threshold is exceeded for both crowns 68 | if(rel.intersection.i > overlap.threshold & rel.intersection.j > overlap.threshold){ 69 | # Label the lower crown for removal 70 | head(crowns) 71 | if(crowns@data[i, "TreeH"] >= crowns@data[j, "TreeH"]){ 72 | keep.vec[j] <- F 73 | }else{ 74 | keep.vec[i] <- F 75 | } 76 | } 77 | } 78 | crowns <- crowns[keep.vec, ] 79 | return(crowns) 80 | } 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /R/match_CrownsStems_function.R: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2018 Dr. Nikolai Knapp, UFZ 2 | # 3 | # This file is part of the MeanShiftR R package. 4 | # 5 | # The MeanShiftR R package is free software: you can redistribute 6 | # it and/or modify it under the terms of the GNU General Public License 7 | # as published by the Free Software Foundation, either version 3 of the 8 | # License, or (at your option) any later version. 9 | # 10 | # MeanShiftR is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with MeanShiftR If not, see . 17 | 18 | 19 | 20 | #' Match crown projection polygons with tree stem positions 21 | #' 22 | #' The function links remote sensing derived crown projection polygons with inventory derived tree stems. 23 | #' The algorithm sorts all polygons by decreasing area size. Then, starting with the largest crown it checks all 24 | #' stem positions that fall inside the crown projection area and selects the stem with the largest diameter 25 | #' and assigns it to the crown. The stem is removed from the set of available stems and the same procedure 26 | #' is conducted for the next smaller crown and further on until the smallest crown. 27 | #' @param crowns.spdf SpatialPolygonsDataFrame of tree crown projection areas 28 | #' @param stems.spdf SpatialPointsDataFrame of tree stem foot positions (required columns: X, Y, DBH, Species, TreeID) 29 | #' @param DBH.min Minimum stem diameter to be considered 30 | #' @return SpatialPolygonsDataFrame of tree crown projection areas with additional columns containing the attributes of the assigned stem for each crown 31 | #' @keywords tree crown projection area polygon point stem foot position DBH diameter link match inventory ground truth 32 | #' @author Nikolai Knapp, nikolai.knapp@ufz.de 33 | 34 | match_CrownsStems <- function(crowns.spdf, stems.spdf, DBH.min=0.05){ 35 | 36 | # Package requirements 37 | # require(data.table) 38 | # require(rgeos) 39 | # require(sp) 40 | # require(raster) 41 | 42 | # Calculate area of each polygon 43 | Area.vec<- rgeos::gArea(crowns.spdf, byid=T) 44 | # Sort the crowns for decreasing area 45 | crowns.spdf <- crowns.spdf[order(Area.vec, decreasing = T),] 46 | 47 | # Filter the inventory data for trees with at least min. DBH 48 | stems.spdf <- subset(stems.spdf, DBH >= DBH.min) 49 | 50 | # Prepare vectors to store results 51 | TreeID.vec <- numeric(nrow(crowns.spdf)) 52 | DBH.vec <- numeric(nrow(crowns.spdf)) 53 | Species.vec <- character(nrow(crowns.spdf)) 54 | X.vec <- numeric(nrow(crowns.spdf)) 55 | Y.vec <- numeric(nrow(crowns.spdf)) 56 | 57 | # Loop through all crown clusters from large to small and search for the 58 | # largest stem underneath each crown 59 | for(i in 1:nrow(crowns.spdf)){ 60 | # i=41 61 | my.crown.spdf <- crowns.spdf[i, ] 62 | my.crown.extent <- raster::extent(my.crown.spdf) 63 | 64 | # Find all stems that fall into the crown projection area 65 | my.pot.stems.spdf <- raster::crop(x=stems.spdf, y=my.crown.extent) 66 | if(!is.null(my.pot.stems.spdf)){ 67 | over.spdf <- sp::over(x=my.pot.stems.spdf, y=my.crown.spdf) 68 | my.pot.stems.spdf <- my.pot.stems.spdf[!is.na(over.spdf[, 1]),] 69 | } 70 | 71 | # Find the largest stem and the associated tree ID 72 | max.DBH <- NA 73 | my.ID <- NA 74 | my.Species <- NA 75 | my.X <- NA 76 | my.Y <- NA 77 | if(!is.null(my.pot.stems.spdf)){ 78 | if(nrow(my.pot.stems.spdf) > 0){ 79 | my.pot.stems.dt <- data.table::data.table(my.pot.stems.spdf@data) 80 | max.DBH <- max(my.pot.stems.dt$DBH) 81 | my.ID <- my.pot.stems.dt[DBH == max.DBH, TreeID] 82 | my.Species <- my.pot.stems.dt[DBH == max.DBH, Species] 83 | my.X <- my.pot.stems.dt[DBH == max.DBH, X] 84 | my.Y <- my.pot.stems.dt[DBH == max.DBH, Y] 85 | # Remove the tree with this ID from the stem table to 86 | # not use it for multiple crown clusters 87 | stems.spdf <- subset(stems.spdf, TreeID != my.ID) 88 | } 89 | } 90 | # Store the findings 91 | TreeID.vec[i] <- my.ID 92 | DBH.vec[i] <- max.DBH 93 | Species.vec[i] <- my.Species 94 | X.vec[i] <- my.X 95 | Y.vec[i] <- my.Y 96 | } 97 | crowns.spdf$StemID <- TreeID.vec 98 | crowns.spdf$StemX <- X.vec 99 | crowns.spdf$StemY <- Y.vec 100 | crowns.spdf$DBH <- DBH.vec 101 | crowns.spdf$Species <- Species.vec 102 | return(crowns.spdf) 103 | } 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | -------------------------------------------------------------------------------- /DemoWorkflow/Demo_Workflow_MeanShiftR.R: -------------------------------------------------------------------------------- 1 | ################################################################################################ 2 | # Demonstration workflow for individual tree crown delineation from a point cloud using the 3 | # adaptive mean shift 3D algorithm (AMS3D; Ferraz et al. 2016) implemented in MeanShiftR package 4 | # Contact: nikolai.knapp@ufz.de 5 | ################################################################################################ 6 | 7 | ############# 8 | # Preparation 9 | ############# 10 | 11 | # Load required packages 12 | .libPaths() 13 | require(MeanShiftR) 14 | 15 | # Read and inspect example data 16 | require(repmis) 17 | source_data("https://github.com/niknap/MeanShiftR/blob/master/DemoWorkflow/Demo_Data_1ha_Traunstein.rda?raw=True") 18 | head(lid.dt) 19 | head(inv.dt) 20 | nrow(lid.dt) 21 | nrow(inv.dt) 22 | 23 | # Display the point cloud (requires function from slidaRtools package available here: https://github.com/niknap/slidaRtools; 24 | # alternatively use the rgl::plot3d function to write your custom 3D plotting code) 25 | require(slidaRtools) 26 | slidaRtools::display.point.cloud.dt(lid.dt, size=2) 27 | display.point.cloud.dt(lid.dt, size=2) 28 | rm(display.point.cloud.dt) 29 | 30 | #################################### 31 | # Data splitting for parallelization 32 | #################################### 33 | 34 | # Split the point cloud into 25-m tiles with 10-m buffers around each tile 35 | lid.list <- split_BufferedPointCloud(pc.dt=lid.dt, plot.width=25, buffer.width=10) 36 | length(lid.list) 37 | 38 | # Check the result by plotting one example tile color coded as core and buffer area 39 | require(slidaRtools) 40 | slidaRtools::display.point.cloud.dt(lid.list[[6]], col.lim=c(0, 1), col.var="Buffer", size=3) 41 | 42 | ################ 43 | # Parallel AMS3D 44 | ################ 45 | 46 | # Apply the parallel AMS3D in the slower "classic" version 47 | system.time(clus.dt <- parallel_MeanShift(pc.list=lid.list, lib.path=.libPaths()[1], frac.cores=0.5, version="classic", 48 | H2CW=0.3, H2CL=0.4, max.iter=20, buffer.width=10, minz=2, ctr.ac=2)) 49 | 50 | # Apply the parallel AMS3D in the fast "voxel" version 51 | system.time(clus.dt <- parallel_MeanShift(pc.list=lid.list, lib.path=.libPaths()[1], frac.cores=0.5, version="voxel", 52 | H2CW=0.3, H2CL=0.4, max.iter=20, buffer.width=10, minz=2, ctr.ac=2)) 53 | 54 | ################## 55 | # Unparallel AMS3D 56 | ################## 57 | 58 | # Apply the AMS3D in the fast "voxel" version on one large 100-m tile (no parallelization) 59 | lid.list <- split_BufferedPointCloud(pc.dt=lid.dt, plot.width=100, buffer.width=10) 60 | length(lid.list) 61 | system.time(clus.dt <- parallel_MeanShift(pc.list=lid.list, lib.path=.libPaths()[1], frac.cores=0.5, version="voxel", 62 | H2CW=0.3, H2CL=0.4, max.iter=20, buffer.width=10, minz=2, ctr.ac=2)) 63 | 64 | system.time(clus.dt <- apply_MeanShift(pc.list=lid.list, lib.path=.libPaths()[1], run.parallel=F, version="voxel", 65 | H2CW=0.3, H2CL=0.4, max.iter=20, minz=2, ctr.ac=2)) 66 | 67 | # Caution: The execution of the following code may take some time!!! 68 | # Apply the AMS3D in the slow "classic" version on one large 100-m tile (no parallelization) 69 | lid.list <- split_BufferedPointCloud(pc.dt=lid.dt, plot.width=100, buffer.width=10) 70 | length(lid.list) 71 | system.time(clus.dt <- parallel_MeanShift(pc.list=lid.list, lib.path=.libPaths()[1], frac.cores=0.5, version="classic", 72 | H2CW=0.3, H2CL=0.4, max.iter=20, buffer.width=10, minz=2, ctr.ac=2)) 73 | 74 | ####################### 75 | # Check output visually 76 | ####################### 77 | 78 | # Count how many tree crown clusters have been found 79 | (Nclus <- length(unique(clus.dt$ID))) 80 | 81 | # Display the clustered point cloud with each tree crown in a random color 82 | slidaRtools::display.point.cloud.dt(clus.dt, col.var="ID", col.palette=rainbow(Nclus)[sample(Nclus)], col.lim=c(0, Nclus), size=3) 83 | 84 | ############################### 85 | # Derive crown projection areas 86 | ############################### 87 | 88 | # Fit polygons of different shapes for the crown projection areas 89 | ellipses.spdf <- make_CrownPolygons(pc.dt=clus.dt, type="ellipse") 90 | circles.spdf <- make_CrownPolygons(pc.dt=clus.dt, type="circle") 91 | chulls.spdf <- make_CrownPolygons(pc.dt=clus.dt, type="convexhull") 92 | 93 | # Create and display a canopy height model (CHM) together with the crown polygons 94 | # (alternative function for CHM generation can be found in the raster package) 95 | require(slidaRtools) 96 | chm.ras <- slidaRtools::raster.from.point.cloud(lid.dt) 97 | plot(chm.ras) 98 | plot(ellipses.spdf, add=T, border="blue") 99 | plot(circles.spdf, add=T, border="red") 100 | plot(chulls.spdf, add=T, border="black") 101 | 102 | ###################################### 103 | # Match crowns with stems in inventory 104 | ###################################### 105 | 106 | # Convert inventory to SpatialPointsDataFrame 107 | inv.spdf <- SpatialPointsDataFrame(coords=cbind(X=inv.dt$X, Y=inv.dt$Y), data=inv.dt) 108 | 109 | # Plot inventory data 110 | plot(inv.spdf, cex=inv.spdf@data$DBH, pch=16, col="brown", add=T) 111 | 112 | # Add Species column which is required for the following function 113 | inv.spdf@data$Species <- NA 114 | 115 | # Find a stem for each crown polygon 116 | ellipses.spdf <- match_CrownsStems(crowns.spdf=ellipses.spdf, stems.spdf=inv.spdf, DBH.min=0.05) 117 | head(ellipses.spdf) 118 | 119 | # Plot tree height vs. DBH 120 | plot(ellipses.spdf@data$TreeH ~ ellipses.spdf@data$DBH, xlab="DBH (m)", ylab="Tree height (m)") 121 | 122 | # Plot mean tree crown diameter vs. DBH 123 | ellipses.spdf@data$MeanCrownDiameter <- 2 * ellipses.spdf@data$MeanRadius 124 | plot(ellipses.spdf@data$MeanCrownDiameter ~ ellipses.spdf@data$DBH, xlab="DBH (m)", ylab="Crown diameter (m)") 125 | 126 | ################################################################ 127 | # Reference: 128 | # Ferraz, A., Saatchi, S., Mallet, C. and Meyer, V. (2016). 129 | # Lidar detection of individual tree size in tropical forests. 130 | # Remote Sensing of Environment. 183. p.pp. 318-333. 131 | ################################################################ 132 | 133 | 134 | 135 | -------------------------------------------------------------------------------- /src/MeanShift_Classical.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018 Dr. Nikolai Knapp, UFZ 2 | // 3 | // This file is part of the MeanShiftR R package. 4 | // 5 | // The MeanShiftR R package is free software: you can redistribute 6 | // it and/or modify it under the terms of the GNU General Public License 7 | // as published by the Free Software Foundation, either version 3 of the 8 | // License, or (at your option) any later version. 9 | // 10 | // MeanShiftR is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with MeanShiftR If not, see . 17 | 18 | #include 19 | #include 20 | #include "LittleFunctionsCollection.h" 21 | using namespace Rcpp; 22 | 23 | 24 | //' Mean shift clustering 25 | //' 26 | //' @title Mean shift clustering 27 | //' @description 28 | //' Adaptive mean shift clustering to delineate tree crowns from lidar point clouds 29 | //' @param pc Point cloud has to be in matrix format with 3-columns representing X, Y and Z and each row representing one point 30 | //' @param H2CW_fac Factor for the ratio of height to crown width. Determines kernel diameter based on its height above ground. 31 | //' @param H2CL_fac Factor for the ratio of height to crown length. Determines kernel height based on its height above ground. 32 | //' @param UniformKernel Boolean to enable the application of a simple uniform kernel without distance weighting (Default False) 33 | //' @param MaxIter Maximum number of iterations, i.e. steps that the kernel can move for each point. If centroid is not found after all iteration, the last position is assigned as centroid and the processing jumps to the next point 34 | //' @return data.frame with X, Y and Z coordinates of each point in the point cloud and X, Y and Z coordinates of the centroid to which the point belongs 35 | //' @export 36 | // [[Rcpp::export]] 37 | DataFrame MeanShift_Classical(NumericMatrix pc, double H2CW_fac, double H2CL_fac, bool UniformKernel=false, int MaxIter=20){ 38 | 39 | // Create three vectors that all have the length of the incoming point cloud. 40 | // In these vectors the coodinates of the centroids will be stored 41 | int nrows = pc.nrow(); 42 | NumericVector centroidx(nrows); 43 | NumericVector centroidy(nrows); 44 | NumericVector centroidz(nrows); 45 | 46 | // Loop through all points to process one after the other 47 | for(int i=0; i. 17 | 18 | 19 | 20 | #' Parallel application of mean shift clustering for individual tree crown delineation 21 | #' 22 | #' The function provides the frame work to apply the adaptive mean shift 3D (AMS3D) algorithm on several 23 | #' sub point clouds of a large investigation area in parallel. It requires a list of sub point clouds as 24 | #' input and returns one large clustered point cloud as output. The input should have buffer zones around 25 | #' the focal areas. The buffer width should correspond to at least the maximal possible tree crown radius. 26 | #' @param pc.list List of point clouds in data.table format containing columns X, Y and Z (produced by split_BufferedPointCloud function) 27 | #' @param lib.path String specifying the path from where to load the R packages. Should be set to .libPaths()[1]. 28 | #' @param frac.cores Fraction of available cores to use for parallelization 29 | #' @param version of the AMS3D algorithm. Can be set to "classic" (slow but precise also with small trees) or "voxel" (fast but based on rounded coordinates of 1-m precision) 30 | #' @param H2CW Factor for the ratio of height to crown width. Determines kernel diameter based on its height above ground. 31 | #' @param H2CL Factor for the ratio of height to crown length. Determines kernel height based on its height above ground. 32 | #' @param max.iter Maximum number of iterations, i.e. steps that the kernel can move for each point. If centroid is not found after all iteration, the last position is assigned as centroid and the processing jumps to the next point 33 | #' @param buffer.width Width of the buffer around the core area in meters 34 | #' @param minz Minimum height above ground for a point to be considered in the analysis. Has to be > 0. 35 | #' @param ctr.ac Centroid accuracy. Specifies the rounding accuracy for centroid positions. After rounding all centroids with the same coordinates are considered to belong to one tree crown. 36 | #' @return data.table of point cloud with points labelled with tree IDs 37 | #' @keywords point cloud split buffer area plot subset parallel 38 | #' @author Nikolai Knapp, nikolai.knapp@ufz.de 39 | 40 | parallel_MeanShift <- function(pc.list, lib.path=NA, frac.cores=0.5, version="classic", H2CW=0.3, H2CL=0.4, 41 | max.iter=20, buffer.width=10, minz=2, ctr.ac=2){ 42 | 43 | # Package requirements 44 | # require(data.table, lib.loc=lib.path) 45 | # require(plyr, lib.loc=lib.path) 46 | # require(parallel, lib.loc=lib.path) 47 | # require(pbapply, lib.loc=lib.path) 48 | # require(Rcpp, lib.loc=lib.path) 49 | 50 | # Calculate the number of cores 51 | N.cores <- parallel::detectCores() 52 | # Initiate cluster 53 | mycl <- parallel::makeCluster(N.cores*frac.cores) 54 | # Prepare the environment on each child worker 55 | parallel::clusterExport(cl=mycl, varlist=c("lib.path", "version", "H2CW", "H2CL", "max.iter", "buffer.width", "minz", "ctr.ac"), envir=environment()) 56 | parallel::clusterEvalQ(cl=mycl, .libPaths(new=lib.path)) 57 | parallel::clusterEvalQ(cl=mycl, require(data.table, lib.loc=lib.path)) 58 | parallel::clusterEvalQ(cl=mycl, require(plyr, lib.loc=lib.path)) 59 | parallel::clusterEvalQ(cl=mycl, require(Rcpp, lib.loc=lib.path)) 60 | parallel::clusterEvalQ(cl=mycl, require(MeanShiftR, lib.loc=lib.path)) 61 | 62 | # Wrapper function that runs mean shift and deals with buffers 63 | run.MeanShift <- function(my.dt){ 64 | 65 | # Remove points below a minimum height (ground and near ground returns) 66 | my.dt <- subset(my.dt, Z >= minz) 67 | 68 | # Get margins 69 | my.minx <- floor(min(my.dt$X)) 70 | my.maxx <- ceiling(max(my.dt$X)) 71 | my.miny <- floor(min(my.dt$Y)) 72 | my.maxy <- ceiling(max(my.dt$Y)) 73 | my.rangex <- my.maxx - my.minx 74 | my.rangey <- my.maxy - my.miny 75 | my.maxz <- ceiling(max(my.dt$Z)) 76 | 77 | # Get margins of the core area 78 | core.minx <- floor(min(my.dt[Buffer==0, X])) 79 | core.maxx <- ceiling(max(my.dt[Buffer==0, X])) 80 | core.miny <- floor(min(my.dt[Buffer==0, Y])) 81 | core.maxy <- ceiling(max(my.dt[Buffer==0, Y])) 82 | 83 | # Shift to coordinate origin 84 | my.dt[, X := X - my.minx] 85 | my.dt[, Y := Y - my.miny] 86 | 87 | # Convert to 3-column matrix 88 | my.mx <- as.matrix(my.dt) 89 | my.mx <- my.mx[, 1:3] 90 | 91 | # Run the mean shift (two different versions) 92 | if(version=="classic"){ 93 | cluster.df <- MeanShift_Classical(pc=my.mx, H2CW_fac=H2CW, H2CL_fac=H2CL, UniformKernel=F, MaxIter=max.iter) 94 | }else if(version=="voxel"){ 95 | cluster.df <- MeanShift_Voxels(pc=my.mx, H2CW_fac=H2CW, H2CL_fac=H2CL, UniformKernel=F, MaxIter=max.iter, maxx=my.rangex, maxy=my.rangey, maxz=my.maxz) 96 | } 97 | 98 | # Round the centroid coordinates 99 | cluster.dt <- data.table::data.table(cluster.df) 100 | cluster.dt[, RoundCtrX := round_any(CtrX, accuracy=ctr.ac)] 101 | cluster.dt[, RoundCtrY := round_any(CtrY, accuracy=ctr.ac)] 102 | cluster.dt[, RoundCtrZ := round_any(CtrZ, accuracy=ctr.ac)] 103 | 104 | # Shift back to original positions 105 | cluster.dt[, X := X + my.minx] 106 | cluster.dt[, Y := Y + my.miny] 107 | cluster.dt[, CtrX := CtrX + my.minx] 108 | cluster.dt[, CtrY := CtrY + my.miny] 109 | cluster.dt[, RoundCtrX := RoundCtrX + my.minx] 110 | cluster.dt[, RoundCtrY := RoundCtrY + my.miny] 111 | 112 | # Subset tree clusters with centers inside the core area of the 113 | # focal subplot and discard the clusters with centers in the buffer area 114 | cluster.dt <- subset(cluster.dt, RoundCtrX >= core.minx & RoundCtrX < core.maxx & 115 | RoundCtrY >= core.miny & RoundCtrY < core.maxy) 116 | 117 | # Collect the clustered point cloud in the results list 118 | return(cluster.dt) 119 | } 120 | 121 | # Apply the mean shift wrapper function in parallel 122 | #result.list <- parLapply(cl=mycl, X=pc.list, fun=run.MeanShift) 123 | 124 | # Apply the mean shift wrapper function in parallel using pblapply to display a progress bar 125 | result.list <- pbapply::pblapply(cl=mycl, X=pc.list, FUN=run.MeanShift) 126 | 127 | # Bind all point clouds from the list in one large data.table 128 | result.dt <- data.table::rbindlist(result.list) 129 | 130 | # Assign IDs to each cluster based on the rounded coordinates 131 | result.dt[ , ID := .GRP, by = .(RoundCtrX, RoundCtrY, RoundCtrZ)] 132 | 133 | # Finish 134 | parallel::stopCluster(mycl) 135 | return(result.dt) 136 | } 137 | 138 | 139 | 140 | 141 | 142 | 143 | -------------------------------------------------------------------------------- /R/apply_MeanShift_function.R: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2018 Dr. Nikolai Knapp, UFZ 2 | # 3 | # This file is part of the MeanShiftR R package. 4 | # 5 | # The MeanShiftR R package is free software: you can redistribute 6 | # it and/or modify it under the terms of the GNU General Public License 7 | # as published by the Free Software Foundation, either version 3 of the 8 | # License, or (at your option) any later version. 9 | # 10 | # MeanShiftR is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with MeanShiftR If not, see . 17 | 18 | 19 | 20 | #' Application of mean shift clustering for individual tree crown delineation with option for parallel processing 21 | #' 22 | #' The function provides the framework to apply the adaptive mean shift 3D (AMS3D) algorithm on several 23 | #' sub point clouds of a large investigation area in parallel. It requires a list of sub point clouds as 24 | #' input and returns one large clustered point cloud as output. The input should have buffer zones around 25 | #' the focal areas. The buffer width should correspond to at least the maximal possible tree crown radius. 26 | #' The function is also recommended for application of AMS3D on single point clouds without parallelization, 27 | #' because it takes care for point cloud pre- and postprocessing internally (e.g., handling the coordinate extent, 28 | #' assigning cluster IDs). This functionality is not provided when using the C++ functions (MeanShift_Classical and 29 | #' MeanShift_Voxels) directly. 30 | #' @param pc.list List of point clouds in data.table format containing columns X, Y and Z (produced by split_BufferedPointCloud function). Also for single point cloud input (unparallel mode) the input has to be a in list format (one-element list). 31 | #' @param lib.path String specifying the path from where to load the R packages. Should be set to .libPaths()[1]. 32 | #' @param frac.cores Fraction of available cores to use for parallelization 33 | #' @param version of the AMS3D algorithm. Can be set to "classic" (slow but precise also with small trees) or "voxel" (fast but based on rounded coordinates of 1-m precision) 34 | #' @param H2CW Factor for the ratio of height to crown width. Determines kernel diameter based on its height above ground. 35 | #' @param H2CL Factor for the ratio of height to crown length. Determines kernel height based on its height above ground. 36 | #' @param max.iter Maximum number of iterations, i.e. steps that the kernel can move for each point. If centroid is not found after all iteration, the last position is assigned as centroid and the processing jumps to the next point 37 | #' @param minz Minimum height above ground for a point to be considered in the analysis. Has to be > 0. 38 | #' @param ctr.ac Centroid accuracy. Specifies the rounding accuracy for centroid positions. After rounding all centroids with the same coordinates are considered to belong to one tree crown. 39 | #' @return data.table of point cloud with points labelled with tree IDs 40 | #' @keywords point cloud split buffer area plot subset parallel 41 | #' @author Nikolai Knapp, nikolai.knapp@ufz.de 42 | 43 | apply_MeanShift <- function(pc.list, lib.path=NA, run.parallel=T, frac.cores=0.5, version="classic", H2CW=0.3, H2CL=0.4, 44 | max.iter=20, minz=2, ctr.ac=2){ 45 | 46 | # Package requirements 47 | # require(data.table, lib.loc=lib.path) 48 | # require(plyr, lib.loc=lib.path) 49 | # require(parallel, lib.loc=lib.path) 50 | # require(pbapply, lib.loc=lib.path) 51 | # require(Rcpp, lib.loc=lib.path) 52 | 53 | # Prepare parallelization 54 | if(run.parallel == T){ 55 | # Calculate the number of cores 56 | N.cores <- parallel::detectCores() 57 | # Initiate cluster 58 | mycl <- parallel::makeCluster(N.cores*frac.cores) 59 | # Prepare the environment on each child worker 60 | parallel::clusterExport(cl=mycl, varlist=c("lib.path", "version", "H2CW", "H2CL", "max.iter", "minz", "ctr.ac"), envir=environment()) 61 | parallel::clusterEvalQ(cl=mycl, .libPaths(new=lib.path)) 62 | parallel::clusterEvalQ(cl=mycl, require(data.table, lib.loc=lib.path)) 63 | parallel::clusterEvalQ(cl=mycl, require(plyr, lib.loc=lib.path)) 64 | parallel::clusterEvalQ(cl=mycl, require(Rcpp, lib.loc=lib.path)) 65 | parallel::clusterEvalQ(cl=mycl, require(MeanShiftR, lib.loc=lib.path)) 66 | } 67 | 68 | # Wrapper function that runs mean shift and deals with buffers 69 | run.MeanShift <- function(my.dt){ 70 | 71 | # Remove points below a minimum height (ground and near ground returns) 72 | my.dt <- subset(my.dt, Z >= minz) 73 | 74 | # Get margins 75 | my.minx <- floor(min(my.dt$X)) 76 | my.maxx <- ceiling(max(my.dt$X)) 77 | my.miny <- floor(min(my.dt$Y)) 78 | my.maxy <- ceiling(max(my.dt$Y)) 79 | my.rangex <- my.maxx - my.minx 80 | my.rangey <- my.maxy - my.miny 81 | my.maxz <- ceiling(max(my.dt$Z)) 82 | 83 | # Get margins of the core area 84 | core.minx <- floor(min(my.dt[Buffer==0, X])) 85 | core.maxx <- ceiling(max(my.dt[Buffer==0, X])) 86 | core.miny <- floor(min(my.dt[Buffer==0, Y])) 87 | core.maxy <- ceiling(max(my.dt[Buffer==0, Y])) 88 | 89 | # Shift to coordinate origin 90 | my.dt[, X := X - my.minx] 91 | my.dt[, Y := Y - my.miny] 92 | 93 | # Convert to 3-column matrix 94 | my.mx <- as.matrix(my.dt) 95 | my.mx <- my.mx[, 1:3] 96 | 97 | # Run the mean shift (different versions) 98 | if(version=="classic"){ 99 | cluster.df <- MeanShift_Classical(pc=my.mx, H2CW_fac=H2CW, H2CL_fac=H2CL, UniformKernel=F, MaxIter=max.iter) 100 | }else if(version=="voxel"){ 101 | cluster.df <- MeanShift_Voxels(pc=my.mx, H2CW_fac=H2CW, H2CL_fac=H2CL, UniformKernel=F, MaxIter=max.iter, maxx=my.rangex, maxy=my.rangey, maxz=my.maxz) 102 | } 103 | 104 | # Round the centroid coordinates 105 | cluster.dt <- data.table::data.table(cluster.df) 106 | cluster.dt[, RoundCtrX := round_any(CtrX, accuracy=ctr.ac)] 107 | cluster.dt[, RoundCtrY := round_any(CtrY, accuracy=ctr.ac)] 108 | cluster.dt[, RoundCtrZ := round_any(CtrZ, accuracy=ctr.ac)] 109 | 110 | # Shift back to original positions 111 | cluster.dt[, X := X + my.minx] 112 | cluster.dt[, Y := Y + my.miny] 113 | cluster.dt[, CtrX := CtrX + my.minx] 114 | cluster.dt[, CtrY := CtrY + my.miny] 115 | cluster.dt[, RoundCtrX := RoundCtrX + my.minx] 116 | cluster.dt[, RoundCtrY := RoundCtrY + my.miny] 117 | 118 | # Subset tree clusters with centers inside the core area of the 119 | # focal subplot and discard the clusters with centers in the buffer area 120 | cluster.dt <- subset(cluster.dt, RoundCtrX >= core.minx & RoundCtrX < core.maxx & 121 | RoundCtrY >= core.miny & RoundCtrY < core.maxy) 122 | 123 | # Collect the clustered point cloud in the results list 124 | return(cluster.dt) 125 | } 126 | 127 | # Apply the mean shift wrapper function 128 | if(run.parallel == F){ 129 | # On single point cloud (unparallel) 130 | result.dt <- run.MeanShift(pc.list[[1]]) 131 | }else{ 132 | # On list of point clouds in parallel using pblapply to display a progress bar 133 | result.list <- pbapply::pblapply(cl=mycl, X=pc.list, FUN=run.MeanShift) 134 | # Bind all point clouds from the list in one large data.table 135 | result.dt <- data.table::rbindlist(result.list) 136 | } 137 | 138 | # Assign IDs to each cluster based on the rounded coordinates 139 | result.dt[ , ID := .GRP, by = .(RoundCtrX, RoundCtrY, RoundCtrZ)] 140 | 141 | # Count the number of points per cluster 142 | result.dt[, NPoints := .N, by=ID] 143 | 144 | # Finish 145 | if(run.parallel == T){ 146 | parallel::stopCluster(mycl) 147 | } 148 | return(result.dt) 149 | } 150 | 151 | 152 | 153 | 154 | 155 | 156 | -------------------------------------------------------------------------------- /src/MeanShift_Voxels.cpp: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2018 Dr. Nikolai Knapp, UFZ 2 | // 3 | // This file is part of the MeanShiftR R package. 4 | // 5 | // The MeanShiftR R package is free software: you can redistribute 6 | // it and/or modify it under the terms of the GNU General Public License 7 | // as published by the Free Software Foundation, either version 3 of the 8 | // License, or (at your option) any later version. 9 | // 10 | // MeanShiftR is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with MeanShiftR If not, see . 17 | 18 | #include 19 | #include 20 | #include "LittleFunctionsCollection.h" 21 | using namespace Rcpp; 22 | using namespace std; 23 | 24 | 25 | //' Mean shift clustering using a discrete voxel space 26 | //' 27 | //' @title Mean shift clustering using a discrete voxel space 28 | //' @description 29 | //' Adaptive mean shift clustering to delineate tree crowns from lidar point clouds. This is a version using 1-m³ voxels instead of exact point coordinates, to speed up processing. 30 | //' @param pc Point cloud has to be in matrix format with 3-columns representing X, Y and Z and each row representing one point 31 | //' @param H2CW_fac Factor for the ratio of height to crown width. Determines kernel diameter based on its height above ground. 32 | //' @param H2CL_fac Factor for the ratio of height to crown length. Determines kernel height based on its height above ground. 33 | //' @param UniformKernel Boolean to enable the application of a simple uniform kernel without distance weighting (Default False) 34 | //' @param MaxIter Maximum number of iterations, i.e. steps that the kernel can move for each point. If centroid is not found after all iteration, the last position is assigned as centroid and the processing jumps to the next point 35 | //' @param maxx Maximum X-coordinate 36 | //' @param maxy Maximum Y-coordinate 37 | //' @param maxz Maximum Z-coordinate 38 | //' @return data.frame with X, Y and Z coordinates of each point in the point cloud and X, Y and Z coordinates of the centroid to which the point belongs 39 | //' @export 40 | // [[Rcpp::export]] 41 | DataFrame MeanShift_Voxels(NumericMatrix pc, double H2CW_fac, double H2CL_fac, bool UniformKernel=false, int MaxIter=20, int maxx=100, int maxy=100, int maxz=60){ 42 | 43 | int nrows = pc.nrow(); 44 | int minx = 0; 45 | int miny = 0; 46 | int minz = 0; 47 | 48 | NumericVector centroidx(nrows); 49 | NumericVector centroidy(nrows); 50 | NumericVector centroidz(nrows); 51 | 52 | std::vector > >array3D; 53 | 54 | double myx; 55 | double myy; 56 | double myz; 57 | int vx; 58 | int vy; 59 | int vz; 60 | int np; 61 | double r; 62 | double d; 63 | double h; 64 | int boxminx; 65 | int boxmaxx; 66 | int boxminy; 67 | int boxmaxy; 68 | int boxminz; 69 | int boxmaxz; 70 | 71 | // Adjust the size of the array3D 72 | array3D.resize((int) maxx+1); 73 | for (int xi=0; xi maxx+1) {boxmaxx = maxx;} 155 | if (boxminy < miny) {boxminy = miny;} 156 | if (boxmaxy > maxy+1) {boxmaxy = maxy;} 157 | if (boxminz < minz) {boxminz = minz;} 158 | if (boxmaxz > maxz+1) {boxmaxz = maxz;} 159 | 160 | // Loop through all voxels in the neighborhood of the point 161 | for(int xi=boxminx; xi 0){ 165 | if(InCylinder(xi, yi, zi, r, h, meanx, meany, meanz) == true){ 166 | 167 | // If the option of a uniform kernel is set to false calculate the centroid 168 | // by multiplying all coodinates by their weights, depending on their relative 169 | // position within the cylinder, summing up the products and dividing by the 170 | // sum of all weights 171 | if(UniformKernel == false){ 172 | np = array3D[xi][yi][zi]; 173 | verticalweight = EpanechnikovFunction(h, meanz, zi); 174 | horizontalweight = GaussFunction(d, meanx, meany, xi, yi); 175 | weight = verticalweight * horizontalweight; 176 | sumx = sumx + weight * np * xi; 177 | sumy = sumy + weight * np * yi; 178 | sumz = sumz + weight * np * zi; 179 | sump = sump + weight * np; 180 | } 181 | // If the option of a uniform kernel is set to true calculate the centroid 182 | // by summing up all coodinates and dividing by the number of points 183 | else 184 | { 185 | np = array3D[xi][yi][zi]; 186 | sumx = sumx + np * xi; 187 | sumy = sumy + np * yi; 188 | sumz = sumz + np * zi; 189 | sump = sump + np * 1.0; 190 | } 191 | } 192 | } 193 | } 194 | } 195 | } 196 | 197 | meanx = sumx / sump; 198 | meany = sumy / sump; 199 | meanz = sumz / sump; 200 | 201 | }while(meanx != oldx && meany != oldy && meanz != oldz && IterCounter < MaxIter); 202 | 203 | centroidx[i] = meanx; 204 | centroidy[i] = meany; 205 | centroidz[i] = meanz; 206 | } 207 | 208 | return DataFrame::create(_["X"]= pc(_,0),_["Y"]= pc(_,1),_["Z"]= pc(_,2),_["CtrX"]= centroidx,_["CtrY"]= centroidy,_["CtrZ"]= centroidz); 209 | } 210 | 211 | 212 | 213 | 214 | -------------------------------------------------------------------------------- /R/split_BufferedPointCloud_function.R: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2018 Dr. Nikolai Knapp, UFZ 2 | # 3 | # This file is part of the MeanShiftR R package. 4 | # 5 | # The MeanShiftR R package is free software: you can redistribute 6 | # it and/or modify it under the terms of the GNU General Public License 7 | # as published by the Free Software Foundation, either version 3 of the 8 | # License, or (at your option) any later version. 9 | # 10 | # MeanShiftR is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with MeanShiftR If not, see . 17 | 18 | 19 | 20 | #' Split point cloud into smaller point clouds with buffer area around 21 | #' 22 | #' The function splits one large point cloud into several smaller point clouds. 23 | #' It allows to specify a buffer width around the core area where points are included. 24 | #' @param pc.dt Point cloud in data.table format containing columns X, Y and Z 25 | #' @param plot.width Width of the core area in meters 26 | #' @param buffer.width Width of the buffer around the core area in meters 27 | #' @return List of sub point clouds and buffer and core points labeled in boolean column "Buffer" 28 | #' @keywords point cloud split buffer area plot subset parallel 29 | #' @author Nikolai Knapp, nikolai.knapp@ufz.de 30 | 31 | split_BufferedPointCloud <- function(pc.dt, plot.width, buffer.width){ 32 | 33 | # Package requirements 34 | #require(data.table) 35 | # require(plyr) 36 | 37 | # Convert to data.table 38 | pc.dt <- data.table::as.data.table(pc.dt) 39 | 40 | # Calculate the absolute lower left corner of the point cloud 41 | abs.llX <- plyr::round_any(min(pc.dt$X, na.rm=T), accuracy=plot.width, f=floor) 42 | abs.llY <- plyr::round_any(min(pc.dt$Y, na.rm=T), accuracy=plot.width, f=floor) 43 | 44 | # Calculate spatial indices for small subplots 45 | #if(data.table::is.data.table(pc.dt)){pc.dt[, sBPC_SpatID := calc_SpatialIndex(xcor=X, ycor=Y, res=plot.width, minx=abs.llX, miny=abs.llY)]} 46 | pc.dt[, sBPC_SpatID := calc_SpatialIndex(xcor=X, ycor=Y, res=plot.width, minx=abs.llX, miny=abs.llY)] 47 | #if(is.data.table(pc.dt)){pc.dt[, sBPC_SpatID := calc_SpatialIndex(xcor=X, ycor=Y, res=plot.width, minx=abs.llX, miny=abs.llY)]} 48 | 49 | # Calculate coordinates of the lower left plot corners 50 | pc.dt[, sBPC_llX := plyr::round_any(X, accuracy=plot.width, f=floor)] 51 | pc.dt[, sBPC_llY := plyr::round_any(Y, accuracy=plot.width, f=floor)] 52 | 53 | # Make a unique data.table with all coordinate corner combinations and spatial indices 54 | coord.dt <- unique(subset(pc.dt, select=c("sBPC_SpatID", "sBPC_llX", "sBPC_llY"))) 55 | data.table::setorderv(coord.dt, cols=c("sBPC_SpatID", "sBPC_llX", "sBPC_llY")) 56 | data.table::setnames(coord.dt, old=names(coord.dt), new=c("sBPC_nSpatID", "sBPC_nllX", "sBPC_nllY")) 57 | 58 | # Create a copy of the point cloud which will become the result and to which the buffers will be added successively 59 | result.dt <- data.table::copy(pc.dt) 60 | result.dt[, Buffer := 0] 61 | 62 | # Add the lower buffer points 63 | buf.dt <- data.table::copy(pc.dt) 64 | # Calculate the neighbor plot's lower left coordinates 65 | buf.dt[, sBPC_nllX := sBPC_llX] 66 | buf.dt[, sBPC_nllY := sBPC_llY+plot.width] 67 | # Add the ID of the neighbor plot 68 | buf.dt <- merge(buf.dt, coord.dt, by=c("sBPC_nllX", "sBPC_nllY"), all.x=T) 69 | # Subset points inside the buffer 70 | buf.dt <- subset(buf.dt, Y < sBPC_nllY & Y >= sBPC_nllY - buffer.width) 71 | # Add the buffer points to the result 72 | buf.dt[, Buffer := 1] 73 | buf.dt[, sBPC_SpatID := sBPC_nSpatID] 74 | buf.dt <- subset(buf.dt, select=names(result.dt)) 75 | result.dt <- rbind(result.dt, buf.dt) 76 | rm(buf.dt) 77 | 78 | # Add the lower left buffer points 79 | buf.dt <- data.table::copy(pc.dt) 80 | # Calculate the neighbor plot's lower left coordinates 81 | buf.dt[, sBPC_nllX := sBPC_llX+plot.width] 82 | buf.dt[, sBPC_nllY := sBPC_llY+plot.width] 83 | # Add the ID of the neigbor plot 84 | buf.dt <- merge(buf.dt, coord.dt, by=c("sBPC_nllX", "sBPC_nllY"), all.x=T) 85 | # Subset points inside the buffer 86 | buf.dt <- subset(buf.dt, X < sBPC_nllX & X >= sBPC_nllX - buffer.width & Y < sBPC_nllY & Y >= sBPC_nllY - buffer.width) 87 | # Add the buffer points to the result 88 | buf.dt[, Buffer := 1] 89 | buf.dt[, sBPC_SpatID := sBPC_nSpatID] 90 | buf.dt <- subset(buf.dt, select=names(result.dt)) 91 | result.dt <- rbind(result.dt, buf.dt) 92 | rm(buf.dt) 93 | 94 | # Add the left buffer points 95 | buf.dt <- data.table::copy(pc.dt) 96 | # Calculate the neighbor plot's lower left coordinates 97 | buf.dt[, sBPC_nllX := sBPC_llX+plot.width] 98 | buf.dt[, sBPC_nllY := sBPC_llY] 99 | # Add the ID of the neigbor plot 100 | buf.dt <- merge(buf.dt, coord.dt, by=c("sBPC_nllX", "sBPC_nllY"), all.x=T) 101 | # Subset points inside the buffer 102 | buf.dt <- subset(buf.dt, X < sBPC_nllX & X >= sBPC_nllX - buffer.width) 103 | # Add the buffer points to the result 104 | buf.dt[, Buffer := 1] 105 | buf.dt[, sBPC_SpatID := sBPC_nSpatID] 106 | buf.dt <- subset(buf.dt, select=names(result.dt)) 107 | result.dt <- rbind(result.dt, buf.dt) 108 | rm(buf.dt) 109 | 110 | # Add the upper left buffer points 111 | buf.dt <- data.table::copy(pc.dt) 112 | # Calculate the neighbor plot's lower left coordinates 113 | buf.dt[, sBPC_nllX := sBPC_llX+plot.width] 114 | buf.dt[, sBPC_nllY := sBPC_llY-plot.width] 115 | # Add the ID of the neigbor plot 116 | buf.dt <- merge(buf.dt, coord.dt, by=c("sBPC_nllX", "sBPC_nllY"), all.x=T) 117 | # Subset points inside the buffer 118 | buf.dt <- subset(buf.dt, X < sBPC_nllX & X >= sBPC_nllX - buffer.width & Y > sBPC_nllY + plot.width & Y <= sBPC_nllY + plot.width + buffer.width) 119 | # Add the buffer points to the result 120 | buf.dt[, Buffer := 1] 121 | buf.dt[, sBPC_SpatID := sBPC_nSpatID] 122 | buf.dt <- subset(buf.dt, select=names(result.dt)) 123 | result.dt <- rbind(result.dt, buf.dt) 124 | rm(buf.dt) 125 | 126 | # Add the upper buffer points 127 | buf.dt <- data.table::copy(pc.dt) 128 | # Calculate the neighbor plot's lower left coordinates 129 | buf.dt[, sBPC_nllX := sBPC_llX] 130 | buf.dt[, sBPC_nllY := sBPC_llY-plot.width] 131 | # Add the ID of the neigbor plot 132 | buf.dt <- merge(buf.dt, coord.dt, by=c("sBPC_nllX", "sBPC_nllY"), all.x=T) 133 | # Subset points inside the buffer 134 | buf.dt <- subset(buf.dt, Y > sBPC_nllY + plot.width & Y <= sBPC_nllY + plot.width + buffer.width) 135 | # Add the buffer points to the result 136 | buf.dt[, Buffer := 1] 137 | buf.dt[, sBPC_SpatID := sBPC_nSpatID] 138 | buf.dt <- subset(buf.dt, select=names(result.dt)) 139 | result.dt <- rbind(result.dt, buf.dt) 140 | rm(buf.dt) 141 | 142 | # Add the upper right buffer points 143 | buf.dt <- data.table::copy(pc.dt) 144 | # Calculate the neighbor plot's lower left coordinates 145 | buf.dt[, sBPC_nllX := sBPC_llX-plot.width] 146 | buf.dt[, sBPC_nllY := sBPC_llY-plot.width] 147 | # Add the ID of the neigbor plot 148 | buf.dt <- merge(buf.dt, coord.dt, by=c("sBPC_nllX", "sBPC_nllY"), all.x=T) 149 | # Subset points inside the buffer 150 | buf.dt <- subset(buf.dt, X > sBPC_nllX + plot.width & X <= sBPC_nllX + plot.width + buffer.width & Y > sBPC_nllY + plot.width & Y <= sBPC_nllY + plot.width + buffer.width) 151 | # Add the buffer points to the result 152 | buf.dt[, Buffer := 1] 153 | buf.dt[, sBPC_SpatID := sBPC_nSpatID] 154 | buf.dt <- subset(buf.dt, select=names(result.dt)) 155 | result.dt <- rbind(result.dt, buf.dt) 156 | rm(buf.dt) 157 | 158 | # Add the right buffer points 159 | buf.dt <- data.table::copy(pc.dt) 160 | # Calculate the neighbor plot's lower left coordinates 161 | buf.dt[, sBPC_nllX := sBPC_llX-plot.width] 162 | buf.dt[, sBPC_nllY := sBPC_llY] 163 | # Add the ID of the neigbor plot 164 | buf.dt <- merge(buf.dt, coord.dt, by=c("sBPC_nllX", "sBPC_nllY"), all.x=T) 165 | # Subset points inside the buffer 166 | buf.dt <- subset(buf.dt, X > sBPC_nllX + plot.width & X <= sBPC_nllX + plot.width + buffer.width) 167 | # Add the buffer points to the result 168 | buf.dt[, Buffer := 1] 169 | buf.dt[, sBPC_SpatID := sBPC_nSpatID] 170 | buf.dt <- subset(buf.dt, select=names(result.dt)) 171 | result.dt <- rbind(result.dt, buf.dt) 172 | rm(buf.dt) 173 | 174 | # Add the lower right buffer points 175 | buf.dt <- data.table::copy(pc.dt) 176 | # Calculate the neighbor plot's lower left coordinates 177 | buf.dt[, sBPC_nllX := sBPC_llX-plot.width] 178 | buf.dt[, sBPC_nllY := sBPC_llY+plot.width] 179 | # Add the ID of the neigbor plot 180 | buf.dt <- merge(buf.dt, coord.dt, by=c("sBPC_nllX", "sBPC_nllY"), all.x=T) 181 | # Subset points inside the buffer 182 | buf.dt <- subset(buf.dt, X > sBPC_nllX + plot.width & X <= sBPC_nllX + plot.width + buffer.width & Y < sBPC_nllY & Y >= sBPC_nllY - buffer.width) 183 | # Add the buffer points to the result 184 | buf.dt[, Buffer := 1] 185 | buf.dt[, sBPC_SpatID := sBPC_nSpatID] 186 | buf.dt <- subset(buf.dt, select=names(result.dt)) 187 | result.dt <- rbind(result.dt, buf.dt) 188 | rm(buf.dt) 189 | 190 | # Remove all rows with NA as spatial index 191 | result.dt <- subset(result.dt, !is.na(sBPC_SpatID)) 192 | 193 | # Split into a list of separate point clouds with buffers based on spatial index 194 | data.table::setorderv(result.dt, cols=c("sBPC_SpatID", "Buffer", "X", "Y")) 195 | result.list <- split(result.dt, by="sBPC_SpatID") 196 | 197 | return(result.list) 198 | 199 | } 200 | 201 | 202 | 203 | 204 | -------------------------------------------------------------------------------- /R/make_CrownPolygons_function.R: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2018 Dr. Nikolai Knapp, UFZ 2 | # 3 | # This file is part of the MeanShiftR R package. 4 | # 5 | # The MeanShiftR R package is free software: you can redistribute 6 | # it and/or modify it under the terms of the GNU General Public License 7 | # as published by the Free Software Foundation, either version 3 of the 8 | # License, or (at your option) any later version. 9 | # 10 | # MeanShiftR is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with MeanShiftR If not, see . 17 | 18 | 19 | 20 | #' Fit polygon hulls around tree crowns in a clustered point cloud to derive crown projection areas 21 | #' 22 | #' The function creates crown projection area polygons from a clustered point cloud of a forest stand. 23 | #' The input point cloud needs to have a column containing tree ID / cluster ID of each point. 24 | #' There are different options for the shape of the polygons. 25 | #' @param pc.dt Point cloud in data.table format containing columns X, Y, Z and ID 26 | #' @param type Shape of the desired polygons ("convexhull", "ellipse" or "circle") 27 | #' @param N.min Minimum number of points in a cluster to be considered as a tree crown 28 | #' @param Ext.min Minimum horizontal extent (in meters, in X- and Y-direction) of a cluster to be considered as a tree crown 29 | #' @param Ext.max Maximum horizontal extent (in meters, in X- and Y-direction) of a cluster to be considered as a tree crown 30 | #' @param proj4string Projection string of class CRS-class 31 | #' @return SpatialPolygonsDataFrame with each feature representing the crown projection area of one tree and columns containing various geometric attributes 32 | #' @keywords tree crown projection area polygons point cloud cluster convex hull ellipse circle perimeter 33 | #' @author Nikolai Knapp, nikolai.knapp@ufz.de 34 | 35 | make_CrownPolygons <- function(pc.dt, type="convexhull", N.min=20, Ext.min=2, Ext.max=50, proj4string=CRS(as.character(NA))){ 36 | 37 | # type="convexhull" 38 | # N.min=20 39 | # Ext.min=2 40 | # Ext.max=50 41 | # pc.dt=clus.dt 42 | 43 | # Package requirements 44 | # require(data.table) 45 | # require(sp) 46 | # require(rgeos) 47 | # require(cluster) 48 | # require(tripack) 49 | # require(raster) 50 | 51 | pc.dt <- data.table::data.table(pc.dt) 52 | 53 | # Count the returns per cluster 54 | pc.dt[, N := .N, by=ID] 55 | 56 | # Subset only clusters that consist of a minimum number of points 57 | sub.dt <- subset(pc.dt, N >= N.min) 58 | 59 | # Subset only clusters that have a minimum and don't exceed a X- and Y-extent 60 | sub.dt[, ExtX := max(X, na.rm=T) - min(X, na.rm=T), by=ID] 61 | sub.dt[, ExtY := max(Y, na.rm=T) - min(Y, na.rm=T), by=ID] 62 | sub2.dt <- subset(sub.dt, ExtX >= Ext.min & ExtY >= Ext.min & ExtX <= Ext.max & ExtY <= Ext.max) 63 | 64 | # Split into a list of point clouds based on crown IDs 65 | points.list <- split(sub2.dt, f=sub2.dt$ID) 66 | # Remove empty elements from the list 67 | 68 | # Pick the selected method 69 | if(type=="convexhull"){ 70 | # Create a list to store the convex hulls 71 | hull.list <- list() 72 | # Loop though the list 73 | for(i in 1:length(points.list)){ 74 | my.points.dt <- points.list[[i]] 75 | # Make a SpatialPointsDataFrame from all points 76 | my.points.spdf <- sp::SpatialPointsDataFrame(coords=cbind(X=my.points.dt$X, Y=my.points.dt$Y), data=my.points.dt, proj4string=proj4string) 77 | # Collect attributes 78 | my.ID <- my.points.spdf$ID[1] 79 | my.CentroidX <- mean(my.points.spdf$X, na.rm=T) 80 | my.CentroidY <- mean(my.points.spdf$Y, na.rm=T) 81 | my.CentroidZ <- mean(my.points.spdf$Z, na.rm=T) 82 | my.TreeH <- max(my.points.spdf$Z, na.rm=T) 83 | my.CrownBaseH <- min(my.points.spdf$Z, na.rm=T) 84 | my.CrownLength <- my.TreeH - my.CrownBaseH 85 | my.NPoints <- my.points.spdf$N[1] 86 | hull.list[[i]] <- rgeos::gConvexHull(my.points.spdf) 87 | hull.list[[i]] <- sp::SpatialPolygonsDataFrame(hull.list[[i]], data=data.frame(ID=my.ID, CentroidX=my.CentroidX, CentroidY=my.CentroidY, CentroidZ=my.CentroidZ, TreeH=my.TreeH, CrownBaseH=my.CrownBaseH, CrownLength=my.CrownLength, NPoints=my.NPoints)) 88 | } 89 | # Bind all list elements together in one SpatialPolygonsDataFrame 90 | hull.spdf <- do.call(raster::bind, hull.list) 91 | # Calculate area and perimeter of each polygon 92 | hull.spdf$ConvexHullArea <- rgeos::gArea(hull.spdf, byid=T) 93 | hull.spdf$ConvexHullPerimeter <- rgeos::gLength(hull.spdf, byid=T) 94 | return(hull.spdf) 95 | } else if(type=="ellipse"){ 96 | # Create a list to store the ellipse hulls 97 | ellipse.list <- list() 98 | ps.list <- list() 99 | # Loop though the list 100 | for(i in 1:length(points.list)){ 101 | my.points.dt <- points.list[[i]] 102 | # Make a SpatialPointsDataFrame from all points 103 | my.points.spdf <- sp::SpatialPointsDataFrame(coords=cbind(X=my.points.dt$X, Y=my.points.dt$Y), data=my.points.dt, proj4string=proj4string) 104 | # Collect attributes 105 | my.ID <- my.points.spdf$ID[1] 106 | my.CentroidX <- mean(my.points.spdf$X, na.rm=T) 107 | my.CentroidY <- mean(my.points.spdf$Y, na.rm=T) 108 | my.CentroidZ <- mean(my.points.spdf$Z, na.rm=T) 109 | my.TreeH <- max(my.points.spdf$Z, na.rm=T) 110 | my.TreeH <- max(my.points.spdf$Z, na.rm=T) 111 | my.CrownBaseH <- min(my.points.spdf$Z, na.rm=T) 112 | my.CrownLength <- my.TreeH - my.CrownBaseH 113 | my.NPoints <- my.points.spdf$N[1] 114 | # Combine the coordinates in a matrix 115 | my.points.mx <- as.matrix(cbind(my.points.spdf$X, my.points.spdf$Y)) 116 | # Fit an ellipse around the data 117 | ellipse <- cluster::ellipsoidhull(my.points.mx) 118 | # Calculate border points of the ellipse 119 | border.points <- cluster::predict.ellipsoid(ellipse) 120 | # Calculate the center of the ellipse 121 | center.point <- colMeans(border.points) 122 | names(center.point) <- c() 123 | # For each border point calculate the distance to the center 124 | dist2center <- (rowSums((t(t(border.points)-center.point))^2))^0.5 125 | # Calculate major and minor semi-axis by finding 126 | # maximal and minimal distance to the center 127 | major.semi.axis <- max(dist2center) 128 | minor.semi.axis <- min(dist2center) 129 | # Get coordinates of the ellipse point closest and farthest to the center 130 | min.dist.point <- border.points[dist2center == minor.semi.axis,] 131 | max.dist.point <- border.points[dist2center == major.semi.axis,] 132 | # Calculate a mean radius 133 | mean.radius <- mean(c(major.semi.axis, minor.semi.axis)) 134 | # Collect ellipse attributes 135 | ellipse.list[[i]] <- data.frame(ID=my.ID, CentroidX=my.CentroidX, CentroidY=my.CentroidY, CentroidZ=my.CentroidZ, TreeH=my.TreeH, 136 | CrownBaseH=my.CrownBaseH, CrownLength=my.CrownLength, NPoints=my.NPoints, 137 | EllipseCenterX=center.point[1], EllipseCenterY=center.point[2], MeanRadius=mean.radius, 138 | MinorSemiAxis=minor.semi.axis, MajorSemiAxis=major.semi.axis) 139 | # Make a polygon 140 | p = Polygon(border.points) 141 | # Add it to the Polygons list 142 | ps.list[[i]] <- Polygons(list(p), ID=i) 143 | } 144 | # Convert polygons to spatial polygons 145 | sps <- sp::SpatialPolygons(ps.list) 146 | # Bind all list elements together in one data.table 147 | ellipse.dt <- do.call(raster::bind, ellipse.list) 148 | # Convert them to a spatial polygon dataframe 149 | ellipse.spdf <- sp::SpatialPolygonsDataFrame(sps, data=ellipse.dt) 150 | # Calculate area and perimeter of each polygon 151 | ellipse.spdf$EllipseArea <- rgeos::gArea(ellipse.spdf, byid=T) 152 | ellipse.spdf$EllipsePerimeter <- rgeos::gLength(ellipse.spdf, byid=T) 153 | return(ellipse.spdf) 154 | } else if(type=="circle"){ 155 | # Create a list to store the circle hulls 156 | circle.list <- list() 157 | ps.list <- list() 158 | # Loop though the list 159 | for(i in 1:length(points.list)){ 160 | my.points.dt <- points.list[[i]] 161 | # Collect attributes 162 | my.ID <- points.list[[i]]$ID[1] 163 | my.CentroidX <- mean(my.points.dt$X, na.rm=T) 164 | my.CentroidY <- mean(my.points.dt$Y, na.rm=T) 165 | my.CentroidZ <- mean(my.points.dt$Z, na.rm=T) 166 | my.TreeH <- max(my.points.dt$Z, na.rm=T) 167 | my.CrownBaseH <- min(my.points.dt$Z, na.rm=T) 168 | my.CrownLength <- my.TreeH - my.CrownBaseH 169 | my.NPoints <- my.points.dt$N[1] 170 | # Add some very small random noise to the coordinates to avoid errors with duplicate 171 | # coordinate combinations in the circumcircle function 172 | my.points.dt[, X := X + 0.01*(runif(nrow(my.points.dt))-0.5)] 173 | my.points.dt[, Y := Y + 0.01*(runif(nrow(my.points.dt))-0.5)] 174 | # Find the smallest circumcircle of the points 175 | circle <- tripack::circumcircle(x=my.points.dt$X, y=my.points.dt$Y) 176 | # Extract center and radius of the circle 177 | CircleCenterX <- circle$x 178 | CircleCenterY <- circle$y 179 | CircleRadius <- circle$radius 180 | # Make the center a spatial object 181 | CircleCenter.sp <- sp::SpatialPoints(coords=data.frame(X=CircleCenterX, Y=CircleCenterY), proj4string=proj4string) 182 | # Create the circle polygon 183 | ps.list[[i]] <- rgeos::gBuffer(CircleCenter.sp, width=CircleRadius, quadsegs=15) 184 | circle.list[[i]] <- data.frame(ID=my.ID, CentroidX=my.CentroidX, CentroidY=my.CentroidY, CentroidZ=my.CentroidZ, TreeH=my.TreeH, 185 | CrownBaseH=my.CrownBaseH, CrownLength=my.CrownLength, NPoints=my.NPoints, 186 | CircleCenterX=CircleCenterX, CircleCenterY=CircleCenterY, Radius=CircleRadius) 187 | } 188 | # Bind all list elements together in one data.table 189 | circle.dt <- do.call(raster::bind, circle.list) 190 | # Bind all list elements together in one SpatialPolygonsDataFrame. 191 | circle.spdf <- do.call(raster::bind, ps.list) 192 | # Convert them to a spatial polygon dataframe 193 | circle.spdf <- sp::SpatialPolygonsDataFrame(circle.spdf, data=circle.dt) 194 | # Calculate area and perimeter of each polygon 195 | circle.spdf$CircleArea <- rgeos::gArea(circle.spdf, byid=T) 196 | circle.spdf$CirclePerimeter <- rgeos::gLength(circle.spdf, byid=T) 197 | return(circle.spdf) 198 | } 199 | } 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | SOFTWARE LICENSE 2 | The MeanShiftR R package allows individual tree crown delineation (ITCD) from 3 | airborne laser scanning point clouds (lidar) using the Adaptive Mean Shift 4 | 3D (AMS3D) clustering algorithm described by Ferraz et al. (2016). It 5 | further contains functions for parallelization of the clustering and post- 6 | processing such as fitting polygons around tree crowns and matching 7 | detected crowns with stem positions on the ground. 8 | 9 | COPYRIGHT NOTICE 10 | © 2018, Helmholtz-Zentrum für Umweltforschung GmbH – UFZ. All rights reserved. 11 | 12 | The code is a property of: 13 | Helmholtz-Zentrum für Umweltforschung GmbH – UFZ 14 | Registered Office: Leipzig 15 | Registration Office: Amtsgericht Leipzig 16 | Trade Register Nr. B 4703 17 | Chairman of the Supervisory Board: MinDirig'in Oda Keppler 18 | Scientific Director: Prof. Dr. Georg Teutsch 19 | Administrative Director: Dr. Sabine König 20 | 21 | Author and contact: 22 | Dr. Nikolai Knapp (nikolai.knapp@ufz.de) 23 | Permoserstraße 15, D-04318 Leipzig, Germany 24 | 25 | This file is part of the MeanShiftR R package. 26 | 27 | The MeanShiftR R package is free software: you can redistribute 28 | it and/or modify it under the terms of the GNU General Public License 29 | as published by the Free Software Foundation, either version 3 of the 30 | License, or (at your option) any later version. 31 | 32 | MeanShiftR is distributed in the hope that it will be useful, 33 | but WITHOUT ANY WARRANTY; without even the implied warranty of 34 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 35 | GNU General Public License for more details. 36 | 37 | You should have received a copy of the GNU General Public License 38 | along with MeanShiftR. If not, see . 39 | 40 | Redistribution 41 | Redistribution and use in source and binary forms, with or without 42 | modification, are permitted provided that the following conditions are met: 43 | - Redistributions of source code must retain the above copyright notice, 44 | the list of conditions for redistribution and modification as well as 45 | the following GNU General Public License. 46 | 47 | - Redistributions in binary form must reproduce the above copyright notice, 48 | this list of conditions, the following GNU General Public License and the 49 | modification conditions in the documentation and/or other materials 50 | provided with the distribution. 51 | 52 | - Neither the name of Helmholtz-Zentrum für Umweltforschung GmbH – UFZ, nor 53 | the names of its contributors may be used to endorse or promote products 54 | derived from this software without specific prior written permission. 55 | 56 | Modification 57 | If software is modified to produce derivative works, such modified software 58 | should be clearly marked, so as not to confuse it with the version available 59 | from Helmholtz-Zentrum für Umweltforschung GmbH – UFZ. 60 | 61 | 62 | 63 | 64 | GNU GENERAL PUBLIC LICENSE 65 | Version 3, 29 June 2007 66 | 67 | Copyright (C) 2007 Free Software Foundation, Inc. 68 | Everyone is permitted to copy and distribute verbatim copies 69 | of this license document, but changing it is not allowed. 70 | 71 | Preamble 72 | 73 | The GNU General Public License is a free, copyleft license for 74 | software and other kinds of works. 75 | 76 | The licenses for most software and other practical works are designed 77 | to take away your freedom to share and change the works. By contrast, 78 | the GNU General Public License is intended to guarantee your freedom to 79 | share and change all versions of a program--to make sure it remains free 80 | software for all its users. We, the Free Software Foundation, use the 81 | GNU General Public License for most of our software; it applies also to 82 | any other work released this way by its authors. You can apply it to 83 | your programs, too. 84 | 85 | When we speak of free software, we are referring to freedom, not 86 | price. Our General Public Licenses are designed to make sure that you 87 | have the freedom to distribute copies of free software (and charge for 88 | them if you wish), that you receive source code or can get it if you 89 | want it, that you can change the software or use pieces of it in new 90 | free programs, and that you know you can do these things. 91 | 92 | To protect your rights, we need to prevent others from denying you 93 | these rights or asking you to surrender the rights. Therefore, you have 94 | certain responsibilities if you distribute copies of the software, or if 95 | you modify it: responsibilities to respect the freedom of others. 96 | 97 | For example, if you distribute copies of such a program, whether 98 | gratis or for a fee, you must pass on to the recipients the same 99 | freedoms that you received. You must make sure that they, too, receive 100 | or can get the source code. And you must show them these terms so they 101 | know their rights. 102 | 103 | Developers that use the GNU GPL protect your rights with two steps: 104 | (1) assert copyright on the software, and (2) offer you this License 105 | giving you legal permission to copy, distribute and/or modify it. 106 | 107 | For the developers' and authors' protection, the GPL clearly explains 108 | that there is no warranty for this free software. For both users' and 109 | authors' sake, the GPL requires that modified versions be marked as 110 | changed, so that their problems will not be attributed erroneously to 111 | authors of previous versions. 112 | 113 | Some devices are designed to deny users access to install or run 114 | modified versions of the software inside them, although the manufacturer 115 | can do so. This is fundamentally incompatible with the aim of 116 | protecting users' freedom to change the software. The systematic 117 | pattern of such abuse occurs in the area of products for individuals to 118 | use, which is precisely where it is most unacceptable. Therefore, we 119 | have designed this version of the GPL to prohibit the practice for those 120 | products. If such problems arise substantially in other domains, we 121 | stand ready to extend this provision to those domains in future versions 122 | of the GPL, as needed to protect the freedom of users. 123 | 124 | Finally, every program is threatened constantly by software patents. 125 | States should not allow patents to restrict development and use of 126 | software on general-purpose computers, but in those that do, we wish to 127 | avoid the special danger that patents applied to a free program could 128 | make it effectively proprietary. To prevent this, the GPL assures that 129 | patents cannot be used to render the program non-free. 130 | 131 | The precise terms and conditions for copying, distribution and 132 | modification follow. 133 | 134 | TERMS AND CONDITIONS 135 | 136 | 0. Definitions. 137 | 138 | "This License" refers to version 3 of the GNU General Public License. 139 | 140 | "Copyright" also means copyright-like laws that apply to other kinds of 141 | works, such as semiconductor masks. 142 | 143 | "The Program" refers to any copyrightable work licensed under this 144 | License. Each licensee is addressed as "you". "Licensees" and 145 | "recipients" may be individuals or organizations. 146 | 147 | To "modify" a work means to copy from or adapt all or part of the work 148 | in a fashion requiring copyright permission, other than the making of an 149 | exact copy. The resulting work is called a "modified version" of the 150 | earlier work or a work "based on" the earlier work. 151 | 152 | A "covered work" means either the unmodified Program or a work based 153 | on the Program. 154 | 155 | To "propagate" a work means to do anything with it that, without 156 | permission, would make you directly or secondarily liable for 157 | infringement under applicable copyright law, except executing it on a 158 | computer or modifying a private copy. Propagation includes copying, 159 | distribution (with or without modification), making available to the 160 | public, and in some countries other activities as well. 161 | 162 | To "convey" a work means any kind of propagation that enables other 163 | parties to make or receive copies. Mere interaction with a user through 164 | a computer network, with no transfer of a copy, is not conveying. 165 | 166 | An interactive user interface displays "Appropriate Legal Notices" 167 | to the extent that it includes a convenient and prominently visible 168 | feature that (1) displays an appropriate copyright notice, and (2) 169 | tells the user that there is no warranty for the work (except to the 170 | extent that warranties are provided), that licensees may convey the 171 | work under this License, and how to view a copy of this License. If 172 | the interface presents a list of user commands or options, such as a 173 | menu, a prominent item in the list meets this criterion. 174 | 175 | 1. Source Code. 176 | 177 | The "source code" for a work means the preferred form of the work 178 | for making modifications to it. "Object code" means any non-source 179 | form of a work. 180 | 181 | A "Standard Interface" means an interface that either is an official 182 | standard defined by a recognized standards body, or, in the case of 183 | interfaces specified for a particular programming language, one that 184 | is widely used among developers working in that language. 185 | 186 | The "System Libraries" of an executable work include anything, other 187 | than the work as a whole, that (a) is included in the normal form of 188 | packaging a Major Component, but which is not part of that Major 189 | Component, and (b) serves only to enable use of the work with that 190 | Major Component, or to implement a Standard Interface for which an 191 | implementation is available to the public in source code form. A 192 | "Major Component", in this context, means a major essential component 193 | (kernel, window system, and so on) of the specific operating system 194 | (if any) on which the executable work runs, or a compiler used to 195 | produce the work, or an object code interpreter used to run it. 196 | 197 | The "Corresponding Source" for a work in object code form means all 198 | the source code needed to generate, install, and (for an executable 199 | work) run the object code and to modify the work, including scripts to 200 | control those activities. However, it does not include the work's 201 | System Libraries, or general-purpose tools or generally available free 202 | programs which are used unmodified in performing those activities but 203 | which are not part of the work. For example, Corresponding Source 204 | includes interface definition files associated with source files for 205 | the work, and the source code for shared libraries and dynamically 206 | linked subprograms that the work is specifically designed to require, 207 | such as by intimate data communication or control flow between those 208 | subprograms and other parts of the work. 209 | 210 | The Corresponding Source need not include anything that users 211 | can regenerate automatically from other parts of the Corresponding 212 | Source. 213 | 214 | The Corresponding Source for a work in source code form is that 215 | same work. 216 | 217 | 2. Basic Permissions. 218 | 219 | All rights granted under this License are granted for the term of 220 | copyright on the Program, and are irrevocable provided the stated 221 | conditions are met. This License explicitly affirms your unlimited 222 | permission to run the unmodified Program. The output from running a 223 | covered work is covered by this License only if the output, given its 224 | content, constitutes a covered work. This License acknowledges your 225 | rights of fair use or other equivalent, as provided by copyright law. 226 | 227 | You may make, run and propagate covered works that you do not 228 | convey, without conditions so long as your license otherwise remains 229 | in force. You may convey covered works to others for the sole purpose 230 | of having them make modifications exclusively for you, or provide you 231 | with facilities for running those works, provided that you comply with 232 | the terms of this License in conveying all material for which you do 233 | not control copyright. Those thus making or running the covered works 234 | for you must do so exclusively on your behalf, under your direction 235 | and control, on terms that prohibit them from making any copies of 236 | your copyrighted material outside their relationship with you. 237 | 238 | Conveying under any other circumstances is permitted solely under 239 | the conditions stated below. Sublicensing is not allowed; section 10 240 | makes it unnecessary. 241 | 242 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 243 | 244 | No covered work shall be deemed part of an effective technological 245 | measure under any applicable law fulfilling obligations under article 246 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 247 | similar laws prohibiting or restricting circumvention of such 248 | measures. 249 | 250 | When you convey a covered work, you waive any legal power to forbid 251 | circumvention of technological measures to the extent such circumvention 252 | is effected by exercising rights under this License with respect to 253 | the covered work, and you disclaim any intention to limit operation or 254 | modification of the work as a means of enforcing, against the work's 255 | users, your or third parties' legal rights to forbid circumvention of 256 | technological measures. 257 | 258 | 4. Conveying Verbatim Copies. 259 | 260 | You may convey verbatim copies of the Program's source code as you 261 | receive it, in any medium, provided that you conspicuously and 262 | appropriately publish on each copy an appropriate copyright notice; 263 | keep intact all notices stating that this License and any 264 | non-permissive terms added in accord with section 7 apply to the code; 265 | keep intact all notices of the absence of any warranty; and give all 266 | recipients a copy of this License along with the Program. 267 | 268 | You may charge any price or no price for each copy that you convey, 269 | and you may offer support or warranty protection for a fee. 270 | 271 | 5. Conveying Modified Source Versions. 272 | 273 | You may convey a work based on the Program, or the modifications to 274 | produce it from the Program, in the form of source code under the 275 | terms of section 4, provided that you also meet all of these conditions: 276 | 277 | a) The work must carry prominent notices stating that you modified 278 | it, and giving a relevant date. 279 | 280 | b) The work must carry prominent notices stating that it is 281 | released under this License and any conditions added under section 282 | 7. This requirement modifies the requirement in section 4 to 283 | "keep intact all notices". 284 | 285 | c) You must license the entire work, as a whole, under this 286 | License to anyone who comes into possession of a copy. This 287 | License will therefore apply, along with any applicable section 7 288 | additional terms, to the whole of the work, and all its parts, 289 | regardless of how they are packaged. This License gives no 290 | permission to license the work in any other way, but it does not 291 | invalidate such permission if you have separately received it. 292 | 293 | d) If the work has interactive user interfaces, each must display 294 | Appropriate Legal Notices; however, if the Program has interactive 295 | interfaces that do not display Appropriate Legal Notices, your 296 | work need not make them do so. 297 | 298 | A compilation of a covered work with other separate and independent 299 | works, which are not by their nature extensions of the covered work, 300 | and which are not combined with it such as to form a larger program, 301 | in or on a volume of a storage or distribution medium, is called an 302 | "aggregate" if the compilation and its resulting copyright are not 303 | used to limit the access or legal rights of the compilation's users 304 | beyond what the individual works permit. Inclusion of a covered work 305 | in an aggregate does not cause this License to apply to the other 306 | parts of the aggregate. 307 | 308 | 6. Conveying Non-Source Forms. 309 | 310 | You may convey a covered work in object code form under the terms 311 | of sections 4 and 5, provided that you also convey the 312 | machine-readable Corresponding Source under the terms of this License, 313 | in one of these ways: 314 | 315 | a) Convey the object code in, or embodied in, a physical product 316 | (including a physical distribution medium), accompanied by the 317 | Corresponding Source fixed on a durable physical medium 318 | customarily used for software interchange. 319 | 320 | b) Convey the object code in, or embodied in, a physical product 321 | (including a physical distribution medium), accompanied by a 322 | written offer, valid for at least three years and valid for as 323 | long as you offer spare parts or customer support for that product 324 | model, to give anyone who possesses the object code either (1) a 325 | copy of the Corresponding Source for all the software in the 326 | product that is covered by this License, on a durable physical 327 | medium customarily used for software interchange, for a price no 328 | more than your reasonable cost of physically performing this 329 | conveying of source, or (2) access to copy the 330 | Corresponding Source from a network server at no charge. 331 | 332 | c) Convey individual copies of the object code with a copy of the 333 | written offer to provide the Corresponding Source. This 334 | alternative is allowed only occasionally and noncommercially, and 335 | only if you received the object code with such an offer, in accord 336 | with subsection 6b. 337 | 338 | d) Convey the object code by offering access from a designated 339 | place (gratis or for a charge), and offer equivalent access to the 340 | Corresponding Source in the same way through the same place at no 341 | further charge. You need not require recipients to copy the 342 | Corresponding Source along with the object code. If the place to 343 | copy the object code is a network server, the Corresponding Source 344 | may be on a different server (operated by you or a third party) 345 | that supports equivalent copying facilities, provided you maintain 346 | clear directions next to the object code saying where to find the 347 | Corresponding Source. Regardless of what server hosts the 348 | Corresponding Source, you remain obligated to ensure that it is 349 | available for as long as needed to satisfy these requirements. 350 | 351 | e) Convey the object code using peer-to-peer transmission, provided 352 | you inform other peers where the object code and Corresponding 353 | Source of the work are being offered to the general public at no 354 | charge under subsection 6d. 355 | 356 | A separable portion of the object code, whose source code is excluded 357 | from the Corresponding Source as a System Library, need not be 358 | included in conveying the object code work. 359 | 360 | A "User Product" is either (1) a "consumer product", which means any 361 | tangible personal property which is normally used for personal, family, 362 | or household purposes, or (2) anything designed or sold for incorporation 363 | into a dwelling. In determining whether a product is a consumer product, 364 | doubtful cases shall be resolved in favor of coverage. For a particular 365 | product received by a particular user, "normally used" refers to a 366 | typical or common use of that class of product, regardless of the status 367 | of the particular user or of the way in which the particular user 368 | actually uses, or expects or is expected to use, the product. A product 369 | is a consumer product regardless of whether the product has substantial 370 | commercial, industrial or non-consumer uses, unless such uses represent 371 | the only significant mode of use of the product. 372 | 373 | "Installation Information" for a User Product means any methods, 374 | procedures, authorization keys, or other information required to install 375 | and execute modified versions of a covered work in that User Product from 376 | a modified version of its Corresponding Source. The information must 377 | suffice to ensure that the continued functioning of the modified object 378 | code is in no case prevented or interfered with solely because 379 | modification has been made. 380 | 381 | If you convey an object code work under this section in, or with, or 382 | specifically for use in, a User Product, and the conveying occurs as 383 | part of a transaction in which the right of possession and use of the 384 | User Product is transferred to the recipient in perpetuity or for a 385 | fixed term (regardless of how the transaction is characterized), the 386 | Corresponding Source conveyed under this section must be accompanied 387 | by the Installation Information. But this requirement does not apply 388 | if neither you nor any third party retains the ability to install 389 | modified object code on the User Product (for example, the work has 390 | been installed in ROM). 391 | 392 | The requirement to provide Installation Information does not include a 393 | requirement to continue to provide support service, warranty, or updates 394 | for a work that has been modified or installed by the recipient, or for 395 | the User Product in which it has been modified or installed. Access to a 396 | network may be denied when the modification itself materially and 397 | adversely affects the operation of the network or violates the rules and 398 | protocols for communication across the network. 399 | 400 | Corresponding Source conveyed, and Installation Information provided, 401 | in accord with this section must be in a format that is publicly 402 | documented (and with an implementation available to the public in 403 | source code form), and must require no special password or key for 404 | unpacking, reading or copying. 405 | 406 | 7. Additional Terms. 407 | 408 | "Additional permissions" are terms that supplement the terms of this 409 | License by making exceptions from one or more of its conditions. 410 | Additional permissions that are applicable to the entire Program shall 411 | be treated as though they were included in this License, to the extent 412 | that they are valid under applicable law. If additional permissions 413 | apply only to part of the Program, that part may be used separately 414 | under those permissions, but the entire Program remains governed by 415 | this License without regard to the additional permissions. 416 | 417 | When you convey a copy of a covered work, you may at your option 418 | remove any additional permissions from that copy, or from any part of 419 | it. (Additional permissions may be written to require their own 420 | removal in certain cases when you modify the work.) You may place 421 | additional permissions on material, added by you to a covered work, 422 | for which you have or can give appropriate copyright permission. 423 | 424 | Notwithstanding any other provision of this License, for material you 425 | add to a covered work, you may (if authorized by the copyright holders of 426 | that material) supplement the terms of this License with terms: 427 | 428 | a) Disclaiming warranty or limiting liability differently from the 429 | terms of sections 15 and 16 of this License; or 430 | 431 | b) Requiring preservation of specified reasonable legal notices or 432 | author attributions in that material or in the Appropriate Legal 433 | Notices displayed by works containing it; or 434 | 435 | c) Prohibiting misrepresentation of the origin of that material, or 436 | requiring that modified versions of such material be marked in 437 | reasonable ways as different from the original version; or 438 | 439 | d) Limiting the use for publicity purposes of names of licensors or 440 | authors of the material; or 441 | 442 | e) Declining to grant rights under trademark law for use of some 443 | trade names, trademarks, or service marks; or 444 | 445 | f) Requiring indemnification of licensors and authors of that 446 | material by anyone who conveys the material (or modified versions of 447 | it) with contractual assumptions of liability to the recipient, for 448 | any liability that these contractual assumptions directly impose on 449 | those licensors and authors. 450 | 451 | All other non-permissive additional terms are considered "further 452 | restrictions" within the meaning of section 10. If the Program as you 453 | received it, or any part of it, contains a notice stating that it is 454 | governed by this License along with a term that is a further 455 | restriction, you may remove that term. If a license document contains 456 | a further restriction but permits relicensing or conveying under this 457 | License, you may add to a covered work material governed by the terms 458 | of that license document, provided that the further restriction does 459 | not survive such relicensing or conveying. 460 | 461 | If you add terms to a covered work in accord with this section, you 462 | must place, in the relevant source files, a statement of the 463 | additional terms that apply to those files, or a notice indicating 464 | where to find the applicable terms. 465 | 466 | Additional terms, permissive or non-permissive, may be stated in the 467 | form of a separately written license, or stated as exceptions; 468 | the above requirements apply either way. 469 | 470 | 8. Termination. 471 | 472 | You may not propagate or modify a covered work except as expressly 473 | provided under this License. Any attempt otherwise to propagate or 474 | modify it is void, and will automatically terminate your rights under 475 | this License (including any patent licenses granted under the third 476 | paragraph of section 11). 477 | 478 | However, if you cease all violation of this License, then your 479 | license from a particular copyright holder is reinstated (a) 480 | provisionally, unless and until the copyright holder explicitly and 481 | finally terminates your license, and (b) permanently, if the copyright 482 | holder fails to notify you of the violation by some reasonable means 483 | prior to 60 days after the cessation. 484 | 485 | Moreover, your license from a particular copyright holder is 486 | reinstated permanently if the copyright holder notifies you of the 487 | violation by some reasonable means, this is the first time you have 488 | received notice of violation of this License (for any work) from that 489 | copyright holder, and you cure the violation prior to 30 days after 490 | your receipt of the notice. 491 | 492 | Termination of your rights under this section does not terminate the 493 | licenses of parties who have received copies or rights from you under 494 | this License. If your rights have been terminated and not permanently 495 | reinstated, you do not qualify to receive new licenses for the same 496 | material under section 10. 497 | 498 | 9. Acceptance Not Required for Having Copies. 499 | 500 | You are not required to accept this License in order to receive or 501 | run a copy of the Program. Ancillary propagation of a covered work 502 | occurring solely as a consequence of using peer-to-peer transmission 503 | to receive a copy likewise does not require acceptance. However, 504 | nothing other than this License grants you permission to propagate or 505 | modify any covered work. These actions infringe copyright if you do 506 | not accept this License. Therefore, by modifying or propagating a 507 | covered work, you indicate your acceptance of this License to do so. 508 | 509 | 10. Automatic Licensing of Downstream Recipients. 510 | 511 | Each time you convey a covered work, the recipient automatically 512 | receives a license from the original licensors, to run, modify and 513 | propagate that work, subject to this License. You are not responsible 514 | for enforcing compliance by third parties with this License. 515 | 516 | An "entity transaction" is a transaction transferring control of an 517 | organization, or substantially all assets of one, or subdividing an 518 | organization, or merging organizations. If propagation of a covered 519 | work results from an entity transaction, each party to that 520 | transaction who receives a copy of the work also receives whatever 521 | licenses to the work the party's predecessor in interest had or could 522 | give under the previous paragraph, plus a right to possession of the 523 | Corresponding Source of the work from the predecessor in interest, if 524 | the predecessor has it or can get it with reasonable efforts. 525 | 526 | You may not impose any further restrictions on the exercise of the 527 | rights granted or affirmed under this License. For example, you may 528 | not impose a license fee, royalty, or other charge for exercise of 529 | rights granted under this License, and you may not initiate litigation 530 | (including a cross-claim or counterclaim in a lawsuit) alleging that 531 | any patent claim is infringed by making, using, selling, offering for 532 | sale, or importing the Program or any portion of it. 533 | 534 | 11. Patents. 535 | 536 | A "contributor" is a copyright holder who authorizes use under this 537 | License of the Program or a work on which the Program is based. The 538 | work thus licensed is called the contributor's "contributor version". 539 | 540 | A contributor's "essential patent claims" are all patent claims 541 | owned or controlled by the contributor, whether already acquired or 542 | hereafter acquired, that would be infringed by some manner, permitted 543 | by this License, of making, using, or selling its contributor version, 544 | but do not include claims that would be infringed only as a 545 | consequence of further modification of the contributor version. For 546 | purposes of this definition, "control" includes the right to grant 547 | patent sublicenses in a manner consistent with the requirements of 548 | this License. 549 | 550 | Each contributor grants you a non-exclusive, worldwide, royalty-free 551 | patent license under the contributor's essential patent claims, to 552 | make, use, sell, offer for sale, import and otherwise run, modify and 553 | propagate the contents of its contributor version. 554 | 555 | In the following three paragraphs, a "patent license" is any express 556 | agreement or commitment, however denominated, not to enforce a patent 557 | (such as an express permission to practice a patent or covenant not to 558 | sue for patent infringement). To "grant" such a patent license to a 559 | party means to make such an agreement or commitment not to enforce a 560 | patent against the party. 561 | 562 | If you convey a covered work, knowingly relying on a patent license, 563 | and the Corresponding Source of the work is not available for anyone 564 | to copy, free of charge and under the terms of this License, through a 565 | publicly available network server or other readily accessible means, 566 | then you must either (1) cause the Corresponding Source to be so 567 | available, or (2) arrange to deprive yourself of the benefit of the 568 | patent license for this particular work, or (3) arrange, in a manner 569 | consistent with the requirements of this License, to extend the patent 570 | license to downstream recipients. "Knowingly relying" means you have 571 | actual knowledge that, but for the patent license, your conveying the 572 | covered work in a country, or your recipient's use of the covered work 573 | in a country, would infringe one or more identifiable patents in that 574 | country that you have reason to believe are valid. 575 | 576 | If, pursuant to or in connection with a single transaction or 577 | arrangement, you convey, or propagate by procuring conveyance of, a 578 | covered work, and grant a patent license to some of the parties 579 | receiving the covered work authorizing them to use, propagate, modify 580 | or convey a specific copy of the covered work, then the patent license 581 | you grant is automatically extended to all recipients of the covered 582 | work and works based on it. 583 | 584 | A patent license is "discriminatory" if it does not include within 585 | the scope of its coverage, prohibits the exercise of, or is 586 | conditioned on the non-exercise of one or more of the rights that are 587 | specifically granted under this License. You may not convey a covered 588 | work if you are a party to an arrangement with a third party that is 589 | in the business of distributing software, under which you make payment 590 | to the third party based on the extent of your activity of conveying 591 | the work, and under which the third party grants, to any of the 592 | parties who would receive the covered work from you, a discriminatory 593 | patent license (a) in connection with copies of the covered work 594 | conveyed by you (or copies made from those copies), or (b) primarily 595 | for and in connection with specific products or compilations that 596 | contain the covered work, unless you entered into that arrangement, 597 | or that patent license was granted, prior to 28 March 2007. 598 | 599 | Nothing in this License shall be construed as excluding or limiting 600 | any implied license or other defenses to infringement that may 601 | otherwise be available to you under applicable patent law. 602 | 603 | 12. No Surrender of Others' Freedom. 604 | 605 | If conditions are imposed on you (whether by court order, agreement or 606 | otherwise) that contradict the conditions of this License, they do not 607 | excuse you from the conditions of this License. If you cannot convey a 608 | covered work so as to satisfy simultaneously your obligations under this 609 | License and any other pertinent obligations, then as a consequence you may 610 | not convey it at all. For example, if you agree to terms that obligate you 611 | to collect a royalty for further conveying from those to whom you convey 612 | the Program, the only way you could satisfy both those terms and this 613 | License would be to refrain entirely from conveying the Program. 614 | 615 | 13. Use with the GNU Affero General Public License. 616 | 617 | Notwithstanding any other provision of this License, you have 618 | permission to link or combine any covered work with a work licensed 619 | under version 3 of the GNU Affero General Public License into a single 620 | combined work, and to convey the resulting work. The terms of this 621 | License will continue to apply to the part which is the covered work, 622 | but the special requirements of the GNU Affero General Public License, 623 | section 13, concerning interaction through a network will apply to the 624 | combination as such. 625 | 626 | 14. Revised Versions of this License. 627 | 628 | The Free Software Foundation may publish revised and/or new versions of 629 | the GNU General Public License from time to time. Such new versions will 630 | be similar in spirit to the present version, but may differ in detail to 631 | address new problems or concerns. 632 | 633 | Each version is given a distinguishing version number. If the 634 | Program specifies that a certain numbered version of the GNU General 635 | Public License "or any later version" applies to it, you have the 636 | option of following the terms and conditions either of that numbered 637 | version or of any later version published by the Free Software 638 | Foundation. If the Program does not specify a version number of the 639 | GNU General Public License, you may choose any version ever published 640 | by the Free Software Foundation. 641 | 642 | If the Program specifies that a proxy can decide which future 643 | versions of the GNU General Public License can be used, that proxy's 644 | public statement of acceptance of a version permanently authorizes you 645 | to choose that version for the Program. 646 | 647 | Later license versions may give you additional or different 648 | permissions. However, no additional obligations are imposed on any 649 | author or copyright holder as a result of your choosing to follow a 650 | later version. 651 | 652 | 15. Disclaimer of Warranty. 653 | 654 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 655 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 656 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 657 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 658 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 659 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 660 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 661 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 662 | 663 | 16. Limitation of Liability. 664 | 665 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 666 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 667 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 668 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 669 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 670 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 671 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 672 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 673 | SUCH DAMAGES. 674 | 675 | 17. Interpretation of Sections 15 and 16. 676 | 677 | If the disclaimer of warranty and limitation of liability provided 678 | above cannot be given local legal effect according to their terms, 679 | reviewing courts shall apply local law that most closely approximates 680 | an absolute waiver of all civil liability in connection with the 681 | Program, unless a warranty or assumption of liability accompanies a 682 | copy of the Program in return for a fee. 683 | 684 | END OF TERMS AND CONDITIONS 685 | 686 | How to Apply These Terms to Your New Programs 687 | 688 | If you develop a new program, and you want it to be of the greatest 689 | possible use to the public, the best way to achieve this is to make it 690 | free software which everyone can redistribute and change under these terms. 691 | 692 | To do so, attach the following notices to the program. It is safest 693 | to attach them to the start of each source file to most effectively 694 | state the exclusion of warranty; and each file should have at least 695 | the "copyright" line and a pointer to where the full notice is found. 696 | 697 | 698 | Copyright (C) 699 | 700 | This program is free software: you can redistribute it and/or modify 701 | it under the terms of the GNU General Public License as published by 702 | the Free Software Foundation, either version 3 of the License, or 703 | (at your option) any later version. 704 | 705 | This program is distributed in the hope that it will be useful, 706 | but WITHOUT ANY WARRANTY; without even the implied warranty of 707 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 708 | GNU General Public License for more details. 709 | 710 | You should have received a copy of the GNU General Public License 711 | along with this program. If not, see . 712 | 713 | Also add information on how to contact you by electronic and paper mail. 714 | 715 | If the program does terminal interaction, make it output a short 716 | notice like this when it starts in an interactive mode: 717 | 718 | Copyright (C) 719 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 720 | This is free software, and you are welcome to redistribute it 721 | under certain conditions; type `show c' for details. 722 | 723 | The hypothetical commands `show w' and `show c' should show the appropriate 724 | parts of the General Public License. Of course, your program's commands 725 | might be different; for a GUI interface, you would use an "about box". 726 | 727 | You should also get your employer (if you work as a programmer) or school, 728 | if any, to sign a "copyright disclaimer" for the program, if necessary. 729 | For more information on this, and how to apply and follow the GNU GPL, see 730 | . 731 | 732 | The GNU General Public License does not permit incorporating your program 733 | into proprietary programs. If your program is a subroutine library, you 734 | may consider it more useful to permit linking proprietary applications with 735 | the library. If this is what you want to do, use the GNU Lesser General 736 | Public License instead of this License. But first, please read 737 | . 738 | --------------------------------------------------------------------------------