├── .Rbuildignore
├── .gitignore
├── CspStandSegmentation.Rproj
├── DESCRIPTION
├── LICENSE
├── NAMESPACE
├── R
├── 2021-11-12_A1_JF_csp_cost_functions.R
├── 2024-06-10_A1_JF_farthest_point_sampling.R
├── 2025-01-07_A1_JF_merge_las_objects.R
├── 2025-01-10_A1_JF_forest_inventory.R
└── RcppExports.R
├── README.md
├── inst
├── extdata
│ └── beech.las
└── figures
│ ├── csp_logo.png
│ └── csp_logo.svg
├── man
├── add_geometry.Rd
├── add_las_attributes.Rd
├── add_voxel_coordinates.Rd
├── comparative_shortest_path.Rd
├── csp_cost_segmentation.Rd
├── eigen_decomposition.Rd
├── fast_unlist.Rd
├── fast_unlist_dist.Rd
├── fds.Rd
├── find_base_coordinates_geom.Rd
├── find_base_coordinates_raster.Rd
├── forest_inventory.Rd
├── forest_inventory_simple.Rd
├── las_merge.Rd
├── p_dist.Rd
├── p_mat_dist.Rd
├── plot_inventory.Rd
├── point_center_angle.Rd
├── point_circle_distance.Rd
├── ransac_circle_fit.Rd
├── suppress_cat.Rd
└── voxelize_points_mean_attributes.Rd
├── src
├── 2021-11-12_A1_JF_csp_cost_cpp_functions.cpp
├── Makevars.win
└── RcppExports.cpp
└── tests
├── testthat.R
└── testthat
├── test-add_geometry.R
├── test-add_las_attributes.R
├── test-add_voxel_coordinates.R
├── test-csp_cost_segmentation.R
└── test-voxelize_points_mean_attributes.R
/.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 |
--------------------------------------------------------------------------------
/CspStandSegmentation.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: CspStandSegmentation
2 | Type: Package
3 | Title: Comparative Shortest Path Stand Segmentation
4 | Version: 0.1.2
5 | Authors@R: c(person("Julian", "Frey", , "julian.frey@wwd.uni-freiburg.de", role = c("aut", "cre"), comment = c(ORCID = "0000-0001-7895-702X")),person("Zoe", "Schindler", , "zoe.schindler@wwd.uni-freiburg.de", role = c("ctb"), comment = c(ORCID = "0000-0003-2972-1920")))
6 | Description: This package provides a function to segment trees from a stand scanned with terrestrial laser scanning. It strongly builds upon the work of the lidR and the TreeLS packages.
7 | License: GPL-3 + file LICENSE
8 | Encoding: UTF-8
9 | LazyData: true
10 | Imports: Rcpp (>= 1.0.5), lidR, dbscan, igraph, foreach, parallel, doParallel,magrittr, data.table, sf, terra, RCSF, conicfit
11 | LinkingTo: Rcpp, RcppArmadillo, lidR, BH
12 | RoxygenNote: 7.3.2
13 | Suggests:
14 | testthat (>= 3.0.0)
15 | Config/testthat/edition: 3
16 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/NAMESPACE:
--------------------------------------------------------------------------------
1 | exportPattern("^[[:alpha:]]+")
2 | importFrom(Rcpp, evalCpp)
3 | importFrom(magrittr, "%>%")
4 | import(lidR)
5 | import(data.table)
6 | import(dbscan)
7 | import(igraph)
8 | import(foreach)
9 | importFrom("stats", "aggregate", "median", "quantile")
10 | export(csp_cost_segmentation)
11 | useDynLib(CspStandSegmentation, .registration = TRUE)
12 |
--------------------------------------------------------------------------------
/R/2021-11-12_A1_JF_csp_cost_functions.R:
--------------------------------------------------------------------------------
1 | # load packages
2 | invisible(lapply(c('lidR','dbscan', 'igraph', 'foreach'), require, character.only = TRUE))
3 |
4 | # ------------------------------------------------------------------------------
5 |
6 | # thx zoe https://github.com/zoeschindler/masterarbeit/blob/main/03_raster_calculation_functions.R
7 |
8 | #' Add geometric features to a LAS object
9 | #'
10 | #' The function calls a fast cpp multi-core function to calculate eigenvalues
11 | #' for the points in a point cloud based on the k nearest neighbors. Afterwards
12 | #' it adds geometric features like Curvature, Linearity, Planarity, Sphericity,
13 | #' Anisotrophy and Verticlity to the points itself.
14 | #'
15 | #' Details of the metrics can be found in: \ Hackel, T., Wegner, J.D. &
16 | #' Schindler, K. (2016) Contour Detection in Unstructured 3D Point Clouds. In
17 | #' 2016 IEEE Conference on Computer Vision and Pattern Recognition (CVPR).
18 | #' Presented at the 2016 IEEE Conference on Computer Vision and Pattern
19 | #' Recognition (CVPR), IEEE, Las Vegas, NV, USA, pp. 1610–1618.
20 | #'
21 | #' @param las A LAS object (see lidR::LAS)
22 | #' @param k the k nearest neighbors to use for the eigenvalue calculation
23 | #' @param n_cores The number of CPU cores to use
24 | #' @return The function returns a single LAS object with the geometric features
25 | #' attached to it in the LAS@data section.
26 | #' @author Julian Frey
27 | #' @examples
28 | #'
29 | #' LASfile <- system.file("extdata", "MixedConifer.laz", package="lidR")
30 | #' las <- lidR::readLAS(LASfile, select = "xyz", filter = "-inside 481250 3812980 481300 3813030")
31 | #'
32 | #' las <- add_geometry(las, k = 5, n_cores = parallel::detectCores()-1)
33 | #' summary(las@data)
34 | #'
35 | #'
36 | #' @export add_geometry
37 | add_geometry <- function(las, k = 10L, n_cores = 1) {
38 | # check if inputs of the right type
39 | if (!lidR::is(las,"LAS")) {
40 | stop('las has to be a LAS object.')
41 | }
42 | if(!(as.integer(k) == k & length(k) == 1 & k > 0 )) {
43 | stop('k has to be one positive integer.')
44 | }
45 | # necessary for raster_geometry
46 | # returns geometric features based on eigenvalues
47 | eigen <- eigen_decomposition(las, k, n_cores) # k neighbours, n cores
48 | las <- las |>
49 | add_lasattribute(eigen[,3] / (eigen[,1] + eigen[,2] + eigen[, 3]), 'Curvature', 'curvature') |>
50 | add_lasattribute((eigen[,1] - eigen[,2]) / eigen[,1], 'Linearity', 'linearity') |>
51 | add_lasattribute((eigen[,2] - eigen[,3]) / eigen[,1], 'Planarity', 'planarity') |>
52 | add_lasattribute(eigen[,3] / eigen[,1], 'Sphericity', 'sphericity') |>
53 | add_lasattribute((eigen[,1] - eigen[,3]) / eigen[,1], 'Anisotropy', 'anisotropy') |>
54 | add_lasattribute(1 - abs(eigen[,4]) ,'Verticality','verticality')
55 | return(las)
56 | }
57 |
58 | # ------------------------------------------------------------------------------
59 |
60 | #' helper function to voxelize a las element
61 | #'
62 | #' Calculate voxel mean values for all numeric attributes in the las@data table
63 | #' including the XYZ-coordinates.
64 | #'
65 | #' @param las a lidR::LAS element
66 | #' @param res voxel resolution in meter
67 | #' @return a las element with XYZ-coordinates as the voxel center and
68 | #' X_gr,Y_gr,Z_gr as the center of gravity (mean point coordinates) as well as
69 | #' all other numeric columns voxel mean values with their original name.
70 | #' @author Julian Frey
71 | #' @seealso \code{\link{voxelize_points}}
72 | #' @examples
73 | #'
74 | #' # read example data
75 | #' file = system.file("extdata", "beech.las", package="CspStandSegmentation")
76 | #' las = lidR::readTLSLAS(file)
77 | #' las |> voxelize_points_mean_attributes(1) |> lidR::plot(color = 'X_gr')
78 | #'
79 | #' @export voxelize_points_mean_attributes
80 | voxelize_points_mean_attributes <- function(las, res) {
81 | # check if inputs of the right type
82 | if (!lidR::is(las,"LAS")) {
83 | stop('las has to be a LAS object.')
84 | }
85 | if(!(is.numeric(res) & length(res) < 3 & res > 0 )) {
86 | stop('res has to be numeric and positive.')
87 | }
88 |
89 | # Checking resolution input validity
90 | if (length(res) == 1L) {
91 | res <- c(res, res)
92 | } else if (length(res) > 2L) {
93 | stop('Wrong resolution provided.')
94 | }
95 |
96 | # create voxel coordinates
97 | by <- lidR:::group_grid_3d(las@data$X, las@data$Y, las@data$Z, res, c(0, 0, 0.5*res[2]))
98 |
99 | # add mean attributes
100 | voxels <- las@data[,lapply(.SD, mean), by = by]
101 | if (length(names(las@data)) > 3) {
102 | data.table::setnames(voxels, c('X', 'Y', 'Z', 'X_gr', 'Y_gr', 'Z_gr', names(las@data)[4:length(names(las@data))]))
103 | } else {
104 | data.table::setnames(voxels, c('X', 'Y', 'Z', 'X_gr', 'Y_gr', 'Z_gr'))
105 | }
106 |
107 | # convert voxels to LAS object
108 | output <- LAS(voxels, header = las@header, crs = st_crs(las), check = FALSE, index = las@index)
109 | return(output)
110 | }
111 |
112 | # ------------------------------------------------------------------------------
113 |
114 | #' Add voxel coordinates to a las file
115 | #'
116 | #' Adds the collums x_vox, y_vox and z_vox in the given ressolution to the las
117 | #' element. This is convenient if information has been derived in voxel space
118 | #' and these should be attached to the original points.
119 | #'
120 | #' Voxel coordinates derived with this function are identical to those derived
121 | #' by lidR::voxelize.
122 | #'
123 | #' @param las an element of lidR::LAS class
124 | #' @param res voxel ressolution in [m]
125 | #' @return las file with additional voxel coordinates
126 | #' @author Julian Frey
127 | #' @examples
128 | #'
129 | #' file = system.file("extdata", "beech.las", package="CspStandSegmentation")
130 | #' las = lidR::readTLSLAS(file)
131 | #'
132 | #' las <- add_voxel_coordinates(las,res = 1)
133 | #'
134 | #' lidR::plot(las, color = 'z_vox')
135 | #'
136 | #' @export add_voxel_coordinates
137 | add_voxel_coordinates <- function(las, res) {
138 | # check if inputs of the right type
139 | if (!lidR::is(las,"LAS")) {
140 | stop('las has to be a LAS object.')
141 | }
142 | if(!(is.numeric(res) & length(res) < 3 & res > 0 )) {
143 | stop('res has to be numeric and positive.')
144 | }
145 |
146 | # create voxel coordinates
147 | vox <- lidR:::group_grid_3d(las@data$X, las@data$Y, las@data$Z, c(res, res), c(0, 0, 0.5*res))
148 |
149 | # add voxel coordinates to LAS
150 | las <- las |>
151 | add_lasattribute(vox[[1]], 'x_vox', 'x_vox') |>
152 | add_lasattribute(vox[[2]], 'y_vox', 'y_vox') |>
153 | add_lasattribute(vox[[3]], 'z_vox', 'z_vox')
154 | return(las)
155 | }
156 |
157 | # ------------------------------------------------------------------------------
158 |
159 | #' Add all las_attributes from las@data to the header of a las element
160 | #'
161 | #' The helper function adds all headings from las@data which are not part of
162 | #' lidR:::LASATTRIBUTES to the las header using lidR::add_lasattribute. Only
163 | #' attributes that are included in the header got saved when using
164 | #' lidR::writeLAS, this is a convenient way to add them.
165 | #'
166 | #' @param las an element of lidR::LAS class
167 | #' @return the las file with updated header
168 | #' @author Julian Frey
169 | #' @examples
170 | #'
171 | #' file <- system.file("extdata", "beech.las", package="CspStandSegmentation")
172 | #' las <- lidR::readTLSLAS(file)
173 | #'
174 | #' las@data$noise <- runif(nrow(las@data))
175 | #' las@data$noiseZ <- las@data$var1 * las@data$Z
176 | #'
177 | #' las <- add_las_attributes(las)
178 | #'
179 | #' @export add_las_attributes
180 | add_las_attributes <- function(las) {
181 | # check if inputs of the right type
182 | if (!lidR::is(las,"LAS")) {
183 | stop('las has to be a LAS object.')
184 | }
185 |
186 | # Add attributes from data.table permanently to attributes
187 | names <- names(las@data)
188 | names <- names[!(names %in% lidR:::LASATTRIBUTES)]
189 | for (name in names) {
190 | if (!with(las@data, is.numeric(get(name)))) {
191 | next
192 | }
193 | las <- las |>
194 | add_lasattribute(name = name, desc = name)
195 | }
196 | return(las)
197 | }
198 |
199 | # ------------------------------------------------------------------------------
200 |
201 | # V_w, L_W, S_w are the weights for 1-verticality, sphericity, linearity
202 |
203 | #' helper function for csp_cost_segemntation
204 | #'
205 | #' The function performs a Dijkstra algorithm on a 3D voxel file to assign
206 | #' every voxel to the closest seed point using the igraph package.
207 | #'
208 | #' @param vox a LAS S4 element with XYZ voxel coordinates in the @data slot.
209 | #' @param adjacency_df a data.frame with voxel ids (row numbers) in the first
210 | #' column and a neighboring voxel ID in the second column and the weight
211 | #' (distance) in the third column. Might be generated using the dbscan::frNN
212 | #' function (which requires reshaping the data).
213 | #' @param seeds seed points for tree positions.
214 | #' @param v_w,l_w,s_w weights for verticality, linearity spericity see
215 | #' \code{\link{csp_cost_segmentation}}
216 | #' @param N_cores Number of CPU cores for multi-threading
217 | #' @param Voxel_size Edge length used to create the voxels. This is only
218 | #' important to gain comparable distance weights on different voxel sizes.
219 | #' Should be greater than 0.
220 | #' @return voxels with the TreeID in the data slot
221 | #' @author Julian Frey
222 | #' @seealso \code{\link{csp_cost_segmentation}}
223 | #'
224 | #' @export comparative_shortest_path
225 | comparative_shortest_path <- function(vox = vox, adjacency_df = adjacency_df, seeds, v_w = 0, l_w = 0, s_w = 0, N_cores = parallel::detectCores() - 1, Voxel_size) {
226 |
227 | # update weights
228 | adjacency_df$weight <- with(vox@data[adjacency_df$adjacency_list], adjacency_df$weight^2 + ((1 - Verticality) * v_w + Sphericity * s_w + Linearity * l_w) * Voxel_size)
229 | adjacency_df$weight[adjacency_df$weight < 0] <- 0.001 * Voxel_size # catch negative weights
230 |
231 | # set distances to seeds 0
232 | adjacency_df$weight[adjacency_df$adjacency_list_id %in% seeds$SeedID] <- 0
233 |
234 | #-----------------------
235 | # compute dijkstra matrix for each seed (trunk)
236 | # and weigh matrix by DBH^2/3 (Tao et al 2015.)
237 | #-----------------------
238 |
239 | # build graph
240 | vox_graph <- adjacency_df |>
241 | igraph::graph_from_data_frame(directed = F) |>
242 | igraph::simplify()
243 |
244 | # calculate a distance (weight) graph per seed using Dijkstra
245 | doParallel::registerDoParallel(cores = N_cores)
246 | dists_list <- foreach::foreach(
247 | t = 1:nrow(seeds),
248 | .noexport = c('las', 'map', 'vox', 'tree_seeds', 'ground', 'dtm', 'adjacency_df', 'inv'),
249 | .errorhandling = c('pass')) %dopar% {
250 | return(igraph::distances(vox_graph, as.character(seeds$SeedID[t]), algorithm = 'dijkstra'))
251 | }
252 | doParallel::stopImplicitCluster()
253 |
254 | unreachable <- which(sapply(dists_list,function(x) is.character(x[[1]])))
255 | if(length(unreachable) > 0) {
256 | warning('Not all base positions could be reached by the graph. Try a lower resolution or a different approach to find tree base positions. Error messages for the unreachable TreeIDs:')
257 | warning(paste0(unreachable , paste(":",paste(dists_list[unreachable]), collapse = " "), "\n"), call. = F)
258 | seeds <- seeds[-unreachable,]
259 | dists_list <- dists_list[-unreachable]
260 | }
261 |
262 | # Combine to matrix
263 | dist_matrix <- simplify2array(dists_list)[1,,]
264 |
265 | # get seed with minimum distance
266 | min_matrix <- apply(dist_matrix, 1, which.min)
267 | min_dist_matrix <- suppressWarnings(apply(dist_matrix, 1, min, na.rm = T))
268 | min_matrix <- data.table::data.table(PointID = as.integer(igraph::V(vox_graph)$name), TreeID = seeds$TreeID[as.integer(min_matrix)], dist = min_dist_matrix)
269 | min_matrix$TreeID[min_dist_matrix == Inf] <- 0 # set SeedIDs 0 for voxels which any seed can't reach
270 |
271 | # assign voxels to seeds (minimum cost/distance to trunk)
272 | vox <- vox |>
273 | remove_lasattribute('TreeID') |>
274 | add_attribute(as.integer(rownames(vox@data)), 'PointID')
275 | vox@data <- merge(vox@data, min_matrix, by = 'PointID')
276 | return(vox)
277 | }
278 |
279 | # ------------------------------------------------------------------------------
280 |
281 | # This is the main function
282 | # It requires a las point cloud of a forest patch and
283 | # a forest inventory as it can be calculated by CspStandSegmentation::find_base_coordinates_raster
284 | # Preferable geometric features should be computed for the point cloud prior
285 | # to the use of this function using 'add_geometry()'.
286 |
287 | #' Comparative Shortest Path with cost weighting tree segmentation
288 | #'
289 | #' Segments single trees from forest point clouds based on tree positions
290 | #' (xyz-coordinates) provided in the map argument.
291 | #'
292 | #' The whole point cloud is voxelized in the given resolution and the center of
293 | #' gravity for the points inside is calculated as voxel coordinate. A graph is
294 | #' build, which connects the voxel coordinates based on a db-scan algorithm. The
295 | #' distances between the voxel coordinates is weighted based on geometric
296 | #' features computed for the points in the voxels. Distances along planar
297 | #' and/or vertical faces like stems are weighted shorter than distances through
298 | #' voxels with high sphericity like leaves and clusters of twigs. This
299 | #' avoids small individuals spreading into the upper canopy.
300 | #' For every voxel center, the weighted distance in the network is calculated to
301 | #' all tree locations from the map argument. The TreeID of the map argument
302 | #' with the shortest distance is assigned to the voxel. All points in the point
303 | #' cloud receive the TreeID from their parent voxel.
304 | #'
305 | #' @param las A lidR LAS S4 object.
306 | #' @param map A data.frame, including the columns
307 | #' X, Y, Z, TreeID, with X and Y depicting the location of the trees. Can be generated using CspStandSegmentation::find_base_coordinates_raster
308 | #' @param Voxel_size The voxel size (3D resolution) for the routing graph to
309 | #' determine the nearest map location for every point in the point cloud.
310 | #' @param V_w verticality weight. Since trunks are vertical structures, routing
311 | #' through voxels with high verticality can be rated 'cheaper.' should be a
312 | #' number between 0 and 1 with 0 meaning no benefit for more vertical
313 | #' structures.
314 | #' @param L_w Linearity weight. Similar to V_w but for linearity, higher
315 | #' values indicate a malus for linear shapes (usually branches).
316 | #' @param S_w Spericity weight. Similar to V_w but for sphericity, higher
317 | #' values indicate a malus for spherical shapes (usually small branches and
318 | #' leaves).
319 | #' @param N_cores number of CPU cores used for parallel routing using the
320 | #' foreach package.
321 | #' @return Returns a copy of the las point cloud with an additional field for
322 | #' the TreeID.
323 | #' @author Julian Frey
324 | #' @seealso \code{\link{comparative_shortest_path}}
325 | #'
326 | #' @examples
327 | #'
328 | #' # read example data
329 | #' file = system.file("extdata", "beech.las", package="CspStandSegmentation")
330 | #' las = lidR::readTLSLAS(file)
331 | #'
332 | #' # Find tree positions as starting points for segmentation
333 | #' map <- CspStandSegmentation::find_base_coordinates_raster(las)
334 | #' # segment trees
335 | #' segmented <- las |>
336 | #' CspStandSegmentation::add_geometry() |>
337 | #' CspStandSegmentation::csp_cost_segmentation(map, 1)
338 | #'
339 | #' lidR::plot(segmented, color = "TreeID")
340 | #'
341 | #' @export csp_cost_segmentation
342 | csp_cost_segmentation <- function(las, map, Voxel_size = 0.3, V_w = 0, L_w = 0, S_w = 0, N_cores = 1) {
343 |
344 | # if map is a LAS object, extract tree positions
345 | if (lidR::is(map,"LAS")) {
346 | # check if TreeID available
347 | if (!('TreeID' %in% names(map@data))) {
348 | stop('TreeID has to be a column in the map data.frame.')
349 | }
350 | inv <- map@data[map@data$TreePosition,]
351 | if (nrow(inv) == 0) {
352 | inv <- aggregate(map@data[map@data$Z > 1 & map@data$Z < 1.5,], by = list(map@data$TreeID[map@data$Z > 1 & map@data$Z < 1.5]), median)
353 | }
354 | }
355 | # check if inputs of the right type
356 | if (!lidR::is(las,"LAS")) {
357 | stop('las has to be a LAS object.')
358 | }
359 | if (!(is.data.frame(map) & all(c('X', 'Y', 'Z', 'TreeID') %in% names(map)))) {
360 | stop('map has to be a data.frame with collumn names X,Y,Z,TreeID.')
361 | }
362 | if(!all(is.numeric(c(Voxel_size, V_w, L_w, S_w, N_cores)))) {
363 | stop('Voxel_size, V_w, L_w, S_w and N_cores have to be numeric.')
364 | }
365 |
366 | if (Voxel_size <= 0) {
367 | stop('Voxel_size has to be greater than 0.')
368 | }
369 | if(lidR::is.empty(las)) {
370 | stop('No points in the point cloud.')
371 | }
372 | if(nrow(map) == 0) {
373 | stop('No tree positions in the map.')
374 | }
375 |
376 | # check if TreeID already exists
377 | if ('TreeID' %in% names(las@data)) {
378 | warning("'las' already contains TreeIDs', which will be overwritten.")
379 | las <- las |>
380 | lidR::remove_lasattribute('TreeID')
381 | }
382 | # Check if geometric features exist in las and compute dummies if not
383 | if(!all(c('Sphericity', 'Linearity', 'Verticality') %in% names(las@data))) {
384 | warning("no geometric features in las. V_w, L_w and/or S_w weights will be ignored.Use 'las <- las |> add_gemetry()' prior to calling this function.")
385 | las <- las |>
386 | lidR::add_lasattribute(0, 'Sphericity', 'Sphericity') |>
387 | lidR::add_lasattribute(0, 'Linearity', 'Linearity') |>
388 | lidR::add_lasattribute(0, 'Verticality', 'Verticality')
389 | }
390 |
391 | # Voxelize las with mean attributes
392 | vox <- voxelize_points_mean_attributes(las, res = Voxel_size)
393 |
394 | inv <- map
395 |
396 | # Add seeds
397 | vox <- vox |>
398 | lidR::add_lasattribute(0, 'TreeID', 'TreeID')
399 | vox@data <- vox@data[,c('X', 'Y', 'Z', 'X_gr', 'Y_gr', 'Z_gr', 'Sphericity', 'Linearity', 'Verticality', 'TreeID')]
400 |
401 | # Lift the starting points if map doesn't have Z values
402 | if (sum(inv$Z) == 0) {
403 | inv$Z <- 0.5
404 | }
405 | if(las@header$`Min Z` > max(inv$Z)) {stop('The minimum Z value of the point cloud is higher than the tree positions. Is the inventory without Z values and the point clound not normalized?')}
406 |
407 | inv <- inv |>
408 | cbind(X_gr = inv$X) |>
409 | cbind(Y_gr = inv$Y) |>
410 | cbind(Z_gr = inv$Z) |>
411 | cbind(Sphericity = 0) |>
412 | cbind(Linearity = 0) |>
413 | cbind(Verticality = 0)
414 | vox@data <- rbind(vox@data, inv[,c('X', 'Y', 'Z', 'X_gr', 'Y_gr', 'Z_gr', 'Sphericity', 'Linearity', 'Verticality', 'TreeID')])
415 |
416 | # Seed positions
417 | seed_range <- (nrow(vox@data) - nrow(inv) + 1):nrow(vox@data)
418 | tree_seeds <- data.frame(SeedID = seed_range, TreeID = vox@data$TreeID[seed_range])
419 | rm(seed_range)
420 |
421 | # Use dbscan to calculate a matrix of neighboring points
422 | neighborhood_list <- dbscan::frNN(vox@data[,c('X_gr', 'Y_gr', 'Z_gr')], Voxel_size * 2, bucketSize = 22)
423 | # dbscan::frNN(vox@data[,c('X_gr', 'Y_gr', 'Z_gr')], Voxel_size * 2, bucketSize = 22) # voxel size * 1.42 (sqrt(1^2 + 1^2)) 1.73
424 |
425 | # The result has to be disentangled we get the adjacent voxel IDs first
426 | adjacency_list <- unlist(neighborhood_list$id)
427 |
428 | # Then we grab the origin voxel using cpp
429 | adjacency_list_id <- fast_unlist(neighborhood_list$id, length(adjacency_list)) + 1 # +1 because of cpp counting
430 |
431 | # We do the same with the distances
432 | dists_vec <- fast_unlist_dist(neighborhood_list$dist, length(adjacency_list))
433 |
434 | # Compile to a data frame
435 | adjacency_df <- data.frame(adjacency_list_id,adjacency_list, weight = dists_vec) #, TreeID = vox@data$TreeID[adjacency_list_id]
436 | rm(adjacency_list, adjacency_list_id, dists_vec, neighborhood_list)
437 |
438 | # Calculate CSP, including the weights
439 | vox2 <- comparative_shortest_path(vox = vox, adjacency_df = adjacency_df, v_w = V_w, l_w = L_w, s_w = S_w, Voxel_size = Voxel_size, N_cores = N_cores, seeds = tree_seeds)
440 |
441 | las <- las |>
442 | add_voxel_coordinates(Voxel_size)
443 | las@data <- merge(las@data, vox2@data[,c('X', 'Y', 'Z', 'TreeID')], by.x = c('x_vox', 'y_vox', 'z_vox'), by.y = c('X', 'Y', 'Z'))
444 | las <- add_las_attributes(las)
445 | return(las)
446 | }
447 |
448 | # ------------------------------------------------------------------------------
449 |
450 | # Function to calculate tree start points based on a raster density approach
451 | #'
452 | #' Find stem base position using a density raster approach
453 | #' @param las an element of lidR::LAS class
454 | #' @param zmin lower search boundary
455 | #' @param zmax upper search boundary
456 | #' @param q quantile of raster density to assign a tree region
457 | #' @param eps search radius to merge base points
458 | #' @param res raster resolution
459 | #' @return data.frame with X, Y, Z and TreeID for stem base positions
460 | #' @author Julian Frey
461 | #' @examples
462 | #' # read example data
463 | #' file = system.file("extdata", "beech.las", package="CspStandSegmentation")
464 | #' tls = lidR::readTLSLAS(file)
465 | #'
466 | #' # Find tree positions
467 | #' map <- CspStandSegmentation::find_base_coordinates_raster(tls)
468 | #' @export find_base_coordinates_raster
469 | find_base_coordinates_raster <- function(las, res = 0.1, zmin = 0.5, zmax = 2, q = 0.975, eps = 0.2){
470 | # check if inputs of the right type
471 | if (!lidR::is(las,"LAS")) {
472 | stop('las has to be a LAS object.')
473 | }
474 | if(!all(is.numeric(c(zmin, zmax, res, q, eps)))) {
475 | stop('zmin, zmax, res, q and eps have to be numeric.')
476 | }
477 | normalized <- T
478 | if (!('Zref' %in% names(las@data))) {
479 | normalized <- F
480 | las <- las |>
481 | lidR::classify_ground(lidR::csf(class_threshold = 0.05, cloth_resolution = 0.05), last_returns = F)
482 | dtm <- lidR::rasterize_terrain(las, 0.5, lidR::tin())
483 | las <- las |> lidR::normalize_height(lidR::tin(), dtm = dtm)
484 | }
485 | slice <- las |> lidR::filter_poi(Z > zmin & Z < zmax)
486 | density <- lidR::pixel_metrics(slice, length(Z), res = res)
487 | height <- lidR::pixel_metrics(slice, mean(Z), res = res)
488 | q_dens <- quantile(terra::values(density), probs = q, na.rm = T)
489 | seed_rast <- terra::as.points(density > q_dens)
490 | seed_rast <- as.data.frame(terra::subset(seed_rast, seed_rast$V1 == 1), geom = "XY")
491 | seed_rast <- cbind(seed_rast, data.frame(cluster = dbscan::dbscan(seed_rast[,c("x", "y")], eps = eps, minPts = 1)$cluster))
492 | seed_rast <- aggregate(seed_rast, by = list(seed_rast$cluster), mean)[, 3:5]
493 | if(normalized){
494 | z_vals <- terra::extract(height, seed_rast[,1:2])
495 | if(any(is.na(z_vals))) z_vals[is.na(z_vals)] <- mean(c(zmin, zmax)) # catch NA's
496 | } else {
497 | z_vals <- terra::extract(dtm, seed_rast[,1:2])[,2]
498 | if(any(is.na(z_vals))) z_vals[is.na(z_vals)] <- mean(terra::values(dtm)) # catch NA's
499 | }
500 |
501 | seed_rast <- cbind(seed_rast, z_vals)[,c(1,2,4,3)]
502 | colnames(seed_rast) <- c('X','Y','Z','TreeID')
503 | return(seed_rast)
504 | }
505 |
506 | # ------------------------------------------------------------------------------
507 |
508 | # own function to calculate tree start points
509 |
510 | #' Find stem base position using a geometric feature filtering and clustering
511 | #' approach
512 | #' @param las an element of lidR::LAS class
513 | #' @param zmin lower search boundary
514 | #' @param zmax upper search boundary
515 | #' @param res cluster search radius
516 | #' @param min_verticality minimum verticality >0 & <1 for a point to be
517 | #' considered a stem point
518 | #' @param min_planarity minimum planarity >0 & <1 for a point to be considered
519 | #' a stem point
520 | #' @param min_cluster_size minimum number of points in the cluster to be considered
521 | #' a tree, if NULL median cluster size is chosen
522 | #' @return data.frame with X, Y, Z and TreeID for stem base positions
523 | #' @author Julian Frey
524 | #' @examples
525 | #' # read example data
526 | #' file = system.file("extdata", "beech.las", package="CspStandSegmentation")
527 | #' tls = lidR::readTLSLAS(file)
528 | #'
529 | #' # Find tree positions
530 | #' map <- CspStandSegmentation::find_base_coordinates_geom(tls)
531 | #' @export find_base_coordinates_geom
532 | find_base_coordinates_geom <- function(las, zmin = 0.5, zmax = 2, res = 0.5, min_verticality = 0.9, min_planarity = 0.5, min_cluster_size = NULL) {
533 | # check if inputs of the right type
534 | if (!lidR::is(las,"LAS")) {
535 | stop('las has to be a LAS object.')
536 | }
537 | if(!all(is.numeric(c(zmin, zmax, res, min_verticality, min_planarity)))) {
538 | stop('zmin, zmax, res, min_verticality and min_planarity have to be numeric.')
539 | }
540 | Zref <- T # flag if a normalized point cloud was given
541 | if (!('Zref' %in% names(las@data))) {
542 | las <- las |>
543 | lidR::classify_ground(lidR::csf(class_threshold = 0.05, cloth_resolution = 0.05), last_returns = F)
544 | dtm <- lidR::rasterize_terrain(las, 0.5, lidR::tin())
545 | las <- las |> lidR::normalize_height(lidR::tin(), dtm = dtm)
546 | Zref <- F
547 | }
548 |
549 | slice <- las |>
550 | filter_poi(Classification != 2 & Z > zmin & Z < zmax)
551 | if (lidR::is.empty(slice)) {
552 | stop('No points found in the specified zmin/xmax range.')
553 | }
554 |
555 | if(!Zref) {
556 | slice <- slice |>
557 | lidR::unnormalize_height()
558 | }
559 |
560 | slice <- slice |>
561 | add_geometry() |>
562 | filter_poi(Planarity > min_planarity & Verticality > min_verticality)
563 | if (lidR::is.empty(slice)) {
564 | stop('No points found in the specified planarity/verticality range. Try lower parameters (> 0 & < 1)')
565 | }
566 |
567 | if (is.null(min_cluster_size)) {
568 | cluster <- slice@data[,1:3] |>
569 | dbscan::dbscan(res, 1)
570 | slice@data$Cluster <- cluster$cluster
571 | slice <- slice |>
572 | filter_poi(Cluster %in% unique(cluster$cluster)[table(cluster$cluster) > median(table(cluster$cluster))])
573 | } else {
574 | cluster <- slice@data[,1:3] |>
575 | dbscan::dbscan(res, 1)
576 | slice@data$Cluster <- cluster$cluster
577 | slice <- slice |>
578 | filter_poi(Cluster %in% unique(cluster$cluster)[table(cluster$cluster) > min_cluster_size])
579 | }
580 | map <- aggregate(slice@data[,1:2], by = list(slice@data$Cluster), mean)
581 | Z <- aggregate(slice@data[,3], by = list(slice@data$Cluster), min)
582 |
583 | map <- data.frame(map[,2:3], Z = Z[,2], TreeID = 1:nrow(map))
584 | }
585 |
--------------------------------------------------------------------------------
/R/2024-06-10_A1_JF_farthest_point_sampling.R:
--------------------------------------------------------------------------------
1 | #' Point distance function
2 | #'
3 | #' calculates euclidean distances for n dimensions
4 | #'
5 | #' @param p1 point 1
6 | #' @param p2 point 2
7 | #'
8 | #' @return the distance between the two points
9 | #' @export p_dist
10 | #'
11 | #' @examples
12 | #' p_dist(c(0,0), c(3,4))
13 | p_dist <- function(p1, p2){
14 | if(length(p1) != length(p2)){
15 | stop("p1 and p2 must have the same length")
16 | }
17 | sqrt(sum((p1 - p2)^2))
18 | }
19 |
20 | #' Point distance function
21 | #'
22 | #' calculates euclidean distances for n dimensions between a matrix of points and a single point
23 | #'
24 | #' @param mat matrix with points as rows
25 | #' @param p point to calculate distances
26 | #'
27 | #' @return the distances between every row of mat and p
28 | #' @export p_mat_dist
29 | #'
30 | #' @examples
31 | #' p_dist(as.matrix(cbind(runf(100),runf(100)), c(3,4))
32 | p_mat_dist <- function(mat, p){
33 | mat2 <- mat
34 | for(c in 1:ncol(mat)){
35 | mat2[,c] <- (mat[,c] - p[c])^2
36 | }
37 | return(sqrt(.rowSums(mat2, nrow(mat2), ncol(mat2))))
38 | }
39 |
40 | #' Farthest Distance Sampling (Farthest Point Sampling)
41 | #'
42 | #' This function selects n points from a matrix of points such that the minimum distance between any two points is maximized.
43 | #' This version is memory efficient and can handle large matrices.
44 | #'
45 | #' @param mat a matrix of points with one row for each point and one column for each dimension, can also be a las object then only XYZ will be used
46 | #' @param n the number of points to select, or if <1 the proportion of points to select
47 | #' @param ret the type of output to return. Options are "idx" (default) to return the indices of the selected points, "mat" to return the selected points.
48 | #' @param scale logical. If TRUE, the dimensions are scaled to have a mean of 0 and a standard deviation of 1 before calculating distances.
49 | #'
50 | #' @return a vector of indices or a matrix of points
51 | #' @export fds
52 | #'
53 | #' @examples
54 | #' mat <- matrix(rnorm(1000), ncol = 10)
55 | #' sample <- fds(mat, 50, ret = "mat")
56 | #' \dontrun{
57 | #' plot(mat, col = "black", pch = 19)
58 | #' points(sample, col = "red", pch = 19)
59 | #' }
60 | fds <- function(mat, n, ret = "idx", scale = F){
61 | # check the inputs
62 | was_las <- FALSE
63 | if(!is.matrix(mat)){
64 | if(class(mat) == "LAS"){
65 | was_las <- TRUE
66 | las <- mat
67 | mat <- as.matrix(las@data[,c("X", "Y", "Z")])
68 | } else {
69 | stop("mat must be a matrix or a LAS object")
70 | }
71 | }
72 |
73 | if(ret != "idx" & ret != "mat"){
74 | stop("ret must be 'idx' or 'mat'")
75 | }
76 | if(n >= nrow(mat)){
77 | warning("n is greater or equal than the number of points in mat. Returning all points.")
78 | if(ret == "mat"){
79 | if(was_las){
80 | return(las)
81 | }
82 | return(mat)
83 | }
84 | return(1:nrow(mat))
85 | }
86 | if(n == 1){
87 | if(was_las){
88 | return(las[sample(1:nrow(mat), 1),])
89 | }
90 | if(ret == "mat"){
91 | return(mat[sample(1:nrow(mat), 1),])
92 | } else {
93 | return(sample(1:nrow(mat), 1))
94 | }
95 | }
96 | if(n < 0){
97 | stop("n must be greater than 0.")
98 | }
99 | if(n < 1){
100 | n <- round(nrow(mat) * n)
101 | }
102 |
103 | # scale dimensions if requested
104 | if(scale){
105 | for(c in 1:ncol(mat)){
106 | mat[,c] <- scale(mat[,c])
107 | }
108 | }
109 |
110 | # select the first point randomly
111 | idx <- which.max(mat[,1])
112 |
113 | # calculate a vector of distances from the first point
114 | dists <- p_mat_dist(mat, mat[idx,])
115 |
116 | # select all further points in a loop
117 | for(i in 2:n){
118 | # select the next point
119 | idx <- c(idx, which.max(dists))
120 | # calculate the distances from the new point
121 | dists2 <- p_mat_dist(mat, mat[idx[i],])
122 | dists <- pmin(dists, dists2)
123 | }
124 |
125 | # return the selected points
126 | if(ret == "mat"){
127 | if(was_las){
128 | las@data <- las@data[idx,]
129 | return(las)
130 | } else {
131 | return(mat[idx,])
132 | }
133 | } else {
134 | return(idx)
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/R/2025-01-07_A1_JF_merge_las_objects.R:
--------------------------------------------------------------------------------
1 | #' Makes one las object from multiple las objects
2 | #'
3 | #' This function merges multiple las objects into one las object. The function checks if all inputs are las objects and if they have the same CRS. The function will also add a column oci with the original cloud index to each las object. The function will then rbind all data by the minimum set of columns. If the fill argument is set to False, columns which do not exist in all las objects will be removed. If the fill argument is set to True, missing columns will be filled with NA.
4 | #'
5 | #'
6 | #' @param ... any number of las objects
7 | #' @param oci add a column with the original cloud index
8 | #' @param fill fill missing columns with NA if it is set to False collumns which do not exist in all las objects will be removed
9 | #'
10 | #' @returns A single las object
11 | #'
12 | #' @examples
13 | #' las1 <- lidR::LAS(data.frame(X = runif(100), Y = runif(100), Z = runif(100)))
14 | #' las2 <- lidR::LAS(data.frame(X = runif(100) + 2, Y = runif(100), Z = runif(100)))
15 | #' las3 <- lidR::LAS(data.frame(X = runif(100) + 4, Y = runif(100), Z = runif(100)))
16 | #' las_merge(las1, las2, las3)
17 | #' # las_merge(las1, las2, las3) |> lidR::plot(color = "oci")
18 | las_merge <- function(..., oci = TRUE, fill = FALSE){
19 | is_las <- function(x) lidR::is(x, "LAS")
20 |
21 | # check if only las objects are passed
22 | if(!all(sapply(list(...), is_las))) stop("All inputs must be LAS objects")
23 |
24 | # check if the crs is the same
25 | crs <- sapply(list(...), function(x) lidR::crs(x))
26 | projargs <- sapply(crs, function(x) x@projargs)
27 | if(any(is.na(projargs))) warning("Some inputs do not have a CRS")
28 | if(!all(sapply(crs, terra::same.crs,y = crs[[1]])) & !all(is.na(projargs))) stop("All inputs must have the same CRS")
29 |
30 | # put all objects in a list
31 | las_list <- list(...)
32 | # add original cloud index to each object
33 | if(oci){
34 | for(i in 1:length(las_list)){
35 | las_list[[i]] <- las_list[[i]] |> lidR::add_lasattribute(i, "oci", "original cloud index")
36 | }
37 | }
38 |
39 | # rbind all data by the minimum set of columns
40 | las_1 <- las_list[[1]]
41 | if(fill){
42 | las_1@data <- data.table::rbindlist(lapply(las_list, function(x) x@data), fill = T)
43 | } else {
44 | # build a minimum set of columns
45 | cols <- lapply(las_list, function(x) colnames(x@data))
46 | # find the intersection of columns
47 | cols <- Reduce(intersect, cols)
48 | las_1@data <- do.call(rbind, lapply(las_list, function(x) x@data[,..cols]))
49 | }
50 |
51 | # quantize the data
52 | las_1 <- las_1 |> lidR::las_quantize() |> lidR::las_update()
53 |
54 | # remove extra byte arguments from header which do not exist any longer
55 | exbytes_header <- names(las_1@header@VLR$Extra_Bytes$`Extra Bytes Description`)
56 | exbytes_data <- names(las_1@data)
57 | exbytes <- setdiff(exbytes_header, exbytes_data)
58 | if(length(exbytes) > 0){
59 | for(i in exbytes){
60 | las_1@header@VLR$Extra_Bytes$`Extra Bytes Description`[[i]] <- NULL
61 | }
62 | }
63 |
64 | return(las_1)
65 | }
66 |
--------------------------------------------------------------------------------
/R/2025-01-10_A1_JF_forest_inventory.R:
--------------------------------------------------------------------------------
1 | ###########
2 | # functions
3 | ###########
4 |
5 | #' Helper function to compute distances from a point to the circle
6 | #' @param point numeric vector of length 2 c(X,Y)
7 | #' @param circle numeric vector of length 3 c(center_X, center_Y, radius)
8 | #' @return numeric distance from the point to the circle
9 | point_circle_distance <- function(point, circle) {
10 | return(abs(sqrt(sum((point - circle[1:2])^2)) - circle[3]))
11 | }
12 |
13 | #' Returns the angle between the center of the circle and a point in degrees
14 | #' @param point numeric vector of length 2 c(X,Y)
15 | #' @param circle numeric vector of length 3 c(center_X, center_Y, radius)
16 | #' @return numeric angle in degrees
17 | point_center_angle <- function(point, circle){
18 | ang <- atan2(point[2] - circle[2], point[1] - circle[1])
19 | return(ang * 180 / pi)
20 | }
21 |
22 | #' Suppress only the cat() output
23 | #' @param f function to be called
24 | #' @return the return value of the function
25 | suppress_cat <- function(f, ...) {
26 | null_device <- if (.Platform$OS.type == "windows") "nul" else "/dev/null"
27 | con <- file(null_device, "w") # Open connection to null device
28 | sink(con) # Redirect output to null device
29 | on.exit({ # Ensure cleanup
30 | sink()
31 | close(con)
32 | })
33 | f(...) # Call the function and capture its return value
34 | }
35 |
36 | #' RANSAC circle fitting algorithm specially adapted for tree DBH estimation
37 | #'
38 | #' This function fits a circle to a set of points using the RANSAC algorithm it maximizes the points that are in the circle and the number of filled 36 degree angle segments
39 | #' Therefore, this function searches for the most complete circle with the highest number of points represented.
40 | #'
41 | #' @param data numeric matrix with 2 columns (X, Y) representing the point cloud
42 | #' @param n_iterations integer maximum number of iterations
43 | #' @param distance_threshold numeric maximum distance from a point to the circle to be considered an inlier
44 | #' @param min_inliers integer minimum number of inliers to consider the circle as valid
45 | ransac_circle_fit <- function(data, n_iterations = 1000, distance_threshold = 0.01, min_inliers = 3) {
46 | # catch if less than 3 points are given
47 | if (nrow(data) < 3) {
48 | return(list(circle = c(mean(data[,1]), mean(data[,2]), NA), inliers = NA, angle_segs = NA, n_iter = 0))
49 | }
50 |
51 | # Initialize best circle
52 | best_circle <- NULL
53 | best_inliers <- 0
54 | best_angle_segs <- 0
55 | n_pts_sample <- min(c(5, nrow(data)))
56 |
57 | # calculate point densities in neighbourhood
58 | p_densities <- dbscan::pointdensity(data, eps = 0.05)
59 |
60 |
61 | for (i in 1:n_iterations) {
62 | # Randomly sample 3 points
63 | sample_points <- data[sample(1:nrow(data), n_pts_sample, prob = p_densities + 1), ] |> as.matrix()
64 |
65 | # Compute circle parameters
66 | tryCatch({
67 | circle <- suppress_cat(conicfit::CircleFitByPratt, sample_points)
68 |
69 | # Count inliers
70 | distances <- apply(data, 1, point_circle_distance, circle = circle)
71 | inliers <- sum(distances < distance_threshold)
72 | angle_segs <- length(unique(floor(apply(data, 1, point_center_angle, circle = circle)/10)))
73 |
74 | # # Update best circle if more inliers are found
75 | # if (inliers > best_inliers && inliers >= min_inliers) {
76 | # best_circle <- list(circle = circle, inliers = inliers)
77 | # best_inliers <- inliers
78 | # }
79 |
80 | # Update best circle if it has more angle segments and/or inliers
81 | if (angle_segs >= best_angle_segs && inliers >= best_inliers) {
82 | best_circle <- list(circle = circle, inliers = inliers, angle_segs = angle_segs, n_iter = i)
83 | best_angle_segs <- angle_segs
84 | best_inliers <- inliers
85 | }
86 |
87 | if((best_angle_segs == nrow(data) | best_angle_segs >= 30) ){ #& inliers == nrow(data)
88 | break
89 | }
90 |
91 | },
92 | warnings = function(w){},
93 | error = function(e) {}) |> suppressWarnings()
94 | }
95 | best_circle$n_iter <- i
96 | return(best_circle)
97 | }
98 |
99 | #' Function to perform a forest inventory based on a segmented las object (needs to contain TreeID)
100 | #'
101 | #' This function estimates a taper curve for evry tree and returns the DBH at 1.3m, its position in XY coordinates, the tree height and the trees 2D projection area.
102 | #'
103 | #' @param las lidR las object with the segmented trees
104 | #' @param slice_min the minimum height of a slice for stems to estimate the taper curve
105 | #' @param slice_max the maximum height of a slice for stems to estimate the taper curve
106 | #' @param increment the increment of the slices
107 | #' @param width the width of the slices
108 | #' @param max_dbh the maximum DBH allowed
109 | #' @param n_cores number of cores to use
110 | #'
111 | #' @returns a data.frame with the TreeID, X, Y, DBH, quality_flag, Height and ConvexHullArea
112 | #'
113 | #' @examples
114 | #' # read example data
115 | #' file = system.file("extdata", "beech.las", package="CspStandSegmentation")
116 | #' tls = lidR::readTLSLAS(file)
117 | #'
118 | #' # find tree positions as starting points for segmentation
119 | #' map <- CspStandSegmentation::find_base_coordinates_raster(tls)
120 | #'
121 | #' # segment trees
122 | #' segmented <- tls |>
123 | #' CspStandSegmentation::add_geometry(n_cores = parallel::detectCores()/2) |>
124 | #' CspStandSegmentation::csp_cost_segmentation(map, 1, N_cores = parallel::detectCores()/2)
125 | #'
126 | #' # show results
127 | #' \dontrun{lidR::plot(segmented, color = "TreeID")}
128 | #'
129 | #' # perform inventory
130 | #' inventory <- CspStandSegmentation::forest_inventory(segmented)
131 | forest_inventory <- function (tls, slice_min = 0.3, slice_max = 4, increment = 0.2, width = 0.1, max_dbh = 1, n_cores = max(c(1, parallel::detectCores()/2 - 1))) {
132 | if (!"TreeID" %in% names(tls)) {
133 | stop("The las object does not contain a TreeID attribute")
134 | }
135 | tls <- lidR::filter_poi(tls, !is.na(TreeID) & TreeID > 0)
136 | if ("Zref" %in% names(tls)) {
137 | dbh_slice <- lidR::filter_poi(tls, Z > slice_min & Z <
138 | slice_max)
139 | } else if ("Znorm" %in% names(tls)) {
140 | dbh_slice <- lidR::filter_poi(tls, Znorm > slice_min &
141 | Znorm < slice_max)
142 | } else {
143 | tls_norm <- lidR::normalize_height(lidR::classify_ground(tls,
144 | lidR::csf()), lidR::tin())
145 | tls <- lidR::add_lasattribute(tls, tls_norm$Z, "Znorm",
146 | "Z normalized")
147 | dbh_slice <- lidR::filter_poi(tls, Znorm > slice_min &
148 | Znorm < slice_max)
149 | }
150 | seq <- seq(slice_min, slice_max, by = increment)
151 | seq <- data.frame(id = 1:length(seq), Zmin = seq - width *
152 | 0.5, Zmax = seq + width * 0.5)
153 | na2true <- function(x) ifelse(is.na(x) | is.infinite(x),
154 | TRUE, x)
155 | points_per_stem <- aggregate(dbh_slice$TreeID, by = list(dbh_slice$TreeID),
156 | FUN = length)
157 | t1 <- Sys.time()
158 | IDs <- points_per_stem$Group.1[points_per_stem$x > 3]
159 | las_list <- list()
160 | for(i in 1:length(IDs)){
161 | las_list[[i]] <- lidR::filter_poi(tls, TreeID == IDs[i])
162 | }
163 | print("Fit a DBH value to every tree:")
164 | require(foreach)
165 | cl = parallel::makeCluster(n_cores)
166 | doParallel::registerDoParallel(cl)
167 | dbh_results <- foreach::foreach(tree = las_list, .combine = rbind, .errorhandling = "remove") %dopar%
168 | {
169 | t <- tree@data$TreeID[1]
170 | if (nrow(tree) < 3) {
171 | dbh <- NA
172 | return(data.frame(TreeID = t, X = mean(tree$X),
173 | Y = mean(tree$Y), DBH = dbh, quality_flag = 1))
174 | warning(paste("to little points in tree",
175 | t))
176 | }
177 | seq <- seq(slice_min, slice_max, by = increment)
178 | seq <- data.frame(id = 1:length(seq), Zmin = seq -
179 | width * 0.5, Zmax = seq + width * 0.5)
180 | t_seq <- cbind(seq, X = NA, Y = NA, r = NA)
181 | rs <- numeric()
182 | xs <- numeric()
183 | ys <- numeric()
184 | for (s in seq$id) {
185 | slice <- lidR::filter_poi(tree, Znorm > t_seq$Zmin[s] &
186 | Znorm < t_seq$Zmax[s])
187 | if (nrow(slice) < 3) {
188 | rs <- c(rs, NA)
189 | xs <- c(xs, NA)
190 | ys <- c(ys, NA)
191 | next
192 | }
193 | else if (nrow(slice) < 100) {
194 | planes <- slice
195 | }
196 | else {
197 | slice <- CspStandSegmentation::add_geometry(slice)
198 | planes <- lidR::filter_poi(slice, Planarity >
199 | quantile(Planarity, 0.95) & Verticality >
200 | quantile(Verticality, 0.95))
201 | q <- 0.95
202 | while (nrow(planes) < 100) {
203 | q <- q - 0.05
204 | planes <- lidR::filter_poi(slice, Planarity >
205 | quantile(Planarity, q) & Verticality >
206 | quantile(Verticality, q))
207 | if (q < 0.2) {
208 | planes <- slice
209 | break
210 | }
211 | }
212 | }
213 | planes <- slice
214 | circle <- CspStandSegmentation::ransac_circle_fit(planes@data[, c("X",
215 | "Y")], n_iterations = 500)
216 | rs <- c(rs, circle$circle[3])
217 | xs <- c(xs, circle$circle[1])
218 | ys <- c(ys, circle$circle[2])
219 | }
220 | t_seq$r <- rs
221 | t_seq$X <- xs
222 | t_seq$Y <- ys
223 | t_seq$r[abs(t_seq$r - median(t_seq$r, na.rm = TRUE)) >
224 | 2 * sd(t_seq$r, na.rm = TRUE)] <- NA
225 | for (s in 2:nrow(t_seq)) {
226 | if (na2true(t_seq$r[s] > suppressWarnings(min(t_seq$r[1:(s -
227 | 1)], na.rm = TRUE) * 1.3)) | na2true(t_seq$r[s] <
228 | 0.04) | all(is.na(t_seq$r[1:s]))) {
229 | t_seq[s, c("X", "Y", "r")] <- NA
230 | }
231 | }
232 | if ((sum(!is.na(t_seq$r)) <= 3) | (sum(!is.na(t_seq$X)) <=
233 | 3) | (sum(!is.na(t_seq$Y)) <= 3)) {
234 | dbh <- mean(t_seq$r, na.rm = TRUE) * 2
235 | if (is.na(dbh) | dbh > max_dbh | dbh < 0) {
236 | return(data.frame(TreeID = t, X = mean(tree$X),
237 | Y = mean(tree$Y), DBH = NA, quality_flag = 2))
238 | }
239 | else {
240 | return(data.frame(TreeID = t, X = mean(tree$X),
241 | Y = mean(tree$Y), DBH = dbh, quality_flag = 2))
242 | }
243 | }
244 | spline_r <- suppressWarnings(with(t_seq[!is.na(t_seq$r),
245 | ], smooth.spline(Zmin, r, df = 3)))
246 | spline_x <- suppressWarnings(with(t_seq[!is.na(t_seq$X),
247 | ], smooth.spline(Zmin, X, df = 20)))
248 | spline_y <- suppressWarnings(with(t_seq[!is.na(t_seq$Y),
249 | ], smooth.spline(Zmin, Y, df = 20)))
250 | r <- as.numeric(predict(spline_r, 1.3)$y)
251 | x <- as.numeric(predict(spline_x, 1.3)$y)
252 | y <- as.numeric(predict(spline_y, 1.3)$y)
253 | dbh <- r * 2
254 | if (is.na(dbh) | dbh > max_dbh | dbh < 0) {
255 | return(data.frame(TreeID = t, X = mean(tree$X),
256 | Y = mean(tree$Y), DBH = NA, quality_flag = 3))
257 | }
258 | else {
259 | return(data.frame(TreeID = t, X = x, Y = y, DBH = dbh,
260 | quality_flag = 4))
261 | }
262 | }
263 | parallel::stopCluster(cl)
264 | dbh_slice <- lidR::add_attribute(dbh_slice, dbh_slice@data$Z -
265 | dbh_slice@data$Znorm, "Zdiff")
266 | tree_pos_height <- aggregate(dbh_slice$Zdiff, by = list(dbh_slice$TreeID),
267 | FUN = mean)
268 | names(tree_pos_height) <- c("TreeID", "Z")
269 | heights <- aggregate(tls@data$Z, by = list(tls@data$TreeID),
270 | FUN = function(x) max(x) - min(x))
271 | names(heights) <- c("TreeID", "Height")
272 | print("Tree heights calculated.")
273 | convhull_area <- function(xy) {
274 | xy <- as.data.frame(xy)
275 | if (nrow(xy) < 3) {
276 | return(NA)
277 | }
278 | ch <- chull(xy)
279 | return(abs(0.5 * sum(xy[ch, 1] * c(tail(xy[ch, 2], -1),
280 | head(xy[ch, 2], 1)) - c(tail(xy[ch, 1], -1), head(xy[ch,
281 | 1], 1)) * xy[ch, 2])))
282 | }
283 | print("Calculating convex hull areas.")
284 | pb = txtProgressBar(min = 0, max = length(IDs), initial = 0,
285 | style = 3)
286 | i <- 1
287 | cpa <- data.frame(TreeID = numeric(), ConvexHullArea = numeric())
288 | for (t in IDs) {
289 | tree <- lidR::filter_poi(tls, TreeID == t & Znorm > 0.5)
290 | if (nrow(tree) < 3) {
291 | cpa <- rbind(cpa, data.frame(TreeID = t, ConvexHullArea = NA))
292 | next
293 | }
294 | cpa <- rbind(cpa, data.frame(TreeID = t, ConvexHullArea = convhull_area(tree@data[,
295 | c("X", "Y")])))
296 | setTxtProgressBar(pb, i)
297 | i <- i + 1
298 | }
299 | dbh_results <- merge(dbh_results, heights, by = "TreeID")
300 | dbh_results <- merge(dbh_results, cpa, by = "TreeID")
301 | dbh_results <- merge(dbh_results, tree_pos_height, by = "TreeID")
302 | return(dbh_results)
303 | }
304 |
305 | #' Function to perform a forest inventory based on a segmented las object (needs to contain TreeID)
306 | #' This version is a faster but more simplistic approach than forest_inventory() for the DBH estimates
307 | #'
308 | #' @param tls lidR las object with the segmented trees
309 | #' @param slice_min the minimum height of a DBH slice
310 | #' @param slice_max the maximum height of a DBH slice
311 | #' @param max_dbh the maximum DBH allowed
312 | #' @param n_cores number of cores to use
313 | #'
314 | #' @return a data.frame with the TreeID, X, Y, DBH, quality_flag, Height and ConvexHullArea
315 | forest_inventory_simple <- function (tls, slice_min = 1.2, slice_max = 1.4, max_dbh = 1, n_cores = max(c(1, parallel::detectCores()/2 - 1)))
316 | {
317 | if (!"TreeID" %in% names(tls)) {
318 | stop("The las object does not contain a TreeID attribute")
319 | }
320 | tls <- lidR::filter_poi(tls, !is.na(TreeID) & TreeID > 0)
321 | if ("Zref" %in% names(tls)) {
322 | dbh_slice <- lidR::filter_poi(tls, Z > slice_min & Z <
323 | slice_max)
324 | } else if ("Znorm" %in% names(tls)) {
325 | dbh_slice <- lidR::filter_poi(tls, Znorm > slice_min &
326 | Znorm < slice_max)
327 | } else {
328 | tls_norm <- lidR::normalize_height(lidR::classify_ground(tls,
329 | lidR::csf()), lidR::tin())
330 | tls <- lidR::add_lasattribute(tls, tls_norm$Z, "Znorm",
331 | "Z normalized")
332 | dbh_slice <- lidR::filter_poi(tls, Znorm > slice_min &
333 | Znorm < slice_max)
334 | }
335 |
336 | na2true <- function(x) ifelse(is.na(x) | is.infinite(x), TRUE, x)
337 |
338 | t1 <- Sys.time()
339 | IDs <- unique(dbh_slice$TreeID)
340 | print("Fit a DBH value to every tree:")
341 | las_list <- list()
342 | for(i in 1:length(IDs)) {
343 | las_list[[i]] <- lidR::filter_poi(tls, TreeID == IDs[i])
344 | }
345 |
346 | require(foreach)
347 | cl = parallel::makeCluster(n_cores)
348 | doParallel::registerDoParallel(cl)
349 | dbh_results <- foreach::foreach(tree = las_list, .combine = rbind, .errorhandling = "remove") %dopar%
350 | {
351 | t <- tree@data$TreeID[1]
352 | if (nrow(tree) < 3) {
353 | dbh <- NA
354 | return(data.frame(TreeID = t, X = mean(tree$X),
355 | Y = mean(tree$Y), DBH = dbh, quality_flag = 1))
356 | warning(paste("to little points in tree",
357 | t))
358 | }
359 |
360 | circle <- CspStandSegmentation::ransac_circle_fit(tree@data[, c("X", "Y")], n_iterations = 500)
361 | return(data.frame(TreeID = t, X = circle$circle[1], Y = circle$circle[2], DBH = min(c( circle$circle[3] * 2,2)), quality_flag = 4))
362 |
363 |
364 | }
365 | parallel::stopCluster(cl)
366 | dbh_slice <- lidR::add_attribute(dbh_slice, dbh_slice@data$Z -
367 | dbh_slice@data$Znorm, "Zdiff")
368 | tree_pos_height <- aggregate(dbh_slice$Zdiff, by = list(dbh_slice$TreeID),
369 | FUN = mean)
370 | names(tree_pos_height) <- c("TreeID", "Z")
371 | heights <- aggregate(tls@data$Z, by = list(as.character(tls@data$TreeID)),
372 | FUN = function(x) max(x) - min(x))
373 | names(heights) <- c("TreeID", "Height")
374 | heights$TreeID <- as.numeric(heights$TreeID)
375 | print("Tree heights calculated.")
376 | convhull_area <- function(xy) {
377 | xy <- as.data.frame(xy)
378 | if (nrow(xy) < 3) {
379 | return(NA)
380 | }
381 | ch <- chull(xy)
382 | return(abs(0.5 * sum(xy[ch, 1] * c(tail(xy[ch, 2], -1),
383 | head(xy[ch, 2], 1)) - c(tail(xy[ch, 1], -1), head(xy[ch,
384 | 1], 1)) * xy[ch, 2])))
385 | }
386 | print("Calculating convex hull areas.")
387 | pb = txtProgressBar(min = 0, max = length(IDs), initial = 0,
388 | style = 3)
389 | i <- 1
390 | cpa <- data.frame(TreeID = numeric(), ConvexHullArea = numeric())
391 | for (t in IDs) {
392 | tree <- lidR::filter_poi(tls, TreeID == t & Znorm > 0.5)
393 | if (nrow(tree) < 3) {
394 | cpa <- rbind(cpa, data.frame(TreeID = t, ConvexHullArea = NA))
395 | next
396 | }
397 | cpa <- rbind(cpa, data.frame(TreeID = t, ConvexHullArea = convhull_area(tree@data[,
398 | c("X", "Y")])))
399 | setTxtProgressBar(pb, i)
400 | i <- i + 1
401 | }
402 | dbh_results2 <- merge(dbh_results, heights, by = "TreeID")
403 | dbh_results2 <- merge(dbh_results2, cpa, by = "TreeID")
404 | dbh_results2 <- merge(dbh_results2, tree_pos_height, by = "TreeID")
405 | return(dbh_results2)
406 | }
407 |
408 |
409 | #' Function to plot the inventory results into a lidR 3d plot of the point cloud
410 | #' @param plot lidR 3d plot
411 | #' @param inventory data.frame with the inventory results
412 | #' @param cex numeric size of the labels
413 | #' @param label_col character color of the labels
414 | #' @param col color of the spheres
415 | #' @return the plot with the inventory results
416 | #' @examples
417 | #' \dontrun{
418 | #' x <- lidR::plot(segmented, color = "TreeID")
419 | #' plot_inventory(x, inventory)
420 | #' }
421 | plot_inventory <- function(plot, inventory,col = NA,cex = 1.5, label_col = "white"){
422 | if(is.na(col)){
423 | col <- rainbow(max(inventory$TreeID) - min(inventory$TreeID))
424 | }
425 | # generate a circle for evry dbh estimation
426 | rgl::spheres3d(inventory$X - plot[1], inventory$Y - plot[2], inventory$Z+1.3, radius = inventory$DBH/2,col = col)
427 | for(i in 1:nrow(inventory)){
428 | rgl::texts3d(inventory$X[i] - plot[1] + inventory$DBH[i], inventory$Y[i] - plot[2] + inventory$DBH[i], inventory$Z[i] + 1.3, text = inventory$TreeID[i], adj = c(0.5,0.5), col = label_col, cex = cex, family = "mono", font = 2)
429 | rgl::lines3d(c(inventory$X[i] - plot[1], inventory$X[i] - plot[1]), c(inventory$Y[i] - plot[2], inventory$Y[i] - plot[2]), c(inventory$Z[i], inventory$Height[i]), col = ifelse(length(col) >= i, col[i], col), lwd = 2)
430 | }
431 | }
432 |
433 |
--------------------------------------------------------------------------------
/R/RcppExports.R:
--------------------------------------------------------------------------------
1 | # Generated by using Rcpp::compileAttributes() -> do not edit by hand
2 | # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
3 |
4 | #' helper function to unlist IDs generated by dbscan::frNN
5 | #'
6 | #'
7 | #' creates a vector of indices from a nested list created by dbscan::frNN
8 | #'
9 | #' @param list a list element created by dbscan::frNN
10 | #' @param l the expected length of the result
11 | #' @author Julian Frey
12 | #' @export fast_unlist
13 | fast_unlist <- function(list, l) {
14 | .Call(`_CspStandSegmentation_fast_unlist`, list, l)
15 | }
16 |
17 | #' helper function to unlist distances computed by dbscan::frNN
18 | #'
19 | #' extracts the distances from a nested list created by dbscan::frNN
20 | #'
21 | #' @param list a list element created by dbscan::frNN
22 | #' @param l the expected length of the result
23 | #' @author Julian Frey
24 | #' @export fast_unlist_dist
25 | fast_unlist_dist <- function(list, l) {
26 | .Call(`_CspStandSegmentation_fast_unlist_dist`, list, l)
27 | }
28 |
29 | #' Fast Eigenvalues decomposition for k nearest neighbors using a C++ function
30 | #'
31 | #' C++ helper function to compute eigenvalues for geometric feature
32 | #' calculation.
33 | #'
34 | #' @param las LAS element
35 | #' @param k k nearest neighbors
36 | #' @param ncpu number of cpu cores to use
37 | #' @return The function returns for every point the 3 eigenvalues and the
38 | #' third element of the third eigenvector. These values are needed to compute
39 | #' planarity, linerity, verticality etc. in the add_geometry function
40 | #' @author Julian Frey
41 | #' @seealso \link{add_geometry}
42 | #' @export eigen_decomposition
43 | eigen_decomposition <- function(las, k, ncpu = 1L) {
44 | .Call(`_CspStandSegmentation_eigen_decomposition`, las, k, ncpu)
45 | }
46 |
47 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## CspStandSegmentation is an R-package for the segmentation of single trees from forest point clouds scanned with terrestrial, mobile or unmanned LiDAR systems
2 |
3 | Authors: Julian Frey and Zoe Schindler, University of Freiburg, Chair of Forest Growth and Dendroecology
4 |
5 |
6 | [](https://doi.org/10.5281/zenodo.14204459)
7 |
8 |
9 |
10 |
11 | ## Installation
12 |
13 | If you are working on Windows operating systems, you will need to install Rtools prior to installation: https://cran.r-project.org/bin/windows/Rtools/>. On Mac, Xcode is required.
14 |
15 | ```R
16 | install.packages(c('devtools', 'Rcpp', 'lidR', 'dbscan', 'igraph', 'foreach', 'doParallel','magrittr', 'data.table'))
17 |
18 | devtools::install_github('https://github.com/JulFrey/CspStandSegmentation')
19 |
20 | # Check if it is working
21 | library(CspStandSegmentation)
22 | example("csp_cost_segmentation")
23 |
24 | ```
25 |
26 | ## Usage
27 | The package is firmly based on the `lidR` package and uses the las file structure. Smaller point clouds can be directly segmented using the ```csp_cost_segmentation``` function. This requires a set of tree positions (map) as starting points, which can be derived using the ```find_base_coordinates_raster``` function, which might require parameter optimization. Theoretically, tree positions might also come from field measurements or manual assignments.:
28 |
29 | ```R
30 | # read example data
31 | file = system.file("extdata", "beech.las", package="CspStandSegmentation")
32 | tls = lidR::readTLSLAS(file)
33 |
34 | # find tree positions as starting points for segmentation
35 | map <- CspStandSegmentation::find_base_coordinates_raster(tls)
36 |
37 | # segment trees
38 | segmented <- tls |>
39 | CspStandSegmentation::add_geometry(n_cores = parallel::detectCores()/2) |>
40 | CspStandSegmentation::csp_cost_segmentation(map, 1, N_cores = parallel::detectCores()/2)
41 |
42 | # show results
43 | lidR::plot(segmented, color = "TreeID")
44 |
45 | # create inventory
46 | inventory <- CspStandSegmentation::forest_inventory(segmented)
47 | head(inventory)
48 | lidR::plot(segmented, color = "TreeID") |> CspStandSegmentation::plot_inventory(inventory)
49 | ```
50 |
51 | For large areas, the package can be used within the lidR LAScatalogue engine to cope with memory limitations. The following example shows how this can be done. The single tiles of segmented trees are saved in a folder in this example and merged afterwards.
52 |
53 | ```R
54 | # packages
55 | library(lidR)
56 | library(CspStandSegmentation)
57 |
58 | # parameters
59 | las_file <- "your_file.laz"
60 | base_dir <- "~/your_project_folder/" # with trailing /
61 | cores <- parallel::detectCores()/2 # number od cpu cores
62 | res <- 0.3 # voxel resolution for segmentation
63 | chunk_size <- 50 # size of one tile in m excl. buffer
64 | chunk_buffer <- 10 # buffer around tile in m
65 |
66 | # main
67 |
68 | # create dir for segmentation tiles
69 | if(!dir.exists(paste0(base_dir,"segmentation_tiles/"))) {
70 | dir.create(paste0(base_dir,"segmentation_tiles/"))
71 | }
72 |
73 | uls = lidR::readTLSLAScatalog(paste0(base_dir,las_file), select = "XYZ0", chunk_size = chunk_size, chunk_buffer = chunk_buffer)
74 | plot(uls, chunk_pattern = T)
75 | # plot(dtm,add = T)
76 | # sf::as_Spatial(sf::st_as_sf(map, coords = c("X", "Y"))) |> plot(add = T)
77 |
78 | opt_output_files(uls) <- paste0(base_dir,"segmentation_tiles/{ID}")
79 | segmented <- catalog_apply(uls, function(cluster) {
80 |
81 | las <- suppressWarnings(readLAS(cluster)) # read files
82 | if (is.empty(las) ) return(NULL) # stop if empty
83 | print(str(cluster))
84 | # find tree positions as starting points for segmentation
85 | map <- CspStandSegmentation::find_base_coordinates_raster(las)
86 |
87 | # add the tile ID*100,000 to the TreeID to ensure unique IDs across all tiles
88 | map$TreeID <- map$TreeID + as.numeric(basename(cluster@save)) * 100000
89 |
90 | # only use seed positions within the tile+buffer and save the tile bbox to only return tree pos within the tile (excl. buffer)
91 | inv <- map
92 | invb <- map
93 | # the bbox includes the buffer, the bbbox excludes the buffer
94 | bbox <- cluster@bbox
95 | bbbox <- cluster@bbbox
96 | inv <- inv[inv$X < bbox[1,2] & inv$X > bbox[1,1] & inv$Y < bbox[2,2] & inv$Y > bbox[2,1],]
97 | invb <- invb[invb$X < bbbox[1,2] & invb$X > bbbox[1,1] & invb$Y < bbbox[2,2] & invb$Y > bbbox[2,1],]
98 | if (nrow(inv) == 0) return(NULL) # stop if no tree pos in tile found
99 | if (is.empty(las) ) return(NULL) # stop if empty
100 |
101 | # Assign all points to trees
102 | las <- las |> add_geometry(n_cores = cores) |> csp_cost_segmentation(invb,res, N_cores = cores, V_w = 0.5)
103 | # las <- las |> csp_cost_segmentation(map,res, N_cores = cores, V_w = 0.5) # this is a faster version which does not make use of the geometric feature weights
104 | if (is.empty(las)) return(NULL)
105 |
106 | las <- las |> filter_poi(TreeID %in% c(0,inv$TreeID)) # only return trees within the tile
107 | if (is.empty(las)) return(NULL) # stop if empty
108 |
109 | # remove unneccesary attributes for further processing
110 | las <- las |> remove_lasattribute('x_vox') |>
111 | remove_lasattribute('y_vox') |>
112 | remove_lasattribute('z_vox') |>
113 | remove_lasattribute('buffer') |>
114 | remove_lasattribute('Linearity') |>
115 | remove_lasattribute('Sphericity') |>
116 | remove_lasattribute('Verticality')
117 |
118 | # validate las
119 | las <- las |> las_quantize() |> las_update()
120 | if (is.empty(las)) return(NULL)
121 | return(las)
122 | }, .options = list(automerge = TRUE))
123 |
124 | # merge segmented trees
125 | segmented <- readTLSLAScatalog(paste0(base_dir,"segmentation_tiles/"), select = "xyz0", chunk_buffer = 0)
126 | opt_merge(segmented) <- TRUE
127 | opt_output_files(segmented) <- paste0("")
128 | segmented <- catalog_apply(segmented, function(cluster) {
129 | las <- suppressWarnings(readLAS(cluster)) # read files
130 | if (is.empty(las) ) return(NULL) # stop if empty
131 | return(las)
132 | }, .options = list(automerge = TRUE))
133 |
134 | # write results in a single file
135 | writeLAS(segmented, paste0(base_dir,"segmented.las"))
136 | ```
137 |
--------------------------------------------------------------------------------
/inst/extdata/beech.las:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JulFrey/CspStandSegmentation/362d39342bc91dfdb45f913573bc8a5b07d1d60e/inst/extdata/beech.las
--------------------------------------------------------------------------------
/inst/figures/csp_logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JulFrey/CspStandSegmentation/362d39342bc91dfdb45f913573bc8a5b07d1d60e/inst/figures/csp_logo.png
--------------------------------------------------------------------------------
/man/add_geometry.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2021-11-12_A1_JF_csp_cost_functions.R
3 | \name{add_geometry}
4 | \alias{add_geometry}
5 | \title{Add geometric features to a LAS object}
6 | \usage{
7 | add_geometry(las, k = 10L, n_cores = 1)
8 | }
9 | \arguments{
10 | \item{las}{A LAS object (see lidR::LAS)}
11 |
12 | \item{k}{the k nearest neighbors to use for the eigenvalue calculation}
13 |
14 | \item{n_cores}{The number of CPU cores to use}
15 | }
16 | \value{
17 | The function returns a single LAS object with the geometric features
18 | attached to it in the LAS@data section.
19 | }
20 | \description{
21 | The function calls a fast cpp multi-core function to calculate eigenvalues
22 | for the points in a point cloud based on the k nearest neighbors. Afterwards
23 | it adds geometric features like Curvature, Linearity, Planarity, Sphericity,
24 | Anisotrophy and Verticlity to the points itself.
25 | }
26 | \details{
27 | Details of the metrics can be found in: \ Hackel, T., Wegner, J.D. &
28 | Schindler, K. (2016) Contour Detection in Unstructured 3D Point Clouds. In
29 | 2016 IEEE Conference on Computer Vision and Pattern Recognition (CVPR).
30 | Presented at the 2016 IEEE Conference on Computer Vision and Pattern
31 | Recognition (CVPR), IEEE, Las Vegas, NV, USA, pp. 1610–1618.
32 | }
33 | \examples{
34 |
35 | LASfile <- system.file("extdata", "MixedConifer.laz", package="lidR")
36 | las <- lidR::readLAS(LASfile, select = "xyz", filter = "-inside 481250 3812980 481300 3813030")
37 |
38 | las <- add_geometry(las, k = 5, n_cores = parallel::detectCores()-1)
39 | summary(las@data)
40 |
41 |
42 | }
43 | \author{
44 | Julian Frey
45 | }
46 |
--------------------------------------------------------------------------------
/man/add_las_attributes.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2021-11-12_A1_JF_csp_cost_functions.R
3 | \name{add_las_attributes}
4 | \alias{add_las_attributes}
5 | \title{Add all las_attributes from las@data to the header of a las element}
6 | \usage{
7 | add_las_attributes(las)
8 | }
9 | \arguments{
10 | \item{las}{an element of lidR::LAS class}
11 | }
12 | \value{
13 | the las file with updated header
14 | }
15 | \description{
16 | The helper function adds all headings from las@data which are not part of
17 | lidR:::LASATTRIBUTES to the las header using lidR::add_lasattribute. Only
18 | attributes that are included in the header got saved when using
19 | lidR::writeLAS, this is a convenient way to add them.
20 | }
21 | \examples{
22 |
23 | file <- system.file("extdata", "beech.las", package="CspStandSegmentation")
24 | las <- lidR::readTLSLAS(file)
25 |
26 | las@data$noise <- runif(nrow(las@data))
27 | las@data$noiseZ <- las@data$var1 * las@data$Z
28 |
29 | las <- add_las_attributes(las)
30 |
31 | }
32 | \author{
33 | Julian Frey
34 | }
35 |
--------------------------------------------------------------------------------
/man/add_voxel_coordinates.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2021-11-12_A1_JF_csp_cost_functions.R
3 | \name{add_voxel_coordinates}
4 | \alias{add_voxel_coordinates}
5 | \title{Add voxel coordinates to a las file}
6 | \usage{
7 | add_voxel_coordinates(las, res)
8 | }
9 | \arguments{
10 | \item{las}{an element of lidR::LAS class}
11 |
12 | \item{res}{voxel ressolution in [m]}
13 | }
14 | \value{
15 | las file with additional voxel coordinates
16 | }
17 | \description{
18 | Adds the collums x_vox, y_vox and z_vox in the given ressolution to the las
19 | element. This is convenient if information has been derived in voxel space
20 | and these should be attached to the original points.
21 | }
22 | \details{
23 | Voxel coordinates derived with this function are identical to those derived
24 | by lidR::voxelize.
25 | }
26 | \examples{
27 |
28 | file = system.file("extdata", "beech.las", package="CspStandSegmentation")
29 | las = lidR::readTLSLAS(file)
30 |
31 | las <- add_voxel_coordinates(las,res = 1)
32 |
33 | lidR::plot(las, color = 'z_vox')
34 |
35 | }
36 | \author{
37 | Julian Frey
38 | }
39 |
--------------------------------------------------------------------------------
/man/comparative_shortest_path.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2021-11-12_A1_JF_csp_cost_functions.R
3 | \name{comparative_shortest_path}
4 | \alias{comparative_shortest_path}
5 | \title{helper function for csp_cost_segemntation}
6 | \usage{
7 | comparative_shortest_path(
8 | vox = vox,
9 | adjacency_df = adjacency_df,
10 | seeds,
11 | v_w = 0,
12 | l_w = 0,
13 | s_w = 0,
14 | N_cores = parallel::detectCores() - 1,
15 | Voxel_size
16 | )
17 | }
18 | \arguments{
19 | \item{vox}{a LAS S4 element with XYZ voxel coordinates in the @data slot.}
20 |
21 | \item{adjacency_df}{a data.frame with voxel ids (row numbers) in the first
22 | column and a neighboring voxel ID in the second column and the weight
23 | (distance) in the third column. Might be generated using the dbscan::frNN
24 | function (which requires reshaping the data).}
25 |
26 | \item{seeds}{seed points for tree positions.}
27 |
28 | \item{v_w, l_w, s_w}{weights for verticality, linearity spericity see
29 | \code{\link{csp_cost_segmentation}}}
30 |
31 | \item{N_cores}{Number of CPU cores for multi-threading}
32 |
33 | \item{Voxel_size}{Edge length used to create the voxels. This is only
34 | important to gain comparable distance weights on different voxel sizes.
35 | Should be greater than 0.}
36 | }
37 | \value{
38 | voxels with the TreeID in the data slot
39 | }
40 | \description{
41 | The function performs a Dijkstra algorithm on a 3D voxel file to assign
42 | every voxel to the closest seed point using the igraph package.
43 | }
44 | \seealso{
45 | \code{\link{csp_cost_segmentation}}
46 | }
47 | \author{
48 | Julian Frey
49 | }
50 |
--------------------------------------------------------------------------------
/man/csp_cost_segmentation.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2021-11-12_A1_JF_csp_cost_functions.R
3 | \name{csp_cost_segmentation}
4 | \alias{csp_cost_segmentation}
5 | \title{Comparative Shortest Path with cost weighting tree segmentation}
6 | \usage{
7 | csp_cost_segmentation(
8 | las,
9 | map,
10 | Voxel_size = 0.3,
11 | V_w = 0,
12 | L_w = 0,
13 | S_w = 0,
14 | N_cores = 1
15 | )
16 | }
17 | \arguments{
18 | \item{las}{A lidR LAS S4 object.}
19 |
20 | \item{map}{A data.frame, including the columns
21 | X, Y, Z, TreeID, with X and Y depicting the location of the trees. Can be generated using CspStandSegmentation::find_base_coordinates_raster}
22 |
23 | \item{Voxel_size}{The voxel size (3D resolution) for the routing graph to
24 | determine the nearest map location for every point in the point cloud.}
25 |
26 | \item{V_w}{verticality weight. Since trunks are vertical structures, routing
27 | through voxels with high verticality can be rated 'cheaper.' should be a
28 | number between 0 and 1 with 0 meaning no benefit for more vertical
29 | structures.}
30 |
31 | \item{L_w}{Linearity weight. Similar to V_w but for linearity, higher
32 | values indicate a malus for linear shapes (usually branches).}
33 |
34 | \item{S_w}{Spericity weight. Similar to V_w but for sphericity, higher
35 | values indicate a malus for spherical shapes (usually small branches and
36 | leaves).}
37 |
38 | \item{N_cores}{number of CPU cores used for parallel routing using the
39 | foreach package.}
40 | }
41 | \value{
42 | Returns a copy of the las point cloud with an additional field for
43 | the TreeID.
44 | }
45 | \description{
46 | Segments single trees from forest point clouds based on tree positions
47 | (xyz-coordinates) provided in the map argument.
48 | }
49 | \details{
50 | The whole point cloud is voxelized in the given resolution and the center of
51 | gravity for the points inside is calculated as voxel coordinate. A graph is
52 | build, which connects the voxel coordinates based on a db-scan algorithm. The
53 | distances between the voxel coordinates is weighted based on geometric
54 | features computed for the points in the voxels. Distances along planar
55 | and/or vertical faces like stems are weighted shorter than distances through
56 | voxels with high sphericity like leaves and clusters of twigs. This
57 | avoids small individuals spreading into the upper canopy.
58 | For every voxel center, the weighted distance in the network is calculated to
59 | all tree locations from the map argument. The TreeID of the map argument
60 | with the shortest distance is assigned to the voxel. All points in the point
61 | cloud receive the TreeID from their parent voxel.
62 | }
63 | \examples{
64 |
65 | # read example data
66 | file = system.file("extdata", "beech.las", package="CspStandSegmentation")
67 | las = lidR::readTLSLAS(file)
68 |
69 | # Find tree positions as starting points for segmentation
70 | map <- CspStandSegmentation::find_base_coordinates_raster(las)
71 | # segment trees
72 | segmented <- las |>
73 | CspStandSegmentation::add_geometry() |>
74 | CspStandSegmentation::csp_cost_segmentation(map, 1)
75 |
76 | lidR::plot(segmented, color = "TreeID")
77 |
78 | }
79 | \seealso{
80 | \code{\link{comparative_shortest_path}}
81 | }
82 | \author{
83 | Julian Frey
84 | }
85 |
--------------------------------------------------------------------------------
/man/eigen_decomposition.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/RcppExports.R
3 | \name{eigen_decomposition}
4 | \alias{eigen_decomposition}
5 | \title{Fast Eigenvalues decomposition for k nearest neighbors using a C++ function}
6 | \usage{
7 | eigen_decomposition(las, k, ncpu = 1L)
8 | }
9 | \arguments{
10 | \item{las}{LAS element}
11 |
12 | \item{k}{k nearest neighbors}
13 |
14 | \item{ncpu}{number of cpu cores to use}
15 | }
16 | \value{
17 | The function returns for every point the 3 eigenvalues and the
18 | third element of the third eigenvector. These values are needed to compute
19 | planarity, linerity, verticality etc. in the add_geometry function
20 | }
21 | \description{
22 | C++ helper function to compute eigenvalues for geometric feature
23 | calculation.
24 | }
25 | \seealso{
26 | \link{add_geometry}
27 | }
28 | \author{
29 | Julian Frey
30 | }
31 |
--------------------------------------------------------------------------------
/man/fast_unlist.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/RcppExports.R
3 | \name{fast_unlist}
4 | \alias{fast_unlist}
5 | \title{helper function to unlist IDs generated by dbscan::frNN}
6 | \usage{
7 | fast_unlist(list, l)
8 | }
9 | \arguments{
10 | \item{list}{a list element created by dbscan::frNN}
11 |
12 | \item{l}{the expected length of the result
13 | @author Julian Frey
14 | @export fast_unlist}
15 | }
16 | \description{
17 | creates a vector of indices from a nested list created by dbscan::frNN
18 | }
19 |
--------------------------------------------------------------------------------
/man/fast_unlist_dist.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/RcppExports.R
3 | \name{fast_unlist_dist}
4 | \alias{fast_unlist_dist}
5 | \title{helper function to unlist distances computed by dbscan::frNN}
6 | \usage{
7 | fast_unlist_dist(list, l)
8 | }
9 | \arguments{
10 | \item{list}{a list element created by dbscan::frNN}
11 |
12 | \item{l}{the expected length of the result}
13 | }
14 | \description{
15 | extracts the distances from a nested list created by dbscan::frNN
16 | }
17 | \author{
18 | Julian Frey
19 | }
20 |
--------------------------------------------------------------------------------
/man/fds.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2024-06-10_A1_JF_farthest_point_sampling.R
3 | \name{fds}
4 | \alias{fds}
5 | \title{Farthest Distance Sampling (Farthest Point Sampling)}
6 | \usage{
7 | fds(mat, n, ret = "idx", scale = F)
8 | }
9 | \arguments{
10 | \item{mat}{a matrix of points with one row for each point and one column for each dimension, can also be a las object then only XYZ will be used}
11 |
12 | \item{n}{the number of points to select, or if <1 the proportion of points to select}
13 |
14 | \item{ret}{the type of output to return. Options are "idx" (default) to return the indices of the selected points, "mat" to return the selected points.}
15 |
16 | \item{scale}{logical. If TRUE, the dimensions are scaled to have a mean of 0 and a standard deviation of 1 before calculating distances.}
17 | }
18 | \value{
19 | a vector of indices or a matrix of points
20 | }
21 | \description{
22 | This function selects n points from a matrix of points such that the minimum distance between any two points is maximized.
23 | This version is memory efficient and can handle large matrices.
24 | }
25 | \examples{
26 | mat <- matrix(rnorm(1000), ncol = 10)
27 | sample <- fds(mat, 50, ret = "mat")
28 | \dontrun{
29 | plot(mat, col = "black", pch = 19)
30 | points(sample, col = "red", pch = 19)
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/man/find_base_coordinates_geom.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2021-11-12_A1_JF_csp_cost_functions.R
3 | \name{find_base_coordinates_geom}
4 | \alias{find_base_coordinates_geom}
5 | \title{Find stem base position using a geometric feature filtering and clustering
6 | approach}
7 | \usage{
8 | find_base_coordinates_geom(
9 | las,
10 | zmin = 0.5,
11 | zmax = 2,
12 | res = 0.5,
13 | min_verticality = 0.9,
14 | min_planarity = 0.5,
15 | min_cluster_size = NULL
16 | )
17 | }
18 | \arguments{
19 | \item{las}{an element of lidR::LAS class}
20 |
21 | \item{zmin}{lower search boundary}
22 |
23 | \item{zmax}{upper search boundary}
24 |
25 | \item{res}{cluster search radius}
26 |
27 | \item{min_verticality}{minimum verticality >0 & <1 for a point to be
28 | considered a stem point}
29 |
30 | \item{min_planarity}{minimum planarity >0 & <1 for a point to be considered
31 | a stem point}
32 |
33 | \item{min_cluster_size}{minimum number of points in the cluster to be considered
34 | a tree, if NULL median cluster size is chosen}
35 | }
36 | \value{
37 | data.frame with X, Y, Z and TreeID for stem base positions
38 | }
39 | \description{
40 | Find stem base position using a geometric feature filtering and clustering
41 | approach
42 | }
43 | \examples{
44 | # read example data
45 | file = system.file("extdata", "beech.las", package="CspStandSegmentation")
46 | tls = lidR::readTLSLAS(file)
47 |
48 | # Find tree positions
49 | map <- CspStandSegmentation::find_base_coordinates_geom(tls)
50 | }
51 | \author{
52 | Julian Frey
53 | }
54 |
--------------------------------------------------------------------------------
/man/find_base_coordinates_raster.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2021-11-12_A1_JF_csp_cost_functions.R
3 | \name{find_base_coordinates_raster}
4 | \alias{find_base_coordinates_raster}
5 | \title{Find stem base position using a density raster approach}
6 | \usage{
7 | find_base_coordinates_raster(
8 | las,
9 | res = 0.1,
10 | zmin = 0.5,
11 | zmax = 2,
12 | q = 0.975,
13 | eps = 0.2
14 | )
15 | }
16 | \arguments{
17 | \item{las}{an element of lidR::LAS class}
18 |
19 | \item{res}{raster resolution}
20 |
21 | \item{zmin}{lower search boundary}
22 |
23 | \item{zmax}{upper search boundary}
24 |
25 | \item{q}{quantile of raster density to assign a tree region}
26 |
27 | \item{eps}{search radius to merge base points}
28 | }
29 | \value{
30 | data.frame with X, Y, Z and TreeID for stem base positions
31 | }
32 | \description{
33 | Find stem base position using a density raster approach
34 | }
35 | \examples{
36 | # read example data
37 | file = system.file("extdata", "beech.las", package="CspStandSegmentation")
38 | tls = lidR::readTLSLAS(file)
39 |
40 | # Find tree positions
41 | map <- CspStandSegmentation::find_base_coordinates_raster(tls)
42 | }
43 | \author{
44 | Julian Frey
45 | }
46 |
--------------------------------------------------------------------------------
/man/forest_inventory.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2025-01-10_A1_JF_forest_inventory.R
3 | \name{forest_inventory}
4 | \alias{forest_inventory}
5 | \title{Function to perform a forest inventory based on a segmented las object (needs to contain TreeID)}
6 | \usage{
7 | forest_inventory(
8 | tls,
9 | slice_min = 0.3,
10 | slice_max = 4,
11 | increment = 0.2,
12 | width = 0.1,
13 | max_dbh = 1,
14 | n_cores = max(c(1, parallel::detectCores()/2 - 1))
15 | )
16 | }
17 | \arguments{
18 | \item{slice_min}{the minimum height of a slice for stems to estimate the taper curve}
19 |
20 | \item{slice_max}{the maximum height of a slice for stems to estimate the taper curve}
21 |
22 | \item{increment}{the increment of the slices}
23 |
24 | \item{width}{the width of the slices}
25 |
26 | \item{max_dbh}{the maximum DBH allowed}
27 |
28 | \item{n_cores}{number of cores to use}
29 |
30 | \item{las}{lidR las object with the segmented trees}
31 | }
32 | \value{
33 | a data.frame with the TreeID, X, Y, DBH, quality_flag, Height and ConvexHullArea
34 | }
35 | \description{
36 | This function estimates a taper curve for evry tree and returns the DBH at 1.3m, its position in XY coordinates, the tree height and the trees 2D projection area.
37 | }
38 | \examples{
39 | # read example data
40 | file = system.file("extdata", "beech.las", package="CspStandSegmentation")
41 | tls = lidR::readTLSLAS(file)
42 |
43 | # find tree positions as starting points for segmentation
44 | map <- CspStandSegmentation::find_base_coordinates_raster(tls)
45 |
46 | # segment trees
47 | segmented <- tls |>
48 | CspStandSegmentation::add_geometry(n_cores = parallel::detectCores()/2) |>
49 | CspStandSegmentation::csp_cost_segmentation(map, 1, N_cores = parallel::detectCores()/2)
50 |
51 | # show results
52 | \dontrun{lidR::plot(segmented, color = "TreeID")}
53 |
54 | # perform inventory
55 | inventory <- CspStandSegmentation::forest_inventory(segmented)
56 | }
57 |
--------------------------------------------------------------------------------
/man/forest_inventory_simple.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2025-01-10_A1_JF_forest_inventory.R
3 | \name{forest_inventory_simple}
4 | \alias{forest_inventory_simple}
5 | \title{Function to perform a forest inventory based on a segmented las object (needs to contain TreeID)
6 | This version is a faster but more simplistic approach than forest_inventory() for the DBH estimates}
7 | \usage{
8 | forest_inventory_simple(
9 | tls,
10 | slice_min = 1.2,
11 | slice_max = 1.4,
12 | max_dbh = 1,
13 | n_cores = max(c(1, parallel::detectCores()/2 - 1))
14 | )
15 | }
16 | \arguments{
17 | \item{tls}{lidR las object with the segmented trees}
18 |
19 | \item{slice_min}{the minimum height of a DBH slice}
20 |
21 | \item{slice_max}{the maximum height of a DBH slice}
22 |
23 | \item{max_dbh}{the maximum DBH allowed}
24 |
25 | \item{n_cores}{number of cores to use}
26 | }
27 | \value{
28 | a data.frame with the TreeID, X, Y, DBH, quality_flag, Height and ConvexHullArea
29 | }
30 | \description{
31 | Function to perform a forest inventory based on a segmented las object (needs to contain TreeID)
32 | This version is a faster but more simplistic approach than forest_inventory() for the DBH estimates
33 | }
34 |
--------------------------------------------------------------------------------
/man/las_merge.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2025-01-07_A1_JF_merge_las_objects.R
3 | \name{las_merge}
4 | \alias{las_merge}
5 | \title{Makes one las object from multiple las objects}
6 | \usage{
7 | las_merge(..., oci = TRUE, fill = FALSE)
8 | }
9 | \arguments{
10 | \item{...}{any number of las objects}
11 |
12 | \item{oci}{add a column with the original cloud index}
13 |
14 | \item{fill}{fill missing columns with NA if it is set to False collumns which do not exist in all las objects will be removed}
15 | }
16 | \value{
17 | A single las object
18 | }
19 | \description{
20 | This function merges multiple las objects into one las object. The function checks if all inputs are las objects and if they have the same CRS. The function will also add a column oci with the original cloud index to each las object. The function will then rbind all data by the minimum set of columns. If the fill argument is set to False, columns which do not exist in all las objects will be removed. If the fill argument is set to True, missing columns will be filled with NA.
21 | }
22 | \examples{
23 | las1 <- lidR::LAS(data.frame(X = runif(100), Y = runif(100), Z = runif(100)))
24 | las2 <- lidR::LAS(data.frame(X = runif(100) + 2, Y = runif(100), Z = runif(100)))
25 | las3 <- lidR::LAS(data.frame(X = runif(100) + 4, Y = runif(100), Z = runif(100)))
26 | las_merge(las1, las2, las3)
27 | # las_merge(las1, las2, las3) |> lidR::plot(color = "oci")
28 | }
29 |
--------------------------------------------------------------------------------
/man/p_dist.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2024-06-10_A1_JF_farthest_point_sampling.R
3 | \name{p_dist}
4 | \alias{p_dist}
5 | \title{Point distance function}
6 | \usage{
7 | p_dist(p1, p2)
8 | }
9 | \arguments{
10 | \item{p1}{point 1}
11 |
12 | \item{p2}{point 2}
13 | }
14 | \value{
15 | the distance between the two points
16 | }
17 | \description{
18 | calculates euclidean distances for n dimensions
19 | }
20 | \examples{
21 | p_dist(c(0,0), c(3,4))
22 | }
23 |
--------------------------------------------------------------------------------
/man/p_mat_dist.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2024-06-10_A1_JF_farthest_point_sampling.R
3 | \name{p_mat_dist}
4 | \alias{p_mat_dist}
5 | \title{Point distance function}
6 | \usage{
7 | p_mat_dist(mat, p)
8 | }
9 | \arguments{
10 | \item{mat}{matrix with points as rows}
11 |
12 | \item{p}{point to calculate distances}
13 | }
14 | \value{
15 | the distances between every row of mat and p
16 | }
17 | \description{
18 | calculates euclidean distances for n dimensions between a matrix of points and a single point
19 | }
20 | \examples{
21 | p_dist(as.matrix(cbind(runf(100),runf(100)), c(3,4))
22 | }
23 |
--------------------------------------------------------------------------------
/man/plot_inventory.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2025-01-10_A1_JF_forest_inventory.R
3 | \name{plot_inventory}
4 | \alias{plot_inventory}
5 | \title{Function to plot the inventory results into a lidR 3d plot of the point cloud}
6 | \usage{
7 | plot_inventory(plot, inventory, col = NA, cex = 1.5, label_col = "white")
8 | }
9 | \arguments{
10 | \item{plot}{lidR 3d plot}
11 |
12 | \item{inventory}{data.frame with the inventory results}
13 |
14 | \item{col}{color of the spheres}
15 |
16 | \item{cex}{numeric size of the labels}
17 |
18 | \item{label_col}{character color of the labels}
19 | }
20 | \value{
21 | the plot with the inventory results
22 | }
23 | \description{
24 | Function to plot the inventory results into a lidR 3d plot of the point cloud
25 | }
26 | \examples{
27 | \dontrun{
28 | x <- lidR::plot(segmented, color = "TreeID")
29 | plot_inventory(x, inventory)
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/man/point_center_angle.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2025-01-10_A1_JF_forest_inventory.R
3 | \name{point_center_angle}
4 | \alias{point_center_angle}
5 | \title{Returns the angle between the center of the circle and a point in degrees}
6 | \usage{
7 | point_center_angle(point, circle)
8 | }
9 | \arguments{
10 | \item{point}{numeric vector of length 2 c(X,Y)}
11 |
12 | \item{circle}{numeric vector of length 3 c(center_X, center_Y, radius)}
13 | }
14 | \value{
15 | numeric angle in degrees
16 | }
17 | \description{
18 | Returns the angle between the center of the circle and a point in degrees
19 | }
20 |
--------------------------------------------------------------------------------
/man/point_circle_distance.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2025-01-10_A1_JF_forest_inventory.R
3 | \name{point_circle_distance}
4 | \alias{point_circle_distance}
5 | \title{Helper function to compute distances from a point to the circle}
6 | \usage{
7 | point_circle_distance(point, circle)
8 | }
9 | \arguments{
10 | \item{point}{numeric vector of length 2 c(X,Y)}
11 |
12 | \item{circle}{numeric vector of length 3 c(center_X, center_Y, radius)}
13 | }
14 | \value{
15 | numeric distance from the point to the circle
16 | }
17 | \description{
18 | Helper function to compute distances from a point to the circle
19 | }
20 |
--------------------------------------------------------------------------------
/man/ransac_circle_fit.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2025-01-10_A1_JF_forest_inventory.R
3 | \name{ransac_circle_fit}
4 | \alias{ransac_circle_fit}
5 | \title{RANSAC circle fitting algorithm specially adapted for tree DBH estimation}
6 | \usage{
7 | ransac_circle_fit(
8 | data,
9 | n_iterations = 1000,
10 | distance_threshold = 0.01,
11 | min_inliers = 3
12 | )
13 | }
14 | \arguments{
15 | \item{data}{numeric matrix with 2 columns (X, Y) representing the point cloud}
16 |
17 | \item{n_iterations}{integer maximum number of iterations}
18 |
19 | \item{distance_threshold}{numeric maximum distance from a point to the circle to be considered an inlier}
20 |
21 | \item{min_inliers}{integer minimum number of inliers to consider the circle as valid}
22 | }
23 | \description{
24 | This function fits a circle to a set of points using the RANSAC algorithm it maximizes the points that are in the circle and the number of filled 36 degree angle segments
25 | Therefore, this function searches for the most complete circle with the highest number of points represented.
26 | }
27 |
--------------------------------------------------------------------------------
/man/suppress_cat.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2025-01-10_A1_JF_forest_inventory.R
3 | \name{suppress_cat}
4 | \alias{suppress_cat}
5 | \title{Suppress only the cat() output}
6 | \usage{
7 | suppress_cat(f, ...)
8 | }
9 | \arguments{
10 | \item{f}{function to be called}
11 | }
12 | \value{
13 | the return value of the function
14 | }
15 | \description{
16 | Suppress only the cat() output
17 | }
18 |
--------------------------------------------------------------------------------
/man/voxelize_points_mean_attributes.Rd:
--------------------------------------------------------------------------------
1 | % Generated by roxygen2: do not edit by hand
2 | % Please edit documentation in R/2021-11-12_A1_JF_csp_cost_functions.R
3 | \name{voxelize_points_mean_attributes}
4 | \alias{voxelize_points_mean_attributes}
5 | \title{helper function to voxelize a las element}
6 | \usage{
7 | voxelize_points_mean_attributes(las, res)
8 | }
9 | \arguments{
10 | \item{las}{a lidR::LAS element}
11 |
12 | \item{res}{voxel resolution in meter}
13 | }
14 | \value{
15 | a las element with XYZ-coordinates as the voxel center and
16 | X_gr,Y_gr,Z_gr as the center of gravity (mean point coordinates) as well as
17 | all other numeric columns voxel mean values with their original name.
18 | }
19 | \description{
20 | Calculate voxel mean values for all numeric attributes in the las@data table
21 | including the XYZ-coordinates.
22 | }
23 | \examples{
24 |
25 | # read example data
26 | file = system.file("extdata", "beech.las", package="CspStandSegmentation")
27 | las = lidR::readTLSLAS(file)
28 | las |> voxelize_points_mean_attributes(1) |> lidR::plot(color = 'X_gr')
29 |
30 | }
31 | \seealso{
32 | \code{\link{voxelize_points}}
33 | }
34 | \author{
35 | Julian Frey
36 | }
37 |
--------------------------------------------------------------------------------
/src/2021-11-12_A1_JF_csp_cost_cpp_functions.cpp:
--------------------------------------------------------------------------------
1 | // [[Rcpp::depends(lidR)]]
2 | // [[Rcpp::depends(RcppArmadillo)]]
3 | // [[Rcpp::plugins(openmp)]]
4 |
5 | #include
6 | #include
7 | #include
8 |
9 | using namespace Rcpp;
10 | using namespace lidR;
11 |
12 |
13 |
14 | //' helper function to unlist IDs generated by dbscan::frNN
15 | //'
16 | //'
17 | //' creates a vector of indices from a nested list created by dbscan::frNN
18 | //'
19 | //' @param list a list element created by dbscan::frNN
20 | //' @param l the expected length of the result
21 | //' @author Julian Frey
22 | //' @export fast_unlist
23 | // [[Rcpp::export]]
24 | IntegerVector fast_unlist(List list, int l){
25 |
26 | // define results
27 | IntegerVector res(l);
28 |
29 | int k = 0;
30 | for (int i = 0; i < list.length(); ++i) {
31 | for (int j = 0; j < as(list[i]).length(); j++){
32 | res[k] = i;
33 | k++;
34 | }
35 | }
36 |
37 | // return indices
38 | return res;
39 | }
40 |
41 | //' helper function to unlist distances computed by dbscan::frNN
42 | //'
43 | //' extracts the distances from a nested list created by dbscan::frNN
44 | //'
45 | //' @param list a list element created by dbscan::frNN
46 | //' @param l the expected length of the result
47 | //' @author Julian Frey
48 | //' @export fast_unlist_dist
49 | // [[Rcpp::export]]
50 | NumericVector fast_unlist_dist(List list, int l){
51 |
52 | // define results
53 | NumericVector res(l);
54 |
55 | int k = 0;
56 | for (int i = 0; i < list.length(); ++i) {
57 | NumericVector dists = as(list[i]);
58 | for (int j = 0; j < dists.length(); j++){
59 | res[k] = dists[j];
60 | k++;
61 | }
62 | }
63 |
64 | // return indices
65 | return res;
66 | }
67 |
68 |
69 | //' Fast Eigenvalues decomposition for k nearest neighbors using a C++ function
70 | //'
71 | //' C++ helper function to compute eigenvalues for geometric feature
72 | //' calculation.
73 | //'
74 | //' @param las LAS element
75 | //' @param k k nearest neighbors
76 | //' @param ncpu number of cpu cores to use
77 | //' @return The function returns for every point the 3 eigenvalues and the
78 | //' third element of the third eigenvector. These values are needed to compute
79 | //' planarity, linerity, verticality etc. in the add_geometry function
80 | //' @author Julian Frey
81 | //' @seealso \link{add_geometry}
82 | //' @export eigen_decomposition
83 | // [[Rcpp::export]]
84 | NumericMatrix eigen_decomposition(S4 las, int k, int ncpu = 1)
85 | {
86 | DataFrame data = as(las.slot("data"));
87 | NumericVector X = data["X"];
88 | NumericVector Y = data["Y"];
89 | NumericVector Z = data["Z"];
90 | unsigned int npoints = X.size();
91 |
92 | NumericMatrix out(npoints, 4);
93 |
94 | SpatialIndex index(las);
95 |
96 | #pragma omp parallel for num_threads(ncpu)
97 | for (unsigned int i = 0 ; i < npoints ; i++)
98 | {
99 | arma::mat A(k,3);
100 | arma::mat coeff; // Principle component matrix
101 | arma::mat score;
102 | arma::vec latent; // Eigenvalues in descending order
103 |
104 | PointXYZ p(X[i], Y[i], Z[i]);
105 |
106 | std::vector pts;
107 | index.knn(p, k, pts);
108 |
109 | for (unsigned int j = 0 ; j < pts.size() ; j++)
110 | {
111 | A(j,0) = pts[j].x;
112 | A(j,1) = pts[j].y;
113 | A(j,2) = pts[j].z;
114 | }
115 |
116 | arma::princomp(coeff, score, latent, A);
117 |
118 | #pragma omp critical
119 | {
120 | out(i, 0) = latent[0];
121 | out(i, 1) = latent[1];
122 | out(i, 2) = latent[2];
123 | out(i, 3) = coeff[8];
124 | }
125 | }
126 |
127 | return out;
128 | }
129 |
--------------------------------------------------------------------------------
/src/Makevars.win:
--------------------------------------------------------------------------------
1 | PKG_CXXFLAGS = $(SHLIB_OPENMP_CXXFLAGS) -I../inst/include/ -DRCPP_NO_MODULES
2 | PKG_LIBS = $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS) $(SHLIB_OPENMP_CXXFLAGS)
3 | CXX_STD = CXX14
4 |
--------------------------------------------------------------------------------
/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 | #include
6 |
7 | using namespace Rcpp;
8 |
9 | #ifdef RCPP_USE_GLOBAL_ROSTREAM
10 | Rcpp::Rostream& Rcpp::Rcout = Rcpp::Rcpp_cout_get();
11 | Rcpp::Rostream& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get();
12 | #endif
13 |
14 | // fast_unlist
15 | IntegerVector fast_unlist(List list, int l);
16 | RcppExport SEXP _CspStandSegmentation_fast_unlist(SEXP listSEXP, SEXP lSEXP) {
17 | BEGIN_RCPP
18 | Rcpp::RObject rcpp_result_gen;
19 | Rcpp::RNGScope rcpp_rngScope_gen;
20 | Rcpp::traits::input_parameter< List >::type list(listSEXP);
21 | Rcpp::traits::input_parameter< int >::type l(lSEXP);
22 | rcpp_result_gen = Rcpp::wrap(fast_unlist(list, l));
23 | return rcpp_result_gen;
24 | END_RCPP
25 | }
26 | // fast_unlist_dist
27 | NumericVector fast_unlist_dist(List list, int l);
28 | RcppExport SEXP _CspStandSegmentation_fast_unlist_dist(SEXP listSEXP, SEXP lSEXP) {
29 | BEGIN_RCPP
30 | Rcpp::RObject rcpp_result_gen;
31 | Rcpp::RNGScope rcpp_rngScope_gen;
32 | Rcpp::traits::input_parameter< List >::type list(listSEXP);
33 | Rcpp::traits::input_parameter< int >::type l(lSEXP);
34 | rcpp_result_gen = Rcpp::wrap(fast_unlist_dist(list, l));
35 | return rcpp_result_gen;
36 | END_RCPP
37 | }
38 | // eigen_decomposition
39 | NumericMatrix eigen_decomposition(S4 las, int k, int ncpu);
40 | RcppExport SEXP _CspStandSegmentation_eigen_decomposition(SEXP lasSEXP, SEXP kSEXP, SEXP ncpuSEXP) {
41 | BEGIN_RCPP
42 | Rcpp::RObject rcpp_result_gen;
43 | Rcpp::RNGScope rcpp_rngScope_gen;
44 | Rcpp::traits::input_parameter< S4 >::type las(lasSEXP);
45 | Rcpp::traits::input_parameter< int >::type k(kSEXP);
46 | Rcpp::traits::input_parameter< int >::type ncpu(ncpuSEXP);
47 | rcpp_result_gen = Rcpp::wrap(eigen_decomposition(las, k, ncpu));
48 | return rcpp_result_gen;
49 | END_RCPP
50 | }
51 |
52 | static const R_CallMethodDef CallEntries[] = {
53 | {"_CspStandSegmentation_fast_unlist", (DL_FUNC) &_CspStandSegmentation_fast_unlist, 2},
54 | {"_CspStandSegmentation_fast_unlist_dist", (DL_FUNC) &_CspStandSegmentation_fast_unlist_dist, 2},
55 | {"_CspStandSegmentation_eigen_decomposition", (DL_FUNC) &_CspStandSegmentation_eigen_decomposition, 3},
56 | {NULL, NULL, 0}
57 | };
58 |
59 | RcppExport void R_init_CspStandSegmentation(DllInfo *dll) {
60 | R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
61 | R_useDynamicSymbols(dll, FALSE);
62 | }
63 |
--------------------------------------------------------------------------------
/tests/testthat.R:
--------------------------------------------------------------------------------
1 | # This file is part of the standard setup for testthat.
2 | # It is recommended that you do not modify it.
3 | #
4 | # Where should you do additional test configuration?
5 | # Learn more about the roles of various files in:
6 | # * https://r-pkgs.org/tests.html
7 | # * https://testthat.r-lib.org/reference/test_package.html#special-files
8 |
9 | library(testthat)
10 | library(CspStandSegmentation)
11 |
12 | test_check("CspStandSegmentation")
13 |
--------------------------------------------------------------------------------
/tests/testthat/test-add_geometry.R:
--------------------------------------------------------------------------------
1 | las <- suppressMessages(suppressWarnings(lidR::LAS(data.frame(X=runif(10),Y=runif(10),Z=runif(10)))))
2 |
3 | testthat::test_that("errors", {
4 | testthat::expect_error(
5 | add_geometry(1,1),
6 | "las has to be a LAS object."
7 | )
8 |
9 | testthat::expect_error(
10 | add_geometry(las, -1),
11 | "k has to be one positive integer."
12 | )
13 | })
14 |
15 | testthat::test_that("output type", {
16 | testthat::expect_s4_class(
17 | add_geometry(las, 1),
18 | "LAS"
19 | )
20 | })
21 |
--------------------------------------------------------------------------------
/tests/testthat/test-add_las_attributes.R:
--------------------------------------------------------------------------------
1 | las <- las <- suppressMessages(suppressWarnings(lidR::LAS(data.frame(X=runif(10),Y=runif(10),Z=runif(10)))))
2 | las@data$test <- 1
3 |
4 | testthat::test_that("errors", {
5 | testthat::expect_error(
6 | add_las_attributes(1),
7 | "las has to be a LAS object."
8 | )
9 | })
10 |
11 | testthat::test_that("output type", {
12 | testthat::expect_s4_class(
13 | add_las_attributes(las),
14 | "LAS"
15 | )
16 | testthat::expect_equal(
17 | length(add_las_attributes(las)@header@VLR),
18 | 1
19 | )
20 | })
21 |
--------------------------------------------------------------------------------
/tests/testthat/test-add_voxel_coordinates.R:
--------------------------------------------------------------------------------
1 | las <- suppressMessages(suppressWarnings(lidR::LAS(data.frame(X=runif(10),Y=runif(10),Z=runif(10)))))
2 |
3 | testthat::test_that("errors", {
4 | testthat::expect_error(
5 | add_voxel_coordinates(1,1),
6 | "las has to be a LAS object."
7 | )
8 |
9 | testthat::expect_error(
10 | add_voxel_coordinates(las, -1),
11 | "res has to be numeric and positive."
12 | )
13 | })
14 |
15 | testthat::test_that("output type", {
16 | testthat::expect_s4_class(
17 | add_voxel_coordinates(las, 1),
18 | "LAS"
19 | )
20 | testthat::expect_equal(
21 | ncol(add_voxel_coordinates(las, 1)@data),
22 | 6
23 | )
24 | })
25 |
--------------------------------------------------------------------------------
/tests/testthat/test-csp_cost_segmentation.R:
--------------------------------------------------------------------------------
1 | las <- suppressMessages(suppressWarnings(lidR::LAS(data.frame(X=runif(10),Y=runif(10),Z=runif(10)))))
2 | map <- data.frame(X=0:1,Y=0:1,Z=0:1,TreeID = 1:2)
3 |
4 | testthat::test_that("errors", {
5 | testthat::expect_error(
6 | csp_cost_segmentation(1,1),
7 | "las has to be a LAS object."
8 | )
9 |
10 | testthat::expect_error(
11 | csp_cost_segmentation(las, data.frame(X=1,Y=1,Z=1,Tree = 1)),
12 | "map has to be a data.frame with collumn names X,Y,Z,TreeID."
13 | )
14 | testthat::expect_error(
15 | csp_cost_segmentation(las, map, "a"),
16 | "Voxel_size, V_w, L_w, S_w and N_cores have to be numeric."
17 | )
18 | })
19 |
--------------------------------------------------------------------------------
/tests/testthat/test-voxelize_points_mean_attributes.R:
--------------------------------------------------------------------------------
1 | las <- suppressMessages(suppressWarnings(lidR::LAS(data.frame(X=runif(10),Y=runif(10),Z=runif(10)))))
2 |
3 | testthat::test_that("errors", {
4 | testthat::expect_error(
5 | voxelize_points_mean_attributes(1,1),
6 | "las has to be a LAS object."
7 | )
8 |
9 | testthat::expect_error(
10 | voxelize_points_mean_attributes(las, -1),
11 | "res has to be numeric and positive."
12 | )
13 | })
14 |
15 | testthat::test_that("output type", {
16 | testthat::expect_s4_class(
17 | voxelize_points_mean_attributes(las, 1),
18 | "LAS"
19 | )
20 | })
21 |
--------------------------------------------------------------------------------