Repository: InverseTampere/TreeQSM Branch: master Commit: 6630bbf516f8 Files: 89 Total size: 484.2 KB Directory structure: gitextract_28rx66s0/ ├── .gitignore ├── LICENSE.md ├── README.md └── src/ ├── create_input.m ├── estimate_precision.m ├── least_squares_fitting/ │ ├── form_rotation_matrices.m │ ├── func_grad_axis.m │ ├── func_grad_circle.m │ ├── func_grad_circle_centre.m │ ├── func_grad_cylinder.m │ ├── least_squares_axis.m │ ├── least_squares_circle.m │ ├── least_squares_circle_centre.m │ ├── least_squares_cylinder.m │ ├── nlssolver.m │ └── rotate_to_z_axis.m ├── main_steps/ │ ├── branches.m │ ├── correct_segments.m │ ├── cover_sets.m │ ├── cylinders.m │ ├── filtering.m │ ├── point_model_distance.m │ ├── relative_size.m │ ├── segments.m │ ├── tree_data.m │ └── tree_sets.m ├── make_models.m ├── make_models_parallel.m ├── plotting/ │ ├── plot2d.m │ ├── plot_branch_segmentation.m │ ├── plot_branches.m │ ├── plot_comparison.m │ ├── plot_cone_model.m │ ├── plot_cylinder_model.m │ ├── plot_cylinder_model2.m │ ├── plot_distribution.m │ ├── plot_large_point_cloud.m │ ├── plot_models_segmentations.m │ ├── plot_point_cloud.m │ ├── plot_scatter.m │ ├── plot_segments.m │ ├── plot_segs.m │ ├── plot_spreads.m │ ├── plot_tree_structure.m │ ├── plot_tree_structure2.m │ ├── plot_triangulation.m │ └── point_cloud_plotting.m ├── results/ │ └── qsm.mat ├── select_optimum.m ├── tools/ │ ├── average.m │ ├── change_precision.m │ ├── connected_components.m │ ├── cross_product.m │ ├── cubical_averaging.m │ ├── cubical_downsampling.m │ ├── cubical_partition.m │ ├── define_input.m │ ├── dimensions.m │ ├── display_time.m │ ├── distances_between_lines.m │ ├── distances_to_line.m │ ├── dot_product.m │ ├── expand.m │ ├── growth_volume_correction.m │ ├── intersect_elements.m │ ├── mat_vec_subtraction.m │ ├── median2.m │ ├── normalize.m │ ├── optimal_parallel_vector.m │ ├── orthonormal_vectors.m │ ├── rotation_matrix.m │ ├── save_model_text.m │ ├── sec2min.m │ ├── select_cylinders.m │ ├── set_difference.m │ ├── simplify_qsm.m │ ├── surface_coverage.m │ ├── surface_coverage2.m │ ├── surface_coverage_filtering.m │ ├── unique2.m │ ├── unique_elements.m │ ├── update_tree_data.m │ └── verticalcat.m ├── treeqsm.m └── triangulation/ ├── boundary_curve.m ├── boundary_curve2.m ├── check_self_intersection.m ├── curve_based_triangulation.m └── initial_boundary_curve.m ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .DS_Store ================================================ FILE: LICENSE.md ================================================ TreeQSM Version 2.4.0 Copyright (C) 2013-2020 Pasi Raumonen TreeQSM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TreeQSM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details. ## GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # TreeQSM **Version 2.4.1** **Reconstruction of quantitative structure models for trees from point cloud data** [![DOI](https://zenodo.org/badge/100592530.svg)](https://zenodo.org/badge/latestdoi/100592530) ![QSM image](https://github.com/InverseTampere/TreeQSM/blob/master/Manual/fig_point_cloud_qsm.png) ### Description TreeQSM is a modelling method that reconstructs quantitative structure models (QSMs) for trees from point clouds. A QSM consists of a hierarchical collection of cylinders estimating topological, geometrical and volumetric details of the woody structure of the tree. The input point cloud, which is usually produced by a terrestrial laser scanner, must contain only one tree, which is intended to be modelled, but the point cloud may contain also some points from the ground and understory. Moreover, the point cloud should not contain significant amount of noise or points from leaves as these are interpreted as points from woody parts of the tree and can therefore lead to erroneous results. Much more details of the method and QSMs can be found from the manual that is part of the code distribution. The TreeQSM is written in Matlab. The main function is _treeqsm.m_, which takes in a point cloud and a structure array specifying the needed parameters. Refer to the manual or the help documentation of a particular function for further details. ### References Web: https://research.tuni.fi/inverse/ Some published papers about the method and applications: Raumonen et al. 2013, Remote Sensing https://www.mdpi.com/2072-4292/5/2/491 Calders et al. 2015, Methods in Ecology and Evolution https://besjournals.onlinelibrary.wiley.com/doi/full/10.1111/2041-210X.12301 Raumonen et al. 2015, ISPRS Annals https://www.isprs-ann-photogramm-remote-sens-spatial-inf-sci.net/II-3-W4/189/2015/ Åkerblom et al. 2015, Remote Sensing https://www.mdpi.com/2072-4292/7/4/4581 Åkerblom et al. 2017, Remote Sensing of Environment https://www.sciencedirect.com/science/article/abs/pii/S0034425716304746 de Tanago Menaca et al. 2017, Methods in Ecology and Evolution https://besjournals.onlinelibrary.wiley.com/doi/10.1111/2041-210X.12904 Åkerblom et al. 2018, Interface Focus http://dx.doi.org/10.1098/rsfs.2017.0045 Disney et al. 2018, Interface Focus http://dx.doi.org/10.1098/rsfs.2017.0048 ### Quick guide Here is a quick guide for testing the code and starting its use. However, it is highly recommended that after the testing the user reads the manual for more information how to best use the code. 1) Start MATLAB and set the main path to the root folder, where _treeqsm.m_ is located.\ 2) Use _Set Path_ --> _Add with Subfolders_ --> _Open_ --> _Save_ --> _Close_ to add the subfolders, where all the codes of the software are, to the paths of MATLAB.\ 3) Import a point cloud of a tree into the workspace. Let us name it P.\ 4) Define suitable inputs:\     >> inputs = define_input(P,1,1,1);\ 5) Reconstruct QSMs:\     >> QSM = treeqsm(P,inputs); ================================================ FILE: src/create_input.m ================================================ % Creates input parameter structure array needed to run "treeqsm" function % and "filtering" function. % NOTE: use this code to define all the parameters but the PatchDiam and % BallRad parameters can be conveniently defined by "define_input" % function. % % Last update 11 May 2022 clear inputs %% QSM reconstruction parameters %%% THE THREE INPUT PARAMETERS TO BE OPTIMIZED. % These CAN BE VARIED AND SHOULD BE OPTIMIZED % One possibility to define these is to use "define_input" code % (These can have multiple values given as vectors, e.g. [0.01 0.02]). % Patch size of the first uniform-size cover: inputs.PatchDiam1 = [0.08 0.12]; % Minimum patch size of the cover sets in the second cover: inputs.PatchDiam2Min = [0.02 0.03]; % Maximum cover set size in the stem's base in the second cover: inputs.PatchDiam2Max = [0.07 0.1]; %%% ADDITIONAL PATCH GENERATION PARAMETERS. % The following parameters CAN BE VARIED BUT CAN BE USUALLY KEPT AS SHOWN % (i.e. little bigger than PatchDiam parameters). % One possibility to define these is to use "define_input" code % Ball radius in the first uniform-size cover generation: inputs.BallRad1 = inputs.PatchDiam1+0.015; % Maximum ball radius in the second cover generation: inputs.BallRad2 = inputs.PatchDiam2Max+0.01; % The following parameters CAN BE USUALLY KEPT FIXED as shown. % Minimum number of points in BallRad1-balls, generally good value is 3: inputs.nmin1 = 3; % Minimum number of points in BallRad2-balls, generally good value is 1: inputs.nmin2 = 1; % Does the point cloud contain points only from the tree (if 1, then yes): inputs.OnlyTree = 1; % Produce a triangulation of the stem's bottom part up to the first main % branch (if 1, then yes): inputs.Tria = 0; % Compute the point-model distances (if 1, then yes): inputs.Dist = 1; %%% RADIUS CORRECTION OPTIONS FOR MODIFYING TOO LARGE AND TOO SMALL CYLINDERS. % These parameters CAN BE USUALLY KEPT FIXED as shown. % Traditional TreeQSM choices: % Minimum cylinder radius, used particularly in the taper corrections: inputs.MinCylRad = 0.0025; % Radius correction based on radius of the parent. If 1, radii in a branch % are always smaller than the radius of the parent in the parent branch: inputs.ParentCor = 1; % Parabola taper correction of radii inside branches. If 1, use the % correction: inputs.TaperCor = 1; % Growth volume correction approach introduced by Jan Hackenberg, % allometry: Radius = a*GrowthVol^b+c inputs.GrowthVolCor = 0; % If 1, use growth volume (GV) correction % fac-parameter of the GV-approach, defines upper and lower bound. When % using GV-approach, consider setting TaperCorr = 0, ParentCorr = 0, % MinCylinderRadius = 0. inputs.GrowthVolFac = 1.5; % Defines the allowed radius: % 1/fac*predicted_radius <= radius <= fac*predicted_radius % However, the radii of the branch tip cylinders are not increased. %% Filtering parameters % NOTE: These are all optional, but needed to run the "filtering" function. % Statistical k-nearest neighbor distance outlier filtering, applied if % filter.k > 0. The value filter.k is the number of nearest neighbors. inputs.filter.k = 10; % Statistical point density outlier filtering, applied if filter.radius > 0. % The value filter.radius is the radius of the ball neighborhood. This is % usually meant as alternative to the above knn-filtering. inputs.filter.radius = 0.00; % The value filter.nsigma is the multiplier of the standard deviation of % the kth-nearest neighbor distance/point density and points whose % kth-nearest neighbor distance/point density is larger/lower than the % average +/- filter.nsigma * std are removed: inputs.filter.nsigma = 1.5; % Small component filtering is applied if filter.ncomp > 0. This filter is % based on cover whose patches are defined by filter.PatchDiam1 and % filter.BallRad1. The points which are included in components that have % less than filter.ncomp patches are removed: inputs.filter.PatchDiam1 = 0.05; inputs.filter.BallRad1 = 0.075; inputs.filter.ncomp = 2; % Cubical downsampling is applied if filter.EdgeLength > 0. % The value filter.EdgeLength is the length of the cube edges: inputs.filter.EdgeLength = 0.004; % Plot the filtering results automatically after the filtering if % filter.plot > 0 inputs.filter.plot = 1; %% Other inputs % These parameters don't affect the QSM-reconstruction but define what is % saved, plotted, and displayed and how the models are named/indexed % Name string for saving output files and naming models: inputs.name = 'tree'; % Tree index. If modelling multiple trees, then they can be indexed uniquely: inputs.tree = 1; % Model index, can separate models if multiple models with the same inputs: inputs.model = 1; % Save the output struct QSM as a matlab-file into \result folder. % If name = 'pine', tree = 2, model = 5, the name of the saved file is % 'QSM_pine_t2_m5.mat': inputs.savemat = 1; % Save the models in .txt-files (check "save_model_text.m"): inputs.savetxt = 1; % What are plotted during reconstruction process: % 2 = plots the QSM, the segmentated point cloud and distributions, % 1 = plots the QSM and the segmentated point cloud % 0 = plots nothing inputs.plot = 2; % What are displayed during the reconstruction: 2 = display all; % 1 = display name, parameters and distances; 0 = display only the name: inputs.disp = 2; ================================================ FILE: src/estimate_precision.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function [TreeData,OptQSMs,OptQSM] = ... estimate_precision(QSMs,NewQSMs,TreeData,OptModels,savename) % --------------------------------------------------------------------- % ESTIMATE_PRECISION.M Combines additional QSMs with optimal inputs % with previously generated QSMs to estimate the % precision (standard deviation) better. % % Version 1.1.0 % Latest update 10 May 2022 % % Copyright (C) 2016-2022 Pasi Raumonen % --------------------------------------------------------------------- % Uses models with the same inputs to estimate the precision (standard % deviation) of the results. Has two sets of models as its inputs: % 1) QSMs can contain models with many different input parameters for each tree % and OptModels contain the indexes of the models that are used here ("optimal % models"); 2) NewQSMs contains only models with the optimal inputs. % % Inputs: % QSMs Contain all the models, possibly from multiple trees % NewQSMs Contains the additional models with optimal inputs, for all trees % TreeData Similar structure array as the "treedata" in QSMs but now each % single-number attribute contains the mean and std computed % from the models with the optimal inputs, and the % sensitivities for PatchDiam-parameters % OptModels Indexes of the optimal models for each tree in "QSMs" % savename Optional input, name string specifying the name of the saved % file containing the outputs % Outputs: % TreeData Updated with new mean and std computed from all the QSMs % with the optimal inputs % OptQSMs Contains all the models with the optimal inputs, for all trees % OptQSM The best model (minimum point-model distance) among the models % with the optimal inputs, for all trees % --------------------------------------------------------------------- % Changes from version 1.0.2 to 1.1.0, 10 May 2022: % 1) Added "TreeData", the output of "select_optimum", as an input, and now % it is updated % Changes from version 1.0.1 to 1.0.2, 26 Nov 2019: % 1) Added the "name" of the point cloud from the inputs.name to the output % TreeData as a field. Also now displays the name together with the tree % number. % Changes from version 1.0.0 to 1.0.1, 08 Oct 2019: % 1) Small change for how the output "TreeData" is initialised %% Reconstruct the outputs OptQSMs = QSMs(vertcat(OptModels{:,1})); % Optimal models from the optimization process OptQSMs = [OptQSMs NewQSMs]; % Combine all the optimal QSMs m = max(size(OptQSMs)); % number of models IndAll = (1:1:m)'; % Find the first non-empty model i = 1; while isempty(OptQSMs(i).cylinder) i = i+1; end % Determine how many single-number attributes there are in treedata names = fieldnames(OptQSMs(i).treedata); n = 1; while numel(OptQSMs(i).treedata.(names{n})) == 1 n = n+1; end n = n-1; treedata = zeros(n,m); % Collect all single-number tree attributes from all models TreeId = zeros(m,1); % Collect tree and model indexes from all models Dist = zeros(m,1); % Collect the distances Keep = true(m,1); % Non-empty models for i = 1:m if ~isempty(OptQSMs(i).cylinder) for j = 1:n treedata(j,i) = OptQSMs(i).treedata.(names{j}); end TreeId(i) = OptQSMs(i).rundata.inputs.tree; Dist(i) = OptQSMs(i).pmdistance.mean; else Keep(i) = false; end end treedata = treedata(:,Keep); TreeId = TreeId(Keep,:); Dist = Dist(Keep); IndAll = IndAll(Keep); TreeIds = unique(TreeId); nt = length(TreeIds); % number of trees % Compute the means and standard deviations OptModel = zeros(nt,1); DataM = zeros(n,nt); DataS = zeros(n,nt); for t = 1:nt I = TreeId == TreeIds(t); ind = IndAll(I); dist = vertcat(Dist(ind)); [~,J] = min(dist); OptModel(t) = ind(J); DataM(:,t) = mean(treedata(:,ind),2); DataS(:,t) = std(treedata(:,ind),[],2); end OptQSM = OptQSMs(OptModel); DataCV = DataS./DataM*100; %% Display some data about optimal models % Decrease the number of non-zero decimals for j = 1:nt DataM(:,j) = change_precision(DataM(:,j)); DataS(:,j) = change_precision(DataS(:,j)); DataCV(:,j) = change_precision(DataCV(:,j)); end % Display optimal inputs, model and attributes for each tree for t = 1:nt disp([' Tree: ',num2str(t),', ',OptQSM(t).rundata.inputs.name]) disp(' Attributes (mean, std, CV(%)):') for i = 1:n str = ([' ',names{i},': ',num2str([DataM(i,t) DataS(i,t) DataCV(i,t)])]); disp(str) end disp('------') end %% Generate TreeData structure for optimal models %TreeData = vertcat(OptQSM(:).treedata); for t = 1:nt for i = 1:n TreeData(t).(names{i})(1:2) = [DataM(i,t) DataS(i,t)]; end TreeData(t).name = OptQSM(t).rundata.inputs.name; end %% Save results if nargin == 5 str = ['results/OptimalQSMs_',savename]; save(str,'TreeData','OptQSMs','OptQSM') end ================================================ FILE: src/least_squares_fitting/form_rotation_matrices.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function [R,dR1,dR2] = form_rotation_matrices(theta) % -------------------------------------------------------------------------- % FORM_ROTATION_MATRICES.M Forms rotation matrices R = R2*R1 and its % derivatives % % Input % theta Plane rotation angles (t1, t2) % % Output % R Rotation matrix % R1 Plane rotation [1 0 0; 0 c1 -s1; 0 s1 c1] % R2 Plane rotation [c2 0 s2; 0 1 0; -s2 0 c2] c = cos(theta); s = sin(theta); R1 = [1 0 0; 0 c(1) -s(1); 0 s(1) c(1)]; R = R1; R2 = [c(2) 0 s(2); 0 1 0; -s(2) 0 c(2)]; R = R2*R; if nargout > 1 dR1 = [0 0 0; 0 -R1(3,2) -R1(2,2); 0 R1(2,2) -R1(3,2)]; end if nargout > 2 dR2 = [-R2(1,3) 0 R2(1,1); 0 0 0; -R2(1,1) 0 -R2(1,3)]; end ================================================ FILE: src/least_squares_fitting/func_grad_axis.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function [dist,J] = func_grad_axis(P,par,weight) % --------------------------------------------------------------------- % FUNC_GRAD_CYLINDER.M Function and gradient calculation for % least-squares cylinder fit. % % Version 2.1.0 % Latest update 14 July 2020 % % Copyright (C) 2013-2020 Pasi Raumonen % --------------------------------------------------------------------- % % Input % par Cylinder parameters [x0 y0 alpha beta r]' % P Point cloud % weight (Optional) Weights for the points % % Output % dist Signed distances of points to the cylinder surface: % dist(i) = sqrt(xh(i)^2 + yh(i)^2) - r, where % [xh yh zh]' = Ry(beta) * Rx(alpha) * ([x y z]' - [x0 y0 0]') % J Jacobian matrix d dist(i)/d par(j). % Changes from version 2.0.0 to 2.1.0, 14 July 2020: % 1) Added optional input for weights of the points % Five cylinder parameters: % Location = axis point intersects xy-plane: x0 and y0 (z0 == 0) % Rotation angles around x and y axis = alpha and beta % Radius = r % % Transformed points: % Pt = [xh yx zh] = Ry(beta) * Rx(alpha) * (P - [x0 y0 0]) % % "Plane points": % Qt = Pt * I2 = [xh yh]; % % Distance: % D(x0,y0,alpha,beta,r) = sqrt( dot(Qt,Qt) )-r = sqrt( Qt*Qt' )-r % % Least squares = minimize Sum( D^2 ) over x0, y0, alpha, beta and r % % rt = sqrt( dot(Qt,Qt) ) % N = Qt/rt % % Jacobian for D with respect to x0, y0, alpha, beta: % dD/di = dot( N,dQt/di ) = dot( Qt/rt,dQt/di ) % % R = Ry*Rx % dQt/dx0 = R*[-1 0 0]' % dQt/dy0 = R*[0 -1 0]' % dQt/dalpha = (P-[x0 y0 0])*DRx'; % dQt/dalpha = (P-[x0 y0 0])*DRy'; x0 = par(1); y0 = par(2); alpha = par(3); beta = par(4); r = par(5); % Determine the rotation matrices and their derivatives [R,DR1,DR2] = form_rotation_matrices([alpha beta]); % Calculate the distances Pt = (P-[x0 y0 0])*R'; xt = Pt(:,1); yt = Pt(:,2); rt = sqrt(xt.*xt + yt.*yt); dist = rt-r; % Distances to the cylinder surface if nargin == 3 dist = weight.*dist; % Weighted distances end % form the Jacobian matrix if nargout > 1 N = [xt./rt yt./rt]; m = size(P,1); J = zeros(m,2); A3 = (P-[x0 y0 0])*DR1'; J(:,1) = sum(N(:,1:2).*A3(:,1:2),2); A4 = (P-[x0 y0 0])*DR2'; J(:,2) = sum(N(:,1:2).*A4(:,1:2),2); if nargin == 3 % Weighted Jacobian J = [weight.*J(:,1) weight.*J(:,2)]; end end ================================================ FILE: src/least_squares_fitting/func_grad_circle.m ================================================ function [dist,J] = func_grad_circle(P,par,weight) % --------------------------------------------------------------------- % FUNC_GRAD_CIRCLE.M Function and gradient calculation for % least-squares circle fit. % % Version 1.0 % Latest update 20 Oct 2017 % % Copyright (C) 2017 Pasi Raumonen % --------------------------------------------------------------------- % % Input % P Point cloud % par Circle parameters [x0 y0 r]' % weight Weights for the points. Weight the distances. % % Output % dist Signed distances of points to the circle: % dist(i) = sqrt((xi-x0)^2 + (yi-y0)^2) - r, where % % J Jacobian matrix d dist(i)/d par(j). % Calculate the distances Vx = P(:,1)-par(1); Vy = P(:,2)-par(2); rt = sqrt(Vx.*Vx + Vy.*Vy); if nargin == 3 dist = weight.*(rt-par(3)); % Weighted distances to the circle else dist = rt-par(3); % Distances to the circle end % form the Jacobian matrix if nargout > 1 m = size(P, 1); J = zeros(m,3); J(:,1) = -Vx./rt; J(:,2) = -Vy./rt; J(:,3) = -1*ones(m,1); % apply the weights if nargin == 3 J = [weight.*J(:,1) weight.*J(:,2) weight.*J(:,3)]; end end ================================================ FILE: src/least_squares_fitting/func_grad_circle_centre.m ================================================ function [dist,J] = func_grad_circle_centre(P,par,weight) % --------------------------------------------------------------------- % FUNC_GRAD_CIRCLE.M Function and gradient calculation for % least-squares circle fit. % % Version 1.0 % Latest update 20 Oct 2017 % % Copyright (C) 2017 Pasi Raumonen % --------------------------------------------------------------------- % % Input % P Point cloud % par Circle parameters [x0 y0 r]' % weight Weights for the points. Weight the distances. % % Output % dist Signed distances of points to the circle: % dist(i) = sqrt((xi-x0)^2 + (yi-y0)^2) - r, where % % J Jacobian matrix d dist(i)/d par(j). % Calculate the distances Vx = P(:,1)-par(1); Vy = P(:,2)-par(2); rt = sqrt(Vx.*Vx+Vy.*Vy); if nargin == 3 dist = weight.*(rt-par(3)); % Weighted distances to the circle else dist = rt-par(3); % Distances to the circle end % form the Jacobian matrix if nargout > 1 m = size(P,1); J = zeros(m,2); J(:,1) = -Vx./rt; J(:,2) = -Vy./rt; % apply the weights if nargin == 3 J = [weight.*J(:,1) weight.*J(:,2)]; end end ================================================ FILE: src/least_squares_fitting/func_grad_cylinder.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function [dist,J] = func_grad_cylinder(par,P,weight) % --------------------------------------------------------------------- % FUNC_GRAD_CYLINDER.M Function and gradient calculation for % least-squares cylinder fit. % % Version 2.2.0 % Latest update 5 Oct 2021 % % Copyright (C) 2013-2021 Pasi Raumonen % --------------------------------------------------------------------- % % Input % par Cylinder parameters [x0 y0 alpha beta r]' % P Point cloud % weight (Optional) Weights for the points % % Output % dist Signed distances of points to the cylinder surface: % dist(i) = sqrt(xh(i)^2 + yh(i)^2) - r, where % [xh yh zh]' = Ry(beta) * Rx(alpha) * ([x y z]' - [x0 y0 0]') % J Jacobian matrix d dist(i)/d par(j). % Five cylinder parameters: % Location = axis point intersects xy-plane: x0 and y0 (z0 == 0) % Rotation angles around x and y axis = alpha and beta % Radius = r % % Transformed points: % Pt = [xh yx zh] = Ry(beta) * Rx(alpha) * (P - [x0 y0 0]) % % "Plane points": % Qt = Pt * I2 = [xh yh]; % % Distance: % D(x0,y0,alpha,beta,r) = sqrt( dot(Qt,Qt) )-r = sqrt( Qt*Qt' )-r % % Least squares = minimize Sum( D^2 ) over x0, y0, alpha, beta and r % % rt = sqrt( dot(Qt,Qt) ) % N = Qt/rt % % Jacobian for D with respect to x0, y0, alpha, beta: % dD/di = dot( N,dQt/di ) = dot( Qt/rt,dQt/di ) % % R = Ry*Rx % dQt/dx0 = R*[-1 0 0]' % dQt/dy0 = R*[0 -1 0]' % dQt/dalpha = (P-[x0 y0 0])*DRx'; % dQt/dalpha = (P-[x0 y0 0])*DRy'; % Changes from version 2.1.0 to 2.2.0, 5 Oct 20201: % 1) Minor changes in syntax % Changes from version 2.0.0 to 2.1.0, 14 July 2020: % 1) Added optional input for weights of the points x0 = par(1); y0 = par(2); alpha = par(3); beta = par(4); r = par(5); % Determine the rotation matrices and their derivatives [R,DR1,DR2] = form_rotation_matrices([alpha beta]); % Calculate the distances Pt = (P-[x0 y0 0])*R'; xt = Pt(:,1); yt = Pt(:,2); rt = sqrt(xt.*xt + yt.*yt); dist = rt-r; % Distances to the cylinder surface if nargin == 3 dist = weight.*dist; % Weighted distances end % form the Jacobian matrix if nargout > 1 N = [xt./rt yt./rt]; m = size(P,1); J = zeros(m,5); A1 = (R*[-1 0 0]')'; A = eye(2); A(1,1) = A1(1); A(2,2) = A1(2); J(:,1) = sum(N(:,1:2)*A,2); A2 = (R*[0 -1 0]')'; A(1,1) = A2(1); A(2,2) = A2(2); J(:,2) = sum(N(:,1:2)*A,2); A3 = (P-[x0 y0 0])*DR1'; J(:,3) = sum(N(:,1:2).*A3(:,1:2),2); A4 = (P-[x0 y0 0])*DR2'; J(:,4) = sum(N(:,1:2).*A4(:,1:2),2); J(:,5) = -1*ones(m,1); if nargin == 3 % Weighted Jacobian J = [weight.*J(:,1) weight.*J(:,2) weight.*J(:,3) ... weight.*J(:,4) weight.*J(:,5)]; end end ================================================ FILE: src/least_squares_fitting/least_squares_axis.m ================================================ function cyl = least_squares_axis(P,Axis,Point0,Rad0,weight) % --------------------------------------------------------------------- % LEAST_SQUARES_AXIS.M Least-squares cylinder axis fitting using % Gauss-Newton when radius and point are given % % Version 1.0 % Latest update 1 Oct 2021 % % Copyright (C) 2017-2021 Pasi Raumonen % --------------------------------------------------------------------- % Input % P 3d point cloud % Axis0 Initial axis estimate (1 x 3) % Point0 Initial estimate of axis point (1 x 3) % Rad0 Initial estimate of the cylinder radius % weight (Optional) Weights for each point % % Output % cyl Structure array with the following fields % axis Cylinder axis (optimized here) % radius Radius of the cylinder (from the input) % start Axis point (from the input) % mad Mean absolute distance of the points to the cylinder surface % SurfCov Surface coverage, how much of the cylinder surface is covered % with points % conv If conv = 1, the algorithm has converged % rel If rel = 1, the algorithm has reliable answer in terms of % matrix inversion with a good enough condition number % --------------------------------------------------------------------- %% Initial estimates and other settings res = 0.03; % "Resolution level" for computing surface coverage par = [0 0]'; maxiter = 50; % maximum number of Gauss-Newton iteration iter = 0; % number of iterations so far conv = false; % converge of Gauss-Newton algorithm rel = true; % are the results reliable, system matrix not badly conditioned if nargin == 4 weight = ones(size(P,1),1); end Rot0 = rotate_to_z_axis(Axis); Pt = (P-Point0)*Rot0'; Par = [0 0 0 0 Rad0]'; %% Gauss-Newton iterations while iter < maxiter && ~conv && rel % Calculate the distances and Jacobian [dist,J] = func_grad_axis(Pt,Par); % Calculate update step and gradient. SS0 = norm(dist); % Squared sum of the distances % solve for the system of equations: % par(i+1) = par(i) - (J'J)^(-1)*J'd(par(i)) A = J'*J; b = J'*dist; warning off p = -A\b; % solve for the system of equations warning on % Update par = par+p; % Check if the updated parameters lower the squared sum value Par = [0; 0; par; Rad0]; dist = func_grad_axis(Pt,Par); SS1 = norm(dist); if SS1 > SS0 % Update did not decreased the squared sum, use update with much % shorter update step par = par-0.95*p; Par = [0; 0; par; Rad0]; dist = func_grad_axis(Pt,Par); SS1 = norm(dist); end % Check reliability rel = true; if rcond(A) < 10000*eps rel = false; end % Check convergence if abs(SS0-SS1) < 1e-5 conv = true; end iter = iter+1; end %% Output % Inverse transformation to find axis and point on axis % corresponding to original data Rot = form_rotation_matrices(par); Axis = Rot0'*Rot'*[0 0 1]'; % axis direction % Compute the point distances to the axis [dist,~,h] = distances_to_line(P,Axis,Point0); dist = dist-Rad0; % distances without weights Len = max(h)-min(h); % Compute mad (for points with maximum weights) if nargin <= 4 mad = mean(abs(dist)); % mean absolute distance to the circle else I = weight == max(weight); mad = mean(abs(dist(I))); % mean absolute distance to the circle end % Compute SurfCov, minimum 3*8 grid if ~any(isnan(par)) && rel && conv nl = ceil(Len/res); nl = max(nl,3); ns = ceil(2*pi*Rad0/res); ns = max(ns,8); ns = min(36,ns); SurfCov = single(surface_coverage(P,Axis,Point0,nl,ns,0.8*Rad0)); else SurfCov = single(0); end %% Define the output clear cir cyl.radius = Rad0; cyl.start = Point0; cyl.axis = Axis'; cyl.mad = mad; cyl.SurfCov = SurfCov; cyl.conv = conv; cyl.rel = rel; ================================================ FILE: src/least_squares_fitting/least_squares_circle.m ================================================ function cir = least_squares_circle(P,Point0,Rad0,weight) % --------------------------------------------------------------------- % LEAST_SQUARES_CIRCLE.M Least-squares circle fitting using Gauss-Newton. % % Version 1.1.0 % Latest update 6 Oct 2021 % % Copyright (C) 2017-2021 Pasi Raumonen % --------------------------------------------------------------------- % Input % P 2d point cloud % Point0 Initial estimate of centre (1 x 2) % Rad0 Initial estimate of the circle radius % weight Optional, weights for each point % % Output % Rad Radius of the cylinder % Point Centre point (1 x 2) % ArcCov Arc point coverage (%), how much of the circle arc is covered with points % conv If conv = 1, the algorithm has converged % rel If rel = 1, the algorithm has reliable answer in terms of % matrix inversion with a good enough condition number % --------------------------------------------------------------------- %% Initial estimates and other settings par = [Point0 Rad0]'; maxiter = 200; % maximum number of Gauss-Newton iteration iter = 0; % number of iterations so far conv = false; % converge of Gauss-Newton algorithm rel = true; % are the reusults reliable in the sense that system matrix was not badly conditioned if nargin == 3 weight = ones(size(P,1),1); end %% Gauss-Newton iterations while iter < maxiter && ~conv && rel % Calculate the distances and Jacobian [dist,J] = func_grad_circle(P,par,weight); % Calculate update step and gradient. SS0 = norm(dist); % Squared sum of the distances % solve for the system of equations: par(i+1) = par(i) - (J'J)^(-1)*J'd(par(i)) A = J'*J; b = J'*dist; warning off p = -A\b; % solve for the system of equations warning on % Update par = par+p; % Check if the updated parameters lower the squared sum value dist = func_grad_circle(P,par,weight); SS1 = norm(dist); if SS1 > SS0 % Update did not decreased the squared sum, use update with much % shorter update step par = par-0.95*p; dist = func_grad_circle(P,par,weight); SS1 = norm(dist); end % Check reliability if rcond(A) < 10000*eps rel = false; end % Check convergence if abs(SS0-SS1) < 1e-5 conv = true; end iter = iter+1; end %% Output Rad = par(3); Point = par(1:2); U = P(:,1)-Point(1); V = P(:,2)-Point(2); dist = sqrt(U.*U+V.*V)-Rad; if nargin <= 3 mad = mean(abs(dist)); % mean absolute distance to the circle else I = weight == max(weight); mad = mean(abs(dist(I))); % mean absolute distance to the circle end % Calculate ArcCov, how much of the circle arc is covered with points if ~any(isnan(par)) if nargin <= 3 I = dist > -0.2*Rad; else I = dist > -0.2*Rad & weight == max(weight); end U = U(I,:); V = V(I,:); ang = atan2(V,U)+pi; ang = ceil(ang/2/pi*100); ang(ang <= 0) = 1; Arc = false(100,1); Arc(ang) = true; ArcCov = nnz(Arc)/100; else ArcCov = 0; end cir.radius = Rad; cir.point = Point'; cir.mad = mad; cir.ArcCov = ArcCov; cir.conv = conv; cir.rel = rel; ================================================ FILE: src/least_squares_fitting/least_squares_circle_centre.m ================================================ function cir = least_squares_circle_centre(P,Point0,Rad0) % --------------------------------------------------------------------- % LEAST_SQUARES_CIRCLE_CENTRE.M Least-squares circle fitting such that % radius is given (fits the centre) % % Version 1.0.0 % Latest update 6 Oct 2021 % % Copyright (C) 2017-2021 Pasi Raumonen % --------------------------------------------------------------------- % Input % P 2d point cloud % Point0 Initial estimate of centre (1 x 2) % Rad0 The circle radius % weight Optional, weights for each point % % Output % cir Structure array with the following fields % Rad Radius of the cylinder % Point Centre point (1 x 2) % ArcCov Arc point coverage (%), how much of the circle arc is covered % with points % conv If conv = 1, the algorithm has converged % rel If rel = 1, the algorithm has reliable answer in terms of % matrix inversion with a good enough condition number % --------------------------------------------------------------------- % Changes from version 1.0.0 to 1.1.0, 6 Oct 2021: % 1) Streamlining code and some computations %% Initial estimates and other settings par = [Point0 Rad0]'; maxiter = 200; % maximum number of Gauss-Newton iteration iter = 0; % number of iterations so far conv = false; % converge of Gauss-Newton algorithm rel = true; % the results reliable (system matrix was not badly conditioned) %% Gauss-Newton iterations while iter < maxiter && ~conv && rel % Calculate the distances and Jacobian [dist,J] = func_grad_circle_centre(P,par); % Calculate update step and gradient. SS0 = norm(dist); % Squared sum of the distances % solve for the system of equations: par(i+1) = par(i) - (J'J)^(-1)*J'd(par(i)) A = J'*J; b = J'*dist; warning off p = -A\b; % solve for the system of equations warning on % Update par(1:2,1) = par(1:2,1)+p; % Check if the updated parameters lower the squared sum value dist = func_grad_circle_centre(P,par); SS1 = norm(dist); if SS1 > SS0 % Update did not decreased the squared sum, use update with much % shorter update step par(1:2,1) = par(1:2,1)-0.95*p; dist = func_grad_circle_centre(P,par); SS1 = norm(dist); end % Check reliability if rcond(A) < 10000*eps rel = false; end % Check convergence if abs(SS0-SS1) < 1e-5 conv = true; end iter = iter+1; end %% Output Point = par(1:2); if conv && rel % Calculate ArcCov, how much of the circle arc is covered with points U = P(:,1)-par(1); V = P(:,2)-par(2); ang = atan2(V,U)+pi; I = false(100,1); ang = ceil(ang/2/pi*100); I(ang) = true; ArcCov = nnz(I)/100; % mean absolute distance to the circle d = sqrt(U.*U+V.*V)-Rad0; mad = mean(abs(d)); else mad = 0; ArcCov = 0; end cir.radius = Rad0; cir.point = Point'; cir.mad = mad; cir.ArcCov = ArcCov; cir.conv = conv; cir.rel = rel; ================================================ FILE: src/least_squares_fitting/least_squares_cylinder.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function cyl = least_squares_cylinder(P,cyl0,weight,Q) % --------------------------------------------------------------------- % LEAST_SQUARES_CYLINDER.M Least-squares cylinder using Gauss-Newton. % % Version 2.0.0 % Latest update 5 Oct 2021 % % Copyright (C) 2013-2021 Pasi Raumonen % --------------------------------------------------------------------- % Input % P Point cloud % cyl0 Initial estimates of the cylinder parameters % weight (Optional) Weights of the points for fitting % Q (Optional) Subset of "P" where the cylinder is intended % % Output % cyl Structure array containing the following fields: % radius Radius of the cylinder % length Length of the cylinder % start Point on the axis at the bottom of the cylinder (1 x 3) % axis Axis direction of the cylinder (1 x 3) % mad Mean absolute distance between points and cylinder surface % SurfCov Relative cover of the cylinder's surface by the points % dist Radial distances from the points to the cylinder (m x 1) % conv If conv = 1, the algorithm has converged % rel If rel = 1, the algorithm has reliable answer in terms of % matrix inversion with a good enough condition number % --------------------------------------------------------------------- % Changes from version 1.3.0 to 2.0.0, 5 Oct 2021: % 1) Included the Gauss-Newton iterations into this function (removed the % call to nlssolver function) % 2) Changed how the updata step is solved from the Jacobian % 3) Simplified some expressions and added comments % 4) mad is computed only from the points along the cylinder length in the % case of the optional input "Q" is given. % 5) Changed the surface coverage estimation by filtering out points whose % distance to the axis is less than 80% of the radius % Changes from version 1.2.0 to 1.3.0, 14 July 2020: % 1) Changed the input parameters of the cylinder to the struct format. % 2) Added optional input for weights % 3) Added optional input "Q", a subset of "P", the cylinder is intended % to be fitted in this subset but it is fitted to "P" to get better % estimate of the axis direction and radius % Changes from version 1.1.0 to 1.2.0, 14 Jan 2020: % 1) Changed the outputs and optionally the inputs to the struct format. % 2) Added new output, "mad", which is the mean absolute distance of the % points from the surface of the cylinder. % 3) Added new output, "SurfCov", that measures how well the surface of the % cylinder is covered by the points. % 4) Added new output, "SurfCovDis", which is a matrix of mean point distances % from layer/sector-intersections to the axis. % 5) Added new output, "SurfCovVol", which is an estimate of the cylinder's % volume based on the radii in "SurfCovDis" and "cylindrical sectors". % 6) Added new optional input "res" which gives the point resolution level % for computing SurfCov: the width and length of sectors/layers. % Changes from version 1.0.0 to 1.1.0, 3 Oct 2019: % 1) Bug fix: --> "Point = Rot0'*([par(1) par(2) 0]')..." %% Initialize data and values res = 0.03; % "Resolution level" for computing surface coverage maxiter = 50; % maximum number of Gauss-Newton iterations iter = 0; conv = false; % Did the iterations converge rel = true; % Are the results reliable (condition number was not very bad) if nargin == 2 NoWeights = true; % No point weight given for the fitting else NoWeights = false; end % Transform the data to close to standard position via a translation % followed by a rotation Rot0 = rotate_to_z_axis(cyl0.axis); Pt = (P-cyl0.start)*Rot0'; % Initial estimates par = [0 0 0 0 cyl0.radius]'; %% Gauss-Newton algorithm % find estimate of rotation-translation-radius parameters that transform % the data so that the best-fit cylinder is one in standard position while iter < maxiter && ~conv && rel %% Calculate the distances and Jacobian if NoWeights [d0,J] = func_grad_cylinder(par,Pt); else [d0,J] = func_grad_cylinder(par,Pt,weight); end %% Calculate update step SS0 = norm(d0); % Squared sum of the distances % solve for the system of equations: % par(i+1) = par(i) - (J'J)^(-1)*J'd0(par(i)) A = J'*J; b = J'*d0; warning off p = -A\b; % solve for the system of equations warning on par = par+p; % update the parameters %% Check reliability if rcond(-A) < 10000*eps rel = false; end %% Check convergence: % The distances with the new parameter values: if NoWeights dist = func_grad_cylinder(par,Pt); else dist = func_grad_cylinder(par,Pt,weight); end SS1 = norm(dist); % Squared sum of the distances if abs(SS0-SS1) < 1e-4 conv = true; end iter = iter + 1; end %% Compute the cylinder parameters and other outputs cyl.radius = single(par(5)); % radius % Inverse transformation to find axis and point on axis % corresponding to original data Rot = form_rotation_matrices(par(3:4)); Axis = Rot0'*Rot'*[0 0 1]'; % axis direction Point = Rot0'*([par(1) par(2) 0]')+cyl0.start'; % axis point % Compute the start, length and mad, translate the axis point to the % cylinder's bottom: % If the fourth input (point cloud Q) is given, use it for the start, % length, mad, and SurfCov if nargin == 4 if size(Q,1) > 5 P = Q; end end H = P*Axis; % heights along the axis hmin = min(H); cyl.length = single(abs(max(H)-hmin)); hpoint = Axis'*Point; Point = Point-(hpoint-hmin)*Axis; % axis point at the cylinder's bottom cyl.start = single(Point'); cyl.axis = single(Axis'); % Compute mad for the points along the cylinder length: if nargin >= 6 I = weight == max(weight); cyl.mad = single(average(abs(dist(I)))); % mean absolute distance else cyl.mad = single(average(abs(dist))); % mean absolute distance end cyl.conv = conv; cyl.rel = rel; % Compute SurfCov, minimum 3*8 grid if ~any(isnan(Axis)) && ~any(isnan(Point)) && rel && conv nl = max(3,ceil(cyl.length/res)); ns = ceil(2*pi*cyl.radius/res); ns = min(36,max(ns,8)); SurfCov = surface_coverage(P,Axis',Point',nl,ns,0.8*cyl.radius); cyl.SurfCov = single(SurfCov); else cyl.SurfCov = single(0); end ================================================ FILE: src/least_squares_fitting/nlssolver.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function [par,d,conv,rel] = nlssolver(par,P,weight) % --------------------------------------------------------------------- % NLSSOLVER.M Nonlinear least squares solver for cylinders. % % Version 2.1.0 % Latest update 14 July 2020 % % Copyright (C) 2013-2020 Pasi Raumonen % --------------------------------------------------------------------- % % Input % par Intial estimates of the parameters % P Point cloud % % Output % par Optimised parameter values % d Distances of points to cylinder % conv True if fitting converged % rel True if condition number was not very bad, fit was reliable % Changes from version 2.0.0 to 2.1.0, 14 July 2020: % 1) Added optional input for weights of the points maxiter = 50; iter = 0; conv = false; rel = true; if nargin == 2 NoWeights = true; else NoWeights = false; end %% Gauss-Newton iterations while iter < maxiter && ~conv && rel %% Calculate the distances and Jacobian if NoWeights [d0, J] = func_grad_cylinder(par,P); else [d0, J] = func_grad_cylinder(par,P,weight); end %% Calculate update step SS0 = norm(d0); % Squared sum of the distances % solve for the system of equations: % par(i+1) = par(i) - (J'J)^(-1)*J'd0(par(i)) A = J'*J; b = J'*d0; warning off p = -A\b; % solve for the system of equations warning on par = par+p; % update the parameters %% Check reliability if rcond(-R) < 10000*eps rel = false; end %% Check convergence: % The distances with the new parameter values: if NoWeights d = func_grad_cylinder(par,P); else d = func_grad_cylinder(par,P,weight); end SS1 = norm(d); % Squared sum of the distances if abs(SS0-SS1) < 1e-4 conv = true; end iter = iter + 1; end ================================================ FILE: src/least_squares_fitting/rotate_to_z_axis.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function [R,D,a] = rotate_to_z_axis(Vec) % -------------------------------------------------------------------------- % ROTATE_TO_Z_AXIS.M Forms the rotation matrix to rotate the vector to % a point along the positive z-axis. % % Input % Vec Vector (3 x 1) % % Output % R Rotation matrix, with R * Vec = [0 0 z]', z > 0 D = cross(Vec,[0 0 1]); if norm(D) > 0 a = acos(Vec(3)); R = rotation_matrix(D,a); else R = eye(3); a = 0; D = [1 0 0]; end ================================================ FILE: src/main_steps/branches.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function branch = branches(cylinder) % --------------------------------------------------------------------- % BRANCHES.M Determines the branching structure and computes branch % attributes % % Version 3.0.0 % Latest update 2 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % Determines the branches (cylinders in a segment define a branch), their order % and topological parent-child-relation. Branch number one is the trunk and % its order is zero. Notice that branch number does not tell its age in the % sense that branch number two would be the oldest branch and the number % three the second oldest. % % Inputs: % cylinder Cylinders, structure array % % Outputs: % branch Branch structure array, contains fields: % Branch order, parent, volume, length, angle, height, azimuth % and diameter % --------------------------------------------------------------------- % Changes from version 2.1.0 to 3.0.0, 2 May 2022: % 1) Changed the code such that the input "segment" and output "cylinder" % are not needed anymore, which simplified the code in many places. % Cylinder info is now computed in "cylinders" function. % Changes from version 2.0.0 to 2.1.0, 25 Jan 2020: % 1) Chanced the coding to simplify and shorten the code % 2) Added branch area and zenith direction as new fields in the % branch-structure array % 3) Removed the line were 'ChildCyls' and'CylsInSegment' fields are % removed from the cylinder-structure array Rad = cylinder.radius; Len = cylinder.length; Axe = cylinder.axis; %% Branches nc = size(Rad,1); % number of cylinder ns = max(cylinder.branch); % number of segments BData = zeros(ns,9); % branch ord, dia, vol, are, len, ang, hei, azi, zen ind = (1:1:nc)'; CiB = cell(ns,1); for i = 1:ns C = ind(cylinder.branch == i); CiB{i} = C; if ~isempty(C) BData(i,1) = cylinder.BranchOrder(C(1)); % branch order BData(i,2) = 2*Rad(C(1)); % branch diameter BData(i,3) = 1000*pi*sum(Len(C).*Rad(C).^2); % branch volume BData(i,4) = 2*pi*sum(Len(C).*Rad(C)); % branch area BData(i,5) = sum(Len(C)); % branch length % if the first cylinder is added to fill a gap, then % use the second cylinder to compute the angle: if cylinder.added(C(1)) && length(C) > 1 FC = C(2); % first cyl in the branch PC = cylinder.parent(C(1)); % parent cylinder of the branch else FC = C(1); PC = cylinder.parent(FC); end if PC > 0 BData(i,6) = 180/pi*acos(Axe(FC,:)*Axe(PC,:)'); % branch angle end BData(i,7) = cylinder.start(C(1),3)-cylinder.start(1,3); % branch height BData(i,8) = 180/pi*atan2(Axe(C(1),2),Axe(C(1),1)); % branch azimuth BData(i,9) = 180/pi*acos(Axe(C(1),3)); % branch zenith end end BData = single(BData); %% Branching structure (topology, parent-child-relation) branch.order = uint8(BData(:,1)); BPar = zeros(ns,1); Chi = cell(nc,1); for i = 1:nc c = ind(cylinder.parent == i); c = c(c ~= cylinder.extension(i)); Chi{i} = c; end for i = 1:ns C = CiB{i}; ChildCyls = unique(vertcat(Chi{C})); CB = unique(cylinder.branch(ChildCyls)); % Child branches BPar(CB) = i; end if ns <= 2^16 branch.parent = uint16(BPar); else branch.parent = uint32(BPar); end %% Finish the definition of branch branch.diameter = BData(:,2); % diameters in meters branch.volume = BData(:,3); % volumes in liters branch.area = BData(:,4); % areas in square meters branch.length = BData(:,5); % lengths in meters branch.angle = BData(:,6); % angles in degrees branch.height = BData(:,7); % heights in meters branch.azimuth = BData(:,8); % azimuth directions in angles branch.zenith = BData(:,9); % zenith directions in angles ================================================ FILE: src/main_steps/correct_segments.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function segment = correct_segments(P,cover,segment,inputs,RemSmall,ModBases,AddChild) % --------------------------------------------------------------------- % CORRECT_SEGMENTS.M Corrects the given segmentation. % % Version 2.0.2 % Latest update 2 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % First segments are modified by making them as long as possible. Here the % stem and 1-st order branches are handled differently as there is also % restriction to how "curved" they can be in the sense of ratio % total_length/base_tip_distance. Then, optionally, small segments that % are close to their parent and have no children are removed as unclear % (are they part of the parent or real segments?). % Then, optionally, the bases of branches are modified by % expanding them into parent segment in order to remove ledges from the % parent from locations of the branches. % Inputs: % P Point cloud % cover Cover sets % segment Segments % inputs The input structure % RemSmall If True, small unclear segments are removed % ModBase If True, bases of the segments are modified % AddChild If True, the expanded (modified) base is added to the child segment. % If AddChild = false and ModBase = true, then the expanded part is % removed from both the child and the parent. % Outputs: % segment Segments % --------------------------------------------------------------------- % Changes from version 2.0.1 to 2.0.2, 2 May 2022: % 1) Added "if ~isempty(SegChildren)... " statement to the % "modify_topology" subfunction where next branch is selected based on % the increasing branching order to prevent a rare bug % Changes from version 2.0.0 to 2.0.1, 2 Oct 2019: % 1) Main function: added "if SPar(i,1) > 1"-statement to ModBase --> % NotAddChild if nargin == 4 RemSmall = true; ModBases = false; elseif nargin == 5 ModBases = false; elseif nargin == 6 AddChild = false; end Bal = cover.ball; Segs = segment.segments; SPar = segment.ParentSegment; SChi = segment.ChildSegment; Ce = P(cover.center,:); %% Make stem and branches as long as possible if RemSmall [Segs,SPar,SChi] = modify_topology(P,Ce,Bal,Segs,SPar,SChi,inputs.PatchDiam2Max); else [Segs,SPar,SChi] = modify_topology(P,Ce,Bal,Segs,SPar,SChi,inputs.PatchDiam1); end %% Remove small child segments if RemSmall [Segs,SPar,SChi] = remove_small(Ce,Segs,SPar,SChi); end % Check the consistency of empty vector sizes ns = size(Segs,1); for i = 1:ns if isempty(SChi{i}) SChi{i} = zeros(0,1,'uint32'); end end if ModBases %% Modify the base of the segments ns = size(Segs,1); base = cell(200,1); if AddChild % Add the expanded base to the child and remove it from the parent for i = 2:ns SegC = Segs{i}; SegP = Segs{SPar(i,1)}; [SegP,Base] = modify_parent(P,Bal,Ce,SegP,SegC,SPar(i,2),inputs.PatchDiam1,base); Segs{SPar(i,1)} = SegP; SegC{1} = Base; Segs{i} = SegC; end else % Only remove the expanded base from the parent for i = 2:ns if SPar(i,1) > 1 SegC = Segs{i}; SegP = Segs{SPar(i,1)}; SegP = modify_parent(P,Bal,Ce,SegP,SegC,SPar(i,2),inputs.PatchDiam2Max,base); Segs{SPar(i,1)} = SegP; end end end end SPar = SPar(:,1); % Modify the size and type of SChi and Segs, if necessary ns = size(Segs,1); for i = 1:ns C = SChi{i}; if size(C,2) > size(C,1) && size(C,1) > 0 SChi{i} = uint32(C'); elseif size(C,1) == 0 || size(C,2) == 0 SChi{i} = zeros(0,1,'uint32'); else SChi{i} = uint32(C); end S = Segs{i}; for j = 1:size(S,1) S{j} = uint32(S{j}); end Segs{i} = S; end segment.segments = Segs; segment.ParentSegment = SPar; segment.ChildSegment = SChi; %% Generate segment data for the points np = size(P,1); ns = size(Segs,1); % Define for each point its segment if ns <= 2^16 SegmentOfPoint = zeros(np,1,'uint16'); else SegmentOfPoint = zeros(np,1,'uint32'); end for i = 1:ns S = Segs{i}; S = vertcat(S{:}); SegmentOfPoint(vertcat(Bal{S})) = i; end segment.SegmentOfPoint = SegmentOfPoint; % Define the indexes of the segments up to 3rd-order C = SChi{1}; segment.branch1indexes = C; if ~isempty(C) C = vertcat(SChi{C}); segment.branch2indexes = C; if ~isempty(C) C = vertcat(SChi{C}); segment.branch3indexes = C; else segment.branch3indexes = zeros(0,1); end else segment.branch2indexes = zeros(0,1); segment.branch3indexes = zeros(0,1); end end % End of main function function StemTop = search_stem_top(P,Ce,Bal,Segs,SPar,dmin) % Search the stem's top segment such that the resulting stem % 1) is one the highest segments (goes to the top of the tree) % 2) is horizontally close to the bottom of the stem (goes straigth up) % 3) has length close to the distance between its bottom and top (is not too curved) nseg = size(Segs,1); SegHeight = zeros(nseg,1); % heights of the tips of the segments HorDist = zeros(nseg,1); % horizontal distances of the tips from stem's center s = Segs{1}{1}; StemCen = average(Ce(s,:)); % center (x,y) of stem base for i = 1:nseg S = Segs{i}{end}(1); SegHeight(i) = Ce(S,3); HorDist(i) = norm(Ce(S,1:2)-StemCen(1:2)); end Top = max(SegHeight); % the height of the highest tip HeiDist = Top-SegHeight; % the height difference to "Top" Dist = sqrt((HorDist.^2+HeiDist.^2)); % Distance to the top LenDisRatio = 2; SearchDist = 0.5; MaxLenDisRatio = 1.05; % the maximum acceptable length/distance ratio of segments SubSegs = zeros(100,1); % Segments to be combined to form the stem while LenDisRatio > MaxLenDisRatio StemTops = (1:1:nseg)'; I = Dist < SearchDist; % only segments with distance to the top < 0.5m while ~any(I) SearchDist = SearchDist+0.5; I = Dist < SearchDist; end StemTops = StemTops(I); % Define i-1 alternative stems from StemTops n = length(StemTops); Stems = cell(n,1); Segment = cell(3000,1); for j = 1:n Seg = Segs{1}; spar = SPar; if StemTops(j) ~= 1 % Tip point was not in the current segment, modify segments SubSegs(1) = StemTops(j); nsegs = 1; segment = StemTops(j); while segment ~= 1 segment = SPar(segment,1); nsegs = nsegs+1; SubSegs(nsegs) = segment; end % Modify stem a = size(Seg,1); Segment(1:a) = Seg; a = a+1; for i = 1:nsegs-2 I = SubSegs(nsegs-i); % segment to be combined to the first segment J = SubSegs(nsegs-i-1); % above segment's child to be combined next SP = spar(I,2); % layer index of the child in the parent SegC = Segs{I}; sp = spar(J,2); % layer index of the child's child in the child if SP >= a-2 % Use the whole parent Segment(a:a+sp-1) = SegC(1:sp); spar(J,2) = a+sp-1; a = a+sp; else % Use only bottom part of the parent Segment(SP+1:SP+sp) = SegC(1:sp); a = SP+sp+1; spar(J,2) = SP+sp; end SubSegs(nsegs-i) = 1; end % Combine the last segment to the branch I = SubSegs(1); SP = spar(I,2); SegC = Segs{I}; nc = size(SegC,1); if SP >= a-2 % Use the whole parent Segment(a:a+nc-1) = SegC; a = a+nc-1; else % divide the parent segment into two parts Segment(SP+1:SP+nc) = SegC; a = SP+nc; end Stems{j,1} = Segment(1:a); else Stems{j,1} = Seg; end end % Calculate the lengths of the candidate stems N = ceil(0.5/dmin/1.4); % number of layers used for linear length approximation Lengths = zeros(n,1); Heights = zeros(n,1); for i = 1:n Seg = Stems{i,1}; ns = size(Seg,1); if ceil(ns/N) > floor(ns/N) m = ceil(ns/N); else m = ceil(ns/N)+1; end Nodes = zeros(m,3); for j = 1:m I = (j-1)*N+1; if I > ns I = ns; end S = Seg{I}; if length(S) > 1 Nodes(j,:) = average(Ce(S,:)); else S = Bal{S}; Nodes(j,:) = average(P(S,:)); end end V = Nodes(2:end,:)-Nodes(1:end-1,:); Lengths(i) = sum(sqrt(sum(V.*V,2))); V = Nodes(end,:)-Nodes(1,:); Heights(i) = norm(V); end LenDisRatio = Lengths./Heights; [LenDisRatio,I] = min(LenDisRatio); StemTop = StemTops(I); SearchDist = SearchDist+1; if SearchDist > 3 MaxLenDisRatio = 1.1; if SearchDist > 5 MaxLenDisRatio = 1.15; if SearchDist > 7 MaxLenDisRatio = 5; end end end end end % End subfunction function BranchTop = search_branch_top(P,Ce,Bal,Segs,SPar,SChi,dmin,BI) % Search the end segment for branch such that the resulting branch % 1) has length close to the distance between its bottom and top % 2) has distance close to the farthest segment end % Inputs % BI Branch (segment) index % Outputs % BranchTop The index of the segment forming the tip of the branch % originating from the base of the given segment BI % Define all the sub-segments of the given segments ns = size(Segs,1); Segments = zeros(ns,1); % the given segment and its sub-segments Segments(1) = BI; t = 2; C = SChi{BI}; while ~isempty(C) n = length(C); Segments(t:t+n-1) = C; C = vertcat(SChi{C}); t = t+n; end if t > 2 t = t-n; end Segments = Segments(1:t); % Determine linear distances from the segment tips to the base of the given % segment LinearDist = zeros(t,1); % linear distances from the Seg = Segs{Segments(1)}; BranchBase = average(Ce(Seg{1},:)); % center of branch's base for i = 1:t Seg = Segs{Segments(i)}; C = average(Ce(Seg{end},:)); % tip LinearDist(i) = norm(C-BranchBase); end LinearDist = LinearDist(1:t); % Sort the segments according their linear distance, from longest to % shortest [LinearDist,I] = sort(LinearDist,'descend'); Segments = Segments(I); % Define alternative branches from Segments Branches = cell(t,1); % the alternative segments as cell layers SubSegs = zeros(100,1); % Segments to be combined Segment = cell(3000,1); for j = 1:t Seg = Segs{BI}; spar = SPar; if Segments(j) ~= BI % Tip point was not in the current segment, modify segments SubSegs(1) = Segments(j); k = 1; S = Segments(j); while S ~= BI S = SPar(S,1); k = k+1; SubSegs(k) = S; end % Modify branch a = size(Seg,1); Segment(1:a) = Seg; a = a+1; for i = 1:k-2 I = SubSegs(k-i); % segment to be combined to the first segment J = SubSegs(k-i-1); % above segment's child to be combined next SP = spar(I,2); % layer index of the child in the parent SegC = Segs{I}; sp = spar(J,2); % layer index of the child's child in the child if SP >= a-2 % Use the whole parent Segment(a:a+sp-1) = SegC(1:sp); spar(J,2) = a+sp-1; a = a+sp; else % Use only bottom part of the parent Segment(SP+1:SP+sp) = SegC(1:sp); a = SP+sp+1; spar(J,2) = SP+sp; end SubSegs(k-i) = 1; end % Combine the last segment to the branch I = SubSegs(1); SP = spar(I,2); SegC = Segs{I}; L = size(SegC,1); if SP >= a-2 % Use the whole parent Segment(a:a+L-1) = SegC; a = a+L-1; else % divide the parent segment into two parts Segment(SP+1:SP+L) = SegC; a = SP+L; end Branches{j,1} = Segment(1:a); else Branches{j,1} = Seg; end end % Calculate the lengths of the candidate branches. Stop, if possible, when % the ratio length/linear distance is less 1.2 (branch is quite straight) N = ceil(0.25/dmin/1.4); % number of layers used for linear length approximation i = 1; % running index for while loop Continue = true; % continue while loop as long as "Continue" is true Lengths = zeros(t,1); % linear lengths of the branches while i <= t && Continue % Approximate the length with line segments connecting nodes along % the segment Seg = Branches{i,1}; ns = size(Seg,1); if ceil(ns/N) > floor(ns/N) m = ceil(ns/N); else m = ceil(ns/N)+1; end Nodes = zeros(m,3); for j = 1:m I = (j-1)*N+1; if I > ns I = ns; end S = Seg{I}; if length(S) > 1 Nodes(j,:) = average(Ce(S,:)); else S = Bal{S}; Nodes(j,:) = average(P(S,:)); end end V = Nodes(2:end,:)-Nodes(1:end-1,:); % line segments Lengths(i) = sum(sqrt(sum(V.*V,2))); % Continue as long as the length is less than 20% longer than the linear dist. % and the linear distance is over 75% of the maximum if Lengths(i)/LinearDist(i) < 1.20 && LinearDist(i) > 0.75*LinearDist(1) Continue = false; BranchTop = Segments(i); end i = i+1; end % If no suitable segment was found, try first with less strict conditions, % and if that does not work, then select the one with the largest linear distance if Continue L = Lengths./LinearDist; i = 1; while i <= t && L(i) > 1.4 && LinearDist(i) > 0.75*LinearDist(1) i = i+1; end if i <= t BranchTop = Segments(i); else BranchTop = Segments(1); end end end % End subfunction function [Segs,SPar,SChi] = modify_topology(P,Ce,Bal,Segs,SPar,SChi,dmin) % Make stem and branches as long as possible ns = size(Segs,1); Fal = false(2*ns,1); nc = ceil(ns/5); SubSegments = zeros(nc,1); % for searching sub-segments SegInd = 1; % the segment under modification UnMod = true(ns,1); UnMod(SegInd) = false; BranchOrder = 0; ChildSegInd = 1; % index of the child segments under modification while any(UnMod) ChildSegs = SChi{SegInd}; % child segments of the segment under modification if size(ChildSegs,1) < size(ChildSegs,2) ChildSegs = ChildSegs'; SChi{SegInd} = ChildSegs; end if ~isempty(Segs(SegInd)) && ~isempty(ChildSegs) if SegInd > 1 && BranchOrder > 1 % 2nd-order and higher branches % Search the tip of the sub-branches with biggest linear % distance from the current branch's base SubSegments(1) = SegInd; NSubSegs = 2; while ~isempty(ChildSegs) n = length(ChildSegs); SubSegments(NSubSegs:NSubSegs+n-1) = ChildSegs; ChildSegs = vertcat(SChi{ChildSegs}); NSubSegs = NSubSegs+n; end if NSubSegs > 2 NSubSegs = NSubSegs-n; end % Find tip-points Top = zeros(NSubSegs,3); for i = 1:NSubSegs Top(i,:) = Ce(Segs{SubSegments(i)}{end}(1),:); end % Define bottom of the branch BotLayer = Segs{SegInd}{1}; Bottom = average(Ce(BotLayer,:)); % End segment is the segment whose tip has greatest distance to % the bottom of the branch V = mat_vec_subtraction(Top,Bottom); d = sum(V.*V,2); [~,I] = max(d); TipSeg = SubSegments(I(1)); elseif SegInd > 1 && BranchOrder <= 1 % first order branches TipSeg = search_branch_top(P,Ce,Bal,Segs,SPar,SChi,dmin,SegInd); else % Stem TipSeg = search_stem_top(P,Ce,Bal,Segs,SPar,dmin); end if TipSeg ~= SegInd % Tip point was not in the current segment, modify segments SubSegments(1) = TipSeg; NSubSegs = 1; while TipSeg ~= SegInd TipSeg = SPar(TipSeg,1); NSubSegs = NSubSegs+1; SubSegments(NSubSegs) = TipSeg; end % refine branch for i = 1:NSubSegs-2 I = SubSegments(NSubSegs-i); % segment to be combined to the first segment J = SubSegments(NSubSegs-i-1); % above segment's child to be combined next SP = SPar(I,2); % layer index of the child in the parent SegP = Segs{SegInd}; SegC = Segs{I}; N = size(SegP,1); sp = SPar(J,2); % layer index of the child's child in the child if SP >= N-2 % Use the whole parent Segs{SegInd} = [SegP; SegC(1:sp)]; if sp < size(SegC,1) % use only part of the child segment Segs{I} = SegC(sp+1:end); SPar(I,2) = N+sp; ChildSegs = SChi{I}; K = SPar(ChildSegs,2) <= sp; c = ChildSegs(~K); SChi{I} = c; SPar(c,2) = SPar(c,2)-sp; ChildSegs = ChildSegs(K); SChi{SegInd} = [SChi{SegInd}; ChildSegs]; SPar(ChildSegs,1) = SegInd; SPar(ChildSegs,2) = N+SPar(ChildSegs,2); else % use the whole child segment Segs{I} = cell(0,1); SPar(I,1) = 0; UnMod(I) = false; ChildSegs = SChi{I}; SChi{I} = zeros(0,1); c = set_difference(SChi{SegInd},I,Fal); SChi{SegInd} = [c; ChildSegs]; SPar(ChildSegs,1) = SegInd; SPar(ChildSegs,2) = N+SPar(ChildSegs,2); end SubSegments(NSubSegs-i) = SegInd; else % divide the parent segment into two parts ns = ns+1; Segs{ns} = SegP(SP+1:end); % the top part of the parent forms a new segment SPar(ns,1) = SegInd; SPar(ns,2) = SP; UnMod(ns) = true; Segs{SegInd} = [SegP(1:SP); SegC(1:sp)]; ChildSegs = SChi{SegInd}; if size(ChildSegs,1) < size(ChildSegs,2) ChildSegs = ChildSegs'; end K = SPar(ChildSegs,2) > SP; SChi{SegInd} = ChildSegs(~K); ChildSegs = ChildSegs(K); SChi{ns} = ChildSegs; SPar(ChildSegs,1) = ns; SPar(ChildSegs,2) = SPar(ChildSegs,2)-SP; SChi{SegInd} = [SChi{SegInd}; ns]; if sp < size(SegC,1) % use only part of the child segment Segs{I} = SegC(sp+1:end); SPar(I,2) = SP+sp; ChildSegs = SChi{I}; K = SPar(ChildSegs,2) <= sp; SChi{I} = ChildSegs(~K); SPar(ChildSegs(~K),2) = SPar(ChildSegs(~K),2)-sp; ChildSegs = ChildSegs(K); SChi{SegInd} = [SChi{SegInd}; ChildSegs]; SPar(ChildSegs,1) = SegInd; SPar(ChildSegs,2) = SP+SPar(ChildSegs,2); else % use the whole child segment Segs{I} = cell(0,1); SPar(I,1) = 0; UnMod(I) = false; ChildSegs = SChi{I}; c = set_difference(SChi{SegInd},I,Fal); SChi{SegInd} = [c; ChildSegs]; SPar(ChildSegs,1) = SegInd; SPar(ChildSegs,2) = SP+SPar(ChildSegs,2); end SubSegments(NSubSegs-i) = SegInd; end end % Combine the last segment to the branch I = SubSegments(1); SP = SPar(I,2); SegP = Segs{SegInd}; SegC = Segs{I}; N = size(SegP,1); if SP >= N-3 % Use the whole parent Segs{SegInd} = [SegP; SegC]; Segs{I} = cell(0); SPar(I,1) = 0; UnMod(I) = false; ChildSegs = SChi{I}; if size(ChildSegs,1) < size(ChildSegs,2) ChildSegs = ChildSegs'; end c = set_difference(SChi{SegInd},I,Fal); SChi{SegInd} = [c; ChildSegs]; SPar(ChildSegs,1) = SegInd; SPar(ChildSegs,2) = N+SPar(ChildSegs,2); else % divide the parent segment into two parts ns = ns+1; Segs{ns} = SegP(SP+1:end); SPar(ns,:) = [SegInd SP]; Segs{SegInd} = [SegP(1:SP); SegC]; Segs{I} = cell(0); SPar(I,1) = 0; UnMod(ns) = true; UnMod(I) = false; ChildSegs = SChi{SegInd}; K = SPar(ChildSegs,2) > SP; SChi{SegInd} = [ChildSegs(~K); ns]; ChildSegs = ChildSegs(K); SChi{ns} = ChildSegs; SPar(ChildSegs,1) = ns; SPar(ChildSegs,2) = SPar(ChildSegs,2)-SP; ChildSegs = SChi{I}; c = set_difference(SChi{SegInd},I,Fal); SChi{SegInd} = [c; ChildSegs]; SPar(ChildSegs,1) = SegInd; SPar(ChildSegs,2) = SP+SPar(ChildSegs,2); end end UnMod(SegInd) = false; else UnMod(SegInd) = false; end % Select the next branch, use increasing branching order if BranchOrder > 0 && any(UnMod(SegChildren)) ChildSegInd = ChildSegInd+1; SegInd = SegChildren(ChildSegInd); elseif BranchOrder == 0 BranchOrder = BranchOrder+1; SegChildren = SChi{1}; if ~isempty(SegChildren) SegInd = SegChildren(1); else UnMod = false; end else BranchOrder = BranchOrder+1; i = 1; SegChildren = SChi{1}; while i < BranchOrder && ~isempty(SegChildren) i = i+1; L = cellfun('length',SChi(SegChildren)); Keep = L > 0; SegChildren = SegChildren(Keep); SegChildren = vertcat(SChi{SegChildren}); end I = UnMod(SegChildren); if any(I) SegChildren = SegChildren(I); SegInd = SegChildren(1); ChildSegInd = 1; end end end % Modify indexes by removing empty segments Empty = true(ns,1); for i = 1:ns if isempty(Segs{i}) Empty(i) = false; end end Segs = Segs(Empty); Ind = (1:1:ns)'; n = nnz(Empty); I = (1:1:n)'; Ind(Empty) = I; SPar = SPar(Empty,:); J = SPar(:,1) > 0; SPar(J,1) = Ind(SPar(J,1)); for i = 1:ns if Empty(i) ChildSegs = SChi{i}; if ~isempty(ChildSegs) ChildSegs = Ind(ChildSegs); SChi{i} = ChildSegs; end end end SChi = SChi(Empty); ns = n; % Modify SChi for i = 1:ns ChildSegs = SChi{i}; if size(ChildSegs,2) > size(ChildSegs,1) && size(ChildSegs,1) > 0 SChi{i} = ChildSegs'; elseif size(ChildSegs,1) == 0 || size(ChildSegs,2) == 0 SChi{i} = zeros(0,1); end Seg = Segs{i}; n = max(size(Seg)); for j = 1:n ChildSegs = Seg{j}; if size(ChildSegs,2) > size(ChildSegs,1) && size(ChildSegs,1) > 0 Seg{j} = ChildSegs'; elseif size(ChildSegs,1) == 0 || size(ChildSegs,2) == 0 Seg{j} = zeros(0,1); end end Segs{i} = Seg; end end % End of function function [Segs,SPar,SChi] = remove_small(Ce,Segs,SPar,SChi) % Removes small child segments % computes and estimate for stem radius at the base Segment = Segs{1}; % current or parent segment ns = size(Segment,1); % layers in the parent if ns > 10 EndL = 10; % ending layer index in parent else EndL = ns; end End = average(Ce(Segment{EndL},:)); % Center of end layer Start = average(Ce(Segment{1},:)); % Center of starting layer V = End-Start; % Vector between starting and ending centers V = V/norm(V); % normalize Sets = vertcat(Segment{1:EndL}); MaxRad = max(distances_to_line(Ce(Sets,:),V,Start)); Nseg = size(Segs,1); Fal = false(Nseg,1); Keep = true(Nseg,1); Sets = zeros(2000,1); for i = 1:Nseg if Keep(i) ChildSegs = SChi{i}; % child segments if ~isempty(ChildSegs) % child segments exists n = length(ChildSegs); % number of children Segment = Segs{i}; % current or parent segment ns = size(Segment,1); % layers in the parent for j = 1:n % check each child separately nl = SPar(ChildSegs(j),2); % the index of the layer in the parent the child begins if nl > 10 StartL = nl-10; % starting layer index in parent else StartL = 1; end if ns-nl > 10 EndL = nl+10; % end layer index in parent else EndL = ns; end End = average(Ce(Segment{EndL},:)); Start = average(Ce(Segment{StartL},:)); V = End-Start; % Vector between starting and ending centers V = V/norm(V); % normalize % cover sets of the child ChildSets = Segs{ChildSegs(j)}; NL = size(ChildSets,1); a = 1; for k = 1:NL S = ChildSets{k}; Sets(a:a+length(S)-1) = S; a = a+length(S); end ChildSets = Sets(1:a-1); % maximum distance in child distChild = max(distances_to_line(Ce(ChildSets,:),V,Start)); if distChild < MaxRad+0.06 % Select the cover sets of the parent between centers NL = EndL-StartL+1; a = 1; for k = 1:NL S = Segment{StartL+(k-1)}; Sets(a:a+length(S)-1) = S; a = a+length(S); end ParentSets = Sets(1:a-1); % maximum distance in parent distPar = max(distances_to_line(Ce(ParentSets,:),V,Start)); if (distChild-distPar < 0.02) || (distChild/distPar < 1.2 && distChild-distPar < 0.06) ChildChildSegs = SChi{ChildSegs(j)}; nc = length(ChildChildSegs); if nc == 0 % Remove, no child segments Keep(ChildSegs(j)) = false; Segs{ChildSegs(j)} = zeros(0,1); SPar(ChildSegs(j),:) = zeros(1,2); SChi{i} = set_difference(ChildSegs,ChildSegs(j),Fal); else L = SChi(ChildChildSegs); L = vertcat(L{:}); % child child segments if isempty(L) J = false(nc,1); for k = 1:nc segment = Segs{ChildChildSegs(k)}; if isempty(segment) J(k) = true; else segment1 = [vertcat(segment{:}); ParentSets]; distSeg = max(distances_to_line(Ce(segment1,:),V,Start)); if (distSeg-distPar < 0.02) || (distSeg/distPar < 1.2 && distSeg-distPar < 0.06) J(k) = true; end end end if all(J) % Remove ChildChildSegs1 = [ChildChildSegs; ChildSegs(j)]; nc = length(ChildChildSegs1); Segs(ChildChildSegs1) = cell(nc,1); Keep(ChildChildSegs1) = false; SPar(ChildChildSegs1,:) = zeros(nc,2); d = set_difference(ChildSegs,ChildSegs(j),Fal); SChi{i} = d; SChi(ChildChildSegs1) = cell(nc,1); end end end end end end end if i == 1 MaxRad = MaxRad/2; end end end % Modify segments and their indexing Segs = Segs(Keep); n = nnz(Keep); Ind = (1:1:Nseg)'; J = (1:1:n)'; Ind(Keep) = J; Ind(~Keep) = 0; SPar = SPar(Keep,:); J = SPar(:,1) > 0; SPar(J,1) = Ind(SPar(J,1)); % Modify SChi for i = 1:Nseg if Keep(i) ChildSegs = SChi{i}; if ~isempty(ChildSegs) ChildSegs = nonzeros(Ind(ChildSegs)); if size(ChildSegs,1) < size(ChildSegs,2) SChi{i} = ChildSegs'; else SChi{i} = ChildSegs; end else SChi{i} = zeros(0,1); end end end SChi = SChi(Keep); end % End of function function [SegP,Base] = modify_parent(P,Bal,Ce,SegP,SegC,nl,PatchDiam,base) % Expands the base of the branch backwards into its parent segment and % then removes the expansion from the parent segment. Base = SegC{1}; if ~isempty(Base) % Define the directions of the segments DirChi = segment_direction(Ce,SegC,1); DirPar = segment_direction(Ce,SegP,nl); if length(Base) > 1 BaseCent = average(Ce(Base,:)); db = distances_to_line(Ce(Base,:), DirChi', BaseCent); % distances of the sets in the base to the axis of the branch DiamBase = 2*max(db); % diameter of the base elseif length(Bal{Base}) > 1 BaseCent = average(P(Bal{Base},:)); db = distances_to_line(P(Bal{Base},:), DirChi', BaseCent); DiamBase = 2*max(db); else BaseCent = Ce(Base,:); DiamBase = 0; end % Determine the number of cover set layers "n" to be checked Angle = abs(DirChi'*DirPar); % abs of cosine of the angle between component and segment directions Nlayer = max([3,ceil(Angle*2*DiamBase/PatchDiam)]); if Nlayer > nl % can go only to the bottom of the segment Nlayer = nl; end % Check the layers layer = 0; base{1} = Base; while layer < Nlayer Sets = SegP{nl-layer}; Seg = average(Ce(Sets,:)); % mean of the cover sets' centers VBase = mat_vec_subtraction(Ce(Sets,:),BaseCent); % vectors from base's center to sets in the segment h = VBase*DirChi; B = repmat(DirChi',length(Sets),1); B = [h.*B(:,1) h.*B(:,2) h.*B(:,3)]; V = VBase-B; distSets = sqrt(sum(V.*V,2)); % distances of the sets in the segment to the axis of the branch VSeg = mat_vec_subtraction(Ce(Sets,:),Seg); % vectors from segments's center to sets in the segment lenBase = sqrt(sum(VBase.*VBase,2)); % lengths of VBase lenSeg = sqrt(sum(VSeg.*VSeg,2)); % lengths of VSeg if Angle < 0.9 K = lenBase < 1.1/(1-0.5*Angle^2)*lenSeg; % sets closer to the base's center than segment's center J = distSets < 1.25*DiamBase; % sets close enough to the axis of the branch I = K&J; else % branch almost parallel to parent I = distSets < 1.25*DiamBase; % only the distance to the branch axis counts end if all(I) || ~any(I) % stop the process if all the segment's or no segment's sets layer = Nlayer; else SegP{nl-layer} = Sets(not(I)); base{layer+2} = Sets(I); layer = layer+1; end end Base = vertcat(base{1:Nlayer+1}); end end % End of function function D = segment_direction(Ce,Seg,nl) % Defines the direction of the segment % Define bottom and top layers if nl-3 > 0 bot = nl-3; else bot = 1; end j = 1; while j < 3 && isempty(Seg{bot}) bot = bot+1; j = j+1; end if nl+2 <= size(Seg,1) top = nl+2; else top = size(Seg,1); end j = 1; while j < 3 && isempty(Seg{top}) top = top-1; j = j+1; end % Direction if top > bot Bot = average(Ce(Seg{bot},:)); Top = average(Ce(Seg{top},:)); V = Top-Bot; D = V'/norm(V); else D = zeros(3,1); end end % End of function ================================================ FILE: src/main_steps/cover_sets.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function cover = cover_sets(P,inputs,RelSize) % --------------------------------------------------------------------- % COVER_SETS.M Creates cover sets (surface patches) and their % neighbor-relation for a point cloud % % Version 2.0.1 % Latest update 2 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % Covers the point cloud with small sets, which are along the surface, % such that each point belongs at most one cover set; i.e. the cover is % a partition of the point cloud. % % The cover is generated such that at first the point cloud is covered % with balls with radius "BallRad". This first cover is such that % 1) the minimum distance between the centers is "PatchDiam", and % 2) the maximum distance from any point to nearest center is also "PatchDiam". % Then the first cover of BallRad-balls is used to define a second cover: % each BallRad-ball "A" defines corresponding cover set "B" in the second cover % such that "B" contains those points of "A" that are nearer to the center of % "A" than any other center of BallRad-balls. The BallRad-balls also define % the neighbors for the second cover: Let CA and CB denote cover sets in % the second cover, and BA and BB their BallRad-balls. Then CB is % a neighbor of CA, and vice versa, if BA and CB intersect or % BB and CA intersect. % % Inputs: % P Point cloud % inputs Input stucture, the following fields are needed: % PatchDiam1 Minimum distance between centers of cover sets; i.e. the % minimum diameter of cover set in uniform covers. Does % not need nor use the third optional input "RelSize". % PatchDiam2Min Minimum diameter of cover sets for variable-size % covers. Needed if "RelSize" is given as input. % PatchDiam2Max Maximum diameter of cover sets for variable-size % covers. Needed if "RelSize" is given as input. % BallRad1 Radius of the balls used to generate the uniform cover. % These balls are also used to determine the neighbors % BallRad2 Maximum radius of the balls used to generate the % varibale-size cover. % nmin1, nmin2 Minimum number of points in a BallRad1- and % BallRad2-balls % RelSize Relative cover set size for each point % % Outputs: % cover Structure array containing the followin fields: % ball Cover sets, (n_sets x 1)-cell % center Center points of the cover sets, (n_sets x 1)-vector % neighbor Neighboring cover sets of each cover set, (n_sets x 1)-cell % Changes from version 2.0.0 to 2.0.1, 2 May 2022: % 1) Added comments and changed some variable names % 2) Enforced that input parameters are type double if ~isa(P,'double') P = double(P); end %% Large balls and centers np = size(P,1); Ball = cell(np,1); % Large balls for generation of the cover sets and their neighbors Cen = zeros(np,1,'uint32'); % the center points of the balls/cover sets NotExa = true(np,1); % the points not yet examined Dist = 1e8*ones(np,1); % distance of point to the closest center BoP = zeros(np,1,'uint32'); % the balls/cover sets the points belong nb = 0; % number of sets generated if nargin == 2 %% Same size cover sets everywhere BallRad = double(inputs.BallRad1); PatchDiamMax = double(inputs.PatchDiam1); nmin = double(inputs.nmin1); % Partition the point cloud into cubes for quick neighbor search [partition,CC] = cubical_partition(P,BallRad); % Generate the balls Radius = BallRad^2; MaxDist = PatchDiamMax^2; % random permutation of points, produces different covers for the same inputs: RandPerm = randperm(np); for i = 1:np if NotExa(RandPerm(i)) Q = RandPerm(i); % the center/seed point of the current cover set % Select the points in the cubical neighborhood of the seed: points = partition(CC(Q,1)-1:CC(Q,1)+1,CC(Q,2)-1:CC(Q,2)+1,CC(Q,3)-1:CC(Q,3)+1); points = vertcat(points{:}); % Compute distances of the points to the seed: V = [P(points,1)-P(Q,1) P(points,2)-P(Q,2) P(points,3)-P(Q,3)]; dist = sum(V.*V,2); % Select the points inside the ball: Inside = dist < Radius; if nnz(Inside) >= nmin ball = points(Inside); % the points forming the ball d = dist(Inside); % the distances of the ball's points core = (d < MaxDist); % the core points of the cover set NotExa(ball(core)) = false; % mark points as examined % define new ball: nb = nb+1; Ball{nb} = ball; Cen(nb) = Q; % Select which points belong to this ball, i.e. are closer this % seed than previously tested seeds: D = Dist(ball); % the previous distances closer = d < D; % which points are closer to this seed ball = ball(closer); % define the ball % update the ball and distance information of the points Dist(ball) = d(closer); BoP(ball) = nb; end end end else %% Use relative sizes (the size varies) % Partition the point cloud into cubes BallRad = double(inputs.BallRad2); PatchDiamMin = double(inputs.PatchDiam2Min); PatchDiamMax = double(inputs.PatchDiam2Max); nmin = double(inputs.nmin2); MRS = PatchDiamMin/PatchDiamMax; % minimum radius r = double(1.5*(double(min(RelSize))/256*(1-MRS)+MRS)*BallRad+1e-5); NE = 1+ceil(BallRad/r); if NE > 4 r = PatchDiamMax/4; NE = 1+ceil(BallRad/r); end [Partition,CC,~,Cubes] = cubical_partition(P,r,NE); I = RelSize == 0; % Don't use points with no size determined NotExa(I) = false; % Define random permutation of points (results in different covers for % same input) so that first small sets are generated RandPerm = zeros(np,1,'uint32'); I = RelSize <= 32; ind = uint32(1:1:np)'; I = ind(I); t1 = length(I); RandPerm(1:1:t1) = I(randperm(t1)); I = RelSize <= 128 & RelSize > 32; I = ind(I); t2 = length(I); RandPerm(t1+1:1:t1+t2) = I(randperm(t2)); t2 = t2+t1; I = RelSize > 128; I = ind(I); t3 = length(I); RandPerm(t2+1:1:t2+t3) = I(randperm(t3)); clearvars ind I Point = zeros(round(np/1000),1,'uint32'); e = BallRad-PatchDiamMax; for i = 1:np if NotExa(RandPerm(i)) Q = RandPerm(i); % the center/seed point of the current cover set % Compute the set size and the cubical neighborhood of the seed point: rs = double(RelSize(Q))/256*(1-MRS)+MRS; % relative radius MaxDist = PatchDiamMax*rs; % diameter of the cover set Radius = MaxDist+sqrt(rs)*e; % radius of the ball including the cover set N = ceil(Radius/r); % = number of cells needed to include the ball cubes = Cubes(CC(Q,1)-N:CC(Q,1)+N,CC(Q,2)-N:CC(Q,2)+N,CC(Q,3)-N:CC(Q,3)+N); I = cubes > 0; cubes = cubes(I); % Cubes forming the neighborhood Par = Partition(cubes); % cell-array of the points in the neighborhood % vertical catenation of the points from the cell-array S = cellfun('length',Par); stop = cumsum(S); start = [0; stop]+1; for k = 1:length(stop) Point(start(k):stop(k)) = Par{k}; end points = Point(1:stop(k)); % Compute the distance of the "points" to the seed: V = [P(points,1)-P(Q,1) P(points,2)-P(Q,2) P(points,3)-P(Q,3)]; dist = sum(V.*V,2); % Select the points inside the ball: Inside = dist < Radius^2; if nnz(Inside) >= nmin ball = points(Inside); % the points forming the ball d = dist(Inside); % the distances of the ball's points core = (d < MaxDist^2); % the core points of the cover set NotExa(ball(core)) = false; % mark points as examined % define new ball: nb = nb+1; Ball{nb} = ball; Cen(nb) = Q; % Select which points belong to this ball, i.e. are closer this % seed than previously tested seeds: D = Dist(ball); % the previous distances closer = d < D; % which points are closer to this seed ball = ball(closer); % define the ball % update the ball and distance information of the points Dist(ball) = d(closer); BoP(ball) = nb; end end end end Ball = Ball(1:nb,:); Cen = Cen(1:nb); clearvars RandPerm NotExa Dist %% Cover sets % Number of points in each ball and index of each point in its ball Num = zeros(nb,1,'uint32'); Ind = zeros(np,1,'uint32'); for i = 1:np if BoP(i) > 0 Num(BoP(i)) = Num(BoP(i))+1; Ind(i) = Num(BoP(i)); end end % Initialization of the "PointsInSets" PointsInSets = cell(nb,1); for i = 1:nb PointsInSets{i} = zeros(Num(i),1,'uint32'); end % Define the "PointsInSets" for i = 1:np if BoP(i) > 0 PointsInSets{BoP(i),1}(Ind(i)) = i; end end %% Neighbors % Define neighbors. Sets A and B are neighbors if the large ball of A % contains points of B. Notice that this is not a symmetric relation. Nei = cell(nb,1); Fal = false(nb,1); for i = 1:nb B = Ball{i}; % the points in the big ball of cover set "i" I = (BoP(B) ~= i); N = B(I); % the points of B not in the cover set "i" N = BoP(N); % select the unique elements of N: n = length(N); if n > 2 Include = true(n,1); for j = 1:n if ~Fal(N(j)) Fal(N(j)) = true; else Include(j) = false; end end Fal(N) = false; N = N(Include); elseif n == 2 if N(1) == N(2) N = N(1); end end Nei{i} = uint32(N); end % Make the relation symmetric by adding, if needed, A as B's neighbor % in the case B is A's neighbor for i = 1:nb N = Nei{i}; for j = 1:length(N) K = (Nei{N(j)} == i); if ~any(K) Nei{N(j)} = uint32([Nei{N(j)}; i]); end end end % Define output cover.ball = PointsInSets; cover.center = Cen; cover.neighbor = Nei; %% Display statistics %disp([' ',num2str(nb),' cover sets, points not covered: ',num2str(np-nnz(BoP))]) ================================================ FILE: src/main_steps/cylinders.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function cylinder = cylinders(P,cover,segment,inputs) % --------------------------------------------------------------------- % CYLINDERS.M Fits cylinders to the branch-segments of the point cloud % % Version 3.0.0 % Latest update 1 Now 2018 % % Copyright (C) 2013-2018 Pasi Raumonen % --------------------------------------------------------------------- % % Reconstructs the surface and volume of branches of input tree with % cylinders. Subdivides each segment to smaller regions to which cylinders % are fitted in least squares sense. Returns the cylinder information and % in addition the child-relation of the cylinders plus the cylinders in % each segment. % --------------------------------------------------------------------- % Inputs: % P Point cloud, matrix % cover Cover sets % segment Segments % input Input parameters of the reconstruction: % MinCylRad Minimum cylinder radius, used in the taper corrections % ParentCor Radius correction based on radius of the parent: radii in % a branch are usually smaller than the radius of the parent % cylinder in the parent branch % TaperCor Parabola taper correction of radii inside branches. % GrowthVolCor If 1, use growth volume correction % GrowthVolFac Growth volume correction factor % % Outputs: % cylinder Structure array containing the following cylinder info: % radius Radii of the cylinders, vector % length Lengths of the cylinders, vector % axis Axes of the cylinders, matrix % start Starting points of the cylinders, matrix % parent Parents of the cylinders, vector % extension Extensions of the cylinders, vector % branch Branch of the cylinder % BranchOrder Branching order of the cylinder % PositionInBranch Position of the cylinder inside the branch % mad Mean absolute distances of points from the cylinder % surface, vector % SurfCov Surface coverage measure, vector % added Added cylinders, logical vector % UnModRadius Unmodified radii % --------------------------------------------------------------------- % Changes from version 3.0.0 to 3.1.0, 6 Oct 2021: % 1) Added the growth volume correction option ("growth_volume_correction") % back, which was removed from the previous version by a mistake. The % "growth_volume_correction" function was also corrected. % 2) Added the fields "branch", "BranchOrder", "PositionInBranch" to the % output structure "cylinder" % 3) Removed the fields "CylsInSegment" and "ChildCyls" from the output % structure "cylinder" % Changes from version 2.0.0 to 3.0.0, 13 Aug 2020: % Many comprehensive and small changes: % 1) "regions" and "cylinder_fitting" are combined into "cylinder_fitting" % and the process is more adaptive as it now fits at least 3 (up to 10) % cylinders of different lengths for each region. % 2) "lcyl" and "FilRad" parameters are not used anymore % 3) Surface coverage ("SurfCov") and mean absolute distance ("mad") are % added to the cylinder structure as fields. % 4) Surface coverage filtering is used in the definition of the regions % and removing outliers % 5) "adjustments" has many changes, particularly in the taper corrections % where the parabola-taper curve is fitted to all the data with surface % coverage as a weight. Adjustment of radii based on the parabola is % closer the parabola the smaller the surface coverage. For the stem the % taper correction is the same as for the branches. The minimum and % maximum radii corrections are also modified. % 6) Syntax has changed, particularly for the "cyl"-structure % Changes from version 2.1.0 to 2.1.1, 26 Nov 2019: % 1) Increased the minimum number "n" of estimated cylinders for % initialization of vectors at the beginning of the code. This is done % to make sure that trees without branches will not cause errors. % Changes from version 2.0.0 to 2.1.0, 3 Oct 2019: % 1) Bug fix: UnmodRadius is now defined as it should, as the radius after % least squares fitting but without parent, taper or growth vol. corrections % 2) Bug fix: Correction in "least_squares_cylinder.m", calculates the % starting point of the cylinder now correctly. % 3) Bug fix: Correct errors related to combining data when a fitted % cylinder is replaced with two shorter ones, in "cylinder_fitting" % 4) Removed some unnecessary command lines for computing radius estimates % in "regions" %% Initialization of variables Segs = segment.segments; SPar = segment.ParentSegment; SChi = segment.ChildSegment; NumOfSeg = max(size(Segs)); % number of segments n = max(2000,min(40*NumOfSeg,2e5)); c = 1; % number of cylinders determined CChi = cell(n,1); % Children of the cylinders CiS = cell(NumOfSeg,1); % Cylinders in the segment cylinder.radius = zeros(n,1,'single'); cylinder.length = zeros(n,1,'single'); cylinder.start = zeros(n,3,'single'); cylinder.axis = zeros(n,3,'single'); cylinder.parent = zeros(n,1,'uint32'); cylinder.extension = zeros(n,1,'uint32'); cylinder.added = false(n,1); cylinder.UnmodRadius = zeros(n,1,'single'); cylinder.branch = zeros(n,1,'uint16'); cylinder.SurfCov = zeros(n,1,'single'); cylinder.mad = zeros(n,1,'single'); %% Determine suitable order of segments (from trunk to the "youngest" child) bases = (1:1:NumOfSeg)'; bases = bases(SPar(:,1) == 0); nb = length(bases); SegmentIndex = zeros(NumOfSeg,1); nc = 0; for i = 1:nb nc = nc+1; SegmentIndex(nc) = bases(i); S = vertcat(SChi{bases(i)}); while ~isempty(S) n = length(S); SegmentIndex(nc+1:nc+n) = S; nc = nc+n; S = vertcat(SChi{S}); end end %% Fit cylinders individually for each segment for k = 1:NumOfSeg si = SegmentIndex(k); if si > 0 %% Some initialization about the segment Seg = Segs{si}; % the current segment under analysis nl = max(size(Seg)); % number of cover set layers in the segment [Sets,IndSets] = verticalcat(Seg); % the cover sets in the segment ns = length(Sets); % number of cover sets in the current segment Points = vertcat(cover.ball{Sets}); % the points in the segments np = length(Points); % number of points in the segment % Determine indexes of points for faster definition of regions BallSize = cellfun('length',cover.ball(Sets)); IndPoints = ones(nl,2); % indexes for points in each layer of the segment for j = 1:nl IndPoints(j,2) = sum(BallSize(IndSets(j,1):IndSets(j,2))); end IndPoints(:,2) = cumsum(IndPoints(:,2)); IndPoints(2:end,1) = IndPoints(2:end,1)+IndPoints(1:end-1,2); Base = Seg{1}; % the base of the segment nb = IndPoints(1,2); % number of points in the base % Reconstruct only large enough segments if nl > 1 && np > nb && ns > 2 && np > 20 && ~isempty(Base) %% Cylinder fitting [cyl,Reg] = cylinder_fitting(P,Points,IndPoints,nl,si); nc = numel(cyl.radius); %% Search possible parent cylinder if nc > 0 && si > 1 [PC,cyl,added] = parent_cylinder(SPar,SChi,CiS,cylinder,cyl,si); nc = numel(cyl.radius); elseif si == 1 PC = zeros(0,1); added = false; else added = false; end cyl.radius0 = cyl.radius; %% Modify cylinders if nc > 0 % Define parent cylinder: parcyl.radius = cylinder.radius(PC); parcyl.length = cylinder.length(PC); parcyl.start = cylinder.start(PC,:); parcyl.axis = cylinder.axis(PC,:); % Modify the cylinders cyl = adjustments(cyl,parcyl,inputs,Reg); end %% Save the cylinders % if at least one acceptable cylinder, then save them Accept = nc > 0 & min(cyl.radius(1:nc)) > 0; if Accept % If the parent cylinder exists, set the parent-child relations if ~isempty(PC) cylinder.parent(c) = PC; if cylinder.extension(PC) == c I = cylinder.branch(PC); cylinder.branch(c:c+nc-1) = I; CiS{I} = [CiS{I}; linspace(c,c+nc-1,nc)']; else CChi{PC} = [CChi{PC}; c]; cylinder.branch(c:c+nc-1) = si; CiS{si} = linspace(c,c+nc-1,nc)'; end else cylinder.branch(c:c+nc-1) = si; CiS{si} = linspace(c,c+nc-1,nc)'; end cylinder.radius(c:c+nc-1) = cyl.radius(1:nc); cylinder.length(c:c+nc-1) = cyl.length(1:nc); cylinder.axis(c:c+nc-1,:) = cyl.axis(1:nc,:); cylinder.start(c:c+nc-1,:) = cyl.start(1:nc,:); cylinder.parent(c+1:c+nc-1) = linspace(c,c+nc-2,nc-1); cylinder.extension(c:c+nc-2) = linspace(c+1,c+nc-1,nc-1); cylinder.UnmodRadius(c:c+nc-1) = cyl.radius0(1:nc); cylinder.SurfCov(c:c+nc-1) = cyl.SurfCov(1:nc); cylinder.mad(c:c+nc-1) = cyl.mad(1:nc); if added cylinder.added(c) = true; cylinder.added(c) = true; end c = c+nc; % number of cylinders so far (plus one) end end end end c = c-1; % number of cylinders %% Define outputs names = fieldnames(cylinder); n = max(size(names)); for k = 1:n cylinder.(names{k}) = single(cylinder.(names{k})(1:c,:)); end if c <= 2^16 cylinder.parent = uint16(cylinder.parent); cylinder.extension = uint16(cylinder.extension); end nb = max(cylinder.branch); if nb <= 2^8 cylinder.branch = uint8(cylinder.branch); elseif nb <= 2^16 cylinder.branch = uint16(cylinder.branch); end cylinder.added = logical(cylinder.added); % Define the branching order: BOrd = zeros(c,1); for i = 1:c if cylinder.parent(i) > 0 p = cylinder.parent(i); if cylinder.extension(p) == i BOrd(i) = BOrd(p); else BOrd(i) = BOrd(p)+1; end end end cylinder.BranchOrder = uint8(BOrd); % Define the cylinder position inside the branch PiB = ones(c,1); for i = 1:NumOfSeg C = CiS{i}; if ~isempty(C) n = length(C); PiB(C) = (1:1:n)'; end end if max(PiB) <= 2^8 cylinder.PositionInBranch = uint8(PiB); else cylinder.PositionInBranch = uint16(PiB); end % Growth volume correction if inputs.GrowthVolCor && c > 0 cylinder = growth_volume_correction(cylinder,inputs); end end % End of main function function [cyl,Reg] = cylinder_fitting(P,Points,Ind,nl,si) if nl > 6 i0 = 1; i = 4; % indexes of the first and last layers of the region t = 0; Reg = cell(nl,1); cyls = cell(11,1); regs = cell(11,1); data = zeros(11,4); while i0 < nl-2 %% Fit at least three cylinders of different lengths bot = Points(Ind(i0,1):Ind(i0+1,2)); Bot = average(P(bot,:)); % Bottom axis point of the region again = true; j = 0; while i+j <= nl && j <= 10 && (j <= 2 || again) %% Select points and estimate axis RegC = Points(Ind(i0,1):Ind(i+j,2)); % candidate region % Top axis point of the region: top = Points(Ind(i+j-1,1):Ind(i+j,2)); Top = average(P(top,:)); % Axis of the cylinder: Axis = Top-Bot; c0.axis = Axis/norm(Axis); % Compute the height along the axis: h = (P(RegC,:)-Bot)*c0.axis'; minh = min(h); % Correct Bot to correspond to the real bottom if j == 0 Bot = Bot+minh*c0.axis; c0.start = Bot; h = (P(RegC,:)-Bot)*c0.axis'; minh = min(h); end if i+j >= nl ht = (Top-c0.start)*c0.axis'; Top = Top+(max(h)-ht)*c0.axis; end % Compute the height of the Top: ht = (Top-c0.start)*c0.axis'; Sec = h <= ht & h >= minh; % only points below the Top c0.length = ht-minh; % length of the region/cylinder % The region for the cylinder fitting: reg = RegC(Sec); Q0 = P(reg,:); %% Filter points and estimate radius if size(Q0,1) > 20 [Keep,c0] = surface_coverage_filtering(Q0,c0,0.02,20); reg = reg(Keep); Q0 = Q0(Keep,:); else c0.radius = 0.01; c0.SurfCov = 0.05; c0.mad = 0.01; c0.conv = 1; c0.rel = 1; end %% Fit cylinder if size(Q0,1) > 9 if i >= nl && t == 0 c = least_squares_cylinder(Q0,c0); elseif i >= nl && t > 0 h = (Q0-CylTop)*c0.axis'; I = h >= 0; Q = Q0(I,:); % the section reg = reg(I); n2 = size(Q,1); n1 = nnz(~I); if n2 > 9 && n1 > 5 Q0 = [Q0(~I,:); Q]; % the point cloud for cylinder fitting W = [1/3*ones(n2,1); 2/3*ones(n1,1)]; % the weights c = least_squares_cylinder(Q0,c0,W,Q); else c = least_squares_cylinder(Q0,c0); end elseif t == 0 top = Points(Ind(i+j-3,1):Ind(i+j-2,2)); Top = average(P(top,:)); % Top axis point of the region ht = (Top-Bot)*c0.axis'; h = (Q0-Bot)*c0.axis'; I = h <= ht; Q = Q0(I,:); % the section reg = reg(I); n2 = size(Q,1); n3 = nnz(~I); if n2 > 9 && n3 > 5 Q0 = [Q; Q0(~I,:)]; % the point cloud for cylinder fitting W = [2/3*ones(n2,1); 1/3*ones(n3,1)]; % the weights c = least_squares_cylinder(Q0,c0,W,Q); else c = least_squares_cylinder(Q0,c0); end else top = Points(Ind(i+j-3,1):Ind(i+j-2,2)); Top = average(P(top,:)); % Top axis point of the region ht = (Top-CylTop)*c0.axis'; h = (Q0-CylTop)*c0.axis'; I1 = h < 0; % the bottom I2 = h >= 0 & h <= ht; % the section I3 = h > ht; % the top Q = Q0(I2,:); reg = reg(I2); n1 = nnz(I1); n2 = size(Q,1); n3 = nnz(I3); if n2 > 9 Q0 = [Q0(I1,:); Q; Q0(I3,:)]; W = [1/4*ones(n1,1); 2/4*ones(n2,1); 1/4*ones(n3,1)]; c = least_squares_cylinder(Q0,c0,W,Q); else c = c0; c.rel = 0; end end if c.conv == 0 c = c0; c.rel = 0; end if c.SurfCov < 0.2 c.rel = 0; end else c = c0; c.rel = 0; end % Collect fit data data(j+1,:) = [c.rel c.conv c.SurfCov c.length/c.radius]; cyls{j+1} = c; regs{j+1} = reg; j = j+1; % If reasonable cylinder fitted, then stop fitting new ones % (but always fit at least three cylinders) RL = c.length/c.radius; % relative length of the cylinder if again && c.rel && c.conv && RL > 2 if si == 1 && c.SurfCov > 0.7 again = false; elseif si > 1 && c.SurfCov > 0.5 again = false; end end end %% Select the best of the fitted cylinders % based on maximum surface coverage OKfit = data(1:j,1) & data(1:j,2) & data(1:j,4) > 1.5; J = (1:1:j)'; t = t+1; if any(OKfit) J = J(OKfit); end [~,I] = max(data(J,3)-0.01*data(J,4)); J = J(I); c = cyls{J}; %% Update the indexes of the layers for the next region: CylTop = c.start+c.length*c.axis; i0 = i0+1; bot = Points(Ind(i0,1):Ind(i0+1,2)); Bot = average(P(bot,:)); % Bottom axis point of the region h = (Bot-CylTop)*c.axis'; i00 = i0; while i0+1 < nl && i0 < i00+5 && h < -c.radius/3 i0 = i0+1; bot = Points(Ind(i0,1):Ind(i0+1,2)); Bot = average(P(bot,:)); % Bottom axis point of the region h = (Bot-CylTop)*c.axis'; end i = i0+5; i = min(i,nl); %% If the next section is very short part of the end of the branch % then simply increase the length of the current cylinder if nl-i0+2 < 4 reg = Points(Ind(nl-5,1):Ind(nl,2)); Q0 = P(reg,:); ht = (c.start+c.length*c.axis)*c.axis'; h = Q0*c.axis'; maxh = max(h); if maxh > ht c.length = c.length+(maxh-ht); end i0 = nl; end Reg{t} = regs{J}; if t == 1 cyl = c; names = fieldnames(cyl); n = max(size(names)); else for k = 1:n cyl.(names{k}) = [cyl.(names{k}); c.(names{k})]; end end %% compute cylinder top for the definition of the next section CylTop = c.start+c.length*c.axis; end Reg = Reg(1:t); else %% Define a region for small segments Q0 = P(Points,:); if size(Q0,1) > 10 %% Define the direction bot = Points(Ind(1,1):Ind(1,2)); Bot = average(P(bot,:)); top = Points(Ind(nl,1):Ind(nl,2)); Top = average(P(top,:)); Axis = Top-Bot; c0.axis = Axis/norm(Axis); h = Q0*c0.axis'; c0.length = max(h)-min(h); hpoint = Bot*c0.axis'; c0.start = Bot-(hpoint-min(h))*c0.axis; %% Define other outputs [Keep,c0] = surface_coverage_filtering(Q0,c0,0.02,20); Reg = cell(1,1); Reg{1} = Points(Keep); Q0 = Q0(Keep,:); cyl = least_squares_cylinder(Q0,c0); if ~cyl.conv || ~cyl.rel cyl = c0; end t = 1; else cyl = 0; t = 0; end end % Define Reg as coordinates for i = 1:t Reg{i} = P(Reg{i},:); end Reg = Reg(1:t); % End of function end function [PC,cyl,added] = parent_cylinder(SPar,SChi,CiS,cylinder,cyl,si) % Finds the parent cylinder from the possible parent segment. % Does this by checking if the axis of the cylinder, if continued, will % cross the nearby cylinders in the parent segment. % Adjust the cylinder so that it starts from the surface of its parent. rad = cyl.radius; len = cyl.length; sta = cyl.start; axe = cyl.axis; % PC Parent cylinder nc = numel(rad); added = false; if SPar(si) > 0 % parent segment exists, find the parent cylinder s = SPar(si); PC = CiS{s}; % the cylinders in the parent segment % select the closest cylinders for closer examination if length(PC) > 1 D = mat_vec_subtraction(-cylinder.start(PC,:),-sta(1,:)); d = sum(D.*D,2); [~,I] = sort(d); if length(PC) > 3 I = I(1:4); end pc = PC(I); ParentFound = false; elseif length(PC) == 1 ParentFound = true; else PC = zeros(0,1); ParentFound = true; end %% Check possible crossing points if ~ParentFound pc0 = pc; n = length(pc); % Calculate the possible crossing points of the cylinder axis, when % extended, on the surfaces of the parent candidate cylinders x = zeros(n,2); % how much the starting point has to move to cross h = zeros(n,2); % the crossing point height in the parent Axe = cylinder.axis(pc,:); Sta = cylinder.start(pc,:); for j = 1:n % Crossing points solved from a quadratic equation A = axe(1,:)-(axe(1,:)*Axe(j,:)')*Axe(j,:); B = sta(1,:)-Sta(j,:)-(sta(1,:)*Axe(j,:)')*Axe(j,:)... +(Sta(j,:)*Axe(j,:)')*Axe(j,:); e = A*A'; f = 2*A*B'; g = B*B'-cylinder.radius(pc(j))^2; di = sqrt(f^2 - 4*e*g); % the discriminant s1 = (-f + di)/(2*e); % how much the starting point must be moved to cross: s2 = (-f - di)/(2*e); if isreal(s1) %% cylinders can cross % the heights of the crossing points x(j,:) = [s1 s2]; h(j,1) = sta(1,:)*Axe(j,:)'+x(j,1)*axe(1,:)*Axe(j,:)'-... Sta(j,:)*Axe(j,:)'; h(j,2) = sta(1,:)*Axe(j,:)'+x(j,2)*axe(1,:)*Axe(j,:)'-... Sta(j,:)*Axe(j,:)'; end end %% Extend to crossing point in the (extended) parent I = x(:,1) ~= 0; % Select only candidates with crossing points pc = pc0(I); x = x(I,:); h = h(I,:); j = 1; n = nnz(I); X = zeros(n,3); % Len = cylinder.length(pc); while j <= n && ~ParentFound if x(j,1) > 0 && x(j,2) < 0 % sp inside the parent and crosses its surface if h(j,1) >= 0 && h(j,1) <= Len(j) && len(1)-x(j,1) > 0 PC = pc(j); sta(1,:) = sta(1,:)+x(j,1)*axe(1,:); len(1) = len(1)-x(j,1); ParentFound = true; elseif len(1)-x(j,1) > 0 if h(j,1) < 0 X(j,:) = [x(j,1) abs(h(j,1)) 0]; else X(j,:) = [x(j,1) h(j,1)-Len(j) 0]; end else X(j,:) = [x(j,1) h(j,1) 1]; end elseif x(j,1) < 0 && x(j,2) > 0 && len(1)-x(j,2) > 0 % sp inside the parent and crosses its surface if h(j,2) >= 0 && h(j,2) <= Len(j) && len(1)-x(j,2) > 0 PC = pc(j); sta(1,:) = sta(1,:)+x(j,2)*axe(1,:); len(1) = len(1)-x(j,2); ParentFound = true; elseif len(1)-x(j,2) > 0 if h(j,2) < 0 X(j,:) = [x(j,2) abs(h(j,2)) 0]; else X(j,:) = [x(j,2) h(j,2)-Len(j) 0]; end else X(j,:) = [x(j,2) h(j,2) 1]; end elseif x(j,1) < 0 && x(j,2) < 0 && x(j,2) < x(j,1) && len(1)-x(j,1) > 0 % sp outside the parent and crosses its surface when extended % backwards if h(j,1) >= 0 && h(j,1) <= Len(j) && len(1)-x(j,1) > 0 PC = pc(j); sta(1,:) = sta(1,:)+x(j,1)*axe(1,:); len(1) = len(1)-x(j,1); ParentFound = true; elseif len(1)-x(j,1) > 0 if h(j,1) < 0 X(j,:) = [x(j,1) abs(h(j,1)) 0]; else X(j,:) = [x(j,1) h(j,1)-Len(j) 0]; end else X(j,:) = [x(j,1) h(j,1) 1]; end elseif x(j,1) < 0 && x(j,2) < 0 && x(j,2) > x(j,1) && len(1)-x(j,2) > 0 % sp outside the parent and crosses its surface when extended % backwards if h(j,2) >= 0 && h(j,2) <= Len(j) && len(1)-x(j,2) > 0 PC = pc(j); sta(1,:) = sta(1,:)+x(j,2)*axe(1,:); len(1) = len(1)-x(j,2); ParentFound = true; elseif len(1)-x(j,2) > 0 if h(j,2) < 0 X(j,:) = [x(j,2) abs(h(j,2)) 0]; else X(j,:) = [x(j,2) h(j,2)-Len(j) 0]; end else X(j,:) = [x(j,2) h(j,2) 1]; end elseif x(j,1) > 0 && x(j,2) > 0 && x(j,2) < x(j,1) && len(1)-x(j,1) > 0 % sp outside the parent but crosses its surface when extended forward if h(j,1) >= 0 && h(j,1) <= Len(j) && len(1)-x(j,1) > 0 PC = pc(j); sta(1,:) = sta(1,:)+x(j,1)*axe(1,:); len(1) = len(1)-x(j,1); ParentFound = true; elseif len(1)-x(j,1) > 0 if h(j,1) < 0 X(j,:) = [x(j,1) abs(h(j,1)) 0]; else X(j,:) = [x(j,1) h(j,1)-Len(j) 0]; end else X(j,:) = [x(j,1) h(j,1) 1]; end elseif x(j,1) > 0 && x(j,2) > 0 && x(j,2) > x(j,1) && len(1)-x(j,2) > 0 % sp outside the parent and crosses its surface when extended forward if h(j,2) >= 0 && h(j,2) <= Len(j) && len(1)-x(j,2) > 0 PC = pc(j); sta(1,:) = sta(1,:)+x(j,2)*axe(1,:); len(1) = len(1)-x(j,2); ParentFound = true; elseif len(1)-x(j,2) > 0 if h(j,1) < 0 X(j,:) = [x(j,2) abs(h(j,2)) 0]; else X(j,:) = [x(j,2) h(j,2)-Len(j) 0]; end else X(j,:) = [x(j,2) h(j,2) 1]; end end j = j+1; end if ~ParentFound && n > 0 [H,I] = min(X(:,2)); X = X(I,:); if X(3) == 0 && H < 0.1*Len(I) PC = pc(I); sta(1,:) = sta(1,:)+X(1)*axe(1,:); len(1) = len(1)-X(1); ParentFound = true; else PC = pc(I); if nc > 1 && X(1) <= rad(1) && abs(X(2)) <= 1.25*cylinder.length(PC) % Remove the first cylinder and adjust the second S = sta(1,:)+X(1)*axe(1,:); V = sta(2,:)+len(2)*axe(2,:)-S; len(2) = norm(V); len = len(2:nc); axe(2,:) = V/norm(V); axe = axe(2:nc,:); sta(2,:) = S; sta = sta(2:nc,:); rad = rad(2:nc); cyl.mad = cyl.mad(2:nc); cyl.SurfCov = cyl.SurfCov(2:nc); nc = nc-1; ParentFound = true; elseif nc > 1 % Remove the first cylinder sta = sta(2:nc,:); len = len(2:nc); axe = axe(2:nc,:); rad = rad(2:nc); cyl.mad = cyl.mad(2:nc); cyl.SurfCov = cyl.SurfCov(2:nc); nc = nc-1; elseif isempty(SChi{si}) % Remove the cylinder nc = 0; PC = zeros(0,1); ParentFound = true; rad = zeros(0,1); elseif X(1) <= rad(1) && abs(X(2)) <= 1.5*cylinder.length(PC) % Adjust the cylinder sta(1,:) = sta(1,:)+X(1)*axe(1,:); len(1) = abs(X(1)); ParentFound = true; end end end if ~ParentFound % The parent is the cylinder in the parent segment whose axis % line is the closest to the axis line of the first cylinder % Or the parent cylinder is the one whose base, when connected % to the first cylinder is the most parallel. % Add new cylinder pc = pc0; [Dist,~,DistOnLines] = distances_between_lines(... sta(1,:),axe(1,:),cylinder.start(pc,:),cylinder.axis(pc,:)); I = DistOnLines >= 0; J = DistOnLines <= cylinder.length(pc); I = I&J; if ~any(I) I = DistOnLines >= -0.2*cylinder.length(pc); J = DistOnLines <= 1.2*cylinder.length(pc); I = I&J; end if any(I) pc = pc(I); Dist = Dist(I); DistOnLines = DistOnLines(I); [~,I] = min(Dist); DistOnLines = DistOnLines(I); PC = pc(I); Q = cylinder.start(PC,:)+DistOnLines*cylinder.axis(PC,:); V = sta(1,:)-Q; L = norm(V); V = V/L; a = acos(V*cylinder.axis(PC,:)'); h = sin(a)*L; S = Q+cylinder.radius(PC)/h*L*V; L = (h-cylinder.radius(PC))/h*L; if L > 0.01 && L/len(1) > 0.2 nc = nc+1; sta = [S; sta]; rad = [rad(1); rad]; axe = [V; axe]; len = [L; len]; cyl.mad = [cyl.mad(1); cyl.mad]; cyl.SurfCov = [cyl.SurfCov(1); cyl.SurfCov]; cyl.rel = [cyl.rel(1); cyl.rel]; cyl.conv = [cyl.conv(1); cyl.conv]; added = true; end else V = -mat_vec_subtraction(cylinder.start(pc,:),sta(1,:)); L0 = sqrt(sum(V.*V,2)); V = [V(:,1)./L0 V(:,2)./L0 V(:,3)./L0]; A = V*axe(1,:)'; [A,I] = max(A); L1 = L0(I); PC = pc(I); V = V(I,:); a = acos(V*cylinder.axis(PC,:)'); h = sin(a)*L1; S = cylinder.start(PC,:)+cylinder.radius(PC)/h*L1*V; L = (h-cylinder.radius(PC))/h*L1; if L > 0.01 && L/len(1) > 0.2 nc = nc+1; sta = [S; sta]; rad = [rad(1); rad]; axe = [V; axe]; len = [L; len]; cyl.mad = [cyl.mad(1); cyl.mad]; cyl.SurfCov = [cyl.SurfCov(1); cyl.SurfCov]; cyl.rel = [cyl.rel(1); cyl.rel]; cyl.conv = [cyl.conv(1); cyl.conv]; added = true; end end end end else % no parent segment exists PC = zeros(0,1); end % define the output cyl.radius = rad(1:nc); cyl.length = len(1:nc,:); cyl.start = sta(1:nc,:); cyl.axis = axe(1:nc,:); cyl.mad = cyl.mad(1:nc); cyl.SurfCov = cyl.SurfCov(1:nc); cyl.conv = cyl.conv(1:nc); cyl.rel = cyl.rel(1:nc); % End of function end function cyl = adjustments(cyl,parcyl,inputs,Regs) nc = size(cyl.radius,1); Mod = false(nc,1); % cylinders modified SC = cyl.SurfCov; %% Determine the maximum and the minimum radius % The maximum based on parent branch if ~isempty(parcyl.radius) MaxR = 0.95*parcyl.radius; MaxR = max(MaxR,inputs.MinCylRad); else % use the maximum from the bottom cylinders a = min(3,nc); MaxR = 1.25*max(cyl.radius(1:a)); end MinR = min(cyl.radius(SC > 0.7)); if ~isempty(MinR) && min(cyl.radius) < MinR/2 MinR = min(cyl.radius(SC > 0.4)); elseif isempty(MinR) MinR = min(cyl.radius(SC > 0.4)); if isempty(MinR) MinR = inputs.MinCylRad; end end %% Check maximum and minimum radii I = cyl.radius < MinR; cyl.radius(I) = MinR; Mod(I) = true; if inputs.ParentCor || nc <= 3 I = (cyl.radius > MaxR & SC < 0.7) | (cyl.radius > 1.2*MaxR); cyl.radius(I) = MaxR; Mod(I) = true; % For short branches modify with more restrictions if nc <= 3 I = (cyl.radius > 0.75*MaxR & SC < 0.7); if any(I) r = max(SC(I)/0.7.*cyl.radius(I),MinR); cyl.radius(I) = r; Mod(I) = true; end end end %% Use taper correction to modify radius of too small and large cylinders % Adjust radii if a small SurfCov and high SurfCov in the previous and % following cylinders for i = 2:nc-1 if SC(i) < 0.7 && SC(i-1) >= 0.7 && SC(i+1) >= 0.7 cyl.radius(i) = 0.5*(cyl.radius(i-1)+cyl.radius(i+1)); Mod(i) = true; end end %% Use taper correction to modify radius of too small and large cylinders if inputs.TaperCor if max(cyl.radius) < 0.001 %% Adjust radii of thin branches to be linearly decreasing if nc > 2 r = sort(cyl.radius); r = r(2:end-1); a = 2*mean(r); if a > max(r) a = min(0.01,max(r)); end b = min(0.5*min(cyl.radius),0.001); cyl.radius = linspace(a,b,nc)'; elseif nc > 1 r = max(cyl.radius); cyl.radius = [r; 0.5*r]; end Mod = true(nc,1); elseif nc > 4 %% Parabola adjustment of maximum and minimum % Define parabola taper shape as maximum (and minimum) radii for % the cylinders with low surface coverage branchlen = sum(cyl.length(1:nc)); % branch length L = cyl.length/2+[0; cumsum(cyl.length(1:nc-1))]; Taper = [L; branchlen]; Taper(:,2) = [1.05*cyl.radius; MinR]; sc = [SC; 1]; % Least square fitting of parabola to "Taper": A = [sum(sc.*Taper(:,1).^4) sum(sc.*Taper(:,1).^2); ... sum(sc.*Taper(:,1).^2) sum(sc)]; y = [sum(sc.*Taper(:,2).*Taper(:,1).^2); sum(sc.*Taper(:,2))]; warning off x = A\y; warning on x(1) = min(x(1),-0.0001); % tapering from the base to the tip Ru = x(1)*L.^2+x(2); % upper bound parabola Ru( Ru < MinR ) = MinR; if max(Ru) > MaxR a = max(Ru); Ru = MaxR/a*Ru; end Rl = 0.75*Ru; % lower bound parabola Rl( Rl < MinR ) = MinR; % Modify radii based on parabola: % change values larger than the parabola-values when SC < 70%: I = cyl.radius > Ru & SC < 0.7; cyl.radius(I) = Ru(I)+(cyl.radius(I)-Ru(I)).*SC(I)/0.7; Mod(I) = true; % change values larger than the parabola-values when SC > 70% and % radius is over 33% larger than the parabola-value: I = cyl.radius > 1.333*Ru & SC >= 0.7; cyl.radius(I) = Ru(I)+(cyl.radius(I)-Ru(I)).*SC(I); Mod(I) = true; % change values smaller than the downscaled parabola-values: I = (cyl.radius < Rl & SC < 0.7) | (cyl.radius < 0.5*Rl); cyl.radius(I) = Rl(I); Mod(I) = true; else %% Adjust radii of short branches to be linearly decreasing R = cyl.radius; if nnz(SC >= 0.7) > 1 a = max(R(SC >= 0.7)); b = min(R(SC >= 0.7)); elseif nnz(SC >= 0.7) == 1 a = max(R(SC >= 0.7)); b = min(R); else a = sum(R.*SC/sum(SC)); b = min(R); end Ru = linspace(a,b,nc)'; I = SC < 0.7 & ~Mod; cyl.radius(I) = Ru(I)+(R(I)-Ru(I)).*SC(I)/0.7; Mod(I) = true; end end %% Modify starting points by optimising them for given radius and axis nr = size(Regs,1); for i = 1:nc if Mod(i) if nr == nc Reg = Regs{i}; elseif i > 1 Reg = Regs{i-1}; end if abs(cyl.radius(i)-cyl.radius0(i)) > 0.005 && ... (nr == nc || (nr < nc && i > 1)) P = Reg-cyl.start(i,:); [U,V] = orthonormal_vectors(cyl.axis(i,:)); P = P*[U V]; cir = least_squares_circle_centre(P,[0 0],cyl.radius(i)); if cir.conv && cir.rel cyl.start(i,:) = cyl.start(i,:)+cir.point(1)*U'+cir.point(2)*V'; cyl.mad(i,1) = cir.mad; [~,V,h] = distances_to_line(Reg,cyl.axis(i,:),cyl.start(i,:)); if min(h) < -0.001 cyl.length(i) = max(h)-min(h); cyl.start(i,:) = cyl.start(i,:)+min(h)*cyl.axis(i,:); [~,V,h] = distances_to_line(Reg,cyl.axis(i,:),cyl.start(i,:)); end a = max(0.02,0.2*cyl.radius(i)); nl = ceil(cyl.length(i)/a); nl = max(nl,4); ns = ceil(2*pi*cyl.radius(i)/a); ns = max(ns,10); ns = min(ns,36); cyl.SurfCov(i,1) = surface_coverage2(... cyl.axis(i,:),cyl.length(i),V,h,nl,ns); end end end end %% Continuous branches % Make cylinders properly "continuous" by moving the starting points % Move the starting point to the plane defined by parent cylinder's top if nc > 1 for j = 2:nc U = cyl.start(j,:)-cyl.start(j-1,:)-cyl.length(j-1)*cyl.axis(j-1,:); if (norm(U) > 0.0001) % First define vector V and W which are orthogonal to the % cylinder axis N N = cyl.axis(j,:)'; if norm(N) > 0 [V,W] = orthonormal_vectors(N); % Now define the new starting point x = [N V W]\U'; cyl.start(j,:) = cyl.start(j,:)-x(1)*N'; if x(1) > 0 cyl.length(j) = cyl.length(j)+x(1); elseif cyl.length(j)+x(1) > 0 cyl.length(j) = cyl.length(j)+x(1); end end end end end %% Connect far away first cylinder to the parent if ~isempty(parcyl.radius) [d,V,h,B] = distances_to_line(cyl.start(1,:),parcyl.axis,parcyl.start); d = d-parcyl.radius; if d > 0.001 taper = cyl.start(1,:); E = taper+cyl.length(1)*cyl.axis(1,:); V = parcyl.radius*V/norm(V); if h >= 0 && h <= parcyl.length cyl.start(1,:) = parcyl.start+B+V; elseif h < 0 cyl.start(1,:) = parcyl.start+V; else cyl.start(1,:) = parcyl.start+parcyl.length*parcyl.axis+V; end cyl.axis(1,:) = E-cyl.start(1,:); cyl.length(1) = norm(cyl.axis(1,:)); cyl.axis(1,:) = cyl.axis(1,:)/cyl.length(1); end end % End of function end ================================================ FILE: src/main_steps/filtering.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function Pass = filtering(P,inputs) % --------------------------------------------------------------------- % FILTERING.M Filters noise from point clouds. % % Version 3.0.0 % Latest update 3 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % Filters the point cloud as follows: % % 1) the possible NaNs are removed. % % 2) (optional, done if filter.k > 0) Statistical kth-nearest neighbor % distance outlier filtering based on user defined "k" (filter.k) and % multiplier for standard deviation (filter.nsigma): Determines the % kth-nearest neighbor distance for all points and then removes the points % whose distances are over average_distance + nsigma*std. Computes the % statistics for each meter layer in vertical direction so that the % average distances and SDs can change as the point density decreases. % % 3) (optional, done if filter.radius > 0) Statistical point density % filtering based on user defined ball radius (filter.radius) and multiplier % for standard deviation (filter.nsigma): Balls of radius "filter.radius" % centered at each point are defined for all points and the number of % points included ("point density") are computed and then removes the points % whose density is smaller than average_density - nsigma*std. Computes the % statistics for each meter layer in vertical direction so that the % average densities and SDs can change as the point density decreases. % % 4) (optional, done if filter.ncomp > 0) Small component filtering based % on user defined cover (filter.PatchDiam1, filter.BallRad1) and threshold % (filter.ncomp): Covers the point cloud and determines the connected % components of the cover and removes the points from the small components % that have less than filter.ncomp cover sets. % % 5) (optional, done if filter.EdgeLength > 0) cubical downsampling of the % point cloud based on user defined cube size (filter.EdgeLength): % selects randomly one point from each cube % % Does the filtering in the above order and thus always applies the next % fitering to the point cloud already filtered by the previous methods. % Statistical kth-nearest neighbor distance outlier filtering and the % statistical point density filtering are meant to be exlusive to each % other. % % Inputs: % P Point cloud % inputs Inputs structure with the following subfields: % filter.EdgeLength Edge length of the cubes in the cubical downsampling % filter.k k of knn method % filter.radius Radius of the balls in the density filtering % filter.nsigma Multiplier for standard deviation, determines how % far from the mean the threshold is in terms of SD. % Used in both the knn and the density filtering % filter.ncomp Threshold number of components in the small % component filtering % filter.PatchDiam1 Defines the patch/cover set size for the component % filtering % filter.BallRad1 Defines the neighbors for the component filtering % filter.plot If true, plots the filtered point cloud % Outputs: % Pass Logical vector indicating points passing the filtering % --------------------------------------------------------------------- % Changes from version 2.0.0 to 3.0.0, 3 May 2022: % Major changes and additions. % 1) Added two new filtering options: statistical kth-nearest neighbor % distance outlier filtering and cubical downsampling. % 2) Changed the old point density filtering, which was based on given % threshold, into statistical point density filtering, where the % threshold is based on user defined statistical measure % 3) All the input parameters are given by "inputs"-structure that can be % defined by "create_input" script % 4) Streamlined the coding and what is displayed %% Initial data processing % Only double precision data if ~isa(P,'double') P = double(P); end % Only x,y,z-data if size(P,2) > 3 P = P(:,1:3); end np = size(P,1); np0 = np; ind = (1:1:np)'; Pass = false(np,1); disp('----------------------') disp(' Filtering...') disp([' Points before filtering: ',num2str(np)]) %% Remove possible NaNs F = ~any(isnan(P),2); if nnz(F) < np disp([' Points with NaN removed: ',num2str(np-nnz(Pass))]) ind = ind(F); end %% Statistical kth-nearest neighbor distance outlier filtering if inputs.filter.k > 0 % Compute the knn distances Q = P(ind,:); np = size(Q,1); [~, kNNdist] = knnsearch(Q,Q,'dist','euclidean','k',inputs.filter.k); kNNdist = kNNdist(:,end); % Change the threshold kNNdistance according the average and standard % deviation for every vertical layer of 1 meter in height hmin = min(Q(:,3)); hmax = max(Q(:,3)); H = ceil(hmax-hmin); F = false(np,1); ind = (1:1:np)'; for i = 1:H I = Q(:,3) < hmin+i & Q(:,3) >= hmin+i-1; points = ind(I); d = kNNdist(points); J = d < mean(d)+inputs.filter.nsigma*std(d); points = points(J); F(points) = 1; end ind = ind(F); disp([' Points removed as statistical outliers: ',num2str(np-length(ind))]) end %% Statistical point density filtering if inputs.filter.radius > 0 Q = P(ind,:); np = size(Q,1); % Partition the point cloud into cubes [partition,CC] = cubical_partition(Q,inputs.filter.radius); % Determine the number of points inside a ball for each point NumOfPoints = zeros(np,1); r1 = inputs.filter.radius^2; for i = 1:np if NumOfPoints(i) == 0 points = partition(CC(i,1)-1:CC(i,1)+1,CC(i,2)-1:CC(i,2)+1,CC(i,3)-1:CC(i,3)+1); points = vertcat(points{:,:}); cube = Q(points,:); p = partition{CC(i,1),CC(i,2),CC(i,3)}; for j = 1:length(p) dist = (Q(p(j),1)-cube(:,1)).^2+(Q(p(j),2)-cube(:,2)).^2+(Q(p(j),3)-cube(:,3)).^2; J = dist < r1; NumOfPoints(p(j)) = nnz(J); end end end % Change the threshold point density according the average and standard % deviation for every vertical layer of 1 meter in height hmin = min(Q(:,3)); hmax = max(Q(:,3)); H = ceil(hmax-hmin); F = false(np,1); ind = (1:1:np)'; for i = 1:H I = Q(:,3) < hmin+i & Q(:,3) >= hmin+i-1; points = ind(I); N = NumOfPoints(points); J = N > mean(N)-inputs.filter.nsigma*std(N); points = points(J); F(points) = 1; end ind = ind(F); disp([' Points removed as statistical outliers: ',num2str(np-length(ind))]) end %% Small component filtering if inputs.filter.ncomp > 0 % Cover the point cloud with patches input.BallRad1 = inputs.filter.BallRad1; input.PatchDiam1 = inputs.filter.PatchDiam1; input.nmin1 = 0; Q = P(ind,:); np = size(Q,1); cover = cover_sets(Q,input); % Determine the separate components Components = connected_components(cover.neighbor,0,inputs.filter.ncomp); % The filtering B = vertcat(Components{:}); % patches in the components points = vertcat(cover.ball{B}); % points in the components F = false(np,1); F(points) = true; ind = ind(F); disp([' Points with small components removed: ',num2str(np-length(ind))]) end %% Cubical downsampling if inputs.filter.EdgeLength > 0 Q = P(ind,:); np = size(Q,1); F = cubical_downsampling(Q,inputs.filter.EdgeLength); ind = ind(F); disp([' Points removed with downsampling: ',num2str(np-length(ind))]) end %% Define the output and display summary results Pass(ind) = true; np = nnz(Pass); disp([' Points removed in total: ',num2str(np0-np)]) disp([' Points removed in total (%): ',num2str(round((1-np/np0)*1000)/10)]) disp([' Points left: ',num2str(np)]) %% Plot the filtered and unfiltered point clouds if inputs.filter.plot plot_comparison(P(Pass,:),P(~Pass,:),1,1,1) plot_point_cloud(P(Pass,:),2,1) end ================================================ FILE: src/main_steps/point_model_distance.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function pmdistance = point_model_distance(P,cylinder) % --------------------------------------------------------------------- % POINT_MODEL_DISTANCE.M Computes the distances of the points to the % cylinder model % % Version 2.1.1 % Latest update 8 Oct 2021 % % Copyright (C) 2015-2021 Pasi Raumonen % --------------------------------------------------------------------- % Changes from version 2.1.0 to 2.1.1, 8 Oct 2021: % 1) Changed the determinationa NE, the number of empty edge layers, so % that is now limited in size, before it is given as input for % cubical_partition function. % Changes from version 2.0.0 to 2.1.0, 26 Nov 2019: % 1) Bug fix: Corrected the computation of the output at the end of the % code so that trees without branches are computed correctly. % Cylinder data Rad = cylinder.radius; Len = cylinder.length; Sta = cylinder.start; Axe = cylinder.axis; BOrd = cylinder.BranchOrder; % Select randomly 25 % or max one million points for the distance comput. np0 = size(P,1); a = min(0.25*np0,1000000); I = logical(round(0.5/(1-a/np0)*rand(np0,1))); P = P(I,:); % Partition the points into cubes L = 2*median(Len); NE = max(3,min(10,ceil(max(Len)/L)))+3; [Partition,~,Info] = cubical_partition(P,L,NE); Min = Info(1:3); EL = Info(7); NE = Info(8); % Calculates the cube-coordinates of the starting points CC = floor([Sta(:,1)-Min(1) Sta(:,2)-Min(2) Sta(:,3)-Min(3)]/EL)+NE+1; % Compute the number of cubes needed for each starting point N = ceil(Len/L); % Correct N so that cube indexes are not too small or large I = CC(:,1) < N+1; N(I) = CC(I,1)-1; I = CC(:,2) < N+1; N(I) = CC(I,2)-1; I = CC(:,3) < N+1; N(I) = CC(I,3)-1; I = CC(:,1)+N+1 > Info(4); N(I) = Info(4)-CC(I,1)-1; I = CC(:,2)+N+1 > Info(5); N(I) = Info(5)-CC(I,2)-1; I = CC(:,3)+N+1 > Info(6); N(I) = Info(6)-CC(I,3)-1; % Calculate the distances to the cylinders n = size(Rad,1); np = size(P,1); Dist = zeros(np,2); % Distance and the closest cylinder of each points Dist(:,1) = 2; % Large distance initially Points = zeros(ceil(np/10),1,'int32'); % Auxiliary variable Data = cell(n,1); for i = 1:n Par = Partition(CC(i,1)-N(i):CC(i,1)+N(i),CC(i,2)-N(i):CC(i,2)+N(i),... CC(i,3)-N(i):CC(i,3)+N(i)); if N(i) > 1 S = cellfun('length',Par); I = S > 0; S = S(I); Par = Par(I); stop = cumsum(S); start = [0; stop]+1; for k = 1:length(stop) Points(start(k):stop(k)) = Par{k}(:); end points = Points(1:stop(k)); else points = vertcat(Par{:}); end [d,~,h] = distances_to_line(P(points,:),Axe(i,:),Sta(i,:)); d = abs(d-Rad(i)); Data{i} = [d h double(points)]; I = d < Dist(points,1); J = h >= 0; K = h <= Len(i); L = d < 0.5; M = I&J&K&L; points = points(M); Dist(points,1) = d(M); Dist(points,2) = i; end % Calculate the distances to the cylinders for points not yet calculated % because they are not "on side of cylinder for i = 1:n if ~isempty(Data{i}) d = Data{i}(:,1); h = Data{i}(:,2); points = Data{i}(:,3); I = d < Dist(points,1); J = h >= -0.1 & h <= 0; K = h <= Len(i)+0.1 & h >= Len(i); L = d < 0.5; M = I&(J|K)&L; points = points(M); Dist(points,1) = d(M); Dist(points,2) = i; end end % Select only the shortest 95% of distances for each cylinder N = zeros(n,1); O = zeros(np,1); for i = 1:np if Dist(i,2) > 0 N(Dist(i,2)) = N(Dist(i,2))+1; O(i) = N(Dist(i,2)); end end Cyl = cell(n,1); for i = 1:n Cyl{i} = zeros(N(i),1); end for i = 1:np if Dist(i,2) > 0 Cyl{Dist(i,2)}(O(i)) = i; end end DistCyl = zeros(n,1); % Average point distance to each cylinder for i = 1:n I = Cyl{i}; m = length(I); if m > 19 % select the smallest 95% of distances d = sort(Dist(I,1)); DistCyl(i) = mean(d(1:floor(0.95*m))); elseif m > 0 DistCyl(i) = mean(Dist(I,1)); end end % Define the output pmdistance.CylDist = single(DistCyl); pmdistance.median = median(DistCyl(:,1)); pmdistance.mean = mean(DistCyl(:,1)); pmdistance.max = max(DistCyl(:,1)); pmdistance.std = std(DistCyl(:,1)); T = BOrd == 0; B1 = BOrd == 1; B2 = BOrd == 2; B = DistCyl(~T,1); T = DistCyl(T,1); B1 = DistCyl(B1,1); B2 = DistCyl(B2,1); pmdistance.TrunkMedian = median(T); pmdistance.TrunkMean = mean(T); pmdistance.TrunkMax = max(T); pmdistance.TrunkStd = std(T); if ~isempty(B) pmdistance.BranchMedian = median(B); pmdistance.BranchMean = mean(B); pmdistance.BranchMax = max(B); pmdistance.BranchStd = std(B); else pmdistance.BranchMedian = 0; pmdistance.BranchMean = 0; pmdistance.BranchMax = 0; pmdistance.BranchStd = 0; end if ~isempty(B1) pmdistance.Branch1Median = median(B1); pmdistance.Branch1Mean = mean(B1); pmdistance.Branch1Max = max(B1); pmdistance.Branch1Std = std(B1); else pmdistance.Branch1Median = 0; pmdistance.Branch1Mean = 0; pmdistance.Branch1Max = 0; pmdistance.Branch1Std = 0; end if ~isempty(B2) pmdistance.Branch2Median = median(B2); pmdistance.Branch2Mean = mean(B2); pmdistance.Branch2Max = max(B2); pmdistance.Branch2Std = std(B2); else pmdistance.Branch2Median = 0; pmdistance.Branch2Mean = 0; pmdistance.Branch2Max = 0; pmdistance.Branch2Std = 0; end ================================================ FILE: src/main_steps/relative_size.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function RS = relative_size(P,cover,segment) % --------------------------------------------------------------------- % RELATIVE_SIZE.M Determines relative cover set size for points in new covers % % Version 2.00 % Latest update 16 Aug 2017 % % Copyright (C) 2014-2017 Pasi Raumonen % --------------------------------------------------------------------- % % Uses existing segmentation and its branching structure to determine % relative size of the cover sets distributed over new covers. The idea is % to decrease the relative size as the branch size decreases. This is % realised so that the relative size at the base of a branch is % proportional to the size of the stem's base, measured as number of % cover sets in the first few layers. Also when we approach the % tip of the branch, the relative size decreases to the minimum. % Maximum relative size is 256 at the bottom of the % stem and the minimum is 1 at the tip of every branch. % % Output: % RS Relative size (1-256), uint8-vector, (n_points x 1) Bal = cover.ball; Cen = cover.center; Nei = cover.neighbor; Segs = segment.segments; SChi = segment.ChildSegment; np = size(P,1); % number of points ns = size(Segs,1); % number of segments %% Use branching order and height as apriori info % Determine the branch orders of the segments Ord = zeros(ns,1); C = SChi{1}; order = 0; while ~isempty(C) order = order+order; Ord(C) = order; C = vertcat(SChi{C}); end maxO = order+1; % maximum branching order (plus one) % Determine tree height Top = max(P(Cen,3)); Bot = min(P(Cen,3)); H = Top-Bot; %% Determine "base size" compared to the stem base % BaseSize is the relative size of the branch base compared to the stem % base, measured as number of cover sets in the first layers of the cover % sets. If it is larger than apriori upper limit based on branching order % and branch height, then correct to the apriori limit BaseSize = zeros(ns,1); % Determine first the base size at the stem S = Segs{1}; n = size(S,1); if n >= 2 m = min([6 n]); BaseSize(1) = mean(cellfun(@length,S(2:m))); else BaseSize(1) = length(S{1}); end % Then define base size for other segments for i = 2:ns S = Segs{i}; n = size(S,1); if n >= 2 m = min([6 n]); BaseSize(i) = ceil(mean(cellfun(@length,S(2:m)))/BaseSize(1)*256); else BaseSize(i) = length(S{1})/BaseSize(1)*256; end bot = min(P(Cen(S{1}),3)); h = bot-Bot; % height of the segment's base BS = ceil(256*(maxO-Ord(i))/maxO*(H-h)/H); % maximum apriori base size if BaseSize(i) > BS BaseSize(i) = BS; end end BaseSize(1) = 256; %% Determine relative size for points TS = 1; RS = zeros(np,1,'uint8'); for i = 1:ns S = Segs{i}; s = size(S,1); for j = 1:s Q = S{j}; RS(vertcat(Bal{Q})) = BaseSize(i)-(BaseSize(i)-TS)*sqrt((j-1)/s); end end %% Adjust the relative size at the base of child segments RS0 = RS; for i = 1:ns C = SChi{i}; n = length(C); if n > 0 for j = 1:n S = Segs{C(j)}; B = S{1}; N = vertcat(Nei{B}); if size(S,1) > 1 N = setdiff(N,S{2}); end N = union(N,B); N = vertcat(Bal{N}); RS(N) = RS0(N)/2; end end end ================================================ FILE: src/main_steps/segments.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function segment = segments(cover,Base,Forb) % --------------------------------------------------------------------- % SEGMENTS.M Segments the covered point cloud into branches. % % Version 2.10 % Latest update 16 Aug 2017 % % Copyright (C) 2013-2017 Pasi Raumonen % --------------------------------------------------------------------- % Segments the tree into branches and records their parent-child-relations. % Bifurcations are recognized by studying connectivity of a "study" % region moving along the tree. In case of multiple connected components % in "study", the components are classified as the continuation and branches. % % Inputs: % cover Cover sets % Base Base of the tree % Forb Cover sets not part of the tree % % Outputs: % segment Structure array containing the followin fields: % segments Segments found, (n_seg x 1)-cell, each cell contains a cell array the cover sets % ParentSegment Parent segment of each segment, (n_seg x 1)-vector, % equals to zero if no parent segment % ChildSegment Children segments of each segment, (n_seg x 1)-cell Nei = cover.neighbor; nb = size(Nei,1); % The number of cover sets a = max([200000 nb/100]); % Estimate for maximum number of segments SBas = cell(a,1); % The segment bases found Segs = cell(a,1); % The segments found SPar = zeros(a,2,'uint32'); % The parent segment of each segment SChi = cell(a,1); % The children segments of each segment % Initialize SChi SChi{1} = zeros(5000,1,'uint32'); C = zeros(200,1); for i = 2:a SChi{i} = C; end NChi = zeros(a,1); % Number of child segments found for each segment Fal = false(nb,1); % Logical false-vector for cover sets s = 1; % The index of the segment under expansion b = s; % The index of the latest found base SBas{s} = Base; Seg = cell(1000,1); % The cover set layers in the current segment Seg{1} = Base; ForbAll = Fal; % The forbidden sets ForbAll(Forb) = true; ForbAll(Base) = true; Forb = ForbAll; % The forbidden sets for the segment under expansion Continue = true; % True as long as the component can be segmented further NewSeg = true; % True if the first Cut for the current segment nl = 1; % The number of cover set layers currently in the segment % Segmenting stops when there are no more segments to be found while Continue && (b < nb) % Update the forbidden sets Forb(Seg{nl}) = true; % Define the study Cut = define_cut(Nei,Seg{nl},Forb,Fal); CutSize = length(Cut); if NewSeg NewSeg = false; ns = min(CutSize,6); end % Define the components of cut and study regions if CutSize > 0 CutComps = cut_components(Nei,Cut,CutSize,Fal,Fal); nc = size(CutComps,1); if nc > 1 [StudyComps,Bases,CompSize,Cont,BaseSize] = ... study_components(Nei,ns,Cut,CutComps,Forb,Fal,Fal); nc = length(Cont); end else nc = 0; end % Classify study region components if nc == 1 % One component, continue expansion of the current segment nl = nl+1; if size(Cut,2) > 1 Seg{nl} = Cut'; else Seg{nl} = Cut; end elseif nc > 1 % Classify the components of the Study region Class = component_classification(CompSize,Cont,BaseSize,CutSize); for i = 1:nc if Class(i) == 1 Base = Bases{i}; ForbAll(Base) = true; Forb(StudyComps{i}) = true; J = Forb(Cut); Cut = Cut(~J); b = b+1; SBas{b} = Base; SPar(b,:) = [s nl]; NChi(s) = NChi(s)+1; SChi{s}(NChi(s)) = b; end end % Define the new cut. % If the cut is empty, determine the new base if isempty(Cut) Segs{s} = Seg(1:nl); S = vertcat(Seg{1:nl}); ForbAll(S) = true; if s < b s = s+1; Seg{1} = SBas{s}; Forb = ForbAll; NewSeg = true; nl = 1; else Continue = false; end else if size(Cut,2) > 1 Cut = Cut'; end nl = nl+1; Seg{nl} = Cut; end else % If the study region has zero size, then the current segment is % complete and determine the base of the next segment Segs{s} = Seg(1:nl); S = vertcat(Seg{1:nl}); ForbAll(S) = true; if s < b s = s+1; Seg{1} = SBas{s}; Forb = ForbAll; NewSeg = true; nl = 1; else Continue = false; end end end Segs = Segs(1:b); SPar = SPar(1:b,:); schi = SChi(1:b); % Define output SChi = cell(b,1); for i = 1:b if NChi(i) > 0 SChi{i} = uint32(schi{i}(1:NChi(i))); else SChi{i} = zeros(0,1,'uint32'); end S = Segs{i}; for j = 1:size(S,1) S{j} = uint32(S{j}); end Segs{i} = S; end clear Segment segment.segments = Segs; segment.ParentSegment = SPar; segment.ChildSegment = SChi; end % End of the main function % Define subfunctions function Cut = define_cut(Nei,CutPre,Forb,Fal) % Defines the "Cut" region Cut = vertcat(Nei{CutPre}); Cut = unique_elements(Cut,Fal); I = Forb(Cut); Cut = Cut(~I); end % End of function function [Components,CompSize] = cut_components(Nei,Cut,CutSize,Fal,False) % Define the connected components of the Cut if CutSize == 1 % Cut is connected and therefore Study is also CompSize = 1; Components = cell(1,1); Components{1} = Cut; elseif CutSize == 2 I = Nei{Cut(1)} == Cut(2); if any(I) Components = cell(1,1); Components{1} = Cut; CompSize = 1; else Components = cell(2,1); Components{1} = Cut(1); Components{2} = Cut(2); CompSize = [1 1]; end elseif CutSize == 3 I = Nei{Cut(1)} == Cut(2); J = Nei{Cut(1)} == Cut(3); K = Nei{Cut(2)} == Cut(3); if any(I)+any(J)+any(K) >= 2 CompSize = 1; Components = cell(1,1); Components{1} = Cut; elseif any(I) Components = cell(2,1); Components{1} = Cut(1:2); Components{2} = Cut(3); CompSize = [2 1]; elseif any(J) Components = cell(2,1); Components{1} = Cut([1 3]'); Components{2} = Cut(2); CompSize = [2 1]; elseif any(K) Components = cell(2,1); Components{1} = Cut(2:3); Components{2} = Cut(1); CompSize = [2 1]; else CompSize = [1 1 1]; Components = cell(3,1); Components{1} = Cut(1); Components{2} = Cut(2); Components{3} = Cut(3); end else Components = cell(CutSize,1); CompSize = zeros(CutSize,1); Comp = zeros(CutSize,1); Fal(Cut) = true; nc = 0; % number of components found m = Cut(1); i = 0; while i < CutSize Added = Nei{m}; I = Fal(Added); Added = Added(I); a = length(Added); Comp(1) = m; Fal(m) = false; t = 1; while a > 0 Comp(t+1:t+a) = Added; Fal(Added) = false; t = t+a; Ext = vertcat(Nei{Added}); Ext = unique_elements(Ext,False); I = Fal(Ext); Added = Ext(I); a = length(Added); end i = i+t; nc = nc+1; Components{nc} = Comp(1:t); CompSize(nc) = t; if i < CutSize J = Fal(Cut); m = Cut(J); m = m(1); end end Components = Components(1:nc); CompSize = CompSize(1:nc); end end % End of function function [Components,Bases,CompSize,Cont,BaseSize] = ... study_components(Nei,ns,Cut,CutComps,Forb,Fal,False) % Define Study as a cell-array Study = cell(ns,1); StudySize = zeros(ns,1); Study{1} = Cut; StudySize(1) = length(Cut); if ns >= 2 N = Cut; i = 1; while i < ns Forb(N) = true; N = vertcat(Nei{N}); N = unique_elements(N,Fal); I = Forb(N); N = N(~I); if ~isempty(N) i = i+1; Study{i} = N; StudySize(i) = length(N); else Study = Study(1:i); StudySize = StudySize(1:i); i = ns+1; end end end % Define study as a vector ns = length(StudySize); studysize = sum(StudySize); study = vertcat(Study{:}); % Determine the components of study nc = size(CutComps,1); i = 1; % index of cut component j = 0; % number of elements attributed to components k = 0; % number of study components Fal(study) = true; Components = cell(nc,1); CompSize = zeros(nc,1); Comp = zeros(studysize,1); while i <= nc C = CutComps{i}; while j < studysize a = length(C); Comp(1:a) = C; Fal(C) = false; if a > 1 Add = unique_elements(vertcat(Nei{C}),False); else Add = Nei{C}; end t = a; I = Fal(Add); Add = Add(I); a = length(Add); while a > 0 Comp(t+1:t+a) = Add; Fal(Add) = false; t = t+a; Add = vertcat(Nei{Add}); Add = unique_elements(Add,False); I = Fal(Add); Add = Add(I); a = length(Add); end j = j+t; k = k+1; Components{k} = Comp(1:t); CompSize(k) = t; if j < studysize C = zeros(0,1); while i < nc && isempty(C) i = i+1; C = CutComps{i}; J = Fal(C); C = C(J); end if i == nc && isempty(C) j = studysize; i = nc+1; end else i = nc+1; end end Components = Components(1:k); CompSize = CompSize(1:k); end % Determine BaseSize and Cont Cont = true(k,1); BaseSize = zeros(k,1); Bases = cell(k,1); if k > 1 Forb(study) = true; Fal(study) = false; Fal(Study{1}) = true; for i = 1:k % Determine the size of the base of the components Set = unique_elements([Components{i}; Study{1}],False); False(Components{i}) = true; I = False(Set)&Fal(Set); False(Components{i}) = false; Set = Set(I); Bases{i} = Set; BaseSize(i) = length(Set); end Fal(Study{1}) = false; Fal(Study{ns}) = true; Forb(study) = true; for i = 1:k % Determine if the component can be extended Set = unique_elements([Components{i}; Study{ns}],False); False(Components{i}) = true; I = False(Set)&Fal(Set); False(Components{i}) = false; Set = Set(I); if ~isempty(Set) N = vertcat(Nei{Set}); N = unique_elements(N,False); I = Forb(N); N = N(~I); if isempty(N) Cont(i) = false; end else Cont(i) = false; end end end end % End of function function Class = component_classification(CompSize,Cont,BaseSize,CutSize) % Classifies study region components: % Class(i) == 0 continuation % Class(i) == 1 branch nc = size(CompSize,1); StudySize = sum(CompSize); Class = ones(nc,1); % true if a component is a branch to be further segmented ContiComp = 0; % Simple initial classification for i = 1:nc if BaseSize(i) == CompSize(i) && ~Cont(i) % component has no expansion, not a branch Class(i) = 0; elseif BaseSize(i) == 1 && CompSize(i) <= 2 && ~Cont(i) % component has very small expansion, not a branch Class(i) = 0; elseif BaseSize(i)/CutSize < 0.05 && 2*BaseSize(i) >= CompSize(i) && ~Cont(i) % component has very small expansion or is very small, not a branch Class(i) = 0; elseif CompSize(i) <= 3 && ~Cont(i) % very small component, not a branch Class(i) = 0; elseif BaseSize(i)/CutSize >= 0.7 || CompSize(i) >= 0.7*StudySize % continuation of the segment Class(i) = 0; ContiComp = i; else % Component is probably a branch end end Branches = Class == 1; if ContiComp == 0 && any(Branches) Ind = (1:1:nc)'; Branches = Ind(Branches); [~,I] = max(CompSize(Branches)); Class(Branches(I)) = 0; end end % End of function ================================================ FILE: src/main_steps/tree_data.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function [treedata,triangulation] = tree_data(cylinder,branch,trunk,inputs) % --------------------------------------------------------------------- % TREE_DATA.M Calculates some tree attributes from cylinder QSM. % % Version 3.0.1 % Latest update 2 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % Inputs: % cylinder: % radius (Rad) Radii of the cylinders % length (Len) Lengths of the cylinders % start (Sta) Starting points of the cylinders % axis (Axe) Axes of the cylinders % branch: % order (BOrd) Branch order data % volume (BVol) Branch volume data % length (BLen) Branch length data % trunk Point cloud of the trunk % inputs Input structure, defines if results are displayed and % plotted and if triangulation results are computed % % Output: % treedata Tree data/attributes in a struct % --------------------------------------------------------------------- % Changes from version 3.0.0 to 3.0.1, 2 May 2022: % 1) Small changes in "crown_measures" when computing crown base to prevent % errors in special cases. % 2) Small change for how to compute the "first major branch" in % "triangulate_stem". % 3) Modified code so that "n" cannot be empty in "branch_distribution" and % cause warning % 4) Decreased the minimum triangle sizes in "triangulate_stem" % 5) The triangulation code has some changes. % 6) Minor streamlining of the code % Changes from version 2.0.2 to 3.0.0, 13 Feb 2020: % 1) Changed the setup for triangulation: % - The size of the triangles is more dependent on the dbh % - The height of the stem section is defined up to the first major branch % (branch diameter > 0.1*dbh or maximum branch diameter) but keeping % the stem diameter above 25% of dbh. % 2) Makes now more tries for triangulation, also changes triangle size % and the length of the stem section if necessary. % 3) Changed the names of some fields in the output: % - VolumeCylDiam --> VolCylDia % - LengthCylDiam --> LenCylDia % - VolumeBranchOrder --> VolBranchOrd % - LengthBranchOrder --> LenBranchOrd % - NumberBranchOrder --> NumBranchOrd % 3) Added many new fields into the output treedata, particularly distributions: % - Total length (trunk length + branch length) ("TotalLength") % - Trunk area and branch area ("TrunkArea" and "BranchArea") % - Crown dimensions: "CrownDiamAve", "CrownDiamMax","CrownAreaConv", % "CrownAreaAlpha", "CrownBaseHeight", "CrownLength", "CrownRatio", % "CrownVolumeConv", "CrownVolumeAlpha". % - Vertical tree profile "VerticalProfile" and tree diameters in % 18 directions at 20 height layers "spreads". % - Branch area as functions of diameter class and branch order % ("AreCylDia" and "AreBranchOrd") % - Volume, area and length of CYLINDERS (tree segments) in 1 meter % HEIGHT classes ("VolCylHei", "AreCylHei", "LenCylHei") % - Volume, area and length of CYLINDERS (tree segments) in 10 deg % ZENITH DIRECTION classes ("VolCylZen", "AreCylZen", "LenCylZen") % - Volume, area and length of CYLINDERS (tree segments) in 10 deg % AZIMUTH DIRECTION classes ("VolCylAzi", "AreCylAzi", "LenCylAzi") % - Volume, area, length and number of all and 1st-order BRANCHES % in 1 cm DIAMETER classes ("AreBranchDia", "AreBranch1Dia", etc.) % - Volume, area, length and number of all and 1st-order BRANCHES % in 1 meter HEIGHT classes ("AreBranchDia", "AreBranch1Dia", etc.) % - Volume, area, length and number of all and 1st-order BRANCHES % in 10 degree BRANCHING ANGLE classes % ("AreBranchAng", "AreBranch1Ang", etc.) % - Volume, area, length and number of all and 1st-order BRANCHES % in 22.5 degree branch AZIMUTH ANGLE classes % ("AreBranchAzi", "AreBranch1Azi", etc.) % - Volume, area, length and number of all and 1st-order BRANCHES % in 10 degree branch ZENITH ANGLE classes % ("AreBranchZen", "AreBranch1Zen", etc.) % 4) Added new area-related fields into the output triangulation: % - side area, top area and bottom area % 5) Added new triangulation related fields to the output treedata: % - TriaTrunkArea side area of the triangulation % - MixTrunkArea trunk area from triangulation and cylinders % - MixTotalArea total area where the MixTrunkArea used instead % of TrunkArea % 6) Structure has more subfunctions. % 7) Changed the coding for cylinder fitting of DBH to conform new output % of the least_square_cylinder. % Changes from version 2.0.1 to 2.0.2, 26 Nov 2019: % 1) Bug fix: Added a statement "C < nc" for a while command that makes sure % that the index "C" does not exceed the number of stem cylinders, when % determining the index of cylinders up to first branch. % 2) Bug fix: Changed "for i = 1:BO" to "for i = 1:max(1,BO)" where % computing branch order data. % 3) Added the plotting of the triangulation model % Changes from version 2.0.0 to 2.0.1, 9 Oct 2019: % 1) Bug fix: Changed the units (from 100m to 1m) for computing the branch % length distribution: branch length per branch order. % Define some variables from cylinder: Rad = cylinder.radius; Len = cylinder.length; nc = length(Rad); ind = (1:1:nc)'; Trunk = cylinder.branch == 1; % Trunk cylinders %% Tree attributes from cylinders % Volumes, areas, lengths, branches treedata.TotalVolume = 1000*pi*Rad.^2'*Len; treedata.TrunkVolume = 1000*pi*Rad(Trunk).^2'*Len(Trunk); treedata.BranchVolume = 1000*pi*Rad(~Trunk).^2'*Len(~Trunk); bottom = min(cylinder.start(:,3)); [top,i] = max(cylinder.start(:,3)); if cylinder.axis(i,3) > 0 top = top+Len(i)*cylinder.axis(i,3); end treedata.TreeHeight = top-bottom; treedata.TrunkLength = sum(Len(Trunk)); treedata.BranchLength = sum(Len(~Trunk)); treedata.TotalLength = treedata.TrunkLength+treedata.BranchLength; NB = length(branch.order)-1; % number of branches treedata.NumberBranches = NB; BO = max(branch.order); % maximum branch order treedata.MaxBranchOrder = BO; treedata.TrunkArea = 2*pi*sum(Rad(Trunk).*Len(Trunk)); treedata.BranchArea = 2*pi*sum(Rad(~Trunk).*Len(~Trunk)); treedata.TotalArea = 2*pi*sum(Rad.*Len); %% Diameter at breast height (dbh) % Dbh from the QSM and from a cylinder fitted particularly to the correct place treedata = dbh_cylinder(treedata,trunk,Trunk,cylinder,ind); %% Crown measures,Vertical profile and spreads [treedata,spreads] = crown_measures(treedata,cylinder,branch); %% Trunk volume and DBH from triangulation if inputs.Tria [treedata,triangulation] = triangulate_stem(... treedata,cylinder,branch,trunk); else triangulation = 0; end %% Tree Location treedata.location = cylinder.start(1,:); %% Stem taper R = Rad(Trunk); n = length(R); Taper = zeros(n+1,2); Taper(1,2) = 2*R(1); Taper(2:end,1) = cumsum(Len(Trunk)); Taper(2:end,2) = [2*R(2:end); 2*R(n)]; treedata.StemTaper = Taper'; %% Vertical profile and spreads treedata.VerticalProfile = mean(spreads,2); treedata.spreads = spreads; %% CYLINDER DISTRIBUTIONS: %% Wood part diameter distributions % Volume, area and length of wood parts as functions of cylinder diameter % (in 1cm diameter classes) treedata = cylinder_distribution(treedata,cylinder,'Dia'); %% Wood part height distributions % Volume, area and length of cylinders as a function of height % (in 1 m height classes) treedata = cylinder_height_distribution(treedata,cylinder,ind); %% Wood part zenith direction distributions % Volume, area and length of wood parts as functions of cylinder zenith % direction (in 10 degree angle classes) treedata = cylinder_distribution(treedata,cylinder,'Zen'); %% Wood part azimuth direction distributions % Volume, area and length of wood parts as functions of cylinder zenith % direction (in 10 degree angle classes) treedata = cylinder_distribution(treedata,cylinder,'Azi'); %% BRANCH DISTRIBUTIONS: %% Branch order distributions % Volume, area, length and number of branches as a function of branch order treedata = branch_order_distribution(treedata,branch); %% Branch diameter distributions % Volume, area, length and number of branches as a function of branch diameter % (in 1cm diameter classes) treedata = branch_distribution(treedata,branch,'Dia'); %% Branch height distribution % Volume, area, length and number of branches as a function of branch height % (in 1 meter classes) for all and 1st-order branches treedata = branch_distribution(treedata,branch,'Hei'); %% Branch angle distribution % Volume, area, length and number of branches as a function of branch angle % (in 10 deg angle classes) for all and 1st-order branches treedata = branch_distribution(treedata,branch,'Ang'); %% Branch azimuth distribution % Volume, area, length and number of branches as a function of branch azimuth % (in 22.5 deg angle classes) for all and 1st-order branches treedata = branch_distribution(treedata,branch,'Azi'); %% Branch zenith distribution % Volume, area, length and number of branches as a function of branch zenith % (in 10 deg angle classes) for all and 1st-order branches treedata = branch_distribution(treedata,branch,'Zen'); %% change into single-format Names = fieldnames(treedata); n = size(Names,1); for i = 1:n treedata.(Names{i}) = single(treedata.(Names{i})); end if inputs.disp == 2 %% Generate units for displaying the treedata Units = zeros(n,3); for i = 1:n if ~inputs.Tria && strcmp(Names{i},'CrownVolumeAlpha') m = i; elseif inputs.Tria && strcmp(Names{i},'TriaTrunkLength') m = i; end if strcmp(Names{i}(1:3),'DBH') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'ume') Units(i,:) = 'L '; elseif strcmp(Names{i}(end-2:end),'ght') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'gth') Units(i,:) = 'm '; elseif strcmp(Names{i}(1:3),'vol') Units(i,:) = 'L '; elseif strcmp(Names{i}(1:3),'len') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'rea') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(1:3),'loc') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-4:end),'aConv') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(end-5:end),'aAlpha') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(end-4:end),'eConv') Units(i,:) = 'm^3'; elseif strcmp(Names{i}(end-5:end),'eAlpha') Units(i,:) = 'm^3'; elseif strcmp(Names{i}(end-2:end),'Ave') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'Max') Units(i,:) = 'm '; end end %% Display treedata disp('------------') disp(' Tree attributes:') for i = 1:m v = change_precision(treedata.(Names{i})); if strcmp(Names{i},'DBHtri') disp(' -----') disp(' Tree attributes from triangulation:') end disp([' ',Names{i},' = ',num2str(v),' ',Units(i,:)]) end disp(' -----') end if inputs.plot > 1 %% Plot distributions figure(6) subplot(2,4,1) plot(Taper(:,1),Taper(:,2),'-b') title('Stem taper') xlabel('Distance from base (m)') ylabel('Diameter (m)') axis tight grid on Q.treedata = treedata; subplot(2,4,2) plot_distribution(Q,6,0,0,'VolCylDia') subplot(2,4,3) plot_distribution(Q,6,0,0,'AreCylDia') subplot(2,4,4) plot_distribution(Q,6,0,0,'LenCylDia') subplot(2,4,5) plot_distribution(Q,6,0,0,'VolBranchOrd') subplot(2,4,6) plot_distribution(Q,6,0,0,'LenBranchOrd') subplot(2,4,7) plot_distribution(Q,6,0,0,'AreBranchOrd') subplot(2,4,8) plot_distribution(Q,6,0,0,'NumBranchOrd') figure(7) subplot(3,3,1) plot_distribution(Q,7,0,0,'VolCylHei') subplot(3,3,2) plot_distribution(Q,7,0,0,'AreCylHei') subplot(3,3,3) plot_distribution(Q,7,0,0,'LenCylHei') subplot(3,3,4) plot_distribution(Q,7,0,0,'VolCylZen') subplot(3,3,5) plot_distribution(Q,7,0,0,'AreCylZen') subplot(3,3,6) plot_distribution(Q,7,0,0,'LenCylZen') subplot(3,3,7) plot_distribution(Q,7,0,0,'VolCylAzi') subplot(3,3,8) plot_distribution(Q,7,0,0,'AreCylAzi') subplot(3,3,9) plot_distribution(Q,7,0,0,'LenCylAzi') figure(8) subplot(3,4,1) %if %%%%%% !!!!!!!! plot_distribution(Q,8,1,0,'VolBranchDia','VolBranch1Dia') subplot(3,4,2) plot_distribution(Q,8,1,0,'AreBranchDia','AreBranch1Dia') subplot(3,4,3) plot_distribution(Q,8,1,0,'LenBranchDia','LenBranch1Dia') subplot(3,4,4) plot_distribution(Q,8,1,0,'NumBranchDia','NumBranch1Dia') subplot(3,4,5) plot_distribution(Q,8,1,0,'VolBranchHei','VolBranch1Hei') subplot(3,4,6) plot_distribution(Q,8,1,0,'AreBranchHei','AreBranch1Hei') subplot(3,4,7) plot_distribution(Q,8,1,0,'LenBranchHei','LenBranch1Hei') subplot(3,4,8) plot_distribution(Q,8,1,0,'NumBranchHei','NumBranch1Hei') subplot(3,4,9) plot_distribution(Q,8,1,0,'VolBranchAng','VolBranch1Ang') subplot(3,4,10) plot_distribution(Q,8,1,0,'AreBranchAng','AreBranch1Ang') subplot(3,4,11) plot_distribution(Q,8,1,0,'LenBranchAng','LenBranch1Ang') subplot(3,4,12) plot_distribution(Q,8,1,0,'NumBranchAng','NumBranch1Ang') figure(9) subplot(2,4,1) plot_distribution(Q,9,1,0,'VolBranchZen','VolBranch1Zen') subplot(2,4,2) plot_distribution(Q,9,1,0,'AreBranchZen','AreBranch1Zen') subplot(2,4,3) plot_distribution(Q,9,1,0,'LenBranchZen','LenBranch1Zen') subplot(2,4,4) plot_distribution(Q,9,1,0,'NumBranchZen','NumBranch1Zen') subplot(2,4,5) plot_distribution(Q,9,1,0,'VolBranchAzi','VolBranch1Azi') subplot(2,4,6) plot_distribution(Q,9,1,0,'AreBranchAzi','AreBranch1Azi') subplot(2,4,7) plot_distribution(Q,9,1,0,'LenBranchAzi','LenBranch1Azi') subplot(2,4,8) plot_distribution(Q,9,1,0,'NumBranchAzi','NumBranch1Azi') end end % End of main function function treedata = dbh_cylinder(treedata,trunk,Trunk,cylinder,ind) % Dbh from the QSM i = 1; n = nnz(Trunk); T = ind(Trunk); while i < n && sum(cylinder.length(T(1:i))) < 1.3 i = i+1; end DBHqsm = 2*cylinder.radius(T(i)); treedata.DBHqsm = DBHqsm; % Determine DBH from cylinder fitted particularly to the correct place % Select the trunk point set V = trunk-cylinder.start(1,:); h = V*cylinder.axis(1,:)'; I = h < 1.5; J = h > 1.1; I = I&J; if nnz(I) > 100 T = trunk(I,:); % Fit cylinder cyl0 = select_cylinders(cylinder,i); cyl = least_squares_cylinder(T,cyl0); RadiusOK = 2*cyl.radius > 0.8*DBHqsm & 2*cyl.radius < 1.2*DBHqsm; if RadiusOK && abs(cylinder.axis(i,:)*cyl.axis') > 0.9 && cyl.conv && cyl.rel treedata.DBHcyl = 2*cyl.radius; else treedata.DBHcyl = DBHqsm; end else treedata.DBHcyl = DBHqsm; end % End of function end function [treedata,spreads] = crown_measures(treedata,cylinder,branch) %% Generate point clouds from the cylinder model Axe = cylinder.axis; Len = cylinder.length; Sta = cylinder.start; Tip = Sta+[Len.*Axe(:,1) Len.*Axe(:,2) Len.*Axe(:,3)]; % tips of the cylinders nc = length(Len); P = zeros(5*nc,3); % four mid points on the cylinder surface t = 0; for i = 1:nc [U,V] = orthonormal_vectors(Axe(i,:)); U = cylinder.radius(i)*U; if cylinder.branch(i) == 1 % For stem cylinders generate more points R = rotation_matrix(Axe(i,:),pi/12); for k = 1:4 M = Sta(i,:)+k/4*Len(i)*Axe(i,:); for j = 1:12 if j > 1 U = R*U; end t = t+1; P(t,:) = M+U'; end end else M = Sta(i,:)+0.5*Len(i)*Axe(i,:); R = rotation_matrix(Axe(i,:),pi/4); for j = 1:4 if j > 1 U = R*U; end t = t+1; P(t,:) = M+U'; end end end P = P(1:t,:); I = ~isnan(P(:,1)); P = P(I,:); P = double([P; Sta; Tip]); P = unique(P,'rows'); %% Vertical profiles (layer diameters/spreads), mean: bot = min(P(:,3)); top = max(P(:,3)); Hei = top-bot; if Hei > 10 m = 20; elseif Hei > 2 m = 10; else m = 5; end spreads = zeros(m,18); for j = 1:m I = P(:,3) >= bot+(j-1)*Hei/m & P(:,3) < bot+j*Hei/m; X = unique(P(I,:),'rows'); if size(X,1) > 5 [K,A] = convhull(X(:,1),X(:,2)); % compute center of gravity for the convex hull and use it as % center for computing average diameters n = length(K); x = X(K,1); y = X(K,2); CX = sum((x(1:n-1)+x(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A; CY = sum((y(1:n-1)+y(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A; V = mat_vec_subtraction(X(:,1:2),[CX CY]); ang = atan2(V(:,2),V(:,1))+pi; [ang,I] = sort(ang); L = sqrt(sum(V.*V,2)); L = L(I); for i = 1:18 I = ang >= (i-1)*pi/18 & ang < i*pi/18; if any(I) L1 = max(L(I)); else L1 = 0; end J = ang >= (i-1)*pi/18+pi & ang < i*pi/18+pi; if any(J) L2 = max(L(J)); else L2 = 0; end spreads(j,i) = L1+L2; end end end %% Crown diameters (spreads), mean and maximum: X = unique(P(:,1:2),'rows'); [K,A] = convhull(X(:,1),X(:,2)); % compute center of gravity for the convex hull and use it as center for % computing average diameters n = length(K); x = X(K,1); y = X(K,2); CX = sum((x(1:n-1)+x(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A; CY = sum((y(1:n-1)+y(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A; V = Tip(:,1:2)-[CX CY]; ang = atan2(V(:,2),V(:,1))+pi; [ang,I] = sort(ang); L = sqrt(sum(V.*V,2)); L = L(I); S = zeros(18,1); for i = 1:18 I = ang >= (i-1)*pi/18 & ang < i*pi/18; if any(I) L1 = max(L(I)); else L1 = 0; end J = ang >= (i-1)*pi/18+pi & ang < i*pi/18+pi; if any(J) L2 = max(L(J)); else L2 = 0; end S(i) = L1+L2; end treedata.CrownDiamAve = mean(S); MaxDiam = 0; for i = 1:n V = mat_vec_subtraction([x y],[x(i) y(i)]); L = max(sqrt(sum(V.*V,2))); if L > MaxDiam MaxDiam = L; end end treedata.CrownDiamMax = L; %% Crown areas from convex hull and alpha shape: treedata.CrownAreaConv = A; alp = max(0.5,treedata.CrownDiamAve/10); shp = alphaShape(X(:,1),X(:,2),alp); treedata.CrownAreaAlpha = shp.area; %% Crown base % Define first major branch as the branch whose diameter > min(0.05*dbh,5cm) % and whose horizontal relative reach is more than the median reach of 1st-ord. % branches (or at maximum 10). The reach is defined as the horizontal % distance from the base to the tip divided by the dbh. dbh = treedata.DBHcyl; nb = length(branch.order); HL = zeros(nb,1); % horizontal reach branches1 = (1:1:nb)'; branches1 = branches1(branch.order == 1); % 1st-order branches nb = length(branches1); nc = size(Sta,1); ind = (1:1:nc)'; for i = 1:nb C = ind(cylinder.branch == branches1(i)); if ~isempty(C) base = Sta(C(1),:); C = C(end); tip = Sta(C,:)+Len(C)*Axe(C); V = tip(1:2)-base(1:2); HL(branches1(i)) = sqrt(V*V')/dbh*2; end end M = min(10,median(HL)); % Sort the branches according to the their heights Hei = branch.height(branches1); [Hei,SortOrd] = sort(Hei); branches1 = branches1(SortOrd); % Search the first/lowest branch: d = min(0.05,0.05*dbh); b = 0; if nb > 1 i = 1; while i < nb i = i+1; if branch.diameter(branches1(i)) > d && HL(branches1(i)) > M b = branches1(i); i = nb+2; end end if i == nb+1 && nb > 1 b = branches1(1); end end if b > 0 % search all the children of the first major branch: nb = size(branch.parent,1); Ind = (1:1:nb)'; chi = Ind(branch.parent == b); B = b; while ~isempty(chi) B = [B; chi]; n = length(chi); C = cell(n,1); for i = 1:n C{i} = Ind(branch.parent == chi(i)); end chi = vertcat(C{:}); end % define crown base height from the ground: BaseHeight = max(Sta(:,3)); % Height of the crown base for i = 1:length(B) C = ind(cylinder.branch == B(i)); ht = min(Tip(C,3)); hb = min(Sta(C,3)); h = min(hb,ht); if h < BaseHeight BaseHeight = h; end end treedata.CrownBaseHeight = BaseHeight-Sta(1,3); %% Crown length and ratio treedata.CrownLength = treedata.TreeHeight-treedata.CrownBaseHeight; treedata.CrownRatio = treedata.CrownLength/treedata.TreeHeight; %% Crown volume from convex hull and alpha shape: I = P(:,3) >= BaseHeight; X = P(I,:); [K,V] = convhull(X(:,1),X(:,2),X(:,3)); treedata.CrownVolumeConv = V; alp = max(0.5,treedata.CrownDiamAve/5); shp = alphaShape(X(:,1),X(:,2),X(:,3),alp,'HoleThreshold',10000); treedata.CrownVolumeAlpha = shp.volume; else % No branches treedata.CrownBaseHeight = treedata.TreeHeight; treedata.CrownLength = 0; treedata.CrownRatio = 0; treedata.CrownVolumeConv = 0; treedata.CrownVolumeAlpha = 0; end % End of function end function [treedata,triangulation] = ... triangulate_stem(treedata,cylinder,branch,trunk) Sta = cylinder.start; Rad = cylinder.radius; Len = cylinder.length; DBHqsm = treedata.DBHqsm; % Determine the first major branch (over 10% of dbh or the maximum % diameter branch): nb = size(branch.diameter,1); ind = (1:1:nb)'; ind = ind(branch.order == 1); [~,I] = sort(branch.height(ind)); ind = ind(I); n = length(ind); b = 1; while b <= n && branch.diameter(ind(b)) < 0.1*DBHqsm b = b+1; end b = ind(b); if b > n [~,b] = max(branch.diameter); end % Determine suitable cylinders up to the first major branch but keep the % stem diameter above one quarter (25%) of dbh: C = 1; nc = size(Sta,1); while C < nc && cylinder.branch(C) < b C = C+1; end n = nnz(cylinder.branch == 1); i = 2; while i < n && Sta(i,3) < Sta(C,3) && Rad(i) > 0.125*DBHqsm i = i+1; end CylInd = max(i,3); TrunkLenTri = Sta(CylInd,3)-Sta(1,3); EmptyTriangulation = false; % Calculate the volumes if size(trunk,1) > 1000 && TrunkLenTri >= 1 % Set the parameters for triangulation: % Compute point density, which is used to increase the triangle % size if the point density is very small PointDensity = zeros(CylInd-1,1); for i = 1:CylInd-1 I = trunk(:,3) >= Sta(i,3) & trunk(:,3) < Sta(i+1,3); PointDensity(i) = pi*Rad(i)*Len(i)/nnz(I); end PointDensity = PointDensity(PointDensity < inf); d = max(PointDensity); % Determine minimum triangle size based on dbh if DBHqsm > 1 MinTriaHeight = 0.1; elseif DBHqsm > 0.50 MinTriaHeight = 0.075; elseif DBHqsm > 0.10 MinTriaHeight = 0.05; else MinTriaHeight = 0.02; end TriaHeight0 = max(MinTriaHeight,4*sqrt(d)); % Select the trunk point set used for triangulation I = trunk(:,3) <= Sta(CylInd,3); Stem = trunk(I,:); % Do the triangulation: triangulation = zeros(1,0); l = 0; while isempty(triangulation) && l < 4 && CylInd > 2 l = l+1; TriaHeight = TriaHeight0; TriaWidth = TriaHeight; k = 0; while isempty(triangulation) && k < 3 k = k+1; j = 0; while isempty(triangulation) && j < 5 triangulation = curve_based_triangulation(Stem,TriaHeight,TriaWidth); j = j+1; end % try different triangle sizes if necessary if isempty(triangulation) && k < 3 TriaHeight = TriaHeight+0.03; TriaWidth = TriaHeight; end end % try different length of stem sections if necessary if isempty(triangulation) && l < 4 && CylInd > 2 CylInd = CylInd-1; I = trunk(:,3) <= Sta(CylInd,3); Stem = trunk(I,:); end end if ~isempty(triangulation) triangulation.cylind = CylInd; % Dbh from triangulation Vert = triangulation.vert; h = Vert(:,3)-triangulation.bottom; [~,I] = min(abs(h-1.3)); H = h(I); I = abs(h-H) < triangulation.triah/2; V = Vert(I,:); V = V([2:end 1],:)-V(1:end,:); d = sqrt(sum(V.*V,2)); treedata.DBHtri = sum(d)/pi; % volumes from the triangulation treedata.TriaTrunkVolume = triangulation.volume; TrunkVolMix = treedata.TrunkVolume-... 1000*pi*sum(Rad(1:CylInd-1).^2.*Len(1:CylInd-1))+triangulation.volume; TrunkAreaMix = treedata.TrunkArea-... 2*pi*sum(Rad(1:CylInd-1).*Len(1:CylInd-1))+triangulation.SideArea; treedata.MixTrunkVolume = TrunkVolMix; treedata.MixTotalVolume = TrunkVolMix+treedata.BranchVolume; treedata.TriaTrunkArea = triangulation.SideArea; treedata.MixTrunkArea = TrunkAreaMix; treedata.MixTotalArea = TrunkAreaMix+treedata.BranchArea; treedata.TriaTrunkLength = TrunkLenTri; else EmptyTriangulation = true; end else EmptyTriangulation = true; end if EmptyTriangulation disp(' No triangulation model produced') clear triangulation treedata.DBHtri = DBHqsm; treedata.TriaTrunkVolume = treedata.TrunkVolume; treedata.TriaTrunkArea = treedata.TrunkArea; treedata.MixTrunkVolume = treedata.TrunkVolume; treedata.MixTrunkArea = treedata.TrunkArea; treedata.MixTotalVolume = treedata.TotalVolume; treedata.MixTotalArea = treedata.TotalArea; treedata.TriaTrunkLength = 0; triangulation.vert = zeros(0,3); triangulation.facet = zeros(0,3); triangulation.fvd = zeros(0,1); triangulation.volume = 0; triangulation.SideArea = 0; triangulation.BottomArea = 0; triangulation.TopArea = 0; triangulation.bottom = 0; triangulation.top = 0; triangulation.triah = 0; triangulation.triaw = 0; triangulation.cylind = 0; end end function treedata = cylinder_distribution(treedata,cyl,dist) %% Wood part diameter, zenith and azimuth direction distributions % Volume, area and length of wood parts as functions of cylinder % diameter, zenith, and azimuth if strcmp(dist,'Dia') Par = cyl.radius; n = ceil(max(200*cyl.radius)); a = 0.005; % diameter in 1 cm classes elseif strcmp(dist,'Zen') Par = 180/pi*acos(cyl.axis(:,3)); n = 18; a = 10; % zenith direction in 10 degree angle classes elseif strcmp(dist,'Azi') Par = 180/pi*atan2(cyl.axis(:,2),cyl.axis(:,1))+180; n = 36; a = 10; % azimuth direction in 10 degree angle classes end CylDist = zeros(3,n); for i = 1:n K = Par >= (i-1)*a & Par < i*a; CylDist(1,i) = 1000*pi*sum(cyl.radius(K).^2.*cyl.length(K)); % vol in L CylDist(2,i) = 2*pi*sum(cyl.radius(K).*cyl.length(K)); % area in m^2 CylDist(3,i) = sum(cyl.length(K)); % length in m end treedata.(['VolCyl',dist]) = CylDist(1,:); treedata.(['AreCyl',dist]) = CylDist(2,:); treedata.(['LenCyl',dist]) = CylDist(3,:); end function treedata = cylinder_height_distribution(treedata,cylinder,ind) Rad = cylinder.radius; Len = cylinder.length; Axe = cylinder.axis; %% Wood part height distributions % Volume, area and length of cylinders as a function of height % (in 1 m height classes) MaxHei= ceil(treedata.TreeHeight); treedata.VolCylHei = zeros(1,MaxHei); treedata.AreCylHei = zeros(1,MaxHei); treedata.LenCylHei = zeros(1,MaxHei); End = cylinder.start+[Len.*Axe(:,1) Len.*Axe(:,2) Len.*Axe(:,3)]; bot = min(cylinder.start(:,3)); B = cylinder.start(:,3)-bot; T = End(:,3)-bot; for j = 1:MaxHei I1 = B >= (j-2) & B < (j-1); % base below this bin J1 = B >= (j-1) & B < j; % base in this bin K1 = B >= j & B < (j+1); % base above this bin I2 = T >= (j-2) & T < (j-1); % top below this bin J2 = T >= (j-1) & T < j; % top in this bin K2 = T >= j & T < (j+1); % top above this bin C1 = ind(J1&J2); % base and top in this bin C2 = ind(J1&K2); % base in this bin, top above C3 = ind(J1&I2); % base in this bin, top below C4 = ind(I1&J2); % base in bin below, top in this C5 = ind(K1&J2); % base in bin above, top in this v1 = 1000*pi*sum(Rad(C1).^2.*Len(C1)); a1 = 2*pi*sum(Rad(C1).*Len(C1)); l1 = sum(Len(C1)); r2 = (j-B(C2))./(T(C2)-B(C2)); % relative portion in this bin v2 = 1000*pi*sum(Rad(C2).^2.*Len(C2).*r2); a2 = 2*pi*sum(Rad(C2).*Len(C2).*r2); l2 = sum(Len(C2).*r2); r3 = (B(C3)-j+1)./(B(C3)-T(C3)); % relative portion in this bin v3 = 1000*pi*sum(Rad(C3).^2.*Len(C3).*r3); a3 = 2*pi*sum(Rad(C3).*Len(C3).*r3); l3 = sum(Len(C3).*r3); r4 = (T(C4)-j+1)./(T(C4)-B(C4)); % relative portion in this bin v4 = 1000*pi*sum(Rad(C4).^2.*Len(C4).*r4); a4 = 2*pi*sum(Rad(C4).*Len(C4).*r4); l4 = sum(Len(C4).*r4); r5 = (j-T(C5))./(B(C5)-T(C5)); % relative portion in this bin v5 = 1000*pi*sum(Rad(C5).^2.*Len(C5).*r5); a5 = 2*pi*sum(Rad(C5).*Len(C5).*r5); l5 = sum(Len(C5).*r5); treedata.VolCylHei(j) = v1+v2+v3+v4+v5; treedata.AreCylHei(j) = a1+a2+a3+a4+a5; treedata.LenCylHei(j) = l1+l2+l3+l4+l5; end end function treedata = branch_distribution(treedata,branch,dist) %% Branch diameter, height, angle, zenith and azimuth distributions % Volume, area, length and number of branches as a function of branch % diamater, height, angle, zenith and aximuth BOrd = branch.order(2:end); BVol = branch.volume(2:end); BAre = branch.area(2:end); BLen = branch.length(2:end); if strcmp(dist,'Dia') Par = branch.diameter(2:end); n = ceil(max(100*Par)); a = 0.005; % diameter in 1 cm classes elseif strcmp(dist,'Hei') Par = branch.height(2:end); n = ceil(treedata.TreeHeight); a = 1; % height in 1 m classes elseif strcmp(dist,'Ang') Par = branch.angle(2:end); n = 18; a = 10; % angle in 10 degree classes elseif strcmp(dist,'Zen') Par = branch.zenith(2:end); n = 18; a = 10; % zenith direction in 10 degree angle classes elseif strcmp(dist,'Azi') Par = branch.azimuth(2:end)+180; n = 36; a = 10; % azimuth direction in 10 degree angle classes end if isempty(n) n = 0; end BranchDist = zeros(8,n); for i = 1:n I = Par >= (i-1)*a & Par < i*a; BranchDist(1,i) = sum(BVol(I)); % volume (all branches) BranchDist(2,i) = sum(BVol(I & BOrd == 1)); % volume (1st-branches) BranchDist(3,i) = sum(BAre(I)); % area (all branches) BranchDist(4,i) = sum(BAre(I & BOrd == 1)); % area (1st-branches) BranchDist(5,i) = sum(BLen(I)); % length (all branches) BranchDist(6,i) = sum(BLen(I & BOrd == 1)); % length (1st-branches) BranchDist(7,i) = nnz(I); % number (all branches) BranchDist(8,i) = nnz(I & BOrd == 1); % number (1st-branches) end treedata.(['VolBranch',dist]) = BranchDist(1,:); treedata.(['VolBranch1',dist]) = BranchDist(2,:); treedata.(['AreBranch',dist]) = BranchDist(3,:); treedata.(['AreBranch1',dist]) = BranchDist(4,:); treedata.(['LenBranch',dist]) = BranchDist(5,:); treedata.(['LenBranch1',dist]) = BranchDist(6,:); treedata.(['NumBranch',dist]) = BranchDist(7,:); treedata.(['NumBranch1',dist]) = BranchDist(8,:); end function treedata = branch_order_distribution(treedata,branch) %% Branch order distributions % Volume, area, length and number of branches as a function of branch order BO = max(branch.order); BranchOrdDist = zeros(BO,4); for i = 1:max(1,BO) I = branch.order == i; BranchOrdDist(i,1) = sum(branch.volume(I)); % volumes BranchOrdDist(i,2) = sum(branch.area(I)); % areas BranchOrdDist(i,3) = sum(branch.length(I)); % lengths BranchOrdDist(i,4) = nnz(I); % number of ith-order branches end treedata.VolBranchOrd = BranchOrdDist(:,1)'; treedata.AreBranchOrd = BranchOrdDist(:,2)'; treedata.LenBranchOrd = BranchOrdDist(:,3)'; treedata.NumBranchOrd = BranchOrdDist(:,4)'; end ================================================ FILE: src/main_steps/tree_sets.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function [cover,Base,Forb] = tree_sets(P,cover,inputs,segment) % --------------------------------------------------------------------- % TREE_SETS.M Determines the base of the trunk and the cover sets % belonging to the tree, updates the neighbor-relation % % Version 2.3.0 % Latest update 2 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % % Determines the cover sets that belong to the tree. Determines also the % base of the tree and updates the neighbor-relation such that all of the % tree is connected, i.e., the cover sets belonging to the tree form a % single connected component. Optionally uses information from existing % segmentation to make sure that stem and 1st-, 2nd-, 3rd-order branches % are properly connnected. % --------------------------------------------------------------------- % Inputs: % P Point cloud % cover Cover sets, their centers and neighbors % PatchDiam Minimum diameter of the cover sets % OnlyTree Logical value indicating if the point cloud contains only % points from the tree to be modelled % segment Previous segments % % Outputs: % cover Cover sets with updated neigbors % Base Base of the trunk (the cover sets forming the base) % Forb Cover sets not part of the tree % --------------------------------------------------------------------- % Changes from version 2.2.0 to 2.3.0, 2 May 2022: % 1) Added new lines of code at the end of the "define_main_branches" to % make sure that the "Trunk" variable defines connected stem % Changes from version 2.1.0 to 2.2.0, 13 Aug 2020: % 1) "define_base_forb": Changed the base height specification from % 0.1*aux.Height to 0.02*aux.Height % 2) "define_base_forb": changed the cylinder fitting syntax corresponding % to the new input and outputs of "least_squares_cylinder" % 3) "make_tree_connected”: Removed "Trunk(Base) = false;" at the beginning % of the function as unnecessary and to prevent errors in a special case % where the Trunk is equal to Base. % 4) "make_tree_connected”: Removed from the end the generation of "Trunk" % again and the new call for the function % 5) "make_tree_connected”: Increased the minimum distance of a component % to be removed from 8m to 12m. % Changes from version 2.0.0 to 2.1.0, 11 Oct 2019: % 1) "define_main_branches": modified the size of neighborhood "balls0", % added seven lines of code, prevents possible error of too low or big % indexes on "Par" % 2) Increased the maximum base height from 0.5m to 1.5m % 3) "make_tree_connected": added at the end a call for the function itself, % if the tree is not yet connected, thus running the function again if % necessary %% Define auxiliar object clear aux aux.nb = max(size(cover.center)); % number of cover sets aux.Fal = false(aux.nb,1); aux.Ind = (1:1:aux.nb)'; aux.Ce = P(cover.center,1:3); % Coordinates of the center points aux.Hmin = min(aux.Ce(:,3)); aux.Height = max(aux.Ce(:,3))-aux.Hmin; %% Define the base of the trunk and the forbidden sets if nargin == 3 [Base,Forb,cover] = define_base_forb(P,cover,aux,inputs); else inputs.OnlyTree = true; [Base,Forb,cover] = define_base_forb(P,cover,aux,inputs,segment); end %% Define the trunk (and the main branches) if nargin == 3 [Trunk,cover] = define_trunk(cover,aux,Base,Forb,inputs); else [Trunk,cover] = define_main_branches(cover,segment,aux,inputs); end %% Update neighbor-relation to make the whole tree connected [cover,Forb] = make_tree_connected(cover,aux,Forb,Base,Trunk,inputs); end % End of the main function function [Base,Forb,cover] = define_base_forb(P,cover,aux,inputs,segment) % Defines the base of the stem and the forbidden sets (the sets containing % points not from the tree, i.e, ground, understory, etc.) Ce = aux.Ce; if inputs.OnlyTree && nargin == 4 % No ground in the point cloud, the base is the lowest part BaseHeight = min(1.5,0.02*aux.Height); I = Ce(:,3) < aux.Hmin+BaseHeight; Base = aux.Ind(I); Forb = aux.Fal; % Make sure the base, as the bottom of point cloud, is not in multiple parts Wb = max(max(Ce(Base,1:2))-min(Ce(Base,1:2))); Wt = max(max(Ce(:,1:2))-min(Ce(:,1:2))); k = 1; while k <= 5 && Wb > 0.3*Wt BaseHeight = BaseHeight-0.05; BaseHeight = max(BaseHeight,0.05); if BaseHeight > 0 I = Ce(:,3) < aux.Hmin+BaseHeight; else [~,I] = min(Ce(:,3)); end Base = aux.Ind(I); Wb = max(max(Ce(Base,1:2))-min(Ce(Base,1:2))); k = k+1; end elseif inputs.OnlyTree % Select the stem sets from the previous segmentation and define the % base BaseHeight = min(1.5,0.02*aux.Height); SoP = segment.SegmentOfPoint(cover.center); stem = aux.Ind(SoP == 1); I = Ce(stem,3) < aux.Hmin+BaseHeight; Base = stem(I); Forb = aux.Fal; else % Point cloud contains non-tree points. % Determine the base from the "height" and "density" of cover sets % by projecting the sets to the xy-plane Bal = cover.ball; Nei = cover.neighbor; % The vertices of the rectangle containing C Min = double(min(Ce)); Max = double(max(Ce(:,1:2))); % Number of rectangles with edge length "E" in the plane E = min(0.1,0.015*aux.Height); n = double(ceil((Max(1:2)-Min(1:2))/E)+1); % Calculates the rectangular-coordinates of the points px = floor((Ce(:,1)-Min(1))/E)+1; py = floor((Ce(:,2)-Min(2))/E)+1; % Sorts the points according a lexicographical order LexOrd = [px py-1]*[1 n(1)]'; [LexOrd,SortOrd] = sort(LexOrd); Partition = cell(n(1),n(2)); hei = zeros(n(1),n(2)); % "height" of the cover sets in the squares den = hei; % density of the cover sets in the squares baseden = hei; p = 1; % The index of the point under comparison while p <= aux.nb t = 1; while (p+t <= aux.nb) && (LexOrd(p) == LexOrd(p+t)) t = t+1; end q = SortOrd(p); J = SortOrd(p:p+t-1); Partition{px(q),py(q)} = J; p = p+t; K = ceil(10*(Ce(J,3)-Min(3)+0.01)/(aux.Height-0.01)); B = K <= 2; K = unique(K); hei(px(q),py(q)) = length(K)/10; den(px(q),py(q)) = t; baseden(px(q),py(q)) = nnz(B); end den = den/max(max(den)); % normalize baseden = baseden/max(max(baseden)); % function whose maximum determines location of the trunk f = den.*hei.*baseden; % smooth the function by averaging over 8-neighbors x = zeros(n(1),n(2)); y = zeros(n(1),n(2)); for i = 2:n(1)-1 for j = 2:n(2)-1 f(i,j) = mean(mean(f(i-1:i+1,j-1:j+1))); x(i,j) = Min(1)+i*E; y(i,j) = Min(2)+j*E; end end f = f/max(max(f)); % Trunk location is around the maximum f-value I = f > 0.5; Trunk0 = Partition(I); % squares that contain the trunk Trunk0 = vertcat(Trunk0{:}); HBottom = min(Ce(Trunk0,3)); I = Ce(Trunk0,3) > HBottom+min(0.02*aux.Height,0.3); J = Ce(Trunk0,3) < HBottom+min(0.08*aux.Height,1.5); I = I&J; % slice close to bottom should contain the trunk Trunk = Trunk0(I); Trunk = union(Trunk,vertcat(Nei{Trunk})); % Expand with neighbors Trunk = union(Trunk,vertcat(Nei{Trunk})); % Expand with neighbors Trunk = union(Trunk,vertcat(Nei{Trunk})); % Expand with neighbors % Define connected components of Trunk and select the largest component [Comp,CS] = connected_components(Nei,Trunk,0,aux.Fal); [~,I] = max(CS); Trunk = Comp{I}; % Fit cylinder to Trunk I = Ce(Trunk,3) < HBottom+min(0.1*aux.Height,2); % Select the bottom part Trunk = Trunk(I); Trunk = union(Trunk,vertcat(Nei{Trunk})); Points = Ce(Trunk,:); c.start = mean(Points); c.axis = [0 0 1]; c.radius = mean(distances_to_line(Points,c.axis,c.start)); c = least_squares_cylinder(Points,c); % Remove far away points and fit new cylinder dis = distances_to_line(Points,c.axis,c.start); [~,I] = sort(abs(dis)); I = I(1:ceil(0.9*length(I))); Points = Points(I,:); Trunk = Trunk(I); c = least_squares_cylinder(Points,c); % Select the sets in the bottom part of the trunk and remove sets too % far away form the cylinder axis (also remove far away points from sets) I = Ce(Trunk0,3) < HBottom+min(0.04*aux.Height,0.6); TrunkBot = Trunk0(I); TrunkBot = union(TrunkBot,vertcat(Nei{TrunkBot})); TrunkBot = union(TrunkBot,vertcat(Nei{TrunkBot})); n = length(TrunkBot); Keep = true(n,1); % Keep sets that are close enough the axis a = max(0.06,0.2*c.radius); b = max(0.04,0.15*c.radius); for i = 1:n d = distances_to_line(Ce(TrunkBot(i),:),c.axis,c.start); if d < c.radius+a B = Bal{Trunk(i)}; d = distances_to_line(P(B,:),c.axis,c.start); I = d < c.radius+b; Bal{Trunk(i)} = B(I); else Keep(i) = false; end end TrunkBot = TrunkBot(Keep); % Select the above part of the trunk and combine with the bottom I = Ce(Trunk0,3) > HBottom+min(0.03*aux.Height,0.45); Trunk = Trunk0(I); Trunk = union(Trunk,vertcat(Nei{Trunk})); Trunk = union(Trunk,TrunkBot); BaseHeight = min(1.5,0.02*aux.Height); % Determine the base Bot = min(Ce(Trunk,3)); J = Ce(Trunk,3) < Bot+BaseHeight; Base = Trunk(J); % Determine "Forb", i.e, ground and non-tree sets by expanding Trunk % as much as possible Trunk = union(Trunk,vertcat(Nei{Trunk})); Forb = aux.Fal; Ground = setdiff(vertcat(Nei{Base}),Trunk); Ground = setdiff(union(Ground,vertcat(Nei{Ground})),Trunk); Forb(Ground) = true; Forb(Base) = false; Add = Forb; while any(Add) Add(vertcat(Nei{Add})) = true; Add(Forb) = false; Add(Trunk) = false; Forb(Add) = true; end % Try to expand the "Forb" more by adding all the bottom sets Bot = min(Ce(Trunk,3)); Ground = Ce(:,3) < Bot+0.03*aux.Height; Forb(Ground) = true; Forb(Trunk) = false; cover.ball = Bal; end end % End of function function [Trunk,cover] = define_trunk(cover,aux,Base,Forb,inputs) % This function tries to make sure that likely "route" of the trunk from % the bottom to the top is connected. However, this does not mean that the % final trunk follows this "route". Nei = cover.neighbor; Ce = aux.Ce; % Determine the output "Trunk" which indicates which sets are part of % likely trunk Trunk = aux.Fal; Trunk(Base) = true; % Expand Trunk from the base above with neighbors as long as possible Exp = Base; % the current "top" of Trunk % select the unique neighbors of Exp Exp = unique_elements([Exp; vertcat(Nei{Exp})],aux.Fal); I = Trunk(Exp); J = Forb(Exp); Exp = Exp(~I|~J); % Only non forbidden sets that are not already in Trunk Trunk(Exp) = true; % Add the expansion Exp to Trunk L = 0.25; % maximum height difference in Exp from its top to bottom H = max(Ce(Trunk,3))-L; % the minimum bottom heigth for the current Exp % true as long as the expansion is possible with original neighbors: FirstMod = true; while ~isempty(Exp) % Expand Trunk similarly as above as long as possible H0 = H; Exp0 = Exp; Exp = union(Exp,vertcat(Nei{Exp})); I = Trunk(Exp); Exp = Exp(~I); I = Ce(Exp,3) >= H; Exp = Exp(I); Trunk(Exp) = true; if ~isempty(Exp) H = max(Ce(Exp,3))-L; end % If the expansion Exp is empty and the top of the tree is still over 5 % meters higher, then search new neighbors from above if (isempty(Exp) || H < H0+inputs.PatchDiam1/2) && H < aux.Height-5 % Generate rectangular partition of the sets if FirstMod FirstMod = false; % The vertices of the rectangle containing C Min = double(min(Ce(:,1:2))); Max = double(max(Ce(:,1:2))); nb = size(Ce,1); % Number of rectangles with edge length "E" in the plane EdgeLenth = 0.2; NRect = double(ceil((Max-Min)/EdgeLenth)+1); % Calculates the rectangular-coordinates of the points px = floor((Ce(:,1)-Min(1))/EdgeLenth)+1; py = floor((Ce(:,2)-Min(2))/EdgeLenth)+1; % Sorts the points according a lexicographical order LexOrd = [px py-1]*[1 NRect(1)]'; [LexOrd,SortOrd] = sort(LexOrd); Partition = cell(NRect(1),NRect(2)); p = 1; % The index of the point under comparison while p <= nb t = 1; while (p+t <= nb) && (LexOrd(p) == LexOrd(p+t)) t = t+1; end q = SortOrd(p); J = SortOrd(p:p+t-1); Partition{px(q),py(q)} = J; p = p+t; end end % Select the region that is connected to a set above it if ~isempty(Exp) Region = Exp; else Region = Exp0; end % Select the minimum and maximum rectangular coordinate of the % region X1 = min(px(Region)); if X1 <= 2 X1 = 3; end X2 = max(px(Region)); if X2 >= NRect(1)-1 X2 = NRect(1)-2; end Y1 = min(py(Region)); if Y1 <= 2 Y1 = 3; end Y2 = max(py(Region)); if Y2 >= NRect(2)-1 Y2 = NRect(2)-2; end % Select the sets in the 2 meter layer above the region sets = Partition(X1-2:X2+2,Y1-2:Y2+2); sets = vertcat(sets{:}); K = aux.Fal; K(sets) = true; % the potential sets I = Ce(:,3) > H; J = Ce(:,3) < H+2; I = I&J&K; I(Trunk) = false; % Must be non-Trunk sets SetsAbove = aux.Ind(I); % Search the closest connection between Region and SetsAbove that % is enough upward sloping (angle to the vertical has cosine larger % than 0.7) if ~isempty(SetsAbove) % Compute the distances and cosines of the connections n = length(Region); m = length(SetsAbove); Dist = zeros(n,m); Cos = zeros(n,m); for i = 1:n V = mat_vec_subtraction(Ce(SetsAbove,:),Ce(Region(i),:)); Len = sum(V.*V,2); v = normalize(V); Dist(i,:) = Len'; Cos(i,:) = v(:,3)'; end I = Cos > 0.7; % select those connection with large enough cosines % if not any, search with smaller cosines t = 0; while ~any(I) t = t+1; I = Cos > 0.7-t*0.05; end % Search the minimum distance Dist(~I) = 3; if n > 1 && m > 1 [d,I] = min(Dist); [~,J] = min(d); I = I(J); elseif n == 1 && m > 1 [~,J] = min(Dist); I = 1; elseif m == 1 && n < 1 [~,I] = min(Dist); J = 1; else I = 1; % the set in component to be connected J = 1; % the set in "trunk" to be connected end % Join to "SetsAbove" I = Region(I); J = SetsAbove(J); % make the connection Nei{I} = [Nei{I}; J]; Nei{J} = [Nei{J}; I]; % Expand "Trunk" again Exp = union(Region,vertcat(Nei{Region})); I = Trunk(Exp); Exp = Exp(~I); I = Ce(Exp,3) >= H; Exp = Exp(I); Trunk(Exp) = true; H = max(Ce(Exp,3))-L; end end end cover.neighbor = Nei; end % End of function function [Trunk,cover] = define_main_branches(cover,segment,aux,inputs) % If previous segmentation exists, then use it to make the sets in its main % branches (stem and first (second or even up to third) order branches) % connected. This ensures that similar branching structure as in the % existing segmentation is possible. Bal = cover.ball; Nei = cover.neighbor; Ce = aux.Ce; % Determine sets in the main branches of previous segmentation nb = size(Bal,1); MainBranches = zeros(nb,1); SegmentOfPoint = segment.SegmentOfPoint; % Determine which branch indexes define the main branches MainBranchIndexes = false(max(SegmentOfPoint),1); MainBranchIndexes(1) = true; MainBranchIndexes(segment.branch1indexes) = true; MainBranchIndexes(segment.branch2indexes) = true; MainBranchIndexes(segment.branch3indexes) = true; for i = 1:nb BranchInd = nonzeros(SegmentOfPoint(Bal{i})); if ~isempty(BranchInd) ind = min(BranchInd); if MainBranchIndexes(ind) MainBranches(i) = min(BranchInd); end end end % Define the trunk sets Trunk = aux.Fal; Trunk(MainBranches > 0) = true; % Update the neighbors to make the main branches connected [Par,CC] = cubical_partition(Ce,3*inputs.PatchDiam2Max,10); Sets = zeros(aux.nb,1,'uint32'); BI = max(MainBranches); N = size(Par); for i = 1:BI if MainBranchIndexes(i) Branch = MainBranches == i; % The sets forming branch "i" % the connected components of "Branch": Comps = connected_components(Nei,Branch,1,aux.Fal); n = size(Comps,1); % Connect the components to each other as long as there are more than % one component while n > 1 for j = 1:n comp = Comps{j}; NC = length(comp); % Determine branch sets closest to the component c = unique(CC(comp,:),'rows'); m = size(c,1); t = 0; NearSets = zeros(0,1); while isempty(NearSets) NearSets = aux.Fal; t = t+1; for k = 1:m x1 = max(1,c(k,1)-t); x2 = min(c(k,1)+t,N(1)); y1 = max(1,c(k,2)-t); y2 = min(c(k,2)+t,N(2)); z1 = max(1,c(k,3)-t); z2 = min(c(k,3)+t,N(3)); balls0 = Par(x1:x2,y1:y2,z1:z2); if t == 1 balls = vertcat(balls0{:}); else S = cellfun('length',balls0); I = S > 0; S = S(I); balls0 = balls0(I); stop = cumsum(S); start = [0; stop]+1; for l = 1:length(stop) Sets(start(l):stop(l)) = balls0{l}; end balls = Sets(1:stop(l)); end I = Branch(balls); balls = balls(I); NearSets(balls) = true; end NearSets(comp) = false; % Only the non-component cover sets NearSets = aux.Ind(NearSets); end % Determine the closest sets for "comp" if ~isempty(NearSets) d = pdist2(Ce(comp,:),Ce(NearSets,:)); if NC == 1 && length(NearSets) == 1 IU = 1; % the set in component to be connected JU = 1; % the set in "trunk" to be connected elseif NC == 1 [du,JU] = min(d); IU = 1; elseif length(NearSets) == 1 [du,IU] = min(d); JU = 1; else [d,IU] = min(d); [du,JU] = min(d); IU = IU(JU); end % Join to the closest component I = comp(IU); J = NearSets(JU); % make the connection Nei{I} = [Nei{I}; J]; Nei{J} = [Nei{J}; I]; end end Comps = connected_components(Nei,Branch,1,aux.Fal); n = size(Comps,1); end end end % Update the neigbors to connect 1st-order branches to the stem Stem = MainBranches == 1; Stem = aux.Ind(Stem); MainBranchIndexes = false(max(SegmentOfPoint),1); MainBranchIndexes(segment.branch1indexes) = true; BI = max(segment.branch1indexes); if isempty(BI) BI = 0; end for i = 2:BI if MainBranchIndexes(i) Branch = MainBranches == i; Branch = aux.Ind(Branch); if ~isempty(Branch) Neigbors = MainBranches(vertcat(Nei{Branch})) == 1; if ~any(Neigbors) d = pdist2(Ce(Branch,:),Ce(Stem,:)); if length(Branch) > 1 && length(Stem) > 1 [d,I] = min(d); [d,J] = min(d); I = I(J); elseif length(Branch) == 1 && length(Stem) > 1 [d,J] = min(d); I = 1; elseif length(Stem) == 1 && length(Branch) > 1 [d,I] = min(d); J = 1; elseif length(Branch) == 1 && length(Stem) == 1 I = 1; % the set in component to be connected J = 1; % the set in "trunk" to be connected end % Join the Branch to Stem I = Branch(I); J = Stem(J); Nei{I} = [Nei{I}; J]; Nei{J} = [Nei{J}; I]; end end end end cover.neighbor = Nei; % Check if the trunk is still in mutliple components and select the bottom % component to define "Trunk": [comps,cs] = connected_components(cover.neighbor,Trunk,aux.Fal); if length(cs) > 1 [cs,I] = sort(cs,'descend'); comps = comps(I); Stem = MainBranches == 1; Trunk = aux.Fal; i = 1; C = comps{i}; while i <= length(cs) && ~any(Stem(C)) i = i+1; C = comps{i}; end Trunk(C) = true; end end % End of function function [cover,Forb] = make_tree_connected(cover,aux,Forb,Base,Trunk,inputs) % Update neighbor-relation for whole tree such that the whole tree is one % connected component Nei = cover.neighbor; Ce = aux.Ce; % Expand trunk as much as possible Trunk(Forb) = false; Exp = Trunk; while any(Exp) Exp(vertcat(Nei{Exp})) = true; Exp(Trunk) = false; Exp(Forb) = false; Exp(Base) = false; Trunk(Exp) = true; end % Define "Other", sets not yet connected to trunk or Forb Other = ~aux.Fal; Other(Forb) = false; Other(Trunk) = false; Other(Base) = false; % Determine parameters on the extent of the "Nearby Space" and acceptable % component size % cell size for "Nearby Space" = k0 times PatchDiam: k0 = min(10,ceil(0.2/inputs.PatchDiam1)); % current cell size, increases by k0 every time when new connections cannot % be made: k = k0; if inputs.OnlyTree Cmin = 0; else Cmin = ceil(0.1/inputs.PatchDiam1); % minimum accepted component size, % smaller ones are added to Forb, the size triples every round end % Determine the components of "Other" if any(Other) Comps = connected_components(Nei,Other,1,aux.Fal); nc = size(Comps,1); NonClassified = true(nc,1); %plot_segs(P,Comps,6,1,cover.ball) %pause else NonClassified = false; end bottom = min(Ce(Base,3)); % repeat search and connecting as long as "Other" sets exists while any(NonClassified) npre = nnz(NonClassified); % number of "Other" sets before new connections again = true; % check connections again with same "distance" if true % Partition the centers of the cover sets into cubes with size k*dmin [Par,CC] = cubical_partition(Ce,k*inputs.PatchDiam1); Neighbors = cell(nc,1); Sizes = zeros(nc,2); Pass = true(nc,1); first_round = true; while again % Check each component: part of "Tree" or "Forb" for i = 1:nc if NonClassified(i) && Pass(i) comp = Comps{i}; % candidate component for joining to the tree % If the component is neighbor of forbidden sets, remove it J = Forb(vertcat(Nei{comp})); if any(J) NonClassified(i) = false; Forb(comp) = true; Other(comp) = false; else % Other wise check nearest sets for a connection NC = length(comp); if first_round % Select the cover sets the nearest to the component c = unique(CC(comp,:),'rows'); m = size(c,1); B = cell(m,1); for j = 1:m balls = Par(c(j,1)-1:c(j,1)+1,... c(j,2)-1:c(j,2)+1,c(j,3)-1:c(j,3)+1); B{j} = vertcat(balls{:}); end NearSets = vertcat(B{:}); % Only the non-component cover sets aux.Fal(comp) = true; I = aux.Fal(NearSets); NearSets = NearSets(~I); aux.Fal(comp) = false; NearSets = unique(NearSets); Neighbors{i} = NearSets; if isempty(NearSets) Pass(i) = false; end % No "Other" sets I = Other(NearSets); NearSets = NearSets(~I); else NearSets = Neighbors{i}; % No "Other" sets I = Other(NearSets); NearSets = NearSets(~I); end % Select different class from NearSets I = Trunk(NearSets); J = Forb(NearSets); trunk = NearSets(I); % "Trunk" sets forb = NearSets(J); % "Forb" sets if length(trunk) ~= Sizes(i,1) || length(forb) ~= Sizes(i,2) Sizes(i,:) = [length(trunk) length(forb)]; % If large component is tall and close to ground, then % search the connection near the component's bottom if NC > 100 hmin = min(Ce(comp,3)); H = max(Ce(comp,3))-hmin; if H > 5 && hmin < bottom+5 I = Ce(NearSets,3) < hmin+0.5; NearSets = NearSets(I); I = Trunk(NearSets); J = Forb(NearSets); trunk = NearSets(I); % "Trunk" sets forb = NearSets(J); % "Forb" sets end end % Determine the closest sets for "trunk" if ~isempty(trunk) d = pdist2(Ce(comp,:),Ce(trunk,:)); if NC == 1 && length(trunk) == 1 dt = d; % the minimum distance IC = 1; % the set in component to be connected IT = 1; % the set in "trunk" to be connected elseif NC == 1 [dt,IT] = min(d); IC = 1; elseif length(trunk) == 1 [dt,IC] = min(d); IT = 1; else [d,IC] = min(d); [dt,IT] = min(d); IC = IC(IT); end else dt = 700; end % Determine the closest sets for "forb" if ~isempty(forb) d = pdist2(Ce(comp,:),Ce(forb,:)); df = min(d); if length(df) > 1 df = min(df); end else df = 1000; end % Determine what to do with the component if (dt > 12 && dt < 100) || (NC < Cmin && dt > 0.5 && dt < 10) % Remove small isolated component Forb(comp) = true; Other(comp) = false; NonClassified(i) = false; elseif 3*df < dt || (df < dt && df > 0.25) % Join the component to "Forb" Forb(comp) = true; Other(comp) = false; NonClassified(i) = false; elseif (df == 1000 && dt == 700) || dt > k*inputs.PatchDiam1 % Isolated component, do nothing else % Join to "Trunk" I = comp(IC); J = trunk(IT); Other(comp) = false; Trunk(comp) = true; NonClassified(i) = false; % make the connection Nei{I} = [Nei{I}; J]; Nei{J} = [Nei{J}; I]; end end end end end first_round = false; % If "Other" has decreased, do another check with same "distance" if nnz(NonClassified) < npre again = true; npre = nnz(NonClassified); else again = false; end end k = k+k0; % increase the cell size of the nearby search space Cmin = 3*Cmin; % increase the acceptable component size end Forb(Base) = false; cover.neighbor = Nei; end % End of function ================================================ FILE: src/make_models.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function QSMs = make_models(dataname,savename,Nmodels,inputs) % --------------------------------------------------------------------- % MAKE_MODELS.M Makes QSMs of given point clouds. % % Version 1.1.0 % Latest update 9 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % % Makes QSMs of given point clouds specified by the "dataname" and by the % other inputs. The results are saved into file named "savename". % Notice, the code does not save indivual QSM runs into their own .mat or % .txt files but saves all models into one big .mat file. % % Inputs: % dataname String specifying the .mat-file containing the point % clouds that are used for the QSM reconstruction. % savename String, the name of the file where the QSMs are saved % Nmodels (Optional) Number of models generated for each input % (cloud and input parameters). Default value is 5. % inputs (Optional) The input parameters structure. Can be defined % below as part of this code. Can also be given as a % structure array where each tree gets its own, possibly % uniquely, defined parameters (e.g. optimal parameters) % but each tree has to have same number of parameter values. % % Output: % QSMs Structure array containing all the QSMs generated % --------------------------------------------------------------------- % Changes from version 1.1.0 to 1.1.1, 18 Aug 2020: % 1) Removed the inputs "lcyl" and "FilRad" from the inputs and the % calculations of number of input parameters % Changes from version 1.0.0 to 1.1.0, 03 Oct 2019: % 1) Added try-catch structure where "treeqsm" is called, so that if there % is an error during the reconstruction process of one tree, then the % larger process of making multiple QSMs from multiple tree is not % stopped. % 2) Changed the way the data is loaded. Previously all the data was % loaded into workspace, now only one point cloud is in the workspace. % 3) Corrected a bug where incomplete QSM was saved as complete QSM % 4) Changed where the input-structure for each tree is reconstructed if nargin < 2 disp('Not enough inputs, no models generated!') QSMs = struct([]); return end if nargin == 2 Nmodels = 5; % Number of models per inputs, usually about 5 models is enough end %% Define the parameter values if nargin == 3 || nargin == 2 % The following parameters can be varied and should be optimised % (each can have multiple values): % Patch size of the first uniform-size cover: inputs.PatchDiam1 = [0.08 0.1]; % Minimum patch size of the cover sets in the second cover: inputs.PatchDiam2Min = [0.015 0.025]; % Maximum cover set size in the stem's base in the second cover: inputs.PatchDiam2Max = [0.06 0.08]; % The following parameters can be varied and but usually can be kept as % shown (i.e. as little bigger than PatchDiam parameters): % Ball radius used for the first uniform-size cover generation: inputs.BallRad1 = inputs.PatchDiam1+0.02; % Maximum ball radius used for the second cover generation: inputs.BallRad2 = inputs.PatchDiam2Max+0.01; % The following parameters can be usually kept fixed as shown: inputs.nmin1 = 3; % Minimum number of points in BallRad1-balls, good value is 3 inputs.nmin2 = 1; % Minimum number of points in BallRad2-balls, good value is 1 inputs.OnlyTree = 1; % If "1", then point cloud contains points only from the tree inputs.Tria = 0; % If "1", then triangulation produces inputs.Dist = 1; % If "1", then computes the point-model distances % Different cylinder radius correction options for modifying too large and % too small cylinders: % Traditional TreeQSM choices: % Minimum cylinder radius, used particularly in the taper corrections: inputs.MinCylRad = 0.0025; % Child branch cylinders radii are always smaller than the parent % branche's cylinder radii: inputs.ParentCor = 1; % Use partially linear (stem) and parabola (branches) taper corrections: inputs.TaperCor = 1; % Growth volume correction approach introduced by Jan Hackenberg, % allometry: GrowthVol = a*Radius^b+c % Use growth volume correction: inputs.GrowthVolCor = 0; % fac-parameter of the growth vol. approach, defines upper and lower % boundary: inputs.GrowthVolFac = 2.5; inputs.name = 'test'; inputs.tree = 0; inputs.plot = 0; inputs.savetxt = 0; inputs.savemat = 0; inputs.disp = 0; end % Compute the number of input parameter combinations in = inputs(1); ninputs = prod([length(in.PatchDiam1) length(in.PatchDiam2Min)... length(in.PatchDiam2Max)]); %% Load data matobj = matfile([dataname,'.mat']); names = fieldnames(matobj); i = 1; n = max(size(names)); while i <= n && ~strcmp(names{i,:},'Properties') i = i+1; end I = (1:1:n); I = setdiff(I,i); names = names(I,1); names = sort(names); nt = max(size(names)); % number of trees/point clouds %% make the models QSMs = struct('cylinder',{},'branch',{},'treedata',{},'rundata',{},... 'pmdistance',{},'triangulation',{}); % Generate Inputs struct that contains the input parameters for each tree if max(size(inputs)) == 1 for i = 1:nt Inputs(i) = inputs; Inputs(i).name = names{i}; Inputs(i).tree = i; Inputs(i).plot = 0; Inputs(i).savetxt = 0; Inputs(i).savemat = 0; Inputs(i).disp = 0; end else Inputs = inputs; end m = 1; for t = 1:nt % trees disp(['Modelling tree ',num2str(t),'/',num2str(nt),' (',Inputs(t).name,'):']) P = matobj.(Inputs(t).name); j = 1; % model number under generation, make "Nmodels" models per tree inputs = Inputs(t); while j <= Nmodels % generate N models per input k = 1; n0 = 0; inputs.model = j; while k <= 5 % try up to five times to generate non-empty models try QSM = treeqsm(P,inputs); catch QSM = struct('cylinder',{},'branch',{},'treedata',{},... 'rundata',{},'pmdistance',{},'triangulation',{}); QSM(ninputs).treedata = 0; end n = max(size(QSM)); Empty = false(n,1); for b = 1:n if isempty(QSM(b).branch) Empty(b) = true; end end if n < ninputs || any(Empty) n = nnz(~Empty); k = k+1; if n >= n0 qsm = QSM(~Empty); n0 = n; end else % Succesfull models generated QSMs(m:m+n-1) = QSM; m = m+n; k = 10; end end if k == 6 disp('Incomplete run!!') QSMs(m:m+n0-1) = qsm; m = m+n0; end j = j+1; end stri = ['results/',savename]; save(stri,'QSMs') end ================================================ FILE: src/make_models_parallel.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function QSMs = make_models_parallel(dataname,savename,Nmodels,inputs) % --------------------------------------------------------------------- % MAKE_MODELS.M Makes QSMs of given point clouds. % % Version 1.1.2 % Latest update 9 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % % Makes QSMs of given point clouds specified by the "dataname" and by the % other inputs. The results are saved into file named "savename". % Notice, the code does not save indivual QSM runs into their own .mat or % .txt files but saves all models into one big .mat file. Same as % MAKE_MODELS but uses parfor command (requires Parallel Computing Toolbox) % which allows the utilization of multiple processors/cores to compute in % parallel number of QSMs with the same inputs. % % Inputs: % dataname String specifying the .mat-file containing the point % clouds that are used for the QSM reconstruction. % savename String, the name of the file where the QSMs are saved % Nmodels (Optional) Number of models generated for each input % (cloud and input parameters). Default value is 5. % inputs (Optional) The input parameters structure. Can be defined % below as part of this code. Can also be given as a % structure array where each tree gets its own, possibly % uniquely, defined parameters (e.g. optimal parameters) % but each tree has to have same number of parameter values. % % Output: % QSMs Structure array containing all the QSMs generated % --------------------------------------------------------------------- % Changes from version 1.1.1 to 1.1.2, 18 Aug 2020: % 1) Removed the inputs "lcyl" and "FilRad" from the inputs and the % calculations of number of input parameters % Changes from version 1.1.0 to 1.1.1, 13 Jan 2020: % 1) Changed "m = m+n;" to "m = m+n(j);" at the end of the function. % Changes from version 1.0.0 to 1.1.0, 03 Oct 2019: % 1) Added try-catch structure where "treeqsm" is called, so that if there % is an error during the reconstruction process of one tree, then the % larger process of making multiple QSMs from multiple tree is not % stopped. % 2) Changed the way the data is loaded. Previously all the data was % loaded into workspace, now only one point cloud is in the workspace. % 3) Corrected a bug where incomplete QSM was saved as complete QSM % 4) Changed where the input-structure for each tree reconstructed % 5) Changed the coding to separate more the results of the different % parallel processes (less warnings and errors) if nargin < 2 disp('Not enough inputs, no models generated!') QSMs = struct([]); return end if nargin == 2 Nmodels = 5; % Number of models per inputs, usually about 5 models is enough end %% Define the parameter values if nargin == 3 || nargin == 2 % The following parameters can be varied and should be optimised % (each can have multiple values): % Patch size of the first uniform-size cover: inputs.PatchDiam1 = [0.08 0.15]; % Minimum patch size of the cover sets in the second cover: inputs.PatchDiam2Min = [0.015 0.025]; % Maximum cover set size in the stem's base in the second cover: inputs.PatchDiam2Max = [0.06 0.08]; % The following parameters can be varied and but usually can be kept as % shown (i.e. as little bigger than PatchDiam parameters): % Ball radius used for the first uniform-size cover generation: inputs.BallRad1 = inputs.PatchDiam1+0.02; % Maximum ball radius used for the second cover generation: inputs.BallRad2 = inputs.PatchDiam2Max+0.01; % The following parameters can be usually kept fixed as shown: inputs.nmin1 = 3; % Minimum number of points in BallRad1-balls, good value is 3 inputs.nmin2 = 1; % Minimum number of points in BallRad2-balls, good value is 1 inputs.OnlyTree = 1; % If "1", then point cloud contains points only from the tree inputs.Tria = 0; % If "1", then triangulation produces inputs.Dist = 1; % If "1", then computes the point-model distances % Different cylinder radius correction options for modifying too large and % too small cylinders: % Traditional TreeQSM choices: % Minimum cylinder radius, used particularly in the taper corrections: inputs.MinCylRad = 0.0025; % Child branch cylinders radii are always smaller than the parent % branche's cylinder radii: inputs.ParentCor = 1; % Use partially linear (stem) and parabola (branches) taper corrections: inputs.TaperCor = 1; % Growth volume correction approach introduced by Jan Hackenberg, % allometry: GrowthVol = a*Radius^b+c % Use growth volume correction: inputs.GrowthVolCor = 0; % fac-parameter of the growth vol. approach, defines upper and lower % boundary: inputs.GrowthVolFac = 2.5; inputs.name = 'test'; inputs.tree = 0; inputs.plot = 0; inputs.savetxt = 0; inputs.savemat = 0; inputs.disp = 0; end % Compute the number of input parameter combinations in = inputs(1); ninputs = prod([length(in.PatchDiam1) length(in.PatchDiam2Min)... length(in.PatchDiam2Max)]); %% Load data matobj = matfile([dataname,'.mat']); names = fieldnames(matobj); i = 1; n = max(size(names)); while i <= n && ~strcmp(names{i,:},'Properties') i = i+1; end I = (1:1:n); I = setdiff(I,i); names = names(I,1); names = sort(names); nt = max(size(names)); % number of trees/point clouds %% make the models QSMs = struct('cylinder',{},'branch',{},'treedata',{},'rundata',{},... 'pmdistance',{},'triangulation',{}); % Generate Inputs struct that contains the input parameters for each tree if max(size(inputs)) == 1 for i = 1:nt Inputs(i) = inputs; Inputs(i).name = names{i}; Inputs(i).tree = i; Inputs(i).plot = 0; Inputs(i).savetxt = 0; Inputs(i).savemat = 0; Inputs(i).disp = 0; end else Inputs = inputs; end m = 1; for t = 1:nt % trees disp(['Modelling tree ',num2str(t),'/',num2str(nt),' (',Inputs(t).name,'):']) P = matobj.(Inputs(t).name); qsms = cell(Nmodels,1); % save here the accepted models qsm = cell(Nmodels,1); % cell-structure to keep different models separate n = ones(Nmodels,1); n0 = zeros(Nmodels,1); k = ones(Nmodels,1); parfor j = 1:Nmodels % generate N models per input inputs = Inputs(t); inputs.model = j; while k(j) <= 5 % try up to five times to generate non-empty models try qsm{j} = treeqsm(P,inputs); catch qsm{j} = struct('cylinder',{},'branch',{},'treedata',{},... 'rundata',{},'pmdistance',{},'triangulation',{}); qsm{j}(ninputs).treedata = 0; end n(j) = max(size(qsm{j})); Empty = false(n(j),1); for b = 1:n(j) if isempty(qsm{j}(b).branch) Empty(b) = true; end end if n(j) < ninputs || any(Empty) n(j) = nnz(~Empty); k(j) = k(j)+1; if n(j) > n0(j) qsms{j} = qsm{j}(~Empty); n0(j) = n(j); end else % Successful models generated qsms{j} = qsm{j}; k(j) = 10; end end if k(j) == 6 disp('Incomplete run!!') end end % Save the models for j = 1:Nmodels QSM = qsms{j}; a = max(size(QSM)); QSMs(m:m+a-1) = QSM; m = m+n(j); end str = ['results/',savename]; save(str,'QSMs') end ================================================ FILE: src/plotting/plot2d.m ================================================ function h = plot2d(X,Y,fig,strtit,strx,stry,leg,E) % 2D-plots, where the data (X and Y), figure number, title, xlabel, ylabel, % legends and error bars can be specied with the inputs. lw = 1.5; % linewidth n = size(Y,1); if n < 9 col = ['-b '; '-r '; '-g '; '-c '; '-m '; '-k '; '-y '; '-.b']; else col = [ 0.00 0.00 1.00 0.00 0.50 0.00 1.00 0.00 0.00 0.00 0.75 0.75 0.75 0.00 0.75 0.75 0.75 0.00 0.25 0.25 0.25 0.75 0.25 0.25 0.95 0.95 0.00 0.25 0.25 0.75 0.75 0.75 0.75 0.00 1.00 0.00 0.76 0.57 0.17 0.54 0.63 0.22 0.34 0.57 0.92 1.00 0.10 0.60 0.88 0.75 0.73 0.10 0.49 0.47 0.66 0.34 0.65 0.99 0.41 0.23]; if n > 20 k = ceil(n/20); col = repmat(col,[k 1]); end end figure(fig) if nargin <= 7 % plots without errorbars if ~iscell(Y) if ~isempty(X) if n < 9 h = plot(X(1,:),Y(1,:),'-b','Linewidth',lw); else h = plot(X(1,:),Y(1,:),'Color',col(1,:),'Linewidth',lw); end else if n < 9 h = plot(Y(1,:),'-b','Linewidth',lw); else h = plot(Y(1,:),'Color',col(1,:),'Linewidth',lw); end end if n > 1 hold on if ~isempty(X) if n < 9 for i = 2:n plot(X(i,:),Y(i,:),col(i,:),'Linewidth',lw) end else for i = 2:n plot(X(i,:),Y(i,:),'Color',col(i,:),'Linewidth',lw) end end else if n < 9 for i = 2:n plot(Y(i,:),col(i,:),'Linewidth',lw) end else for i = 2:n plot(Y(i,:),'Color',col(i,:),'Linewidth',lw) end end end hold off end else if ~isempty(X) x = X{1}; end y = Y{1}; if ~isempty(X) if n < 9 h = plot(x,y,'-b','Linewidth',lw); else h = plot(x,y,'Color',col(1,:),'Linewidth',lw); end else if n < 9 h = plot(y,'-b','Linewidth',lw); else h = plot(y,'Color',col(1,:),'Linewidth',lw); end end if n > 1 hold on if ~isempty(X) for i = 2:n x = X{i}; y = Y{i}; if n < 9 plot(x,y,col(i,:),'Linewidth',lw) else plot(x,y,'Color',col(i,:),'Linewidth',lw) end end else for i = 2:n y = Y{i}; if n < 9 plot(y,col(i,:),'Linewidth',lw) else plot(y,'Color',col(i,:),'Linewidth',lw) end end end hold off end end else % plots with errorbars if ~iscell(Y) if ~isempty(X) if n < 9 h = errorbar(X(1,:),Y(1,:),E(1,:),'-b','Linewidth',lw); else h = errorbar(X(1,:),Y(1,:),E(1,:),'Color',col(1,:),'Linewidth',lw); end else if n < 9 h = errorbar(Y(1,:),E(1,:),'-b','Linewidth',lw); else h = errorbar(Y(1,:),E(1,:),'Color',col(1,:),'Linewidth',lw); end end if n > 1 hold on if ~isempty(X) if n < 9 for i = 2:n errorbar(X(i,:),Y(i,:),E(1,:),col(i,:),'Linewidth',lw) end else for i = 2:n errorbar(X(i,:),Y(i,:),E(1,:),'Color',col(i,:),'Linewidth',lw) end end else if n < 9 for i = 2:n errorbar(Y(i,:),E(1,:),col(i,:),'Linewidth',lw) end else for i = 2:n errorbar(Y(i,:),E(1,:),'Color',col(i,:),'Linewidth',lw) end end end hold off end else if ~isempty(X) x = X{1}; end y = Y{1}; e = E{1}; if ~isempty(X) if n < 9 h = errorbar(x,y,e(1,:),'-b','Linewidth',lw); else h = errorbar(x,y,'Color',e(1,:),col(1,:),'Linewidth',lw); end else if n < 9 h = errorbar(y,e(1,:),'-b','Linewidth',lw); else h = errorbar(y,e(1,:),'Color',col(1,:),'Linewidth',lw); end end if n > 1 hold on if ~isempty(X) for i = 2:n x = X{i}; y = Y{i}; e = E{i}; if n < 9 h = errorbar(x,y,e(1,:),col(i,:),'Linewidth',lw); else h = errorbar(x,y,e(1,:),'Color',col(i,:),'Linewidth',lw); end end else for i = 2:n y = Y{i}; e = E{i}; if n < 9 errorbar(y,e(1,:),col(i,:),'Linewidth',lw); else errorbar(y,e(1,:),'Color',col(i,:),'Linewidth',lw); end end end hold off end end end grid on t = title(strtit); x = xlabel(strx); y = ylabel(stry); if nargin > 6 legend(leg) end set(gca,'fontsize',12) set(gca,'FontWeight','bold') set(t,'fontsize',12) set(t,'FontWeight','bold') set(x,'fontsize',12) set(x,'FontWeight','bold') set(y,'fontsize',12) set(y,'FontWeight','bold') ================================================ FILE: src/plotting/plot_branch_segmentation.m ================================================ function plot_branch_segmentation(P,cover,segment,Color,fig,ms,segind,BO) % --------------------------------------------------------------------- % PLOT_BRANCH_SEGMENTATION.M Plots branch-segmented point cloud, coloring % based on branching order or branches % % Version 1.0.0 % Latest update 13 July 2020 % % Copyright (C) 2013-2020 Pasi Raumonen % --------------------------------------------------------------------- % % If the coloring is based on branches (Color = 'branch'), then each segment % is colored with unique color. If the coloring is based on branching order % (Color = 'order'), then Blue = trunk, Green = 1st-order branches, % Red = 2nd-order branches, etc. % % If segind = 1 and BO = 0, then plots the stem. If segind = 1 and BO = 1, % then plots the stem and the 1st-order branches. If segind = 1 and % BO >= maximum branching order or BO input is not given, then plots the % whole tree. If segind = 2 and BO is not given or it is high enough, then % plots the branch whose index is 2 and all its sub-branches. % % Inputs % P Point cloud % cover Cover sets structure % segment Segments structure % Color Color option, 'order' or 'branch' % fig Figure number % ms Marker size % segind Index of the segment where the plotting of tree structure starts. % BO How many branching orders are plotted. 0 = stem, 1 = 1st order, etc n = nargin; if n < 8 BO = 1000; if n < 7 segind = 1; if n < 6 ms = 1; if n < 5 fig = 1; if n == 3 Color = 'order'; end end end end end Bal = cover.ball; Segs = segment.segments; SChi = segment.ChildSegment; SPar = segment.ParentSegment; ns = max(size(Segs)); if iscell(Segs{1}) Seg = cell(ns,1); for i = 1:ns m = size(Segs{i},1); S = zeros(0); for j = 1:m s = Segs{i}(j); s = s{:}; S = [S; s]; end Seg{i} = S; end else Seg = Segs; end if strcmp(Color,'branch') Color = 1; % Color the segments with unique colors col = rand(ns,3); for i = 2:ns C = col(SPar(i),:); c = col(i,:); while sum(abs(C-c)) < 0.2 c = rand(1,3); end col(i,:) = c; end elseif strcmp(Color,'order') Color = 0; % Color the cylinders in branches based on the branch order col = [ 0.00 0.00 1.00 0.00 0.50 0.00 1.00 0.00 0.00 0.00 0.75 0.75 0.75 0.00 0.75 0.75 0.75 0.00 0.25 0.25 0.25 0.75 0.25 0.25 0.95 0.95 0.00 0.25 0.25 0.75 0.75 0.75 0.75 0.00 1.00 0.00 0.76 0.57 0.17 0.54 0.63 0.22 0.34 0.57 0.92 1.00 0.10 0.60 0.88 0.75 0.73 0.10 0.49 0.47 0.66 0.34 0.65 0.99 0.41 0.23]; col = repmat(col,[10,1]); end segments = segind; C = SChi{segind}; b = 1; order = 1; while ~isempty(C) && b <= BO b = b+1; segments = [segments; C]; order = [order; b*ones(length(C),1)]; C = vertcat(SChi{C}); end ns = length(segments); figure(fig) for i = 1:ns if i == 2 hold on end S = vertcat(Bal{Seg{segments(i)}}); if Color % Coloring based on branch plot3(P(S,1),P(S,2),P(S,3),'.','Color',col(segments(i),:),'Markersize',ms) else % Coloring based on branch order plot3(P(S,1),P(S,2),P(S,3),'.','Color',col(order(i),:),'Markersize',ms) end end hold off axis equal ================================================ FILE: src/plotting/plot_branches.m ================================================ function plot_branches(P,cover,segment,fig,ms,segind,BO) n = nargin; if n < 7 BO = 1000; if n < 6 segind = 1; if n < 5 ms = 1; if n == 3 fig = 1; end end end end Bal = cover.ball; Segs = segment.segments; SChi = segment.ChildSegment; SPar = segment.ParentSegment; if iscell(Segs{1}) ns = max(size(Segs)); Seg = cell(ns,1); for i = 1:ns m = size(Segs{i},1); S = zeros(0); for j = 1:m s = Segs{i}(j); s = s{:}; S = [S; s]; end Seg{i} = S; end else Seg = Segs; end % Color the segments with unique colors col = rand(ns,3); for i = 2:ns C = col(SPar(i),:); c = col(i,:); while sum(abs(C-c)) < 0.2 c = rand(1,3); end col(i,:) = c; end segments = segind; C = SChi{segind}; b = 0; while ~isempty(C) && b <= BO b = b+1; segments = [segments; C]; C = SChi{segind}; end ns = length(segment); figure(fig) for i = 1:ns if i == 2 hold on end S = vertcat(Bal{Seg{segments(i)}}); plot3(P(S,1),P(S,2),P(S,3),'.','Color',col(segments(i),:),'Markersize',ms) end hold off ================================================ FILE: src/plotting/plot_comparison.m ================================================ function plot_comparison(P1,P2,fig,ms1,ms2) % Plots two point clouds "P1" and "P2" so that those points of "P2" which are % not in "P1" are plotted in red whereas the common points are plotted in % blue. "fig" and "ms1" and "ms2" are the figure number and marker sizes. if nargin == 3 ms1 = 3; ms2 = 3; elseif nargin == 4 ms2 = 3; end if ms1 == 0 ms1 = 3; end if ms2 == 0 ms2 = 3; end P2 = setdiff(P2,P1,'rows'); figure(fig) if size(P1,2) == 3 plot3(P1(:,1),P1(:,2),P1(:,3),'.b','Markersize',ms1) hold on plot3(P2(:,1),P2(:,2),P2(:,3),'.r','Markersize',ms2) elseif size(P1,2) == 2 plot(P1(:,1),P1(:,2),'.b','Markersize',ms1) hold on plot(P2(:,1),P2(:,2),'.r','Markersize',ms2) end hold off axis equal ================================================ FILE: src/plotting/plot_cone_model.m ================================================ function plot_cone_model(cylinder,fig,nf,alp,Ind) % Plots the given cylinder model as truncated cones defined by the cylinders. % cylinder Structure array containin the cylinder info % (radius, length, start, axis, BranchOrder) % fig Figure number % nf Number of facets in the cyliders (in the thickest cylinder, % scales down with radius to 4 which is the minimum) % alp Alpha value (1 = no trasparency, 0 = complete transparency) % Ind Indexes of cylinders to be plotted from a subset of cylinders % (Optional, if not given then all cylinders are plotted) if isstruct(cylinder) Rad = cylinder.radius; Len = cylinder.length; Sta = cylinder.start; %Sta = mat_vec_subtraction(Sta,Sta(1,:)); Axe = cylinder.axis; Bran = cylinder.branch; PiB = cylinder.PositionInBranch; nb = max(Bran); else Rad = cylinder(:,1); Len = cylinder(:,2); Sta = cylinder(:,3:5); %Sta = mat_vec_subtraction(Sta,Sta(1,:)); Axe = cylinder(:,6:8); Bran = cylinder(:,12); PiB = cylinder(:,14); nb = max(Bran); end if nargin == 5 Rad = Rad(Ind); Len = Len(Ind); Sta = Sta(Ind,:); Axe = Axe(Ind,:); end nc = size(Rad,1); Cir = cell(nf,2); for i = 4:nf Cir{i,1} = [cos((1/i:1/i:1)*2*pi)' sin((1/i:1/i:1)*2*pi)' zeros(i,1)]; Cir{i,2} = [(1:1:i)' (i+1:1:2*i)' [(i+2:1:2*i)'; i+1] [(2:1:i)'; 1]]; end Vert = zeros(2*nc*(nf+1),3); Facets = zeros(nc*(nf+1),4); t = 1; f = 1; % Scale, rotate and translate the standard cylinders Ind = (1:1:nc)'; for j = 1:nb I = Bran == j; I = Ind(I); if ~isempty(I) P = PiB(I); [P,J] = sort(P); I = I(J); n = ceil(sqrt(mean(Rad(I))/Rad(1))*nf); n = min(n,nf); n = max(n,4); C0 = Cir{n,1}; m = length(I); for i = 1:m C = C0; % Scale radius C(1:n,1:2) = Rad(I(i))*C(1:n,1:2); if i == m % Define the last circle of the branch C1 = C; C1(:,1:2) = min(0.005/Rad(I(i)),1)*C(:,1:2); end % Rotate if i == 1 ang = real(acos(Axe(I(i),3))); Axis = cross([0 0 1]',Axe(I(i),:)'); Rot = rotation_matrix(Axis,ang); C = C*Rot'; elseif i > 1 ang = real(acos(Axe(I(i),3))); Axis = cross([0 0 1]',Axe(I(i),:)'); Rot = rotation_matrix(Axis,ang); C = C*Rot'; %%% Should be somehow corrected so that high angles between %%% cylinders do not cause narrowing the surface!!! if i == m ang = real(acos(Axe(I(i),3))); Axis = cross([0 0 1]',Axe(I(i),:)'); Rot = rotation_matrix(Axis,ang); C1 = C1*Rot'; end end % Translate C = mat_vec_subtraction(C,-Sta(I(i),:)); if i == m C1 = mat_vec_subtraction(C1,-(Sta(I(i),:)+Len(I(i))*Axe(I(i),:))); end % Save the new vertices Vert(t:t+n-1,:) = C; if i == m t = t+n; Vert(t:t+n-1,:) = C1; end t = t+n; % Define the new facets if i == 1 && i == m Facets(f:f+n-1,:) = Cir{n,2}+t-2*n-1; f = f+n; elseif i > 1 && i < m Facets(f:f+n-1,:) = Cir{n,2}+t-2*n-1; f = f+n; elseif i > 1 && i == m Facets(f:f+n-1,:) = Cir{n,2}+t-3*n-1; f = f+n; Facets(f:f+n-1,:) = Cir{n,2}+t-2*n-1; f = f+n; end end end end t = t-1; f = f-1; Vert = Vert(1:t,:); Facets = Facets(1:f,:); fvd = [139/255*ones(f,1) 69/255*ones(f,1) 19/255*ones(f,1)]; figure(fig) plot3(Vert(1,1),Vert(1,2),Vert(1,3)) patch('Vertices',Vert,'Faces',Facets,'FaceVertexCData',fvd,'FaceColor','flat') alpha(alp) axis equal grid on view(-37.5,30) ================================================ FILE: src/plotting/plot_cylinder_model.m ================================================ function plot_cylinder_model(cylinder,Color,fig,nf,alp,Ind) % --------------------------------------------------------------------- % PLOT_CYLINDER_MODEL.M Plots the given cylinder model % % Version 1.2.0 % Latest update 3 Aug 2021 % % Copyright (C) 2013-2021 Pasi Raumonen % --------------------------------------------------------------------- % Plots the cylinder model. % cylinder Structure array containin the cylinder info % (radius, length, start, axis, BranchOrder) % fig Figure number % nf Number of facets in the cyliders (in the thickest cylinder, % scales down with radius to 4 which is the minimum) % alp Alpha value (1 = no trasparency, 0 = complete transparency) % Color If equals to "order", colors the cylinders based on branching % order, otherwise colors each branch with unique color % Ind Indexes of cylinders to be plotted from a subset of cylinders % (Optional, if not given then all cylinders are plotted) % Changes from version 1.1.0 to 1.2.0, 3 Aug 2021: % 1) Changed the surface plot ("patch") so that the edges are not plotted % with separate color, so the surface looks more smooth. Similarly added % shading. (These are added at the end of the file) % 2) Added cylinder branch "Bran" and branch order "BOrd" vectors where the % coloring options are defined to prevent some errors % Changes from version 1.0.0 to 1.1.0, 13 July 2020: % 1) Added option for choosing the coloring based either on branch order or % unique color for each branch % 2) Removed the possibility of the input "cylinder" being a matrix % 3) Added default values for inputs n = nargin; if n < 5 alp = 1; if n < 4 nf = 20; if n < 3 fig = 1; if n == 1 Color = 'order'; end end end end Rad = cylinder.radius; Len = cylinder.length; Sta = cylinder.start; %Sta = Sta-Sta(1,:); Axe = cylinder.axis; if strcmp(Color,'order') BOrd = cylinder.BranchOrder; Bran = cylinder.branch; end if strcmp(Color,'branch') Bran = cylinder.branch; BOrd = cylinder.BranchOrder; end if nargin == 6 Rad = Rad(Ind); Len = Len(Ind); Sta = Sta(Ind,:); Axe = Axe(Ind,:); BOrd = BOrd(Ind); if strcmp(Color,'branch') Bran = Bran(Ind); end end nc = size(Rad,1); % Number of cylinder if strcmp(Color,'order') Color = 1; % Color the cylinders in branches based on the branch order col = [ 0.00 0.00 1.00 0.00 0.50 0.00 1.00 0.00 0.00 0.00 0.75 0.75 0.75 0.00 0.75 0.75 0.75 0.00 0.25 0.25 0.25 0.75 0.25 0.25 0.95 0.95 0.00 0.25 0.25 0.75 0.75 0.75 0.75 0.00 1.00 0.00 0.76 0.57 0.17 0.54 0.63 0.22 0.34 0.57 0.92 1.00 0.10 0.60 0.88 0.75 0.73 0.10 0.49 0.47 0.66 0.34 0.65 0.99 0.41 0.23]; col = repmat(col,[10,1]); elseif strcmp(Color,'branch') Color = 0; % Color the cylinders in branches with an unique color of each branch N = double(max(Bran)); col = rand(N,3); Par = cylinder.parent; for i = 2:nc if Par(i) > 0 && Bran(Par(i)) ~= Bran(i) C = col(Bran(Par(i)),:); c = col(Bran(i),:); while sum(abs(C-c)) < 0.2 c = rand(1,3); end col(Bran(i),:) = c; end end end Cir = cell(nf,2); for i = 4:nf B = [cos((1/i:1/i:1)*2*pi)' sin((1/i:1/i:1)*2*pi)' zeros(i,1)]; T = [cos((1/i:1/i:1)*2*pi)' sin((1/i:1/i:1)*2*pi)' ones(i,1)]; Cir{i,1} = [B; T]; Cir{i,2} = [(1:1:i)' (i+1:1:2*i)' [(i+2:1:2*i)'; i+1] [(2:1:i)'; 1]]; end Vert = zeros(2*nc*(nf+1),3); Facets = zeros(nc*(nf+1),4); fvd = zeros(nc*(nf+1),3); t = 1; f = 1; % Scale, rotate and translate the standard cylinders for i = 1:nc n = ceil(sqrt(Rad(i)/Rad(1))*nf); n = min(n,nf); n = max(n,4); C = Cir{n,1}; % Scale C(:,1:2) = Rad(i)*C(:,1:2); C(n+1:end,3) = Len(i)*C(n+1:end,3); % Rotate ang = real(acos(Axe(i,3))); Axis = cross([0 0 1]',Axe(i,:)'); Rot = rotation_matrix(Axis,ang); C = (Rot*C')'; % Translate C = mat_vec_subtraction(C,-Sta(i,:)); Vert(t:t+2*n-1,:) = C; Facets(f:f+n-1,:) = Cir{n,2}+t-1; if Color == 1 fvd(f:f+n-1,:) = repmat(col(BOrd(i)+1,:),[n 1]); else fvd(f:f+n-1,:) = repmat(col(Bran(i),:),[n 1]); end t = t+2*n; f = f+n; end t = t-1; f = f-1; Vert = Vert(1:t,:); Facets = Facets(1:f,:); fvd = fvd(1:f,:); figure(fig) plot3(Vert(1,1),Vert(1,2),Vert(1,3)) patch('Vertices',Vert,'Faces',Facets,'FaceVertexCData',fvd,'FaceColor','flat') alpha(alp) axis equal grid on view(-37.5,30) shading flat lightangle(gca,-45,30) lighting gouraud ================================================ FILE: src/plotting/plot_cylinder_model2.m ================================================ function plot_cylinder_model2(cylinder,fig,nf,alp,Ind) % Plots the cylinder model. % cylinder Structure array containin the cylinder info % (radius, length, start, axis, BranchOrder) % fig Figure number % nf Number of facets in the cyliders (in the thickest cylinder, % scales down with radius to 4 which is the minimum) % alp Alpha value (1 = no trasparency, 0 = complete transparency) % Ind Indexes of cylinders to be plotted from a subset of cylinders % (Optional, if not given then all cylinders are plotted) Rad = cylinder.radius; Rad2 = cylinder.TopRadius; Len = cylinder.length; Sta = cylinder.start; Sta = mat_vec_subtraction(Sta,Sta(1,:)); Axe = cylinder.axis; BOrd = cylinder.BranchOrder; if nargin == 5 Rad = Rad(Ind); Len = Len(Ind); Sta = Sta(Ind,:); Axe = Axe(Ind,:); BOrd = BOrd(Ind); end nc = size(Rad,1); col = [ 0.00 0.00 1.00 0.00 0.50 0.00 1.00 0.00 0.00 0.00 0.75 0.75 0.75 0.00 0.75 0.75 0.75 0.00 0.25 0.25 0.25 0.75 0.25 0.25 0.95 0.95 0.00 0.25 0.25 0.75 0.75 0.75 0.75 0.00 1.00 0.00 0.76 0.57 0.17 0.54 0.63 0.22 0.34 0.57 0.92 1.00 0.10 0.60 0.88 0.75 0.73 0.10 0.49 0.47 0.66 0.34 0.65 0.99 0.41 0.23]; N = max(BOrd)+1; if N <= 20 col = col(1:N,:); else m = ceil(N/20); col = repmat(col,[m,1]); col = col(1:N,:); end Cir = cell(nf,2); for i = 4:nf B = [cos((1/i:1/i:1)*2*pi)' sin((1/i:1/i:1)*2*pi)' zeros(i,1)]; T = [cos((1/i:1/i:1)*2*pi)' sin((1/i:1/i:1)*2*pi)' ones(i,1)]; Cir{i,1} = [B; T]; Cir{i,2} = [(1:1:i)' (i+1:1:2*i)' [(i+2:1:2*i)'; i+1] [(2:1:i)'; 1]]; end Vert = zeros(2*nc*(nf+1),3); Facets = zeros(nc*(nf+1),4); fvd = zeros(nc*(nf+1),3); t = 1; f = 1; % Scale, rotate and translate the standard cylinders for i = 1:nc n = ceil(sqrt(Rad(i)/Rad(1))*nf); n = min(n,nf); n = max(n,4); C = Cir{n,1}; % Scale m = size(C,1); C(1:m/2,1:2) = Rad(i)*C(1:m/2,1:2); C(m/2+1:m,1:2) = Rad2(i)*C(m/2+1:m,1:2); C(n+1:end,3) = Len(i)*C(n+1:end,3); % Rotate ang = real(acos(Axe(i,3))); Axis = cross([0 0 1]',Axe(i,:)'); Rot = rotation_matrix(Axis,ang); C = (Rot*C')'; % Translate C = mat_vec_subtraction(C,-Sta(i,:)); Vert(t:t+2*n-1,:) = C; Facets(f:f+n-1,:) = Cir{n,2}+t-1; fvd(f:f+n-1,:) = repmat(col(BOrd(i)+1,:),[n 1]); t = t+2*n; f = f+n; end t = t-1; f = f-1; Vert = Vert(1:t,:); Facets = Facets(1:f,:); fvd = fvd(1:f,:); figure(fig) plot3(Vert(1),Vert(2),Vert(3)) patch('Vertices',Vert,'Faces',Facets,'FaceVertexCData',fvd,'FaceColor','flat') alpha(alp) axis equal grid on view(-37.5,30) ================================================ FILE: src/plotting/plot_distribution.m ================================================ function plot_distribution(QSM,fig,rela,cumu,dis,dis2,dis3,dis4) % --------------------------------------------------------------------- % PLOT_DISTRIBUTION Plots the specified distribution(s) in the % "treedata" field of the QSM structure array. % % Version 1.1.0 % Latest update 3 May 2022 % % Copyright (C) 2020-2022 Pasi Raumonen % --------------------------------------------------------------------- % % Inputs: % QSM The output of treeqsm function, may contain multiple models if % only one distribution. If multiple distributions are plotted, % then only one model. % fig Figure number % rela If rela = 1, then plots relative values (%), otherwise plots % absolute values % cumu If cumu = 1, then plot cumulative distribution % dis Distribution to be plotted, string name, e.g. 'VolCylDia'. % The name string is the one used in the "treedata" % dis2 Optional, Second distribution to be plotted. Notice with more % than one distribution, only one model. % dis3 Optional, Third distribution to be plotted % dis4 Optional, Fourth distribution to be plotted % --------------------------------------------------------------------- % Changes from version 1.0.0 to 1.1.0, 3 May 2022: % 1) Added new input "cum" for plottig the distributions as cumulative. % 2) Added return if distributions are empty or all zero % Generate strings for title, xlabel and ylabel: if strcmp(dis(1:3),'Vol') str = 'volume'; ylab = 'Volume (L)'; elseif strcmp(dis(1:3),'Are') str = 'area'; ylab = 'Area (m^2)'; elseif strcmp(dis(1:3),'Len') str = 'length'; ylab = 'Length (m)'; elseif strcmp(dis(1:3),'Num') str = 'number'; ylab = 'Number'; end if strcmp(dis(end-2:end),'Dia') str2 = 'diameter'; xlab = 'diameter (cm)'; elseif strcmp(dis(end-2:end),'Hei') str2 = 'height'; xlab = 'height (m)'; elseif strcmp(dis(end-2:end),'Ord') str2 = 'order'; xlab = 'order'; elseif strcmp(dis(end-2:end),'Ang') str2 = 'angle'; xlab = 'angle (deg)'; elseif strcmp(dis(end-2:end),'Azi') str2 = 'azimuth direction'; xlab = 'azimuth direction (deg)'; elseif strcmp(dis(end-2:end),'Zen') str2 = 'zenith direction'; xlab = 'zenith direction (deg)'; end % Collect the distributions if nargin == 5 % Multiple QSMs, one and the same distribution m = max(size(QSM)); D = QSM(1).treedata.(dis); n = size(D,2); for i = 2:m d = QSM(i).treedata.(dis); k = size(d,2); if k > n n = k; D(m,n) = 0; D(i,1:n) = d; elseif k < n D(i,1:k) = d; else D(i,:) = d; end end D = D(:,1:n); else % One QSM, multiple distributions of the same type % (e.g. diameter distributions: 'NumCylDia', 'VolCylDia' and 'LenCylDia') m = nargin-4; D = QSM.treedata.(dis); n = size(D,2); if n == 0 || all(D == 0) return end for i = 2:m if i == 2 D(m,n) = 0; D(i,:) = QSM.treedata.(dis2); elseif i == 3 D(i,:) = QSM.treedata.(dis3); else D(i,:) = QSM.treedata.(dis4); end end end if rela % use relative value for i = 1:m D(i,:) = D(i,:)/sum(D(i,:))*100; end ylab = 'Relative value (%)'; end if cumu % use cumulative distribution D = cumsum(D,2); end % Generate the bar plot figure(fig) if strcmp(dis(end-3:end),'hAzi') || strcmp(dis(end-3:end),'1Azi') || strcmp(dis(end-2:end),'Azi') bar(-170:10:180,D') elseif strcmp(dis(end-2:end),'Zen') || strcmp(dis(end-2:end),'Ang') bar(10:10:10*n,D') else bar(1:1:n,D') end % Generate the title of the plot if strcmp(dis(end-2:end),'Ord') && ~strcmp(dis(1:3),'Num') tit = ['Branch ',str,' per branching order']; elseif strcmp(dis(end-2:end),'Ord') tit = 'Number of branches per branching order'; elseif strcmp(dis(1:3),'Num') tit = ['Number of branches per ',str2,' class']; elseif strcmp(dis(end-3),'h') || strcmp(dis(end-3),'1') tit = ['Branch ',str,' per ',str2,' class']; else tit = ['Tree segment ',str,' per ',str2,' class']; end n = nargin; if n > 5 if ~strcmp(dis(1:3),dis2(1:3)) if strcmp(dis(4),'C') tit = 'Tree segment distribution'; else tit = 'Branch distribution'; end elseif n > 6 if ~strcmp(dis(1:3),dis3(1:3)) if strcmp(dis(4),'C') tit = 'Tree segment distribution'; else tit = 'Branch distribution'; end elseif n > 7 if ~strcmp(dis(1:3),dis4(1:3)) if strcmp(dis(4),'C') tit = 'Tree segment distribution'; else tit = 'Branch distribution'; end end end end end title(tit) % Generate the x-axis label if strcmp(dis(end-5:end-3),'Cyl') xlab = ['Cylinder ',xlab]; else xlab = ['Branch ',xlab]; end xlabel(xlab) % Generate the y-axis label ylabel(ylab); % Tight axes and grid lines axis tight grid on m = max(size(QSM)); % Add legends, if needed if m > 1 L = cell(m,1); for i = 1:m L{i} = ['model',num2str(i)]; end legend(L,'location','best') elseif nargin > 5 m = nargin-4; L = cell(m,1); for i = 1:m if i == 1 L{i} = dis(1:end-3); elseif i == 2 L{i} = dis2(1:end-3); elseif i == 3 L{i} = dis3(1:end-3); else L{i} = dis4(1:end-3); end end legend(L,'location','best') end ================================================ FILE: src/plotting/plot_large_point_cloud.m ================================================ function plot_large_point_cloud(P,fig,ms,rel) % Plots a random subset of a large point cloud. The user specifies the % relative size of the subset (input "rel" given as in percentage points). % % Inputs: % P Point cloud % fig Figure number % ms Marker size % rel Subset size in percentage points (%). % E.g. if rel = 12, then about 12 % poinst are plotted rel = 0.5/(1-rel/100); % Compute a coeffiecient I = logical(round(rel*rand(size(P,1),1))); plot_point_cloud(P(I,:),fig,ms) ================================================ FILE: src/plotting/plot_models_segmentations.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function plot_models_segmentations(P,cover,segment,cylinder,trunk,triangulation) % --------------------------------------------------------------------- % PLOT_MODELS_SEGMENTATION.M Plots the segmented point clouds and % cylinder/triangulation models % % Version 1.1.0 % Latest update 13 July 2020 % % Copyright (C) 2013-2020 Pasi Raumonen % --------------------------------------------------------------------- % Inputs: % P Point cloud % cover cover-structure array % segment segment-structure array % cylinder cylinder-structure array % trunk point cloud of the trunk % triangulation triangulation-structure array % Changes from version 1.0.0 to 1.1.0, 13 July 2020: % 1) plots now figure 1 and 2 with two subplots; in the first the colors % are based on branching order and in the second they are based on % branch %% figure 1: branch-segmented point cloud % colors denote the branching order and branches figure(1) subplot(1,2,1) plot_branch_segmentation(P,cover,segment,'order') subplot(1,2,2) plot_branch_segmentation(P,cover,segment,'branch') %% figure 2: cylinder model % colors denote the branching order and branches Sta = cylinder.start; P = P-Sta(1,:); if nargin > 5 trunk = trunk-Sta(1,:); Vert = double(triangulation.vert); Vert = Vert-Sta(1,:); end Sta = Sta-Sta(1,:); cylinder.start = Sta; figure(2) subplot(1,2,1) plot_cylinder_model(cylinder,'order',2,10) subplot(1,2,2) plot_cylinder_model(cylinder,'branch',2,10) %% figure 3, segmented point cloud and cylinder model plot_branch_segmentation(P,cover,segment,'order',3,1) hold on plot_cylinder_model(cylinder,'order',3,10,0.7) hold off if nargin > 4 %% figure 4, triangulation model (bottom) and cylinder model (top) % of the stem Facets = double(triangulation.facet); CylInd = triangulation.cylind; fvd = triangulation.fvd; if max(size(Vert)) > 5 Bran = cylinder.branch; nc = size(Bran,1); ind = (1:1:nc)'; C = ind(Bran == 1); n = size(trunk,1); I = logical(round(0.55*rand(n,1))); figure(4) point_cloud_plotting(trunk(I,:),4,3) patch('Vertices',Vert,'Faces',Facets,'FaceVertexCData',fvd,... 'FaceColor','flat') alpha(1) hold on plot_cylinder_model(cylinder,'order',4,20,1,(CylInd:C(end))) axis equal hold off else disp('No triangulation model generated!') end end ================================================ FILE: src/plotting/plot_point_cloud.m ================================================ function plot_point_cloud(P,fig,ms,col) % Plots the given point cloud. % % PLOT_POINT_CLOUD(P,FIG,MS,col) plots point cloud P in figure FIG using % marker size MS and point color COL (string). P is a 2- or 3-column matrix % where the first, second and third column gives the X-, Y-, and % Z-coordinates of the points. % % PLOT_POINT_CLOUD(P,FIG) plots point cloud P in figure FIG using % marker size 3 and color blue ('b'). % % PLOT_POINT_CLOUD(P) plots point cloud P in figure 1 using marker size 3 % and color blue ('b'). if nargin == 1 fig = 1; ms = 3; col = 'b'; elseif nargin == 2 ms = 3; col = 'b'; elseif nargin == 3 col = 'b'; end if ms == 0 ms = 3; end col = ['.',col]; figure(fig) if size(P,2) == 3 plot3(P(:,1),P(:,2),P(:,3),col,'Markersize',ms) elseif size(P,2) == 2 plot(P(:,1),P(:,2),col,'Markersize',ms) end axis equal ================================================ FILE: src/plotting/plot_scatter.m ================================================ function plot_scatter(P,C,fig,ms) % A scatter plot where the color of each 2d or 3d point is specified by a % number. % % Inputs: % P point cloud % C color data (vector, value for each point in P) % fig figure number % ms marker size S = normalize(C); figure(fig) if size(P,2) == 3 scatter3(P(:,1),P(:,2),P(:,3),ms*ones(size(P,1),1),C,'filled') %scatter3(P(:,1),P(:,2),P(:,3),ms*S.*ones(size(P,1),1),C,'filled') elseif size(P,2) == 2 scatter(P(:,1),P(:,2),ms*S.*ones(size(P,1),1),C,'filled') end axis equal if size(C,2) == 1 colormap(jet(25)) %caxis([0 max(C)]) if min(C) < max(C) caxis([min(C) max(C)]) end colorbar end ================================================ FILE: src/plotting/plot_segments.m ================================================ function plot_segments(P,Bal,fig,ms,seg1,seg2,seg3,seg4,seg5) % Plots point cloud segments/subsets defined as subsets of cover sets. % If the subsets intersect, then assiggnes the common points to the % segments given first. % % Inputs % P Point cloud % Bal Cover sets. Bal = cover.ball % fig figure number % seg1 Segment/subset 1, color blue % seg2 (Optional) Segment/subset 2, color red % seg3 (Optional) Segment/subset 3, color green % seg4 (Optional) Segment/subset 4, color cyan % seg5 (Optional) Segment/subset 5, color magenta if nargin == 5 S1 = unique(vertcat(Bal{seg1})); figure(fig) plot3(P(S1,1),P(S1,2),P(S1,3),'b.','Markersize',ms) axis equal elseif nargin == 6 S1 = unique(vertcat(Bal{seg1})); S2 = unique(vertcat(Bal{seg2})); S2 = setdiff(S2,S1); figure(fig) plot3(P(S1,1),P(S1,2),P(S1,3),'b.','Markersize',1.5*ms) hold on plot3(P(S2,1),P(S2,2),P(S2,3),'r.','Markersize',ms) axis equal hold off elseif nargin == 7 S1 = unique(vertcat(Bal{seg1})); S2 = unique(vertcat(Bal{seg2})); S3 = unique(vertcat(Bal{seg3})); S2 = setdiff(S2,S1); S3 = setdiff(S3,S1); S3 = setdiff(S3,S2); figure(fig) plot3(P(S1,1),P(S1,2),P(S1,3),'b.','Markersize',ms) hold on plot3(P(S2,1),P(S2,2),P(S2,3),'r.','Markersize',ms) plot3(P(S3,1),P(S3,2),P(S3,3),'g.','Markersize',ms) axis equal hold off elseif nargin == 8 S1 = unique(vertcat(Bal{seg1})); S2 = unique(vertcat(Bal{seg2})); S3 = unique(vertcat(Bal{seg3})); S4 = unique(vertcat(Bal{seg4})); S2 = setdiff(S2,S1); S3 = setdiff(S3,S1); S3 = setdiff(S3,S2); S4 = setdiff(S4,S1); S4 = setdiff(S4,S2); S4 = setdiff(S4,S3); figure(fig) plot3(P(S1,1),P(S1,2),P(S1,3),'b.','Markersize',ms) hold on plot3(P(S2,1),P(S2,2),P(S2,3),'r.','Markersize',ms) plot3(P(S3,1),P(S3,2),P(S3,3),'g.','Markersize',ms) plot3(P(S4,1),P(S4,2),P(S4,3),'c.','Markersize',ms) axis equal hold off elseif nargin == 9 S1 = unique(vertcat(Bal{seg1})); S2 = unique(vertcat(Bal{seg2})); S3 = unique(vertcat(Bal{seg3})); S4 = unique(vertcat(Bal{seg4})); S5 = unique(vertcat(Bal{seg5})); S2 = setdiff(S2,S1); S3 = setdiff(S3,S1); S3 = setdiff(S3,S2); S4 = setdiff(S4,S1); S4 = setdiff(S4,S2); S4 = setdiff(S4,S3); S5 = setdiff(S5,S1); S5 = setdiff(S5,S2); S5 = setdiff(S5,S3); S5 = setdiff(S5,S4); figure(fig) plot3(P(S1,1),P(S1,2),P(S1,3),'b.','Markersize',ms) hold on plot3(P(S2,1),P(S2,2),P(S2,3),'r.','Markersize',ms) plot3(P(S3,1),P(S3,2),P(S3,3),'g.','Markersize',ms) plot3(P(S4,1),P(S4,2),P(S4,3),'c.','Markersize',ms) plot3(P(S5,1),P(S5,2),P(S5,3),'m.','Markersize',ms) axis equal hold off end ================================================ FILE: src/plotting/plot_segs.m ================================================ function plot_segs(P,comps,fig,ms,Bal) % Plots the point cloud segments given in the cell array "comps". % If 4 inputs, cells contain the point indexes. If 5 input, cells contain % the indexes of the cover sets given by "Bal". % "fig" is the figure number and "ms" is the marker size. col = [ 0.00 0.00 1.00 0.00 0.50 0.00 1.00 0.00 0.00 0.00 0.75 0.75 0.75 0.00 0.75 0.75 0.75 0.00 0.25 0.25 0.25 0.75 0.25 0.25 0.95 0.95 0.00 0.25 0.25 0.75 0.75 0.75 0.75 0.00 1.00 0.00 0.76 0.57 0.17 0.54 0.63 0.22 0.34 0.57 0.92 1.00 0.10 0.60 0.88 0.75 0.73 0.10 0.49 0.47 0.66 0.34 0.65 0.99 0.41 0.23]; n = max(size(comps)); if n < 100 col = repmat(col,[ceil(n/20),1]); else col = rand(n,3); end S = comps{1}; if iscell(S) n = size(comps,1); for i = 1:n S = comps{i}; if ~isempty(S) S = vertcat(S{:}); comps{i} = S; else comps{i} = zeros(0,1); end end end if nargin == 4 % Plot the segments figure(fig) C = comps{1}; plot3(P(C,1),P(C,2),P(C,3),'.','Color',col(1,:),'Markersize',ms) hold on for i = 2:n C = comps{i}; plot3(P(C,1),P(C,2),P(C,3),'.','Color',col(i,:),'Markersize',ms) end axis equal hold off pause(0.1) else np = size(P,1); D = false(np,1); C = unique(vertcat(Bal{comps{1}})); figure(fig) plot3(P(C,1),P(C,2),P(C,3),'.','Color',col(1,:),'Markersize',ms) hold on for i = 2:n if ~isempty(comps{i}) C = unique(vertcat(Bal{comps{i}})); I = D(C); C = C(~I); D(C) = true; plot3(P(C,1),P(C,2),P(C,3),'.','Color',col(i,:),'Markersize',ms) end end hold off axis equal pause(0.1) end ================================================ FILE: src/plotting/plot_spreads.m ================================================ function plot_spreads(treedata,fig,lw,rel) % Plots the spreads as a polar plot with different height layers presented % with different colors. Inputs "fig" and "lw" define the figure number and % the line width. Input Rel = 1 specifies relative spreads, i.e. the % maximum spread is one, otherwise use the actual values. if nargin == 2 lw = 1; rel = 1; elseif nargin == 3 rel = 1; end spreads = treedata.spreads; figure(fig) n = size(spreads,1); col = zeros(n,3); col(:,1) = (0:1/n:(n-1)/n)'; col(:,3) = (1:-1/n:1/n)'; d = max(max(spreads)); D = [spreads(1,end) spreads(1,:)]; if rel polarplot(D/d,'-','Color',col(1,:),'Linewidth',lw) else polarplot(D,'-','Color',col(1,:),'Linewidth',lw) end hold on for i = 1:n D = [spreads(i,end) spreads(i,:)]; if rel polarplot(D/d,'-','Color',col(i,:),'Linewidth',lw) else polarplot(D,'-','Color',col(i,:),'Linewidth',lw) end end hold off if rel rlim([0 1]) else rlim([0 d]) end ================================================ FILE: src/plotting/plot_tree_structure.m ================================================ function plot_tree_structure(P,cover,segment,fig,ms,segind,BO) % --------------------------------------------------------------------- % PLOT_TREE_STRUCTURE.M Plots branch-segmented point cloud with unique % color for each branching order % % Version 1.1.0 % Latest update 13 July 2020 % % Copyright (C) 2013-2020 Pasi Raumonen % --------------------------------------------------------------------- % % Blue = trunk, Green = 1st-order branches, Red = 2nd-order branches, etc. % If segind = 1 and BO = 0, then plots the stem. If segind = 1 and BO = 1, % then plots the stem and the 1st-order branches. If segind = 1 and % BO >= maximum branching order or BO input is not given, then plots the % whole tree. If segind = 2 and BO is not given or it is high enough, then % plots the branch whose index is 2 and all its sub-branches. % % Inputs % P Point cloud % cover Cover sets structure % Segs Segments structure % fig Figure number % ms Marker size % segind Index of the segment where the plotting of tree structure % starts. % BO How many branching orders are plotted. 0 = stem, 1 = 1st order, etc % % Changes from version 1.0.0 to 1.1.0, 13 July 2020: % 1) Added option for choosing the coloring based either on branch order or % unique color for each branch n = nargin; if n < 7 BO = 1000; if n < 6 segind = 1; if n < 5 ms = 1; if n == 3 fig = 1; end end end end Bal = cover.ball; Segs = segment.segments; SChi = segment.ChildSegment; col = [ 0.00 0.00 1.00 0.00 0.50 0.00 1.00 0.00 0.00 0.00 0.75 0.75 0.75 0.00 0.75 0.75 0.75 0.00 0.25 0.25 0.25 0.75 0.25 0.25 0.95 0.95 0.00 0.25 0.25 0.75 0.75 0.75 0.75 0.00 1.00 0.00 0.76 0.57 0.17 0.54 0.63 0.22 0.34 0.57 0.92 1.00 0.10 0.60 0.88 0.75 0.73 0.10 0.49 0.47 0.66 0.34 0.65 0.99 0.41 0.23]; col = repmat(col,[1000,1]); if iscell(Segs{1}) n = max(size(Segs)); Seg = cell(n,1); for i = 1:n m = size(Segs{i},1); S = zeros(0); for j = 1:m s = Segs{i}(j); s = s{:}; S = [S; s]; end Seg{i} = S; end else Seg = Segs; end S = vertcat(Bal{Seg{segind}}); figure(fig) plot3(P(S,1),P(S,2),P(S,3),'.','Color',col(1,:),'Markersize',ms) axis equal %forb = S; if BO > 0 hold on c = SChi{segind}; order = 1; while (order <= BO) && (~isempty(c)) C = vertcat(Bal{vertcat(Seg{c})}); %C = setdiff(C,forb); figure(fig) plot3(P(C,1),P(C,2),P(C,3),'.','Color',col(order+1,:),'Markersize',ms) axis equal c = unique(vertcat(SChi{c})); order = order+1; %forb = union(forb,C); end hold off end ================================================ FILE: src/plotting/plot_tree_structure2.m ================================================ function plot_tree_structure2(P,Bal,Segs,SChi,fig,ms,BO,segind) % Plots the branch-segmented tree point cloud so that each branching order % has its own color Blue = trunk, green = 1st-order branches, % red = 2nd-order branches, etc. % % Inputs % P Point cloud % Bal Cover sets, Bal = cover.bal % Segs Segments, Segs = segment.segments % SChi Child segments, SChi = segment.ChildSegment % fig Figure number % ms Marker size % BO How many branching orders are plotted. 0 = all orders % segind Index of the segment where the plotting of tree structure % starts. If segnum = 1 and BO = 0, then plots the whole % tree. If segnum = 1 and B0 = 2, then plots the stem and % the 1st-order branches. If segnum = 2 and BO = 0, then % plots the branch whose index is 2 and all its sub-branches. col = [ 0.00 0.00 1.00 0.00 0.50 0.00 1.00 0.00 0.00 0.00 0.75 0.75 0.75 0.00 0.75 0.75 0.75 0.00 0.25 0.25 0.25 0.75 0.25 0.25 0.95 0.95 0.00 0.25 0.25 0.75 0.75 0.75 0.75 0.00 1.00 0.00 0.76 0.57 0.17 0.54 0.63 0.22 0.34 0.57 0.92 1.00 0.10 0.60 0.88 0.75 0.73 0.10 0.49 0.47 0.66 0.34 0.65 0.99 0.41 0.23]; col = repmat(col,[1000,1]); if iscell(Segs{1}) n = max(size(Segs)); Seg = cell(n,1); for i = 1:n m = size(Segs{i},1); S = zeros(0); for j = 1:m s = Segs{i}(j); s = s{:}; S = [S; s]; end Seg{i} = S; end else Seg = Segs; end if BO == 0 BO = 1000; end S = vertcat(Bal{Seg{segind}}); figure(fig) plot3(P(S,1),P(S,2),P(S,3),'.','Color',col(1,:),'Markersize',ms) axis equal forb = S; if BO > 1 %pause hold on c = SChi{segind}; i = 2; while (i <= BO) && (~isempty(c)) C = vertcat(Bal{unique(vertcat(Seg{c}))}); C = setdiff(C,forb); figure(fig) plot3(P(C,1),P(C,2),P(C,3),'.','Color',col(i,:),'Markersize',ms) axis equal c = unique(vertcat(SChi{c})); i = i+1; forb = union(forb,C); if i <= BO %pause end end hold off end ================================================ FILE: src/plotting/plot_triangulation.m ================================================ function plot_triangulation(QSM,fig,nf,AllTree) % Plots the triangulation model of the stem's bottom part and the cylinder % model (rest of the stem or the rest of the tree). The optional inputs % "fig", "nf", "All" are the figure number, number of facets for the % cylinders, and if All = 1, then all the tree is plotted. n = nargin; if n < 4 AllTree = 0; if n < 3 nf = 20; if n == 1 fig = 1; end end end Vert = double(QSM.triangulation.vert); Facets = double(QSM.triangulation.facet); CylInd = QSM.triangulation.cylind; fvd = QSM.triangulation.fvd; Bran = QSM.cylinder.branch; nc = size(Bran,1); ind = (1:1:nc)'; C = ind(Bran == 1); figure(fig) patch('Vertices',Vert,'Faces',Facets,'FaceVertexCData',fvd,'FaceColor','flat') hold on if AllTree Ind = (CylInd:1:nc)'; else Ind = (CylInd:1:C(end))'; end plot_cylinder_model(QSM.cylinder,fig,nf,1,'branch',Ind) axis equal hold off alpha(1) ================================================ FILE: src/plotting/point_cloud_plotting.m ================================================ function point_cloud_plotting(P,fig,ms,Bal,Sub) % Plots the given point cloud "P". With additional inputs one can plot only % those points that are included in the cover sets "Bal" or in the % subcollection "Sub" of the cover sets. % "fig" and "ms" are the figure number and marker size. if nargin == 2 ms = 3; elseif ms == 0 ms = 3; end if nargin < 4 figure(fig) if size(P,2) == 3 plot3(P(:,1),P(:,2),P(:,3),'.b','Markersize',ms) elseif size(P,2) == 2 plot(P(:,1),P(:,2),'.b','Markersize',ms) end axis equal elseif nargin == 4 I = vertcat(Bal{:}); figure(fig) plot3(P(I,1),P(I,2),P(I,3),'.b','Markersize',ms) axis equal else if iscell(Sub) S = vertcat(Sub{:}); Sub = vertcat(S{:}); I = vertcat(Bal{Sub}); figure(fig) plot3(P(I,1),P(I,2),P(I,3),'.b','Markersize',ms) axis equal else I = vertcat(Bal{Sub}); figure(fig) plot3(P(I,1),P(I,2),P(I,3),'.b','Markersize',ms) axis equal end end ================================================ FILE: src/select_optimum.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function [TreeData,OptModels,OptInputs,OptQSM] = ... select_optimum(QSMs,Metric,savename) % --------------------------------------------------------------------- % SELECT_OPTIMUM.M Selects optimum models based on point-cylinder model % distances or standard deviations of attributes % % Version 1.4.0 % Latest update 2 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % % Works for single or multiple tree cases where the input QSMs contains % multiple models for the same tree with different inputs and multiple runs % with the same inputs. Allows the user to select from 34 different metrics % for the optimization. These include average point-model distances from % all, trunk, branch, 1st-order branch and 2nd-order branch cylinders plus % some combinations where e.g. "mean trunk and mean branch" or "mean trunk % and mean 1st-order branch" point-model distances are added together. % Similarly for the maximum point-model distances and the sums of mean and % the maximum distances. % The difference between "all" and "trunk and branch" is that "all" % is the average of all cylinder distances which usually emphasizes % branch cylinder as there usually much more those, whereas "trunk and branch" % gives equal weight for trunk and branch cylinders. % The other options for metric are based on minimizing the standard deviations % of volumes (total, trunk, branch, trunk+branch which have equal emphasis % between trunk and branches), lengths (trunk, branches) or total number of % branches. Here the idea is that if the variance (standard deviation) of % some attribute between models with the same inputs is small, then it % indicates some kind of robustness which might indicate that the inputs % are close to optimal. % The optimal single model out of the models with the optimal inputs is % selected based on the minimum mean point-model-distance. % % Inputs: % QSMs Contain all the QSMs, possibly from multiple trees % Metric Optional input, Metric to be minimized: % CYLINDER-DISTANCE METRICS: % 'all_mean_dis' = mean distances from (mdf) all cylinders, DEFAULT option % 'trunk_mean_dis' = mdf trunk cylinders, % 'branch_mean_dis' = mdf all branch cylinders, % '1branch_mean_dis' = mdf 1st-order branch cylinders, % '2branch_mean_dis' = mdf 2nd-order branch cylinders, % 'trunk+branch_mean_dis' = mdf trunk + mdf branch cylinders, % 'trunk+1branch_mean_dis' = mdf trunk + mdf 1st-ord branch cyls, % 'trunk+1branch+2branch_mean_dis' = above + mdf 2nd-ord branch cyls % '1branch+2branch_mean_dis' = mdf 1branch cyls + mdf 2branch cyls % 'all_max_dis' = maximum distances from (mdf) all cylinders % 'trunk_max_dis' = mdf trunk cylinders, % 'branch_max_dis' = mdf all branch cylinders, % '1branch_max_dis' = mdf 1st-order branch cylinders, % '2branch_max_dis' = mdf 2nd-order branch cylinders, % 'trunk+branch_max_dis' = mdf trunk + mdf branch cylinders, % 'trunk+1branch_max_dis' = mdf trunk + mdf 1st-ord branch cyls, % 'trunk+1branch+2branch_max_dis' = above + mdf 2nd-ord branch cyls. % '1branch+2branch_max_dis' = mdf 1branch cyls + mdf 2branch cyls % 'all_mean+max_dis' = mean + maximum distances from (m+mdf) all cylinders % 'trunk_mean+max_dis' = (m+mdf) trunk cylinders, % 'branch_mean+max_dis' = (m+mdf) all branch cylinders, % '1branch_mean+max_dis' = (m+mdf) 1st-order branch cylinders, % '2branch_mean+max_dis' = (m+mdf) 2nd-order branch cylinders, % 'trunk+branch_mean+max_dis' = (m+mdf) trunk + (m+mdf) branch cylinders, % 'trunk+1branch_mean+max_dis' = (m+mdf) trunk + (m+mdf) 1branch cyls, % 'trunk+1branch+2branch_mean+max_dis' = above + (m+mdf) 2branch cyls. % '1branch+2branch_mean+max_dis' = (m+mdf) 1branch cyls + (m+mdf) 2branch cyls % STANDARD DEVIATION METRICS: % 'tot_vol_std' = standard deviation of total volume % 'trunk_vol_std' = standard deviation of trunk volume % 'branch_vol_std' = standard deviation of branch volume % 'trunk+branch_vol_std' = standard deviation of trunk plus branch volume % 'tot_are_std' = standard deviation of total area % 'trunk_are_std' = standard deviation of trunk area % 'branch_are_std' = standard deviation of branch area % 'trunk+branch_are_std' = standard deviation of trunk plus branch area % 'trunk_len_std' = standard deviation of trunk length % 'branch_len_std' = standard deviation of branch length % 'branch_num_std' = standard deviation of number of branches % BRANCH-ORDER DISTRIBUTION METRICS: % 'branch_vol_ord3_mean' = mean difference in volume of 1-3 branch orders % 'branch_are_ord3_mean' = mean difference in area of 1-3 branch orders % 'branch_len_ord3_mean' = mean difference in length of 1-3 branch orders % 'branch_num_ord3_mean' = mean difference in number of 1-3 branch orders % 'branch_vol_ord3_max' = max difference in volume of 1-3 branch orders % 'branch_are_ord3_max' = max difference in area of 1-3 branch orders % 'branch_len_ord3_max' = max difference in length of 1-3 branch orders % 'branch_num_ord3_max' = max difference in number of 1-3 branch orders % 'branch_vol_ord6_mean' = mean difference in volume of 1-6 branch orders % 'branch_are_ord6_mean' = mean difference in area of 1-6 branch orders % 'branch_len_ord6_mean' = mean difference in length of 1-6 branch orders % 'branch_num_ord6_mean' = mean difference in number of 1-6 branch orders % 'branch_vol_ord6_max' = max difference in volume of 1-6 branch orders % 'branch_are_ord6_max' = max difference in area of 1-6 branch orders % 'branch_len_ord6_max' = max difference in length of 1-6 branch orders % 'branch_num_ord6_max' = max difference in number of 1-6 branch orders % CYLINDER DISTRIBUTION METRICS: % 'cyl_vol_dia10_mean') = mean diff. in volume of 1-10cm diam cyl classes % 'cyl_are_dia10_mean') = mean diff. in area of 1-10cm diam cyl classes % 'cyl_len_dia10_mean') = mean diff. in length of 1-10cm diam cyl classes % 'cyl_vol_dia10_max') = max diff. in volume of 1-10cm diam cyl classes % 'cyl_are_dia10_max') = max diff. in area of 1-10cm diam cyl classes % 'cyl_len_dia10_max') = max diff. in length of 1-10cm diam cyl classes % 'cyl_vol_dia20_mean') = mean diff. in volume of 1-20cm diam cyl classes % 'cyl_are_dia20_mean') = mean diff. in area of 1-20cm diam cyl classes % 'cyl_len_dia20_mean') = mean diff. in length of 1-20cm diam cyl classes % 'cyl_vol_dia20_max') = max diff. in volume of 1-20cm diam cyl classes % 'cyl_are_dia20_max') = max diff. in area of 1-20cm diam cyl classes % 'cyl_len_dia20_max') = max diff. in length of 1-20cm diam cyl classes % 'cyl_vol_zen_mean') = mean diff. in volume of cyl zenith distribution % 'cyl_are_zen_mean') = mean diff. in area of cyl zenith distribution % 'cyl_len_zen_mean') = mean diff. in length of cyl zenith distribution % 'cyl_vol_zen_max') = max diff. in volume of cyl zenith distribution % 'cyl_are_zen_max') = max diff. in area of cyl zenith distribution % 'cyl_len_zen_max') = max diff. in length of cyl zenith distribution % SURFACE COVERAGE METRICS: % metric to be minimized is 1-mean(surface_coverage) or 1-min(SC) % 'all_mean_surf' = mean surface coverage from (msc) all cylinders % 'trunk_mean_surf' = msc trunk cylinders, % 'branch_mean_surf' = msc all branch cylinders, % '1branch_mean_surf' = msc 1st-order branch cylinders, % '2branch_mean_surf' = msc 2nd-order branch cylinders, % 'trunk+branch_mean_surf' = msc trunk + msc branch cylinders, % 'trunk+1branch_mean_surf' = msc trunk + msc 1st-ord branch cyls, % 'trunk+1branch+2branch_mean_surf' = above + msc 2nd-ord branch cyls % '1branch+2branch_mean_surf' = msc 1branch cyls + msc 2branch cyls % 'all_min_surf' = minimum surface coverage from (msc) all cylinders % 'trunk_min_surf' = msc trunk cylinders, % 'branch_min_surf' = msc all branch cylinders, % '1branch_min_surf' = msc 1st-order branch cylinders, % '2branch_min_surf' = msc 2nd-order branch cylinders, % 'trunk+branch_min_surf' = msc trunk + msc branch cylinders, % 'trunk+1branch_min_surf' = msc trunk + msc 1st-ord branch cyls, % 'trunk+1branch+2branch_min_surf' = above + msc 2nd-ord branch cyls. % '1branch+2branch_min_surf' = msc 1branch cyls + msc 2branch cyls % savename Optional input, name string specifying the name of the saved file % containing the outputs % % Outputs: % TreeData Similar structure array as the "treedata" in QSMs but now each % attribute contains the mean and std computed from the models % with the optimal inputs. Also contains the sensitivities % for the inputs PatchDiam1, PatchDiam2Min, PatchDiam2Max. % Thus for single number attributes (e.g. TotalVolume) there % are five numbers [mean std sensi_PD1 sensi_PD2Min sensi_PD2Max] % OptModels Indexes of the models with the optimal inputs (column 1) and % the index of the optimal single model (column 2) in "QSMs" % for each tree % OptInputs The optimal input parameters for each tree % OptQSMs The single best QSM for each tree, OptQSMs = QSMs(OptModel); % --------------------------------------------------------------------- % Changes from version 1.3.1 to 1.4.0, 2 May 2022: % 1) Added estimation of (relative) sensitivity of the single number % attributes in TreeData for the inputs PatchDiam1, PatchDiam2Min, % PatchDiam2Max. Now TreeData contains also these values as the columns % 3 to 5. % 2) Corrected a small bug in the subfunction "collect_data" (assignment % of values for "CylSurfCov(i,:)"). The bug caused error for QSMs whose % maximum branch order is less than 2. % 3) Bug fix for 3 lines (caused error for some cases and for other cases % the optimal single model was wrongly selected): % [~,T] = min(dist(ind,best)); --> [~,T] = min(Data.CylDist(ind,best)); % Changes from version 1.2.0 to 1.3.0, 4 Aug 2020: % 1) Removed two inputs ("lcyl" and "FilRad") from the inputs to be % optimised. This corresponds to changes in the cylinder fitting. % 2) Added more choices for the optimisation criteria or cost % functions ("metric") that are minimised. There is now 91 metrics and % the new ones include surface coverage based metrics. % Changes from version 1.1.1 to 1.2.0, 4 Feb 2020: % 1) Major change in the structure: subfunctions % 2) Added more choices for the optimisation criteria or cost % functions ("metric") that are minimised. There is now 73 metrics and in % particular the new ones include some area related metrics and branch % and cylinder distribution based metrics. % Changes from version 1.1.0 to 1.1.1, 26 Nov 2019: % 1) Added the "name" of the point cloud from the inputs.name to the output % TreeData as a field. Also now displays the name together with the tree % number. % 2) TreeData contains now correctly fields ("location", "StemTaper", % "VolumeBranchOrder", etc) from the Optimal QSMs. % Changes from version 1.0.0 to 1.1.0, 08 Oct 2019: % 1) Added the posibility to select the optimisation criteria or cost % function ("metric") that is minimised from 34 different options. % Previously only one option was used. The used metric is also included % in "OptInputs" output as one of the fields. % 2) Added OptQSM as one of the outputs %% Select the metric based on the input if nargin > 1 [met,Metric] = select_metric(Metric); else met = 1; Metric = 'all_mean_dis'; end % The metric for selecting the optimal single model from the models with % the optimal inputs is the mean point-model-distance. best = 1; %% Collect data % Find the first non-empty model i = 1; while isempty(QSMs(i).cylinder) i = i+1; end % Determine how many single-number attributes there are in treedata names = fieldnames(QSMs(i).treedata); n = 1; while numel(QSMs(i).treedata.(names{n})) == 1 n = n+1; end n = n-1; Names = names(1:n); L = max(cellfun('length',Names))+1; for i = 1:n name = Names{i}; name(L) = ' '; Names{i} = name; end % Collect data: [treedata,inputs,TreeId,Data] = collect_data(QSMs,names,n); % Trees and their unique IDs TreeIds = unique(TreeId(:,1)); nt = length(TreeIds); % number of trees DataM = zeros(n,nt); DataS = zeros(n,nt); % Standard deviation of tree data for each tree DataM2 = DataM; DataM3 = DataM; DataS2 = DataS; DataS3 = DataS; OptIn = zeros(nt,9); % Optimal input values OptDist = zeros(nt,9); % Smallest metric values % average treedata and inputs for each tree-input-combination: TreeDataAll = zeros(nt,5*5*5,n); Inputs = zeros(nt,5*5*5,3); IndAll = (1:1:size(TreeId,1))'; % Indexes of the optimal single models in QSMs: OptModel = zeros(nt,3); % The indexes of models in QSMs with the optimal inputs (col 1) % and the indexes of the optimal single models (col 2): OptModels = cell(nt,2); NInputs = zeros(nt,1); %% Process each tree separately for tree = 1:nt % Select the models for the tree Models = TreeId(:,1) == TreeIds(tree); %% Determine the input parameter values InputParComb = unique(inputs(Models,:),'rows'); % Input parameter combinations IV = cell(3,1); N = zeros(3,1); for i = 1:3 I = unique(InputParComb(:,i)); IV{i} = I; N(i) = length(I); end %% Determine metric-value for each input % (average over number of models with the same inputs) input = cell(1,N(1)*N(2)*N(3)); distM = zeros(1,N(1)*N(2)*N(3)); % average distances or volume stds b = 0; for d = 1:N(1) % PatchDiam1 J = abs(inputs(:,1)-IV{1}(d)) < 0.0001; for a = 1:N(2) % PatchDiam2Min K = abs(inputs(:,2)-IV{2}(a)) < 0.0001; for i = 1:N(3) % PatchDiam2Max L = abs(inputs(:,3)-IV{3}(i)) < 0.0001; % Select models for the tree with the same inputs: T = Models & J & K & L; b = b+1; input{b} = [d a i]; % Compute the metric value; D = compute_metric_value(met,T,treedata,Data); distM(b) = D; % Collect the data and inputs TreeDataAll(tree,b,:) = mean(treedata(:,T),2); Inputs(tree,b,:) = [IV{1}(d) IV{2}(a) IV{3}(i)]; end end end %% Determine the optimal inputs and models ninputs = prod(N); NInputs(tree) = ninputs; [d,J] = sort(distM); O = input{J(1)}; OptIn(tree,1:3) = [IV{1}(O(1)) IV{2}(O(2)) IV{3}(O(3))]; OptDist(tree,1) = d(1); if ninputs > 1 O = input{J(2)}; OptIn(tree,4:6) = [IV{1}(O(1)) IV{2}(O(2)) IV{3}(O(3))]; OptDist(tree,2) = d(2); if ninputs > 2 O = input{J(3)}; OptIn(tree,7:9) = [IV{1}(O(1)) IV{2}(O(2)) IV{3}(O(3))]; OptDist(tree,3) = d(3); end end %% Mean of tree data for each tree computed from the optimal models: % Select the optimal models for each tree: In the case of multiple models % with same inputs, select the one model with the optimal inputs that % has the minimum metric value. J = abs(inputs(:,1)-OptIn(tree,1)) < 0.0001; K = abs(inputs(:,2)-OptIn(tree,2)) < 0.0001; L = abs(inputs(:,3)-OptIn(tree,3)) < 0.0001; T = Models & J & K & L; ind = IndAll(T); [~,T] = min(Data.CylDist(ind,best)); OptModel(tree,1) = ind(T); OptModels{tree,1} = ind; OptModels{tree,2} = ind(T); DataM(:,tree) = mean(treedata(:,ind),2); DataS(:,tree) = std(treedata(:,ind),[],2); if ninputs > 1 J = abs(inputs(:,1)-OptIn(tree,4)) < 0.0001; K = abs(inputs(:,2)-OptIn(tree,5)) < 0.0001; L = abs(inputs(:,3)-OptIn(tree,6)) < 0.0001; T = Models & J & K & L; ind = IndAll(T); [~,T] = min(Data.CylDist(ind,best)); OptModel(tree,2) = ind(T); DataM2(:,tree) = mean(treedata(:,ind),2); DataS2(:,tree) = std(treedata(:,ind),[],2); if ninputs > 2 J = abs(inputs(:,1)-OptIn(tree,7)) < 0.0001; K = abs(inputs(:,2)-OptIn(tree,8)) < 0.0001; L = abs(inputs(:,3)-OptIn(tree,9)) < 0.0001; T = Models & J & K & L; ind = IndAll(T); [~,T] = min(Data.CylDist(ind,best)); OptModel(tree,3) = ind(T); DataM3(:,tree) = mean(treedata(:,ind),2); DataS3(:,tree) = std(treedata(:,ind),[],2); end end % Decrease the number on non-zero decimals DataM(:,tree) = change_precision(DataM(:,tree)); DataS(:,tree) = change_precision(DataS(:,tree)); if ninputs > 1 DataM2(:,tree) = change_precision(DataM2(:,tree)); DataS2(:,tree) = change_precision(DataS2(:,tree)); if ninputs > 2 DataM3(:,tree) = change_precision(DataM3(:,tree)); DataS3(:,tree) = change_precision(DataS3(:,tree)); end end % Define the output "OptInputs" OptM = IndAll(OptModel(tree,1)); OptInputs(tree) = QSMs(OptM).rundata.inputs; if ninputs > 1 OptM2 = IndAll(OptModel(tree,2)); OI2(tree) = QSMs(OptM2).rundata.inputs; if ninputs > 2 OptM3 = IndAll(OptModel(tree,3)); OI3(tree) = QSMs(OptM3).rundata.inputs; end end end N = max(NInputs); TreeDataAll = TreeDataAll(:,1:N,:); Inputs = Inputs(:,1:N,:); % Compute Coefficient of variation for the data OptModel = IndAll(OptModel(:,1)); OptQSM = QSMs(OptModel); DataCV = DataS./DataM*100; % Coefficient of variation if ninputs > 1 DataCV2 = DataS2./DataM2*100; % Coefficient of variation if ninputs > 2 DataCV3 = DataS3./DataM3*100; % Coefficient of variation end end % Decrease the number on non-zero decimals for j = 1:nt DataCV(:,j) = change_precision(DataCV(:,j)); if ninputs > 1 DataCV2(:,j) = change_precision(DataCV2(:,j)); if ninputs > 2 DataCV3(:,j) = change_precision(DataCV3(:,j)); end end end %% Display some data about optimal models % Display optimal inputs, model and attributes for each tree for t = 1:nt disp('-------------------------------') disp([' Tree: ',num2str(OptInputs(t).tree),', ',OptInputs(t).name]) if NInputs(t) == 1 disp([' Metric: ',Metric]) disp([' Metric value: ',num2str(1000*OptDist(t,1))]) disp([' Optimal inputs: PatchDiam1 = ',... num2str(OptInputs(t).PatchDiam1)]) disp([' PatchDiam2Min = ',... num2str(OptInputs(t).PatchDiam2Min)]) disp([' PatchDiam2Max = ',... num2str(OptInputs(t).PatchDiam2Max)]) disp([' Optimal model: ',num2str(OptModel(t))]) sec = num2str(round(QSMs(OptModel(t)).rundata.time(end))); disp([' Reconstruction time for the optimal model: ',sec,' seconds']) disp(' Attributes (mean, std, CV(%)):') for i = 1:n str = ([' ',Names{i},': ',num2str([... DataM(i,t) DataS(i,t) DataCV(i,t)])]); disp(str) end elseif NInputs(t) == 2 disp(' The best two cases:') disp([' Metric: ',Metric]) disp([' Metric values: ',num2str(OptDist(t,1:2))]) disp([' inputs: PatchDiam1 = ',... num2str([OptInputs(t).PatchDiam1 OI2(t).PatchDiam1])]) disp([' PatchDiam2Min = ',... num2str([OptInputs(t).PatchDiam2Min OI2(t).PatchDiam2Min])]) disp([' PatchDiam2Max = ',... num2str([OptInputs(t).PatchDiam2Max OI2(t).PatchDiam2Max])]) disp([' Optimal model: ',num2str(OptModel(t))]) sec = num2str(round(QSMs(OptModel(t)).rundata.time(end))); disp([' Reconstruction time for the optimal model: ',sec,' seconds']) disp(' Attributes (mean, std, CV(%), second best mean):') for i = 1:n str = ([' ',Names{i},': ',num2str([DataM(i,t) ... DataS(i,t) DataCV(i,t) DataM2(i,t)])]); disp(str) end elseif NInputs(t) > 2 disp(' The best three cases:') disp([' Metric: ',Metric]) disp([' Metric values: ',num2str(OptDist(t,1:3))]) disp([' inputs: PatchDiam1 = ',num2str([... OptInputs(t).PatchDiam1 OI2(t).PatchDiam1 OI3(t).PatchDiam1])]) disp([' PatchDiam2Min = ',num2str([... OptInputs(t).PatchDiam2Min OI2(t).PatchDiam2Min OI3(t).PatchDiam2Min])]) disp([' PatchDiam2Max = ',num2str([... OptInputs(t).PatchDiam2Max OI2(t).PatchDiam2Max OI3(t).PatchDiam2Max])]) disp([' Optimal model: ',num2str(OptModel(t))]) sec = num2str(round(QSMs(OptModel(t)).rundata.time(end))); disp([' Reconstruction time for the optimal model: ',sec,' seconds']) str = [' Attributes (mean, std, CV(%),',... ' second best mean, third best mean, sensitivity):']; disp(str) for i = 1:n sensi = max(abs([DataM(i,t)-DataM2(i,t)... DataM(i,t)-DataM3(i,t)])/DataM(i,t)); sensi2 = 100*sensi; sensi = 100*sensi/DataCV(i,t); sensi2 = change_precision(sensi2); sensi = change_precision(sensi); str = ([' ',Names{i},': ',num2str([DataM(i,t) DataS(i,t) ... DataCV(i,t) DataM2(i,t) DataM3(i,t) sensi sensi2])]); disp(str) end end disp('------') end %% Compute the sensitivity of the tree attributes relative to PatchDiam-parameters Sensi = sensitivity_analysis(TreeDataAll,TreeId,Inputs,OptIn,NInputs); %% Generate TreeData sructure for optimal models clear TreeData TreeData = vertcat(OptQSM(:).treedata); for t = 1:nt for i = 1:n TreeData(t).(names{i}) = [DataM(i,t) DataS(i,t) squeeze(Sensi(t,i,:))']; end TreeData(t).name = OptInputs(t).name; end %% Add the metric for the "OptInputs" for i = 1:nt OptInputs(i).metric = Metric; end %% Save results if nargin == 3 str = ['results/OptimalQSMs_',savename]; save(str,'TreeData','OptModels','OptInputs','OptQSM') str = ['results/tree_data_',savename,'.txt']; fid = fopen(str, 'wt'); fprintf(fid, [repmat('%g\t', 1, size(DataM,2)-1) '%g\n'], DataM.'); fclose(fid); end % End of main function end function [treedata,inputs,TreeId,Data] = collect_data(... QSMs,names,Nattri) Nmod = max(size(QSMs)); % number of models treedata = zeros(Nattri,Nmod); % Collect all tree attributes from all models inputs = zeros(Nmod,3); % collect the inputs from all models % ([PatchDiam1 PatchDiam2Min PatchDiam2Max]) CylDist = zeros(Nmod,10); % collect the distances from all models CylSurfCov = zeros(Nmod,10); % collect the surface coverages from all models s = 6; % maximum branch order OrdDis = zeros(Nmod,4*s); % collect the distributions from all the models r = 20; % maximum cylinder diameter CylDiaDis = zeros(Nmod,3*r); CylZenDis = zeros(Nmod,54); TreeId = zeros(Nmod,2); % collectd the tree and model indexes from all models Keep = true(Nmod,1); % Non-empty models for i = 1:Nmod if ~isempty(QSMs(i).cylinder) % Collect input-parameter values and tree IDs: p = QSMs(i).rundata.inputs; inputs(i,:) = [p.PatchDiam1 p.PatchDiam2Min p.PatchDiam2Max]; TreeId(i,:) = [p.tree p.model]; % Collect cylinder-point distances: mean of all cylinders, % mean of trunk, branch, 1st- and 2nd-order branch cylinders. % And the maximum of the previous: D = QSMs(i).pmdistance; CylDist(i,:) = [D.mean D.TrunkMean D.BranchMean D.Branch1Mean ... D.Branch2Mean D.max D.TrunkMax D.BranchMax D.Branch1Max ... D.Branch2Max]; % Collect surface coverages: mean of all cylinders, % mean of trunk, branch, 1st- and 2nd-order branch cylinders. % And the minimum of the previous: D = QSMs(i).cylinder.SurfCov; T = QSMs(i).cylinder.branch == 1; B1 = QSMs(i).cylinder.BranchOrder == 1; B2 = QSMs(i).cylinder.BranchOrder == 2; if ~any(B1) CylSurfCov(i,:) = [mean(D) mean(D(T)) 0 0 0 ... min(D) min(D(T)) 0 0 0]; elseif ~any(B2) CylSurfCov(i,:) = [mean(D) mean(D(T)) mean(D(~T)) mean(D(B1)) ... 0 min(D) min(D(T)) min(D(~T)) min(D(B1)) 0]; else CylSurfCov(i,:) = [mean(D) mean(D(T)) mean(D(~T)) mean(D(B1)) ... mean(D(B2)) min(D) min(D(T)) min(D(~T)) min(D(B1)) min(D(B2))]; end % Collect branch-order distributions: d = QSMs(i).treedata.VolBranchOrd; nd = length(d); if nd > 0 a = min(nd,s); OrdDis(i,1:a) = d(1:a); OrdDis(i,s+1:s+a) = QSMs(i).treedata.AreBranchOrd(1:a); OrdDis(i,2*s+1:2*s+a) = QSMs(i).treedata.LenBranchOrd(1:a); OrdDis(i,3*s+1:3*s+a) = QSMs(i).treedata.NumBranchOrd(1:a); end % Collect cylinder diameter distributions: d = QSMs(i).treedata.VolCylDia; nd = length(d); if nd > 0 a = min(nd,r); CylDiaDis(i,1:a) = d(1:a); CylDiaDis(i,r+1:r+a) = QSMs(i).treedata.AreCylDia(1:a); CylDiaDis(i,2*r+1:2*r+a) = QSMs(i).treedata.LenCylDia(1:a); end % Collect cylinder zenith direction distributions: d = QSMs(i).treedata.VolCylZen; if ~isempty(d) CylZenDis(i,1:18) = d; CylZenDis(i,19:36) = QSMs(i).treedata.AreCylZen; CylZenDis(i,37:54) = QSMs(i).treedata.LenCylZen; end % Collect the treedata values from each model for j = 1:Nattri treedata(j,i) = QSMs(i).treedata.(names{j}); end else Keep(i) = false; end end treedata = treedata(:,Keep); inputs = inputs(Keep,:); TreeId = TreeId(Keep,:); clear Data Data.CylDist = CylDist(Keep,:); Data.CylSurfCov = CylSurfCov(Keep,:); Data.BranchOrdDis = OrdDis(Keep,:); Data.CylDiaDis = CylDiaDis(Keep,:); Data.CylZenDis = CylZenDis(Keep,:); % End of function end function [met,Metric] = select_metric(Metric) % Mean distance metrics: if strcmp(Metric,'all_mean_dis') met = 1; elseif strcmp(Metric,'trunk_mean_dis') met = 2; elseif strcmp(Metric,'branch_mean_dis') met = 3; elseif strcmp(Metric,'1branch_mean_dis') met = 4; elseif strcmp(Metric,'2branch_mean_dis') met = 5; elseif strcmp(Metric,'trunk+branch_mean_dis') met = 6; elseif strcmp(Metric,'trunk+1branch_mean_dis') met = 7; elseif strcmp(Metric,'trunk+1branch+2branch_mean_dis') met = 8; elseif strcmp(Metric,'1branch+2branch_mean_dis') met = 9; % Maximum distance metrics: elseif strcmp(Metric,'all_max_dis') met = 10; elseif strcmp(Metric,'trunk_max_dis') met = 11; elseif strcmp(Metric,'branch_max_dis') met = 12; elseif strcmp(Metric,'1branch_max_dis') met = 13; elseif strcmp(Metric,'2branch_max_dis') met = 14; elseif strcmp(Metric,'trunk+branch_max_dis') met = 15; elseif strcmp(Metric,'trunk+1branch_max_dis') met = 16; elseif strcmp(Metric,'trunk+1branch+2branch_max_dis') met = 17; elseif strcmp(Metric,'1branch+2branch_max_dis') met = 18; % Mean plus Maximum distance metrics: elseif strcmp(Metric,'all_mean+max_dis') met = 19; elseif strcmp(Metric,'trunk_mean+max_dis') met = 20; elseif strcmp(Metric,'branch_mean+max_dis') met = 21; elseif strcmp(Metric,'1branch_mean+max_dis') met = 22; elseif strcmp(Metric,'2branch_mean+max_dis') met = 23; elseif strcmp(Metric,'trunk+branch_mean+max_dis') met = 24; elseif strcmp(Metric,'trunk+1branch_mean+max_dis') met = 25; elseif strcmp(Metric,'trunk+1branch+2branch_mean+max_dis') met = 26; elseif strcmp(Metric,'1branch+2branch_mean+max_dis') met = 27; % Standard deviation metrics: elseif strcmp(Metric,'tot_vol_std') met = 28; elseif strcmp(Metric,'trunk_vol_std') met = 29; elseif strcmp(Metric,'branch_vol_std') met = 30; elseif strcmp(Metric,'trunk+branch_vol_std') met = 31; elseif strcmp(Metric,'tot_are_std') met = 32; elseif strcmp(Metric,'trunk_are_std') met = 33; elseif strcmp(Metric,'branch_are_std') met = 34; elseif strcmp(Metric,'trunk+branch_are_std') met = 35; elseif strcmp(Metric,'trunk_len_std') met = 36; elseif strcmp(Metric,'trunk+branch_len_std') met = 37; elseif strcmp(Metric,'branch_len_std') met = 38; elseif strcmp(Metric,'branch_num_std') met = 39; % Branch order distribution metrics: elseif strcmp(Metric,'branch_vol_ord3_mean') met = 40; elseif strcmp(Metric,'branch_are_ord3_mean') met = 41; elseif strcmp(Metric,'branch_len_ord3_mean') met = 42; elseif strcmp(Metric,'branch_num_ord3_mean') met = 43; elseif strcmp(Metric,'branch_vol_ord3_max') met = 44; elseif strcmp(Metric,'branch_are_ord3_max') met = 45; elseif strcmp(Metric,'branch_len_ord3_max') met = 46; elseif strcmp(Metric,'branch_num_ord3_max') met = 47; elseif strcmp(Metric,'branch_vol_ord6_mean') met = 48; elseif strcmp(Metric,'branch_are_ord6_mean') met = 49; elseif strcmp(Metric,'branch_len_ord6_mean') met = 50; elseif strcmp(Metric,'branch_num_ord6_mean') met = 51; elseif strcmp(Metric,'branch_vol_ord6_max') met = 52; elseif strcmp(Metric,'branch_are_ord6_max') met = 53; elseif strcmp(Metric,'branch_len_ord6_max') met = 54; elseif strcmp(Metric,'branch_num_ord6_max') met = 55; % Cylinder distribution metrics: elseif strcmp(Metric,'cyl_vol_dia10_mean') met = 56; elseif strcmp(Metric,'cyl_are_dia10_mean') met = 57; elseif strcmp(Metric,'cyl_len_dia10_mean') met = 58; elseif strcmp(Metric,'cyl_vol_dia10_max') met = 59; elseif strcmp(Metric,'cyl_are_dia10_max') met = 60; elseif strcmp(Metric,'cyl_len_dia10_max') met = 61; elseif strcmp(Metric,'cyl_vol_dia20_mean') met = 62; elseif strcmp(Metric,'cyl_are_dia20_mean') met = 63; elseif strcmp(Metric,'cyl_len_dia20_mean') met = 64; elseif strcmp(Metric,'cyl_vol_dia20_max') met = 65; elseif strcmp(Metric,'cyl_are_dia20_max') met = 66; elseif strcmp(Metric,'cyl_len_dia20_max') met = 67; elseif strcmp(Metric,'cyl_vol_zen_mean') met = 68; elseif strcmp(Metric,'cyl_are_zen_mean') met = 69; elseif strcmp(Metric,'cyl_len_zen_mean') met = 70; elseif strcmp(Metric,'cyl_vol_zen_max') met = 71; elseif strcmp(Metric,'cyl_are_zen_max') met = 72; elseif strcmp(Metric,'cyl_len_zen_max') met = 73; % Mean surface coverage metrics: elseif strcmp(Metric,'all_mean_surf') met = 74; elseif strcmp(Metric,'trunk_mean_surf') met = 75; elseif strcmp(Metric,'branch_mean_surf') met = 76; elseif strcmp(Metric,'1branch_mean_surf') met = 77; elseif strcmp(Metric,'2branch_mean_surf') met = 78; elseif strcmp(Metric,'trunk+branch_mean_surf') met = 79; elseif strcmp(Metric,'trunk+1branch_mean_surf') met = 80; elseif strcmp(Metric,'trunk+1branch+2branch_mean_surf') met = 81; elseif strcmp(Metric,'1branch+2branch_mean_surf') met = 82; % Minimum surface coverage metrics: elseif strcmp(Metric,'all_min_surf') met = 83; elseif strcmp(Metric,'trunk_min_surf') met = 84; elseif strcmp(Metric,'branch_min_surf') met = 85; elseif strcmp(Metric,'1branch_min_surf') met = 86; elseif strcmp(Metric,'2branch_min_surf') met = 87; elseif strcmp(Metric,'trunk+branch_min_surf') met = 88; elseif strcmp(Metric,'trunk+1branch_min_surf') met = 89; elseif strcmp(Metric,'trunk+1branch+2branch_min_surf') met = 90; elseif strcmp(Metric,'1branch+2branch_min_surf') met = 91; % Not given in right form, take the default option else met = 1; Metric = 'all_mean_dis'; end % End of function end function D = compute_metric_value(met,T,treedata,Data) if met <= 27 % cylinder distance metrics: D = mean(Data.CylDist(T,:),1); D(6:10) = 0.5*D(6:10); % Half the maximum values end if met < 10 % mean cylinder distance metrics: if met == 1 % all_mean_dis D = D(1); elseif met == 2 % trunk_mean_dis D = D(2); elseif met == 3 % branch_mean_dis D = D(3); elseif met == 4 % 1branch_mean_dis D = D(4); elseif met == 5 % 2branch_mean_dis D = D(5); elseif met == 6 % trunk+branch_mean_dis D = D(2)+D(3); elseif met == 7 % trunk+1branch_mean_dis D = D(2)+D(4); elseif met == 8 % trunk+1branch+2branch_mean_dis D = D(2)+D(4)+D(5); elseif met == 9 % 1branch+2branch_mean_dis D = D(4)+D(5); end elseif met < 19 % maximum cylinder distance metrics: if met == 10 % all_max_dis D = D(6); elseif met == 11 % trunk_max_dis D = D(7); elseif met == 12 % branch_max_dis D = D(8); elseif met == 13 % 1branch_max_dis D = D(9); elseif met == 14 % 2branch_max_dis D = D(10); elseif met == 15 % trunk+branch_max_dis D = D(7)+D(8); elseif met == 16 % trunk+1branch_max_dis D = D(7)+D(9); elseif met == 17 % trunk+1branch+2branch_max_dis D = D(7)+D(9)+D(10); elseif met == 18 % 1branch+2branch_max_dis D = D(9)+D(10); end elseif met < 28 % Mean plus maximum cylinder distance metrics: if met == 19 % all_mean+max_dis D = D(1)+D(6); elseif met == 20 % trunk_mean+max_dis D = D(2)+D(7); elseif met == 21 % branch_mean+max_dis D = D(3)+D(8); elseif met == 22 % 1branch_mean+max_dis D = D(4)+D(9); elseif met == 23 % 2branch_mean+max_dis D = D(5)+D(10); elseif met == 24 % trunk+branch_mean+max_dis D = D(2)+D(3)+D(7)+D(8); elseif met == 25 % trunk+1branch_mean+max_dis D = D(2)+D(4)+D(7)+D(9); elseif met == 26 % trunk+1branch+2branch_mean+max_dis D = D(2)+D(4)+D(5)+D(7)+D(9)+D(10); elseif met == 27 % 1branch+2branch_mean+max_dis D = D(4)+D(5)+D(9)+D(10); end elseif met < 39 % Standard deviation metrics: if met == 28 % tot_vol_std D = std(treedata(1,T)); elseif met == 29 % trunk_vol_std D = std(treedata(2,T)); elseif met == 30 % branch_vol_std D = std(treedata(3,T)); elseif met == 31 % trunk+branch_vol_std D = std(treedata(2,T))+std(treedata(3,T)); elseif met == 32 % tot_are_std D = std(treedata(12,T)); elseif met == 33 % trunk_are_std D = std(treedata(10,T)); elseif met == 34 % branch_are_std D = std(treedata(11,T)); elseif met == 35 % trunk+branch_are_std D = std(treedata(10,T))+std(treedata(11,T)); elseif met == 36 % trunk_len_std D = std(treedata(5,T)); elseif met == 37 % branch_len_std D = std(treedata(6,T)); elseif met == 38 % trunk+branch_len_std D = std(treedata(5,T))+std(treedata(6,T)); elseif met == 39 % branch_num_std D = std(treedata(8,T)); end elseif met < 56 % Branch order metrics: dis = max(Data.BranchOrdDis(T,:),[],1)-min(Data.BranchOrdDis(T,:),[],1); M = mean(Data.BranchOrdDis(T,:),1); I = M > 0; dis(I) = dis(I)./M(I); if met == 40 % branch_vol_ord3_mean D = mean(dis(1:3)); elseif met == 41 % branch_are_ord3_mean D = mean(dis(7:9)); elseif met == 42 % branch_len_ord3_mean D = mean(dis(13:15)); elseif met == 43 % branch_num_ord3_mean D = mean(dis(19:21)); elseif met == 44 % branch_vol_ord3_max D = max(dis(1:3)); elseif met == 45 % branch_are_ord3_max D = max(dis(7:9)); elseif met == 46 % branch_len_ord3_max D = max(dis(13:15)); elseif met == 47 % branch_vol_ord3_max D = max(dis(19:21)); elseif met == 48 % branch_vol_ord6_mean D = mean(dis(1:6)); elseif met == 49 % branch_are_ord6_mean D = mean(dis(7:12)); elseif met == 50 % branch_len_ord6_mean D = mean(dis(13:18)); elseif met == 51 % branch_num_ord6_mean D = mean(dis(19:24)); elseif met == 52 % branch_vol_ord6_max D = max(dis(1:6)); elseif met == 53 % branch_are_ord6_max D = max(dis(7:12)); elseif met == 54 % branch_len_ord6_max D = max(dis(13:18)); elseif met == 55 % branch_vol_ord6_max D = max(dis(19:24)); end elseif met < 68 % Cylinder diameter distribution metrics: dis = max(Data.CylDiaDis(T,:),[],1)-min(Data.CylDiaDis(T,:),[],1); M = mean(Data.CylDiaDis(T,:),1); I = M > 0; dis(I) = dis(I)./M(I); if met == 56 % cyl_vol_dia10_mean D = mean(dis(1:10)); elseif met == 57 % cyl_are_dia10_mean D = mean(dis(21:30)); elseif met == 58 % cyl_len_dia10_mean D = mean(dis(41:50)); elseif met == 59 % cyl_vol_dia10_max D = max(dis(1:10)); elseif met == 60 % cyl_are_dia10_max D = max(dis(21:30)); elseif met == 61 % cyl_len_dia10_max D = max(dis(41:50)); elseif met == 62 % cyl_vol_dia20_mean D = mean(dis(1:20)); elseif met == 63 % cyl_are_dia20_mean D = mean(dis(21:40)); elseif met == 64 % cyl_len_dia20_mean D = mean(dis(41:60)); elseif met == 65 % cyl_vol_dia20_max D = max(dis(1:20)); elseif met == 66 % cyl_are_dia20_max D = max(dis(21:40)); elseif met == 67 % cyl_len_dia20_max D = max(dis(41:60)); end elseif met < 74 % Cylinder zenith distribution metrics: dis = max(Data.CylZenDis(T,:),[],1)-min(Data.CylZenDis(T,:),[],1); M = mean(Data.CylZenDis(T,:),1); I = M > 0; dis(I) = dis(I)./M(I); if met == 68 % cyl_vol_zen_mean D = mean(dis(1:18)); elseif met == 69 % cyl_are_zen_mean D = mean(dis(19:36)); elseif met == 70 % cyl_len_zen_mean D = mean(dis(37:54)); elseif met == 71 % cyl_vol_zen_max D = max(dis(1:18)); elseif met == 72 % cyl_are_zen_max D = max(dis(19:36)); elseif met == 73 % cyl_len_zen_max D = max(dis(37:54)); end elseif met < 92 % Surface coverage metrics: D = 1-mean(Data.CylSurfCov(T,:),1); if met == 74 % all_mean_surf D = D(1); elseif met == 75 % trunk_mean_surf D = D(2); elseif met == 76 % branch_mean_surf D = D(3); elseif met == 77 % 1branch_mean_surf D = D(4); elseif met == 78 % 2branch_mean_surf D = D(5); elseif met == 79 % trunk+branch_mean_surf D = D(2)+D(3); elseif met == 80 % trunk+1branch_mean_surf D = D(2)+D(4); elseif met == 81 % trunk+1branch+2branch_mean_surf D = D(2)+D(4)+D(5); elseif met == 82 % 1branch+2branch_mean_surf D = D(4)+D(5); elseif met == 83 % all_min_surf D = D(6); elseif met == 84 % trunk_min_surf D = D(7); elseif met == 85 % branch_min_surf D = D(8); elseif met == 86 % 1branch_min_surf D = D(9); elseif met == 87 % 2branch_min_surf D = D(10); elseif met == 88 % trunk+branch_min_surf D = D(6)+D(7); elseif met == 89 % trunk+1branch_min_surf D = D(6)+D(8); elseif met == 90 % trunk+1branch+2branch_min_surf D = D(6)+D(9)+D(10); elseif met == 91 % 1branch+2branch_min_surf D = D(9)+D(10); end end % End of function end function Sensi = sensitivity_analysis(TreeDataAll,TreeId,Inputs,OptIn,NInputs) % Computes the sensitivity of tree attributes (e.g. total volume) to the % changes of input parameter, the PatchDiam parameters, values. The % sensitivity is normalized, i.e. the relative change of attribute value % (= max change in attribute value divided by the value with the optimal % inputs) is divided by the relative change of input parameter value. The % sensitivity is also expressed as percentage, i.e. multiplied by 100. The % sensitivity is computed relative PatchDiam1, PatchDiam2Min, and % PatchDiam2Max. The sensitivity is computed only from the attributes with % the input parameter values the closest to the optimal value. This way we % get the local sensitivity in the neighborhood of the optimal input. % % Output: % Sensi 3D-array (#trees,#attributes,#inputs) TreeIds = unique(TreeId(:,1)); % Unique tree IDs nt = length(TreeIds); % number of trees A = [2 3; 1 3; 1 2]; % Keep other two inputs constant and let one varie Sensi = zeros(nt,size(TreeDataAll,3),3); % initialization of the output for t = 1:nt % trees if NInputs(t) > 1 D = squeeze(TreeDataAll(t,1:NInputs(t),:))'; % Select the attributes for the tree In = squeeze(Inputs(t,1:NInputs(t),:)); % Select the inputs for the tree n = size(In,1); % number of different input-combinations I = all(In == OptIn(t,1:3),2); % Which data are with the optimal inputs ind = (1:1:n)'; I = ind(I); for i = 1:3 % inputs if length(unique(In(:,i))) > 1 dI = abs(max(In(:,i),[],2)-OptIn(t,i)); dImin = min(dI(dI > 0)); % the minimum nonzero absolute change in inputs dI = dImin/OptIn(t,i); % relative change in the attributes K1 = abs(max(In(:,i),[],2)-min(OptIn(t,i),[],2)) < dImin+0.0001; K = K1 & abs(max(In(:,i),[],2)-min(OptIn(t,i),[],2)) > 0.0001; K = ind(K); % the inputs the closest to the optimal input J = all(In(K,A(i,:)) == OptIn(t,A(i,:)),2); J = K(J); % input i the closest to the optimal and the other two equal the optimal dD = max(abs(D(:,J)-D(:,I)),[],2); dD = dD./D(:,I); % relative change in the input d = dD/dI*100; % relative sensitivity as a percentage Sensi(t,:,i) = round(100*d)/100; end end end end % End of function end ================================================ FILE: src/tools/average.m ================================================ function A = average(X) % Computes the average of columns of the matrix X n = size(X,1); if n > 1 A = sum(X)/n; else A = X; end ================================================ FILE: src/tools/change_precision.m ================================================ function v = change_precision(v) % Decrease the number of nonzero decimals in the vector v according to the % exponent of the number for displaying and writing. n = length(v); for i = 1:n if abs(v(i)) >= 1e3 v(i) = round(v(i)); elseif abs(v(i)) >= 1e2 v(i) = round(10*v(i))/10; elseif abs(v(i)) >= 1e1 v(i) = round(100*v(i))/100; elseif abs(v(i)) >= 1e0 v(i) = round(1000*v(i))/1000; elseif abs(v(i)) >= 1e-1 v(i) = round(10000*v(i))/10000; else v(i) = round(100000*v(i))/100000; end end ================================================ FILE: src/tools/connected_components.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function [Components,CompSize] = connected_components(Nei,Sub,MinSize,Fal) % --------------------------------------------------------------------- % CONNECTED_COMPONENTS.M Determines the connected components of cover % sets using their neighbour-relation % % Version 1.1 % Latest update 16 Aug 2017 % % Copyright (C) 2013-2017 Pasi Raumonen % --------------------------------------------------------------------- % Determines connected components of the subset of cover sets defined % by "Sub" such that each component has at least "MinSize" % number of cover sets. % % Inputs: % Nei Neighboring cover sets of each cover set, (n_sets x 1)-cell % Sub Subset whose components are determined, % length(Sub) < 2 means no subset and thus the whole point cloud % "Sub" may be also a vector of cover set indexes in the subset % or a logical (n_sets)-vector, where n_sets is the number of % all cover sets % MinSize Minimum number of cover sets in an acceptable component % Fal Logical false vector for the cover sets % % Outputs: % Components Connected components, (n_comp x 1)-cell % CompSize Number of sets in the components, (n_comp x 1)-vector if length(Sub) <= 3 && ~islogical(Sub) && Sub(1) > 0 % Very small subset, i.e. at most 3 cover sets n = length(Sub); if n == 1 Components = cell(1,1); Components{1} = uint32(Sub); CompSize = 1; elseif n == 2 I = Nei{Sub(1)} == Sub(2); if any(I) Components = cell(1,1); Components{1} = uint32((Sub)); CompSize = 1; else Components = cell(2,1); Components{1} = uint32(Sub(1)); Components{2} = uint32(Sub(2)); CompSize = [1 1]; end elseif n == 3 I = Nei{Sub(1)} == Sub(2); J = Nei{Sub(1)} == Sub(3); K = Nei{Sub(2)} == Sub(3); if any(I)+any(J)+any(K) >= 2 Components = cell(1,1); Components{1} = uint32(Sub); CompSize = 1; elseif any(I) Components = cell(2,1); Components{1} = uint32(Sub(1:2)); Components{2} = uint32(Sub(3)); CompSize = [2 1]; elseif any(J) Components = cell(2,1); Components{1} = uint32(Sub([1 3])); Components{2} = uint32(Sub(2)); CompSize = [2 1]; elseif any(K) Components = cell(2,1); Components{1} = uint32(Sub(2:3)); Components{2} = uint32(Sub(1)); CompSize = [2 1]; else Components = cell(3,1); Components{1} = uint32(Sub(1)); Components{2} = uint32(Sub(2)); Components{3} = uint32(Sub(3)); CompSize = [1 1 1]; end end elseif any(Sub) || (length(Sub) == 1 && Sub(1) == 0) nb = size(Nei,1); if nargin == 3 Fal = false(nb,1); end if length(Sub) == 1 && Sub == 0 % All the cover sets ns = nb; if nargin == 3 Sub = true(nb,1); else Sub = ~Fal; end elseif ~islogical(Sub) % Subset of cover sets ns = length(Sub); if nargin == 3 sub = false(nb,1); else sub = Fal; end sub(Sub) = true; Sub = sub; else % Subset of cover sets ns = nnz(Sub); end Components = cell(ns,1); CompSize = zeros(ns,1,'uint32'); nc = 0; % number of components found m = 1; while ~Sub(m) m = m+1; end i = 0; Comp = zeros(ns,1,'uint32'); while i < ns Add = Nei{m}; I = Sub(Add); Add = Add(I); a = length(Add); Comp(1) = m; Sub(m) = false; t = 1; while a > 0 Comp(t+1:t+a) = Add; Sub(Add) = false; t = t+a; Add = vertcat(Nei{Add}); I = Sub(Add); Add = Add(I); % select the unique elements of Add: n = length(Add); if n > 2 I = true(n,1); for j = 1:n if ~Fal(Add(j)) Fal(Add(j)) = true; else I(j) = false; end end Fal(Add) = false; Add = Add(I); elseif n == 2 if Add(1) == Add(2) Add = Add(1); end end a = length(Add); end i = i+t; if t >= MinSize nc = nc+1; Components{nc} = uint32(Comp(1:t)); CompSize(nc) = t; end if i < ns while m <= nb && Sub(m) == false m = m+1; end end end Components = Components(1:nc); CompSize = CompSize(1:nc); else Components = cell(0,1); CompSize = 0; end ================================================ FILE: src/tools/cross_product.m ================================================ function C = cross_product(A,B) % Calculates the cross product C of the 3-vectors A and B C = [A(2)*B(3)-A(3)*B(2); A(3)*B(1)-A(1)*B(3); A(1)*B(2)-A(2)*B(1)]; ================================================ FILE: src/tools/cubical_averaging.m ================================================ function DSP = cubical_averaging(P,CubeSize) tic % Downsamples the given point cloud by averaging points from each % cube of side length CubeSize. % The vertices of the big cube containing P Min = double(min(P)); Max = double(max(P)); % Number of cubes with edge length "EdgeLength" in the sides % of the big cube N = double(ceil((Max-Min)/CubeSize)+1); CubeCoord = floor([P(:,1)-Min(1) P(:,2)-Min(2) P(:,3)-Min(3)]/CubeSize)+1; % Sorts the points according a lexicographical order LexOrd = [CubeCoord(:,1) CubeCoord(:,2)-1 CubeCoord(:,3)-1]*[1 N(1) N(1)*N(2)]'; [LexOrd,SortOrd] = sort(LexOrd); nc = size(unique(LexOrd),1); % number of points in the downsampled point cloud np = size(P,1); % number of points DSP = zeros(nc,3); % Downsampled point cloud p = 1; % The index of the point under comparison q = 0; while p <= np t = 1; while (p+t <= np) && (LexOrd(p) == LexOrd(p+t)) t = t+1; end q = q+1; DSP(q,:) = average(P(SortOrd(p:p+t-1),:)); p = p+t; end toc disp([' Points before: ',num2str(np)]) disp([' Filtered points: ',num2str(np-nc)]) disp([' Points left: ',num2str(nc)]); ================================================ FILE: src/tools/cubical_downsampling.m ================================================ function Pass = cubical_downsampling(P,CubeSize) % Downsamples the given point cloud by selecting one point from each % cube of side length "CubeSize". % The vertices of the big cube containing P Min = double(min(P)); Max = double(max(P)); % Number of cubes with edge length "EdgeLength" in the sides % of the big cube N = double(ceil((Max-Min)/CubeSize)+1); % Process the data in 1e7-point blocks to consume much less memory np = size(P,1); m = 1e7; if np < m m = np; end nblocks = ceil(np/m); % number of blocks % Downsample R = cell(nblocks,1); p = 1; for i = 1:nblocks if i < nblocks % Compute the cube coordinates of the points C = floor([double(P(p:p+m-1,1))-Min(1) double(P(p:p+m-1,2))-Min(2)... double(P(p:p+m-1,3))-Min(3)]/CubeSize)+1; % Compute the lexicographical order of the cubes S = [C(:,1) C(:,2)-1 C(:,3)-1]*[1 N(1) N(1)*N(2)]'; [S,I] = unique(S); % Select the unique cubes J = (p:1:p+m-1)'; J = J(I); R{i} = [S J]; else C = floor([double(P(p:end,1))-Min(1) double(P(p:end,2))-Min(2)... double(P(p:end,3))-Min(3)]/CubeSize)+1; S = [C(:,1) C(:,2)-1 C(:,3)-1]*[1 N(1) N(1)*N(2)]'; [S,I] = unique(S); J = (p:1:np)'; J = J(I); R{i} = [S J]; end p = p+m; end % Select the unique cubes and their points R = vertcat(R{:}); [~,I] = unique(R(:,1)); Pass = false(np,1); Pass(R(I,2)) = true; ================================================ FILE: src/tools/cubical_partition.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function [Partition,CubeCoord,Info,Cubes] = cubical_partition(P,EL,NE) % --------------------------------------------------------------------- % CUBICAL_PARTITION.M Partitions the point cloud into cubes. % % Version 1.1.0 % Latest update 6 Oct 2021 % % Copyright (C) 2015-2021 Pasi Raumonen % --------------------------------------------------------------------- % Inputs: % P Point cloud, (n_points x 3)-matrix % EL Length of the cube edges % NE Number of empty edge layers % % Outputs: % Partition Point cloud partitioned into cubical cells, % (nx x ny x nz)-cell, where nx,ny,nz are the number % of cubes in x,y,z-directions, respectively. If "Cubes" % is outputed, then "Partition" is (n x 1)-cell, where each % cell corresponds to a nonempty cube. % % CC (n_points x 3)-matrix whose rows are the cube coordinates % of each point: x,y,z-coordinates % Info The minimum coordinate values and number of cubes in each % coordinate direction % Cubes (Optional) (nx x ny x nz)-matrix (array), each nonzero % element indicates that its cube is nonempty and the % number indicates which cell in "Partition" contains the % points of the cube. % --------------------------------------------------------------------- % Changes from version 1.0.0 to 1.1.0, 6 Oct 2021: % 1) Changed the determinationa EL and NE so that the while loop don't % continue endlessly in some cases if nargin == 2 NE = 3; end % The vertices of the big cube containing P Min = double(min(P)); Max = double(max(P)); % Number of cubes with edge length "EdgeLength" in the sides % of the big cube N = double(ceil((Max-Min)/EL)+2*NE+1); t = 0; while t < 10 && 8*N(1)*N(2)*N(3) > 4e9 t = t+1; EL = 1.1*EL; N = double(ceil((Max-Min)/EL)+2*NE+1); end if 8*N(1)*N(2)*N(3) > 4e9 NE = 3; N = double(ceil((Max-Min)/EL)+2*NE+1); end Info = [Min N EL NE]; % Calculates the cube-coordinates of the points CubeCoord = floor([P(:,1)-Min(1) P(:,2)-Min(2) P(:,3)-Min(3)]/EL)+NE+1; % Sorts the points according a lexicographical order LexOrd = [CubeCoord(:,1) CubeCoord(:,2)-1 CubeCoord(:,3)-1]*[1 N(1) N(1)*N(2)]'; CubeCoord = uint16(CubeCoord); [LexOrd,SortOrd] = sort(LexOrd); SortOrd = uint32(SortOrd); LexOrd = uint32(LexOrd); if nargout <= 3 % Define "Partition" Partition = cell(N(1),N(2),N(3)); np = size(P,1); % number of points p = 1; % The index of the point under comparison while p <= np t = 1; while (p+t <= np) && (LexOrd(p) == LexOrd(p+t)) t = t+1; end q = SortOrd(p); Partition{CubeCoord(q,1),CubeCoord(q,2),CubeCoord(q,3)} = SortOrd(p:p+t-1); p = p+t; end else nc = size(unique(LexOrd),1); % Define "Partition" Cubes = zeros(N(1),N(2),N(3),'uint32'); Partition = cell(nc,1); np = size(P,1); % number of points p = 1; % The index of the point under comparison c = 0; while p <= np t = 1; while (p+t <= np) && (LexOrd(p) == LexOrd(p+t)) t = t+1; end q = SortOrd(p); c = c+1; Partition{c,1} = SortOrd(p:p+t-1); Cubes(CubeCoord(q,1),CubeCoord(q,2),CubeCoord(q,3)) = c; p = p+t; end end ================================================ FILE: src/tools/define_input.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function inputs = define_input(Clouds,nPD1,nPD2Min,nPD2Max) % --------------------------------------------------------------------- % DEFINE_INPUT.M Defines the required inputs (PatchDiam and BallRad % parameters) for TreeQSM based in estimated tree % radius. % % Version 1.0.0 % Latest update 4 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % Takes in a single tree point clouds, that preferably contains only points % from the tree and not e.g. from groung. User defines the number of % PatchDiam1, PatchDiam2Min, PatchDiam2Max parameter values needed. Then % the code estimates automatically these parameter values based on the % tree stem radius and tree height. Thus this code can be used to generate % the inputs needed for QSM reconstruction with TreeQSM. % % Inputs: % P Point cloud of a tree OR string specifying the name of the .mat % file where multiple point clouds are saved % nPD1 Number of parameter values estimated for PatchDiam1 % nPD2Min Number of parameter values estimated for PatchDiam2Min % nPD2Max Number of parameter values estimated for PatchDiam2Max % % Output: % inputs Input structure with the estimated parameter values % --------------------------------------------------------------------- % Create inputs-structure create_input Inputs = inputs; % If given multiple clouds, extract the names if ischar(Clouds) || isstring(Clouds) matobj = matfile([Clouds,'.mat']); names = fieldnames(matobj); i = 1; n = max(size(names)); while i <= n && ~strcmp(names{i,:},'Properties') i = i+1; end I = (1:1:n); I = setdiff(I,i); names = names(I,1); names = sort(names); nt = max(size(names)); % number of trees/point clouds else P = Clouds; nt = 1; end inputs(nt).PatchDiam1 = 0; %% Estimate the PatchDiam and BallRad parameters for i = 1:nt if nt > 1 % Select point cloud P = matobj.(names{i}); inputs(i) = Inputs; inputs(i).name = names{i}; inputs(i).tree = i; inputs(i).plot = 0; inputs(i).savetxt = 0; inputs(i).savemat = 0; inputs(i).disp = 0; end %% Estimate the stem diameter close to bottom % Define height Hb = min(P(:,3)); Ht = max(P(:,3)); TreeHeight = double(Ht-Hb); Hei = P(:,3)-Hb; % Select a section (0.02-0.1*tree_height) from the bottom of the tree hSecTop = min(4,0.1*TreeHeight); hSecBot = 0.02*TreeHeight; hSec = hSecTop-hSecBot; Sec = Hei > hSecBot & Hei < hSecTop; StemBot = P(Sec,1:3); % Estimate stem axis (point and direction) AxisPoint = mean(StemBot); V = StemBot-AxisPoint; V = normalize(V); AxisDir = optimal_parallel_vector(V); % Estimate stem diameter d = distances_to_line(StemBot,AxisDir,AxisPoint); Rstem = double(median(d)); % Point resolution (distance between points) Res = sqrt((2*pi*Rstem*hSec)/size(StemBot,1)); %% Define the PatchDiam parameters % PatchDiam1 is around stem radius divided by 3. pd1 = Rstem/3;%*max(1,TreeHeight/20); if nPD1 == 1 inputs(i).PatchDiam1 = pd1; else n = nPD1; inputs(i).PatchDiam1 = linspace((0.90-(n-2)*0.1)*pd1,(1.10+(n-2)*0.1)*pd1,n); end % PatchDiam2Min is around stem radius divided by 6 and increased for % over 20 m heigh trees. pd2 = Rstem/6*min(1,20/TreeHeight); if nPD2Min == 1 inputs(i).PatchDiam2Min = pd2; else n = nPD2Min; inputs(i).PatchDiam2Min = linspace((0.90-(n-2)*0.1)*pd2,(1.10+(n-2)*0.1)*pd2,n); end % PatchDiam2Max is around stem radius divided by 2.5. pd3 = Rstem/2.5;%*max(1,TreeHeight/20); if nPD2Max == 1 inputs(i).PatchDiam2Max = pd3; else n = nPD2Max; inputs(i).PatchDiam2Max = linspace((0.90-(n-2)*0.1)*pd3,(1.10+(n-2)*0.1)*pd3,n); end % Define the BallRad parameters: inputs(i).BallRad1 = max([inputs(i).PatchDiam1+1.5*Res; min(1.25*inputs(i).PatchDiam1,inputs(i).PatchDiam1+0.025)]); inputs(i).BallRad2 = max([inputs(i).PatchDiam2Max+1.25*Res; min(1.2*inputs(i).PatchDiam2Max,inputs(i).PatchDiam2Max+0.025)]); %plot_point_cloud(P,1,1) end ================================================ FILE: src/tools/dimensions.m ================================================ function [D,dir] = dimensions(points,varargin) % Calculates the box-dimensions and dimension estimates of the point set % "points". Returns also the corresponding direction vectors. if nargin == 2 P = varargin{1}; points = P(points,:); elseif nargin == 3 P = varargin{1}; Bal = varargin{2}; I = vertcat(Bal{points}); points = P(I,:); end if size(points,2) == 3 X = cov(points); [U,S,~] = svd(X); dp1 = points*U(:,1); dp2 = points*U(:,2); dp3 = points*U(:,3); D = [max(dp1)-min(dp1) max(dp2)-min(dp2) max(dp3)-min(dp3) ... (S(1,1)-S(2,2))/S(1,1) (S(2,2)-S(3,3))/S(1,1) S(3,3)/S(1,1)]; dir = [U(:,1)' U(:,2)' U(:,3)']; else X = cov(points); [U,S,~] = svd(X); dp1 = points*U(:,1); dp2 = points*U(:,2); D = [max(dp1)-min(dp1) max(dp2)-min(dp2) ... (S(1,1)-S(2,2))/S(1,1) S(2,2)/S(1,1)]; dir = [U(:,1)' U(:,2)']; end ================================================ FILE: src/tools/display_time.m ================================================ function display_time(T1,T2,string,display) % Display the two times given. "T1" is the time named with the "string" and % "T2" is named "Total". % Changes 12 Mar 2018: moved the if statement with display from the end to % the beginning if display [tmin,tsec] = sec2min(T1); [Tmin,Tsec] = sec2min(T2); if tmin < 60 && Tmin < 60 if tmin < 1 && Tmin < 1 str = [string,' ',num2str(tsec),' sec. Total: ',num2str(Tsec),' sec']; elseif tmin < 1 str = [string,' ',num2str(tsec),' sec. Total: ',num2str(Tmin),... ' min ',num2str(Tsec),' sec']; else str = [string,' ',num2str(tmin),' min ',num2str(tsec),... ' sec. Total: ',num2str(Tmin),' min ',num2str(Tsec),' sec']; end elseif tmin < 60 Thour = floor(Tmin/60); Tmin = Tmin-Thour*60; str = [string,' ',num2str(tmin),' min ',num2str(tsec),... ' sec. Total: ',num2str(Thour),' hours ',num2str(Tmin),' min']; else thour = floor(tmin/60); tmin = tmin-thour*60; Thour = floor(Tmin/60); Tmin = Tmin-Thour*60; str = [string,' ',num2str(thour),' hours ',num2str(tmin),... ' min. Total: ',num2str(Thour),' hours ',num2str(Tmin),' min']; end disp(str) end ================================================ FILE: src/tools/distances_between_lines.m ================================================ function [DistLines,DistOnRay,DistOnLines] = distances_between_lines(PointRay,DirRay,PointLines,DirLines) % Calculates the distances between a ray and lines % PointRay A point of the ray % DirRay Unit direction vector of the line % PointLines One point of every line % DirLines Unit direction vectors of the lines PointLines = double(PointLines); PointRay = double(PointRay); DirLines = double(DirLines); DirRay = double(DirRay); % Calculate unit vectors N orthogonal to the ray and the lines N = [DirRay(2)*DirLines(:,3)-DirRay(3)*DirLines(:,2) ... DirRay(3)*DirLines(:,1)-DirRay(1)*DirLines(:,3) ... DirRay(1)*DirLines(:,2)-DirRay(2)*DirLines(:,1)]; l = sqrt(sum(N.*N,2)); N = [1./l.*N(:,1) 1./l.*N(:,2) 1./l.*N(:,3)]; % Calculate the distances between the lines A = -mat_vec_subtraction(PointLines,PointRay); DistLines = sqrt(abs(sum(A.*N,2))); % distance between lines and the ray % Calculate the distances on ray and on lines b = DirLines*DirRay'; d = A*DirRay'; e = sum(A.*DirLines,2); DistOnRay = (b.*e-d)./(1-b.^2); % Distances to PointRay from the closest points on the ray DistOnLines = (e-b.*d)./(1-b.^2); % Distances to PointLines from the closest points on the lines ================================================ FILE: src/tools/distances_to_line.m ================================================ function [d,V,h,B] = distances_to_line(Q,LineDirec,LinePoint) % Calculates the distances of the points, given in the rows of the % matrix Q, to the line defined by one of its point and its direction. % "LineDirec" must be a unit (1x3)-vector and LinePoint must be a (1x3)-vector. % % Last update 8 Oct 2021 A = Q-LinePoint; h = A*LineDirec'; B = h*LineDirec; V = A-B; d = sqrt(sum(V.*V,2)); ================================================ FILE: src/tools/dot_product.m ================================================ function C = dot_product(A,B) % Computes the dot product of the corresponding rows of the matrices A and B C = sum(A.*B,2); ================================================ FILE: src/tools/expand.m ================================================ function C = expand(Nei,C,n,Forb) % Expands the given subset "C" of cover sets "n" times with their neighbors, % and optionally, prevents the expansion into "Forb" sets. "C" is a vector % and "Forb" can be a number vector or a logical vector. if nargin == 3 for i = 1:n C = union(C,vertcat(Nei{C})); end if size(C,2) > 1 C = C'; end else if islogical(Forb) for i = 1:n C = union(C,vertcat(Nei{C})); I = Forb(C); C = C(~I); end else for i = 1:n C = union(C,vertcat(Nei{C})); C = setdiff(C,Forb); end end if size(C,2) > 1 C = C'; end end ================================================ FILE: src/tools/growth_volume_correction.m ================================================ function cylinder = growth_volume_correction(cylinder,inputs) % --------------------------------------------------------------------- % GROWTH_VOLUME_CORRECTION.M Use growth volume allometry approach to % modify the radius of cylinders. % % Version 2.0.0 % Latest update 16 Sep 2021 % % Copyright (C) 2013-2021 Pasi Raumonen % --------------------------------------------------------------------- % % Use growth volume (= the total volume "supported by the cylinder") % allometry approach to modify the radius of too large and too small % cylinders. Uses the allometry: % % Radius = a * GrowthVolume^b + c % % If cylinder's radius is over fac-times or under 1/fac-times the radius % predicted from the growth volume allometry, then correct the radius to % match the allometry. However, the radius of the cylinders in the branch % tips are never incresed, only decreased by the correction. More details % can be from Jan Hackenberg's "SimpleTree" papers and documents. % --------------------------------------------------------------------- % Inputs: % cylinder Structure array that needs to contains the following fields: % radius (Rad) Radii of the cylinders, vector % length (Len) Lengths of the cylinders, vector % parent (CPar) Parents of the cylinders, vector % inputs.GrowthVolFac The factor "fac", defines the upper and lower % allowed radius from the predicted one: % 1/fac*predicted_rad <= rad <= fac*predicted_rad % --------------------------------------------------------------------- % Changes from version 1.0.0 to 2.0.0, 16 Sep 2021: % 1) Changed the roles of RADIUS and GROWTH_VOLUME in the allometry, i.e. % the radius is now predicted from the growth volume % 2) Do not increase the radius of the branch tip cylinders disp('----------') disp('Growth volume based correction of cylinder radii:') Rad = double(cylinder.radius); Rad0 = Rad; Len = double(cylinder.length); CPar = cylinder.parent; CExt = cylinder.extension; initial_volume = round(1000*pi*sum(Rad.^2.*Len)); disp([' Initial_volume (L): ',num2str(initial_volume)]) %% Define the child cylinders for each cylinder n = length(Rad); CChi = cell(n,1); ind = (1:1:n)'; for i = 1:n CChi{i} = ind(CPar == i); end %% Compute the growth volume GrowthVol = zeros(n,1); % growth volume S = cellfun('length',CChi); modify = S == 0; GrowthVol(modify) = pi*Rad(modify).^2.*Len(modify); parents = unique(CPar(modify)); if parents(1) == 0 parents = parents(2:end); end while ~isempty(parents) V = pi*Rad(parents).^2.*Len(parents); m = length(parents); for i = 1:m GrowthVol(parents(i)) = V(i)+sum(GrowthVol(CChi{parents(i)})); end parents = unique(CPar(parents)); if parents(1) == 0 parents = parents(2:end); end end %% Fit the allometry: Rad = a*GV^b; options = optimset('Display','off'); X = lsqcurvefit(@allometry,[0.5 0.5 0],GrowthVol,Rad,[],[],options); disp(' Allometry model parameters R = a*GV^b+c:') disp([' Multiplier a: ', num2str(X(1))]) disp([' Exponent b: ', num2str(X(2))]) if length(X) > 2 disp([' Intersect c: ', num2str(X(3))]) end %% Compute the predicted radius from the allometry PredRad = allometry(X,GrowthVol); %% Correct the radii based on the predictions % If cylinder's radius is over fac-times or under 1/fac-times the % predicted radius, then correct the radius to match the allometry fac = inputs.GrowthVolFac; modify = Rad < PredRad/fac | Rad > fac*PredRad; modify(Rad < PredRad/fac & CExt == 0) = 0; % Do not increase the radius at tips CorRad = PredRad(modify); % Plot allometry and radii modification gvm = max(GrowthVol); gv = (0:0.001:gvm); PRad = allometry(X,gv); figure(1) plot(GrowthVol,Rad,'.b','Markersize',2) hold on plot(gv,PRad,'-r','Linewidth',2) plot(gv,PRad/fac,'-g','Linewidth',2) plot(gv,fac*PRad,'-g','Linewidth',2) hold off grid on xlabel('Growth volume (m^3)') ylabel('Radius (m)') legend('radius','predicted radius','minimum radius','maximum radius','Location','NorthWest') figure(2) histogram(CorRad-Rad(modify)) xlabel('Change in radius') title('Number of cylinders per change in radius class') % Determine the maximum radius change R = Rad(modify); D = max(abs(R-CorRad)); % Maximum radius change J = abs(R-CorRad) == D; D = CorRad(J)-R(J); % modify the radius according to allometry Rad(modify) = CorRad; cylinder.radius = Rad; disp([' Modified ',num2str(nnz(modify)),' of the ',num2str(n),' cylinders']) disp([' Largest radius change (cm): ',num2str(round(1000*D)/10)]) corrected_volume = round(1000*pi*sum(Rad.^2.*Len)); disp([' Corrected volume (L): ', num2str(corrected_volume)]) disp([' Change in volume (L): ', num2str(corrected_volume-initial_volume)]) disp('----------') % % Plot cylinder models where the color indicates change (green = no change, % % red = decreased radius, cyan = increased radius) % cylinder.branch = ones(n,1); % cylinder.BranchOrder = ones(n,1); % I = Rad < Rad0; % cylinder.BranchOrder(I) = 2; % I = Rad > Rad0; % cylinder.BranchOrder(I) = 3; % plot_cylinder_model(cylinder,'order',3,20,1) % % cyl = cylinder; % cyl.radius = Rad0; % plot_cylinder_model(cyl,'order',4,20,1) end % End of main function function F = allometry(x,xdata) F = x(1)*xdata.^x(2)+x(3); end ================================================ FILE: src/tools/intersect_elements.m ================================================ function Set = intersect_elements(Set1,Set2,False1,False2) % Determines the intersection of Set1 and Set2. Set = unique_elements([Set1; Set2],False1); False1(Set1) = true; False2(Set2) = true; I = False1(Set)&False2(Set); Set = Set(I); ================================================ FILE: src/tools/mat_vec_subtraction.m ================================================ function A = mat_vec_subtraction(A,v) % Subtracts from each row of the matrix A the vector v. % If A is (n x m)-matrix, then v needs to be m-vector. for i = 1:size(A,2) A(:,i) = A(:,i)-v(i); end ================================================ FILE: src/tools/median2.m ================================================ function y = median2(X) % Computes the median of the given vector. n = size(X,1); if n > 1 X = sort(X); m = floor(n/2); if 2*m == n y = (X(m)+X(m+1))/2; elseif m == 0 y = (X(1)+X(2))/2; else y = X(m+1); end else y = X; end ================================================ FILE: src/tools/normalize.m ================================================ function [A,L] = normalize(A) % Normalize rows of the matrix L = sqrt(sum(A.*A,2)); n = size(A,2); for i = 1:n A(:,i) = A(:,i)./L; end ================================================ FILE: src/tools/optimal_parallel_vector.m ================================================ function [v,mean_res,sigmah,residual] = optimal_parallel_vector(V) % For a given set of unit vectors (the rows of the matrix "V"), % returns a unit vector ("v") that is the most parallel to them all % in the sense that the sum of squared dot products of v with the % vectors of V is maximized. A = V'*V; [U,~,~] = svd(A); v = U(:,1)'; if nargout > 1 residual = abs(V*v'); mean_res = mean(residual); sigmah = std(residual); end ================================================ FILE: src/tools/orthonormal_vectors.m ================================================ function [V,W] = orthonormal_vectors(U) % Generate vectors V and W that are unit vectors orthogonal to themselves % and to the input vector U V = rand(3,1); V = cross_product(V,U); while norm(V) == 0 V = rand(3,1); V = cross_product(V,U); end W = cross_product(V,U); W = W/norm(W); V = V/norm(V); if size(V,2) > 1 V = V'; end if size(W,2) > 1 W = W'; end ================================================ FILE: src/tools/rotation_matrix.m ================================================ function R = rotation_matrix(A,angle) % Returns the rotation matrix for the given axis A and angle (in radians) A = A/norm(A); R = zeros(3,3); c = cos(angle); s = sin(angle); R(1,:) = [A(1)^2+(1-A(1)^2)*c A(1)*A(2)*(1-c)-A(3)*s A(1)*A(3)*(1-c)+A(2)*s]; R(2,:) = [A(1)*A(2)*(1-c)+A(3)*s A(2)^2+(1-A(2)^2)*c A(2)*A(3)*(1-c)-A(1)*s]; R(3,:) = [A(1)*A(3)*(1-c)-A(2)*s A(2)*A(3)*(1-c)+A(1)*s A(3)^2+(1-A(3)^2)*c]; ================================================ FILE: src/tools/save_model_text.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function save_model_text(QSM,savename) % --------------------------------------------------------------------- % SAVE_MODEL_TEXT.M Saves QSM (cylinder, branch, treedata) into text % files % % Version 1.1.0 % Latest update 17 Aug 2020 % % Copyright (C) 2013-2020 Pasi Raumonen % --------------------------------------------------------------------- % Save the cylinder, branch, and treedata structures in text-formats (.txt) % into /result-folder with the input "savename" defining the file names: % 'cylinder_',savename,'.txt' % 'branch_',savename,'.txt' % 'treedata_',savename,'.txt' % !!! Notice that only part of the treedata, the single number tree % attributes are saved in the text-file. % Every user can change this code easily to define what is saved into % their text-files. % Changes from version 1.0.0 to 1.1.0, 17 Aug 2020: % 1) Added the new fields of cylinder, branch and treedata structures % 2) Added header names to the files % 3) Changed the names of the files to be saved % 4) Changed the name of second input from "string" to "savename" % 5) Changed the rounding of some parameters and attributes cylinder = QSM.cylinder; branch = QSM.branch; treedata = QSM.treedata; %% Form cylinder data, branch data and tree data % Use less decimals Rad = round(10000*cylinder.radius)/10000; % radius (m) Len = round(10000*cylinder.length)/10000; % length (m) Sta = round(10000*cylinder.start)/10000; % starting point (m) Axe = round(10000*cylinder.axis)/10000; % axis (m) CPar = single(cylinder.parent); % parent cylinder CExt = single(cylinder.extension); % extension cylinder Added = single(cylinder.added); % is cylinder added to fil a gap Rad0 = round(10000*cylinder.UnmodRadius)/10000; % unmodified radius (m) B = single(cylinder.branch); % branch index of the cylinder BO = single(cylinder.BranchOrder); % branch order of the branch PIB = single(cylinder.PositionInBranch); % position of the cyl. in the branch Mad = single(round(10000*cylinder.mad)/10000); % mean abso. distance (m) SC = single(round(10000*cylinder.SurfCov)/10000); % surface coverage CylData = [Rad Len Sta Axe CPar CExt B BO PIB Mad SC Added Rad0]; NamesC = ['radius (m)',"length (m)","start_point","axis_direction",... "parent","extension","branch","branch_order","position_in_branch",... "mad","SurfCov","added","UnmodRadius (m)"]; BOrd = single(branch.order); % branch order BPar = single(branch.parent); % parent branch BDia = round(10000*branch.diameter)/10000; % diameter (m) BVol = round(10000*branch.volume)/10000; % volume (L) BAre = round(10000*branch.area)/10000; % area (m^2) BLen = round(1000*branch.length)/1000; % length (m) BAng = round(10*branch.angle)/10; % angle (deg) BHei = round(1000*branch.height)/1000; % height (m) BAzi = round(10*branch.azimuth)/10; % azimuth (deg) BZen = round(10*branch.zenith)/10; % zenith (deg) BranchData = [BOrd BPar BDia BVol BAre BLen BHei BAng BAzi BZen]; NamesB = ["order","parent","diameter (m)","volume (L)","area (m^2)",... "length (m)","height (m)","angle (deg)","azimuth (deg)","zenith (deg)"]; % Extract the field names of treedata Names = fieldnames(treedata); n = 1; while ~strcmp(Names{n},'location') n = n+1; end n = n-1; Names = Names(1:n); TreeData = zeros(n,1); % TreeData contains TotalVolume, TrunkVolume, BranchVolume, etc for i = 1:n TreeData(i) = treedata.(Names{i,:}); end TreeData = change_precision(TreeData); % use less decimals NamesD = string(Names); %% Save the data as text-files str = ['results/cylinder_',savename,'.txt']; fid = fopen(str, 'wt'); fprintf(fid, [repmat('%s\t', 1, size(NamesC,2)-1) '%s\n'], NamesC.'); fprintf(fid, [repmat('%g\t', 1, size(CylData,2)-1) '%g\n'], CylData.'); fclose(fid); str = ['results/branch_',savename,'.txt']; fid = fopen(str, 'wt'); fprintf(fid, [repmat('%s\t', 1, size(NamesB,2)-1) '%s\n'], NamesB.'); fprintf(fid, [repmat('%g\t', 1, size(BranchData,2)-1) '%g\n'], BranchData.'); fclose(fid); str = ['results/treedata_',savename,'.txt']; fid = fopen(str, 'wt'); NamesD(:,2) = TreeData; fprintf(fid,'%s\t %g\n',NamesD.'); fclose(fid); ================================================ FILE: src/tools/sec2min.m ================================================ function [Tmin,Tsec] = sec2min(T) % Transforms the given number of seconds into minutes and residual seconds Tmin = floor(T/60); Tsec = round((T-Tmin*60)*10)/10; ================================================ FILE: src/tools/select_cylinders.m ================================================ function cylinder = select_cylinders(cylinder,Ind) Names = fieldnames(cylinder); n = size(Names,1); for i = 1:n cylinder.(Names{i}) = cylinder.(Names{i})(Ind,:); end ================================================ FILE: src/tools/set_difference.m ================================================ function Set1 = set_difference(Set1,Set2,False) % Performs the set difference so that the common elements of Set1 and Set2 % are removed from Set1, which is the output. Uses logical vector whose % length must be up to the maximum element of the sets. False(Set2) = true; I = False(Set1); Set1 = Set1(~I); ================================================ FILE: src/tools/simplify_qsm.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function QSM = simplify_qsm(QSM,MaxOrder,SmallRadii,ReplaceIterations,Plot,Disp) % --------------------------------------------------------------------- % SIMPLIFY_QSM.M Simplifies cylinder QSMs by restricting the maximum % branching order, by removing thin branches, and by % replacing two concecutive cylinders with a longer cylinder % % Version 2.0.0 % Latest update 4 May 2022 % % Copyright (C) 2015-2022 Pasi Raumonen % --------------------------------------------------------------------- % % Inputs: % QSM QSM-structure, output of treeqsm.m, must contain only one model % MaxOrder Maximum branching order, higher order branches removed % SmallRadii Minimum acceptable radius for a branch at its base % ReplaceIterations Number of iterations for replacing two concecutive % cylinders inside one branch with one longer cylinder % Plot If true/1, then plots the cylinder models before and % after the simplification % Disp If Disp == 1, then display the simplication results % (the number of cylinders after each step). If % Disp == 2, then display also the treedata results for % the original and simplified QSMs. If Disp == 0, then % nothing is displayed. % % Output: % Modified QSM NOTICE: cylinder, branch and treedata are modified. % Changes from version 1.1.0 to 2.0.0, 4 May 2022: % 1) Added modification of branch and treedata structures based on the % modified cylinders % 2) Added input for plotting and displaying the results % 3) Corrected some bugs that could cause errors in some special cases if nargin <= 4 Plot = 0; Disp = 1; elseif nargin <= 5 Disp = 1; end if Disp == 2 inputs = QSM.rundata.inputs; display_treedata(QSM.treedata,inputs) end % Plot the cylinder model before the simplification if Plot plot_cylinder_model(QSM.cylinder,'branch',1,20,1) end %% Maximum branching order c = QSM.cylinder; nc = size(c.radius,1); if Disp >= 1 disp([' ',num2str(nc),' cylinders originally']) end % Cylinders with branching order up to MaxBranchOrder SmallOrder = c.BranchOrder <= MaxOrder; N = fieldnames(c); n = max(size(N)); for i = 1:n c.(N{i}) = c.(N{i})(SmallOrder,:); end % Modify topology information Ind = (1:1:nc)'; m = nnz(SmallOrder); Ind(SmallOrder) = (1:1:m)'; I = c.parent > 0; c.parent(I) = Ind(c.parent(I)); I = c.extension > 0; c.extension(I) = Ind(c.extension(I)); if Disp == 1 nc = nnz(SmallOrder); disp([' ',num2str(nc),' cylinders after branching order simplification']) end %% Small branches if nargin >= 3 && SmallRadii > 0 nc = size(c.radius,1); % Determine child branches BPar = QSM.branch.parent; nb = size(BPar,1); BChi = cell(nb,1); for i = 1:nb P = BPar(i); if P > 0 BChi{P} = [BChi{P}; i]; end end % Remove branches whose radii is too small compared to its parent Large = true(nc,1); Pass = true(nb,1); for i = 1:nb if Pass(i) if QSM.branch.diameter(i) < SmallRadii B = i; BC = BChi{B}; while ~isempty(BC) B = [B; BC]; BC = vertcat(BChi{BC}); end Pass(B) = false; m = length(B); for k = 1:m Large(c.branch == B(k)) = false; end end end end % Modify topology information Ind = (1:1:nc)'; m = nnz(Large); Ind(Large) = (1:1:m)'; I = c.parent > 0; c.parent(I) = Ind(c.parent(I)); I = c.extension > 0; c.extension(I) = Ind(c.extension(I)); % Update/reduce cylinders for i = 1:n c.(N{i}) = c.(N{i})(Large,:); end if Disp >= 1 nc = nnz(Large); disp([' ',num2str(nc),' cylinders after small branch simplification']) end end %% Cylinder replacing if nargin >= 4 && ReplaceIterations > 0 % Determine child cylinders nc = size(c.radius,1); CChi = cell(nc,1); for i = 1:nc P = c.parent(i); if P > 0 PE = c.extension(P); if PE ~= i CChi{P} = [CChi{P}; i]; end end end % Replace cylinders for j = 1:ReplaceIterations nc = size(c.radius,1); Ind = (1:1:nc)'; Keep = false(nc,1); i = 1; while i <= nc t = 1; while i+t <= nc && c.branch(i+t) == c.branch(i) t = t+1; end Cyls = (i:1:i+t-1)'; S = c.start(Cyls,:); A = c.axis(Cyls,:); L = c.length(Cyls); if t == 1 % one cylinder in the branch Keep(i) = true; elseif ceil(t/2) == floor(t/2) % even number of cylinders in the branch I = (1:2:t)'; % select 1., 3., 5., ... % Correct radii, axes and lengths E = S(end,:)+L(end)*A(end,:); S = S(I,:); m = length(I); if m > 1 A = [S(2:end,:); E]-S(1:end,:); else A = E-S(1,:); end L = sqrt(sum(A.*A,2)); A = [A(:,1)./L A(:,2)./L A(:,3)./L]; cyls = Cyls(I); Keep(cyls) = true; V = pi*c.radius(Cyls).^2.*c.length(Cyls); J = (2:2:t)'; V = V(I)+V(J); R = sqrt(V./L/pi); c.radius(cyls) = R; else % odd number of cylinders I = [1 2:2:t]'; % select 1., 2., 4., 6., ... % Correct radii, axes and lengths E = S(end,:)+L(end)*A(end,:); S = S(I,:); l = L(1); a = A(I,:); m = length(I); if m > 2 a(2:end,:) = [S(3:end,:); E]-S(2:end,:); else a(2,:) = E-S(2,:); end A = a; L = sqrt(sum(A.*A,2)); L(1) = l; A(2:end,:) = [A(2:end,1)./L(2:end) A(2:end,2)./L(2:end) A(2:end,3)./L(2:end)]; cyls = Cyls(I); Keep(cyls) = true; V = pi*c.radius(Cyls).^2.*c.length(Cyls); J = (3:2:t)'; V = V(I(2:end))+V(J); R = sqrt(V./L(2:end)/pi); c.radius(cyls(2:end)) = R; end if t > 1 % Modify cylinders c.length(cyls) = L; c.axis(cyls,:) = A; % Correct branching/topology information c.PositionInBranch(cyls) = (1:1:m)'; c.extension(cyls) = [cyls(2:end); 0]; c.parent(cyls(2:end)) = cyls(1:end-1); par = c.parent(cyls(1)); if par > 0 && ~Keep(par) par0 = c.parent(par); if Keep(par0) && c.extension(par0) == par c.parent(cyls(1)) = par0; end end % Correct child branches chi = vertcat(CChi{Cyls}); if ~isempty(chi) par = c.parent(chi); J = Keep(par); par = par(~J)-1; c.parent(chi(~J)) = par; par = c.parent(chi); rp = c.radius(par); sp = c.start(par,:); ap = c.axis(par,:); lc = c.length(chi); sc = c.start(chi,:); ac = c.axis(chi,:); ec = sc+[lc.*ac(:,1) lc.*ac(:,2) lc.*ac(:,3)]; m = length(chi); for k = 1:m [d,V,h,B] = distances_to_line(sc(k,:),ap(k,:),sp(k,:)); V = V/d; sc(k,:) = sp(k,:)+rp(k)*V+B; end ac = ec-sc; [ac,lc] = normalize(ac); c.length(chi) = lc; c.start(chi,:) = sc; c.axis(chi,:) = ac; end end i = i+t; end % Change topology (parent, extension) indexes m = nnz(Keep); Ind(Keep) = (1:1:m)'; I = c.parent > 0; c.parent(I) = Ind(c.parent(I)); I = c.extension > 0; c.extension(I) = Ind(c.extension(I)); % Update/reduce cylinders for i = 1:n c.(N{i}) = c.(N{i})(Keep,:); end if j < ReplaceIterations % Determine child cylinders nc = size(c.radius,1); CChi = cell(nc,1); for i = 1:nc P = c.parent(i); if P > 0 PE = c.extension(P); if PE ~= i CChi{P} = [CChi{P}; i]; end end end end end if Disp >= 1 nc = size(c.radius,1); disp([' ',num2str(nc),' cylinders after cylinder replacements']) end end if Disp >= 1 nc = size(c.radius,1); disp([' ',num2str(nc),' cylinders after all simplifications']) end %% Updata the QSM % Update the branch branch = branches(c); % Update the treedata inputs = QSM.rundata.inputs; inputs.plot = 0; % Display if Disp == 2 inputs.disp = 2; else inputs.disp = 0; end treedata = update_tree_data(QSM,c,branch,inputs); % Update the cylinder, branch, and treedata of the QSM QSM.cylinder = c; QSM.branch = branch; QSM.treedata = treedata; % Plot the cylinder model after the simplification if Plot plot_cylinder_model(QSM.cylinder,'branch',2,20,1) end end % End of main function function display_treedata(treedata,inputs) %% Generate units for displaying the treedata Names = fieldnames(treedata); n = size(Names,1); Units = zeros(n,3); m = 23; for i = 1:n if ~inputs.Tria && strcmp(Names{i},'CrownVolumeAlpha') m = i; elseif inputs.Tria && strcmp(Names{i},'TriaTrunkLength') m = i; end if strcmp(Names{i}(1:3),'DBH') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'ume') Units(i,:) = 'L '; elseif strcmp(Names{i}(end-2:end),'ght') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'gth') Units(i,:) = 'm '; elseif strcmp(Names{i}(1:3),'vol') Units(i,:) = 'L '; elseif strcmp(Names{i}(1:3),'len') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'rea') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(1:3),'loc') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-4:end),'aConv') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(end-5:end),'aAlpha') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(end-4:end),'eConv') Units(i,:) = 'm^3'; elseif strcmp(Names{i}(end-5:end),'eAlpha') Units(i,:) = 'm^3'; elseif strcmp(Names{i}(end-2:end),'Ave') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'Max') Units(i,:) = 'm '; end end %% Display treedata disp('------------') disp(' Tree attributes before simplification:') for i = 1:m v = change_precision(treedata.(Names{i})); if strcmp(Names{i},'DBHtri') disp(' -----') disp(' Tree attributes from triangulation:') end disp([' ',Names{i},' = ',num2str(v),' ',Units(i,:)]) end disp(' -----') end ================================================ FILE: src/tools/surface_coverage.m ================================================ function [SurfCov,Dis,CylVol,dis] = surface_coverage(P,Axis,Point,nl,ns,Dmin,Dmax) % --------------------------------------------------------------------- % SURFACE_COVERAGE.M Computes point surface coverage measure % % Version 1.1.0 % Last update 7 Oct 2021 % % Copyright (C) 2017-2021 Pasi Raumonen % --------------------------------------------------------------------- % Inputs: % Axis Axis direction (1 x 3) % Point Starting point of the cylinder (1 x 3) % nl Number of layers in the axis direction used for to partition % the cylinder surface into layer/sectors % ns Number of sectors used to partition the cylinder surface into % layer/sectors % Dmin (Optional) Minimum point distance from the axis to be included % into SurfCov calculations % Dmax (Optional) Maximum point distance from the axis to be included % into SurfCov calculations % % Output: % SurfCov Number between 0 and 1 descring how big portion of the cylinder % surface is covered with points % Dis (Optional) Mean distances of the distances of the layer/sectors % CylVol (Optional) Volume of the cylinder estimated by the mean % distances of the layer/sectors as cylindrical sections % dis (Optional) Same as "Dis" but empty cells are interpolated % --------------------------------------------------------------------- % Computes surface coverage (number between 0 and 1) of points on cylinder % surface defined by "Axis" and "Point". % Changes from version 1.0.0 to 1.1.0, 7 Oct 2021: % 1) Added two possible inputs, minimum and maximum distance, % Dmin and Dmax, which can be used to filter out points for the surface % coverage calculations % 2) Computes the SurfCov estimate with four baseline directions used in % the sector determination and selects the largest value % 3) Smalle changes to speed up computations %% Compute the distances and heights of the points [d,V,h] = distances_to_line(P,Axis,Point); h = h-min(h); Len = max(h); %% (Optional) Filter out points based on the distance to the axis if nargin >= 6 Keep = d > Dmin; if nargin == 7 Keep = Keep & d < Dmax; end V = V(Keep,:); h = h(Keep); end %% Compute SurfCov % from 4 different baseline directions to determine the angles and select % the maximum value V0 = V; [U,W] = orthonormal_vectors(Axis); % First planar axes R = rotation_matrix(Axis,2*pi/ns/4); % Rotation matrix to rotate the axes SurfCov = zeros(1,4); for i = 1:4 %% Rotate the axes if i > 1 U = R*U; W = R*W; end %% Compute the angles (sectors) of the points V = V0*[U W]; ang = atan2(V(:,2),V(:,1))+pi; %% Compute lexicographic order (sector,layer) of every point Layer = ceil(h/Len*nl); Layer(Layer <= 0) = 1; Layer(Layer > nl) = nl; Sector = ceil(ang/2/pi*ns); Sector(Sector <= 0) = 1; LexOrd = [Layer Sector-1]*[1 nl]'; %% Compute SurfCov Cov = zeros(nl,ns); Cov(LexOrd) = 1; SurfCov(i) = nnz(Cov)/nl/ns; end SurfCov = max(SurfCov); %% Compute volume estimate if nargout > 1 % Sort according to increasing lexicographic order [LexOrd,SortOrd] = sort(LexOrd); d = d(SortOrd); % Compute mean distance of the sector-layer intersections Dis = zeros(nl,ns); % mean distances np = length(LexOrd); % number of points p = 1; while p <= np t = 1; while (p+t <= np) && (LexOrd(p) == LexOrd(p+t)) t = t+1; end Dis(LexOrd(p)) = average(d(p:p+t-1)); p = p+t; end if nargout > 2 % Interpolate missing distances D = Dis; dis = Dis; Dinv = D((nl:-1:1)',:); D = [Dinv Dinv Dinv; D D D; Dinv Dinv Dinv]; Zero = Dis == 0; RadMean = average(Dis(Dis > 0)); for i = 1:nl for j = 1:ns if Zero(i,j) if nnz(D(i+nl-1:i+nl+1,j+ns-1:j+ns+1)) > 1 d = D(i+nl-1:i+nl+1,j+ns-1:j+ns+1); dis(i,j) = average(d(d > 0)); elseif nnz(D(i+nl-2:i+nl+2,j+ns-2:j+ns+2)) > 1 d = D(i+nl-2:i+nl+2,j+ns-2:j+ns+2); dis(i,j) = average(d(d > 0)); elseif nnz(D(i+nl-3:i+nl+3,j+ns-3:j+ns+3)) > 1 d = D(i+nl-3:i+nl+3,j+ns-3:j+ns+3); dis(i,j) = average(d(d > 0)); else dis(i,j) = RadMean; end end end end % Compute the volume estimate r = dis(:); CylVol = 1000*pi*sum(r.^2)/ns*Len/nl; end end ================================================ FILE: src/tools/surface_coverage2.m ================================================ function SurfCov = surface_coverage2(Axis,Len,Vec,height,nl,ns) % Computes surface coverage (number between 0 and 1) of points on cylinder % surface defined by "Axis" and "Len". "Vec" are the vectors connecting % points to the Axis and "height" are the heights of the points from % the base of the cylinder [U,W] = orthonormal_vectors(Axis); Vec = Vec*[U W]; ang = atan2(Vec(:,2),Vec(:,1))+pi; I = ceil(height/Len*nl); I(I == 0) = 1; I(I > nl) = nl; J = ceil(ang/2/pi*ns); J(J == 0) = 1; K = [I J-1]*[1 nl]'; SurfCov = length(unique(K))/nl/ns; ================================================ FILE: src/tools/surface_coverage_filtering.m ================================================ function [Pass,c] = surface_coverage_filtering(P,c,lh,ns) % --------------------------------------------------------------------- % SURFACE_COVERAGE_FILTERING.M Filters a point cloud based on the % assumption that it samples a cylinder % % Version 1.1.0 % Latest update 6 Oct 2021 % % Copyright (C) 2017-2021 Pasi Raumonen % --------------------------------------------------------------------- % Filter a 3d-point cloud based on given cylinder (axis and radius) by % dividing the point cloud into "ns" equal-angle sectors and "lh"-height % layers along the axis. For each sector-layer intersection (a region in % the cylinder surface) keep only the points closest to the axis. % Inputs: % P Point cloud, (n_points x 3)-matrix % c Cylinder, stucture array with fields "axis", "start", % "length" % lh Height of the layers % ns Number of sectors % % Outputs: % Pass Logical vector indicating which points pass the filtering % c Cylinder, stucture array with additional fields "radius", % "SurfCov", "mad", "conv", "rel", estimated from the % filtering % --------------------------------------------------------------------- % Changes from version 1.0.0 to 1.1.0, 6 Oct 2021: % 1) Small changes to make the code little faster % 2) Change the radius estimation to make it much faster % Compute the distances, heights and angles of the points [d,V,h] = distances_to_line(P,c.axis,c.start); h = h-min(h); [U,W] = orthonormal_vectors(c.axis); V = V*[U W]; ang = atan2(V(:,2),V(:,1))+pi; % Sort based on lexicographic order of (sector,layer) nl = ceil(c.length/lh); Layer = ceil(h/c.length*nl); Layer(Layer == 0) = 1; Layer(Layer > nl) = nl; Sector = ceil(ang/2/pi*ns); Sector(Sector == 0) = 1; LexOrd = [Layer Sector-1]*[1 nl]'; [LexOrd,SortOrd] = sort(LexOrd); ds = d(SortOrd); % Estimate the distances for each sector-layer intersection Dis = zeros(nl,ns); np = size(P,1); % number of points p = 1; while p <= np t = 1; while (p+t <= np) && (LexOrd(p) == LexOrd(p+t)) t = t+1; end D = min(ds(p:p+t-1)); Dis(LexOrd(p)) = min(1.05*D,D+0.02); p = p+t; end % Compute the number of sectors based on the estimated radius R = median(Dis(Dis > 0)); a = max(0.02,0.2*R); ns = ceil(2*pi*R/a); ns = min(36,max(ns,8)); nl = ceil(c.length/a); nl = max(nl,3); % Sort based on lexicographic order of (sector,layer) Layer = ceil(h/c.length*nl); Layer(Layer == 0) = 1; Layer(Layer > nl) = nl; Sector = ceil(ang/2/pi*ns); Sector(Sector == 0) = 1; LexOrd = [Layer Sector-1]*[1 nl]'; [LexOrd,SortOrd] = sort(LexOrd); d = d(SortOrd); % Filtering for each sector-layer intersection Dis = zeros(nl,ns); Pass = false(np,1); p = 1; % index of point under processing k = 0; % number of nonempty cells r = max(0.01,0.05*R); % cell diameter from the closest point while p <= np t = 1; while (p+t <= np) && (LexOrd(p) == LexOrd(p+t)) t = t+1; end ind = p:p+t-1; D = d(ind); Dmin = min(D); I = D <= Dmin+r; Pass(ind(I)) = true; Dis(LexOrd(p)) = min(1.05*Dmin,Dmin+0.02); p = p+t; k = k+1; end d = d(Pass); % Sort the "Pass"-vector back to original point cloud order n = length(SortOrd); InvSortOrd = zeros(n,1); InvSortOrd(SortOrd) = (1:1:n)'; Pass = Pass(InvSortOrd); % Compute radius, SurfCov and mad R = median(Dis(Dis > 0)); mad = sum(abs(d-R))/length(d); c.radius = R; c.SurfCov = k/nl/ns; c.mad = mad; c.conv = 1; c.rel = 1; ================================================ FILE: src/tools/unique2.m ================================================ function SetUni = unique2(Set) n = length(Set); if n > 0 Set = sort(Set); d = Set(2:n)-Set(1:n-1); A = Set(2:n); I = d > 0; SetUni = [Set(1); A(I)]; else SetUni = Set; end ================================================ FILE: src/tools/unique_elements.m ================================================ function Set = unique_elements(Set,False) n = length(Set); if n > 2 I = true(n,1); for j = 1:n if ~False(Set(j)) False(Set(j)) = true; else I(j) = false; end end Set = Set(I); elseif n == 2 if Set(1) == Set(2) Set = Set(1); end end ================================================ FILE: src/tools/update_tree_data.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function treedata = update_tree_data(QSM,cylinder,branch,inputs) % --------------------------------------------------------------------- % UPDATE_TREE_DATA.M Updates the treedata structure, e.g. after % simplification of QSM % % Version 1.0.0 % Latest update 4 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % Inputs: % treedata Treedata structure from "tree_data" % cylinder Cylinder structure from "cylinders" % branch Branch structure from "branches" % % Output: % treedata Tree data/attributes in a struct % --------------------------------------------------------------------- % Define some variables from cylinder: treedata = QSM.treedata; Rad = cylinder.radius; Len = cylinder.length; Sta = cylinder.start; Axe = cylinder.axis; nc = length(Rad); ind = (1:1:nc)'; Trunk = cylinder.branch == 1; % Trunk cylinders %% Tree attributes from cylinders % Volumes, areas, lengths, branches treedata.TotalVolume = 1000*pi*Rad.^2'*Len; treedata.TrunkVolume = 1000*pi*Rad(Trunk).^2'*Len(Trunk); treedata.BranchVolume = 1000*pi*Rad(~Trunk).^2'*Len(~Trunk); bottom = min(Sta(:,3)); [top,i] = max(Sta(:,3)); if Axe(i,3) > 0 top = top+Len(i)*Axe(i,3); end treedata.TreeHeight = top-bottom; treedata.TrunkLength = sum(Len(Trunk)); treedata.BranchLength = sum(Len(~Trunk)); treedata.TotalLength = treedata.TrunkLength+treedata.BranchLength; NB = length(branch.order)-1; % number of branches treedata.NumberBranches = NB; BO = max(branch.order); % maximum branch order treedata.MaxBranchOrder = BO; treedata.TrunkArea = 2*pi*sum(Rad(Trunk).*Len(Trunk)); treedata.BranchArea = 2*pi*sum(Rad(~Trunk).*Len(~Trunk)); treedata.TotalArea = 2*pi*sum(Rad.*Len); %% Crown measures,Vertical profile and spreads [treedata,spreads] = crown_measures(treedata,cylinder,branch); %% Update triangulation information if inputs.Tria treedata = update_triangulation(QSM,treedata,cylinder); end %% Tree Location treedata.location = Sta(1,:); %% Stem taper R = Rad(Trunk); n = length(R); Taper = zeros(n+1,2); Taper(1,2) = 2*R(1); Taper(2:end,1) = cumsum(Len(Trunk)); Taper(2:end,2) = [2*R(2:end); 2*R(n)]; treedata.StemTaper = Taper'; %% Vertical profile and spreads treedata.VerticalProfile = mean(spreads,2); treedata.spreads = spreads; %% CYLINDER DISTRIBUTIONS: %% Wood part diameter distributions % Volume, area and length of wood parts as functions of cylinder diameter % (in 1cm diameter classes) treedata = cylinder_distribution(treedata,Rad,Len,Axe,'Dia'); %% Wood part height distributions % Volume, area and length of cylinders as a function of height % (in 1 m height classes) treedata = cylinder_height_distribution(treedata,Rad,Len,Sta,Axe,ind); %% Wood part zenith direction distributions % Volume, area and length of wood parts as functions of cylinder zenith % direction (in 10 degree angle classes) treedata = cylinder_distribution(treedata,Rad,Len,Axe,'Zen'); %% Wood part azimuth direction distributions % Volume, area and length of wood parts as functions of cylinder zenith % direction (in 10 degree angle classes) treedata = cylinder_distribution(treedata,Rad,Len,Axe,'Azi'); %% BRANCH DISTRIBUTIONS: %% Branch order distributions % Volume, area, length and number of branches as a function of branch order treedata = branch_order_distribution(treedata,branch); %% Branch diameter distributions % Volume, area, length and number of branches as a function of branch diameter % (in 1cm diameter classes) treedata = branch_distribution(treedata,branch,'Dia'); %% Branch height distribution % Volume, area, length and number of branches as a function of branch height % (in 1 meter classes) for all and 1st-order branches treedata = branch_distribution(treedata,branch,'Hei'); %% Branch angle distribution % Volume, area, length and number of branches as a function of branch angle % (in 10 deg angle classes) for all and 1st-order branches treedata = branch_distribution(treedata,branch,'Ang'); %% Branch azimuth distribution % Volume, area, length and number of branches as a function of branch azimuth % (in 22.5 deg angle classes) for all and 1st-order branches treedata = branch_distribution(treedata,branch,'Azi'); %% Branch zenith distribution % Volume, area, length and number of branches as a function of branch zenith % (in 10 deg angle classes) for all and 1st-order branches treedata = branch_distribution(treedata,branch,'Zen'); %% change into single-format Names = fieldnames(treedata); n = size(Names,1); for i = 1:n treedata.(Names{i}) = single(treedata.(Names{i})); end if inputs.disp == 2 %% Generate units for displaying the treedata Units = zeros(n,3); m = 23; for i = 1:n if ~inputs.Tria && strcmp(Names{i},'CrownVolumeAlpha') m = i; elseif inputs.Tria && strcmp(Names{i},'TriaTrunkLength') m = i; end if strcmp(Names{i}(1:3),'DBH') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'ume') Units(i,:) = 'L '; elseif strcmp(Names{i}(end-2:end),'ght') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'gth') Units(i,:) = 'm '; elseif strcmp(Names{i}(1:3),'vol') Units(i,:) = 'L '; elseif strcmp(Names{i}(1:3),'len') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'rea') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(1:3),'loc') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-4:end),'aConv') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(end-5:end),'aAlpha') Units(i,:) = 'm^2'; elseif strcmp(Names{i}(end-4:end),'eConv') Units(i,:) = 'm^3'; elseif strcmp(Names{i}(end-5:end),'eAlpha') Units(i,:) = 'm^3'; elseif strcmp(Names{i}(end-2:end),'Ave') Units(i,:) = 'm '; elseif strcmp(Names{i}(end-2:end),'Max') Units(i,:) = 'm '; end end %% Display treedata disp('------------') disp(' Tree attributes:') for i = 1:m v = change_precision(treedata.(Names{i})); if strcmp(Names{i},'DBHtri') disp(' -----') disp(' Tree attributes from triangulation:') end disp([' ',Names{i},' = ',num2str(v),' ',Units(i,:)]) end disp(' -----') end if inputs.plot > 1 %% Plot distributions figure(6) subplot(2,4,1) plot(Taper(:,1),Taper(:,2),'-b') title('Stem taper') xlabel('Distance from base (m)') ylabel('Diameter (m)') axis tight grid on Q.treedata = treedata; subplot(2,4,2) plot_distribution(Q,6,0,0,'VolCylDia') subplot(2,4,3) plot_distribution(Q,6,0,0,'AreCylDia') subplot(2,4,4) plot_distribution(Q,6,0,0,'LenCylDia') subplot(2,4,5) plot_distribution(Q,6,0,0,'VolBranchOrd') subplot(2,4,6) plot_distribution(Q,6,0,0,'LenBranchOrd') subplot(2,4,7) plot_distribution(Q,6,0,0,'AreBranchOrd') subplot(2,4,8) plot_distribution(Q,6,0,0,'NumBranchOrd') figure(7) subplot(3,3,1) plot_distribution(Q,7,0,0,'VolCylHei') subplot(3,3,2) plot_distribution(Q,7,0,0,'AreCylHei') subplot(3,3,3) plot_distribution(Q,7,0,0,'LenCylHei') subplot(3,3,4) plot_distribution(Q,7,0,0,'VolCylZen') subplot(3,3,5) plot_distribution(Q,7,0,0,'AreCylZen') subplot(3,3,6) plot_distribution(Q,7,0,0,'LenCylZen') subplot(3,3,7) plot_distribution(Q,7,0,0,'VolCylAzi') subplot(3,3,8) plot_distribution(Q,7,0,0,'AreCylAzi') subplot(3,3,9) plot_distribution(Q,7,0,0,'LenCylAzi') figure(8) subplot(3,4,1) plot_distribution(Q,8,1,0,'VolBranchDia','VolBranch1Dia') subplot(3,4,2) plot_distribution(Q,8,1,0,'AreBranchDia','AreBranch1Dia') subplot(3,4,3) plot_distribution(Q,8,1,0,'LenBranchDia','LenBranch1Dia') subplot(3,4,4) plot_distribution(Q,8,1,0,'NumBranchDia','NumBranch1Dia') subplot(3,4,5) plot_distribution(Q,8,1,0,'VolBranchHei','VolBranch1Hei') subplot(3,4,6) plot_distribution(Q,8,1,0,'AreBranchHei','AreBranch1Hei') subplot(3,4,7) plot_distribution(Q,8,1,0,'LenBranchHei','LenBranch1Hei') subplot(3,4,8) plot_distribution(Q,8,1,0,'NumBranchHei','NumBranch1Hei') subplot(3,4,9) plot_distribution(Q,8,1,0,'VolBranchAng','VolBranch1Ang') subplot(3,4,10) plot_distribution(Q,8,1,0,'AreBranchAng','AreBranch1Ang') subplot(3,4,11) plot_distribution(Q,8,1,0,'LenBranchAng','LenBranch1Ang') subplot(3,4,12) plot_distribution(Q,8,1,0,'NumBranchAng','NumBranch1Ang') figure(9) subplot(2,4,1) plot_distribution(Q,9,1,0,'VolBranchZen','VolBranch1Zen') subplot(2,4,2) plot_distribution(Q,9,1,0,'AreBranchZen','AreBranch1Zen') subplot(2,4,3) plot_distribution(Q,9,1,0,'LenBranchZen','LenBranch1Zen') subplot(2,4,4) plot_distribution(Q,9,1,0,'NumBranchZen','NumBranch1Zen') subplot(2,4,5) plot_distribution(Q,9,1,0,'VolBranchAzi','VolBranch1Azi') subplot(2,4,6) plot_distribution(Q,9,1,0,'AreBranchAzi','AreBranch1Azi') subplot(2,4,7) plot_distribution(Q,9,1,0,'LenBranchAzi','LenBranch1Azi') subplot(2,4,8) plot_distribution(Q,9,1,0,'NumBranchAzi','NumBranch1Azi') end end % End of main function function [treedata,spreads] = crown_measures(treedata,cylinder,branch) %% Generate point clouds from the cylinder model Axe = cylinder.axis; Len = cylinder.length; Sta = cylinder.start; Tip = Sta+[Len.*Axe(:,1) Len.*Axe(:,2) Len.*Axe(:,3)]; % tips of the cylinders nc = length(Len); P = zeros(5*nc,3); % four mid points on the cylinder surface t = 0; for i = 1:nc [U,V] = orthonormal_vectors(Axe(i,:)); U = cylinder.radius(i)*U; if cylinder.branch(i) == 1 % For stem cylinders generate more points for k = 1:4 M = Sta(i,:)+k*Len(i)/4*Axe(i,:); R = rotation_matrix(Axe(i,:),pi/12); for j = 1:12 if j > 1 U = R*U; end t = t+1; P(t,:) = M+U'; end end else M = Sta(i,:)+Len(i)/2*Axe(i,:); R = rotation_matrix(Axe(i,:),pi/4); for j = 1:4 if j > 1 U = R*U; end t = t+1; P(t,:) = M+U'; end end end P = P(1:t,:); P = double([P; Sta; Tip]); P = unique(P,'rows'); %% Vertical profiles (layer diameters/spreads), mean: bot = min(P(:,3)); top = max(P(:,3)); Hei = top-bot; if Hei > 10 m = 20; elseif Hei > 2 m = 10; else m = 5; end spreads = zeros(m,18); for j = 1:m I = P(:,3) >= bot+(j-1)*Hei/m & P(:,3) < bot+j*Hei/m; X = unique(P(I,:),'rows'); if size(X,1) > 5 [K,A] = convhull(X(:,1),X(:,2)); % compute center of gravity for the convex hull and use it as % center for computing average diameters n = length(K); x = X(K,1); y = X(K,2); CX = sum((x(1:n-1)+x(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A; CY = sum((y(1:n-1)+y(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A; V = mat_vec_subtraction(X(:,1:2),[CX CY]); ang = atan2(V(:,2),V(:,1))+pi; [ang,I] = sort(ang); L = sqrt(sum(V.*V,2)); L = L(I); for i = 1:18 I = ang >= (i-1)*pi/18 & ang < i*pi/18; if any(I) L1 = max(L(I)); else L1 = 0; end J = ang >= (i-1)*pi/18+pi & ang < i*pi/18+pi; if any(J) L2 = max(L(J)); else L2 = 0; end spreads(j,i) = L1+L2; end end end %% Crown diameters (spreads), mean and maximum: X = unique(P(:,1:2),'rows'); [K,A] = convhull(X(:,1),X(:,2)); % compute center of gravity for the convex hull and use it as center for % computing average diameters n = length(K); x = X(K,1); y = X(K,2); CX = sum((x(1:n-1)+x(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A; CY = sum((y(1:n-1)+y(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A; V = mat_vec_subtraction(Tip(:,1:2),[CX CY]); ang = atan2(V(:,2),V(:,1))+pi; [ang,I] = sort(ang); L = sqrt(sum(V.*V,2)); L = L(I); S = zeros(18,1); for i = 1:18 I = ang >= (i-1)*pi/18 & ang < i*pi/18; if any(I) L1 = max(L(I)); else L1 = 0; end J = ang >= (i-1)*pi/18+pi & ang < i*pi/18+pi; if any(J) L2 = max(L(J)); else L2 = 0; end S(i) = L1+L2; end treedata.CrownDiamAve = mean(S); MaxDiam = 0; for i = 1:n V = mat_vec_subtraction([x y],[x(i) y(i)]); L = max(sqrt(sum(V.*V,2))); if L > MaxDiam MaxDiam = L; end end treedata.CrownDiamMax = L; %% Crown areas from convex hull and alpha shape: treedata.CrownAreaConv = A; alp = max(0.5,treedata.CrownDiamAve/10); shp = alphaShape(X(:,1),X(:,2),alp); treedata.CrownAreaAlpha = shp.area; %% Crown base % Define first major branch as the branch whose diameter > min(0.05*dbh,5cm) % and whose horizontal relative reach is more than the median reach of 1st-ord. % branches (or at maximum 10). The reach is defined as the horizontal % distance from the base to the tip divided by the dbh. dbh = treedata.DBHcyl; nb = length(branch.order); HL = zeros(nb,1); % horizontal reach branches1 = (1:1:nb)'; branches1 = branches1(branch.order == 1); % 1st-order branches nb = length(branches1); nc = size(Sta,1); ind = (1:1:nc)'; for i = 1:nb C = ind(cylinder.branch == branches1(i)); if ~isempty(C) base = Sta(C(1),:); C = C(end); tip = Sta(C,:)+Len(C)*Axe(C); V = tip(1:2)-base(1:2); HL(branches1(i)) = sqrt(V*V')/dbh*2; end end M = min(10,median(HL)); % Sort the branches according to the their heights Hei = branch.height(branches1); [Hei,SortOrd] = sort(Hei); branches1 = branches1(SortOrd); % Search the first/lowest branch: d = min(0.05,0.05*dbh); b = 0; if nb > 1 i = 1; while i < nb i = i+1; if branch.diameter(branches1(i)) > d && HL(branches1(i)) > M b = branches1(i); i = nb+2; end end if i == nb+1 && nb > 1 b = branches1(1); end end if b > 0 % search all the children of the first major branch: nb = size(branch.parent,1); Ind = (1:1:nb)'; chi = Ind(branch.parent == b); B = b; while ~isempty(chi) B = [B; chi]; n = length(chi); C = cell(n,1); for i = 1:n C{i} = Ind(branch.parent == chi(i)); end chi = vertcat(C{:}); end % define crown base height from the ground: BaseHeight = max(Sta(:,3)); % Height of the crown base for i = 1:length(B) C = ind(cylinder.branch == B(i)); ht = min(Tip(C,3)); hb = min(Sta(C,3)); h = min(hb,ht); if h < BaseHeight BaseHeight = h; end end treedata.CrownBaseHeight = BaseHeight-Sta(1,3); %% Crown length and ratio treedata.CrownLength = treedata.TreeHeight-treedata.CrownBaseHeight; treedata.CrownRatio = treedata.CrownLength/treedata.TreeHeight; %% Crown volume from convex hull and alpha shape: I = P(:,3) >= BaseHeight; X = P(I,:); [K,V] = convhull(X(:,1),X(:,2),X(:,3)); treedata.CrownVolumeConv = V; alp = max(0.5,treedata.CrownDiamAve/5); shp = alphaShape(X(:,1),X(:,2),X(:,3),alp,'HoleThreshold',10000); treedata.CrownVolumeAlpha = shp.volume; else % No branches treedata.CrownBaseHeight = treedata.TreeHeight; treedata.CrownLength = 0; treedata.CrownRatio = 0; treedata.CrownVolumeConv = 0; treedata.CrownVolumeAlpha = 0; end end % End of function function treedata = update_triangulation(QSM,treedata,cylinder) % Update the mixed results: if ~isempty(QSM.triangulation) CylInd = QSM.triangulation.cylind; Rad = cylinder.radius; Len = cylinder.length; % Determine the new stem cylinder that is about the location where the % triangulation stops: nc = length(Rad); ind = (1:1:nc)'; ind = ind(cylinder.branch == 1); % cylinders in the stem S = QSM.cylinder.start(CylInd,:); % The place where the triangulation stops V = cylinder.start(ind,:)-S; d = sqrt(sum(V.*V,2)); [d,I] = min(d); V = V(I,:); CylInd = ind(I); % The new cylinder closest to the correct place if d < 0.01 TrunkVolMix = treedata.TrunkVolume-... 1000*pi*sum(Rad(1:CylInd-1).^2.*Len(1:CylInd-1))+QSM.triangulation.volume; TrunkAreaMix = treedata.TrunkArea-... 2*pi*sum(Rad(1:CylInd-1).*Len(1:CylInd-1))+QSM.triangulation.SideArea; else % Select the following cylinder h = V*cylinder.axis(CylInd,:)'; if h < 0 CylInd = CylInd+1; V = cylinder.start(CylInd,:)-S; h = V*cylinder.axis(CylInd,:)'; end Len(CylInd-1) = Len(CylInd-1)-h; TrunkVolMix = treedata.TrunkVolume-... 1000*pi*sum(Rad(1:CylInd-1).^2.*Len(1:CylInd-1))+QSM.triangulation.volume; TrunkAreaMix = treedata.TrunkArea-... 2*pi*sum(Rad(1:CylInd-1).*Len(1:CylInd-1))+QSM.triangulation.SideArea; end treedata.MixTrunkVolume = TrunkVolMix; treedata.MixTotalVolume = TrunkVolMix+treedata.BranchVolume; treedata.MixTrunkArea = TrunkAreaMix; treedata.MixTotalArea = TrunkAreaMix+treedata.BranchArea; end end function treedata = cylinder_distribution(treedata,Rad,Len,Axe,dist) %% Wood part diameter, zenith and azimuth direction distributions % Volume, area and length of wood parts as functions of cylinder % diameter, zenith, and azimuth if strcmp(dist,'Dia') Par = Rad; n = ceil(max(200*Rad)); a = 0.005; % diameter in 1 cm classes elseif strcmp(dist,'Zen') Par = 180/pi*acos(Axe(:,3)); n = 18; a = 10; % zenith direction in 10 degree angle classes elseif strcmp(dist,'Azi') Par = 180/pi*atan2(Axe(:,2),Axe(:,1))+180; n = 36; a = 10; % azimuth direction in 10 degree angle classes end CylDist = zeros(3,n); for i = 1:n K = Par >= (i-1)*a & Par < i*a; CylDist(1,i) = 1000*pi*sum(Rad(K).^2.*Len(K)); % volumes in litres CylDist(2,i) = 2*pi*sum(Rad(K).*Len(K)); % areas in litres CylDist(3,i) = sum(Len(K)); % lengths in meters end treedata.(['VolCyl',dist]) = CylDist(1,:); treedata.(['AreCyl',dist]) = CylDist(2,:); treedata.(['LenCyl',dist]) = CylDist(3,:); end function treedata = cylinder_height_distribution(treedata,Rad,Len,Sta,Axe,ind) %% Wood part height distributions % Volume, area and length of cylinders as a function of height % (in 1 m height classes) MaxHei= ceil(treedata.TreeHeight); treedata.VolCylHei = zeros(1,MaxHei); treedata.AreCylHei = zeros(1,MaxHei); treedata.LenCylHei = zeros(1,MaxHei); End = Sta+[Len.*Axe(:,1) Len.*Axe(:,2) Len.*Axe(:,3)]; bot = min(Sta(:,3)); B = Sta(:,3)-bot; T = End(:,3)-bot; for j = 1:MaxHei I1 = B >= (j-2) & B < (j-1); % base below this bin J1 = B >= (j-1) & B < j; % base in this bin K1 = B >= j & B < (j+1); % base above this bin I2 = T >= (j-2) & T < (j-1); % top below this bin J2 = T >= (j-1) & T < j; % top in this bin K2 = T >= j & T < (j+1); % top above this bin C1 = ind(J1&J2); % base and top in this bin C2 = ind(J1&K2); % base in this bin, top above C3 = ind(J1&I2); % base in this bin, top below C4 = ind(I1&J2); % base in bin below, top in this C5 = ind(K1&J2); % base in bin above, top in this v1 = 1000*pi*sum(Rad(C1).^2.*Len(C1)); a1 = 2*pi*sum(Rad(C1).*Len(C1)); l1 = sum(Len(C1)); r2 = (j-B(C2))./(T(C2)-B(C2)); % relative portion in this bin v2 = 1000*pi*sum(Rad(C2).^2.*Len(C2).*r2); a2 = 2*pi*sum(Rad(C2).*Len(C2).*r2); l2 = sum(Len(C2).*r2); r3 = (B(C3)-j+1)./(B(C3)-T(C3)); % relative portion in this bin v3 = 1000*pi*sum(Rad(C3).^2.*Len(C3).*r3); a3 = 2*pi*sum(Rad(C3).*Len(C3).*r3); l3 = sum(Len(C3).*r3); r4 = (T(C4)-j+1)./(T(C4)-B(C4)); % relative portion in this bin v4 = 1000*pi*sum(Rad(C4).^2.*Len(C4).*r4); a4 = 2*pi*sum(Rad(C4).*Len(C4).*r4); l4 = sum(Len(C4).*r4); r5 = (j-T(C5))./(B(C5)-T(C5)); % relative portion in this bin v5 = 1000*pi*sum(Rad(C5).^2.*Len(C5).*r5); a5 = 2*pi*sum(Rad(C5).*Len(C5).*r5); l5 = sum(Len(C5).*r5); treedata.VolCylHei(j) = v1+v2+v3+v4+v5; treedata.AreCylHei(j) = a1+a2+a3+a4+a5; treedata.LenCylHei(j) = l1+l2+l3+l4+l5; end end function treedata = branch_distribution(treedata,branch,dist) %% Branch diameter, height, angle, zenith and azimuth distributions % Volume, area, length and number of branches as a function of branch % diamater, height, angle, zenith and aximuth BOrd = branch.order(2:end); BVol = branch.volume(2:end); BAre = branch.area(2:end); BLen = branch.length(2:end); if strcmp(dist,'Dia') Par = branch.diameter(2:end); n = ceil(max(100*Par)); a = 0.005; % diameter in 1 cm classes elseif strcmp(dist,'Hei') Par = branch.height(2:end); n = ceil(treedata.TreeHeight); a = 1; % height in 1 m classes elseif strcmp(dist,'Ang') Par = branch.angle(2:end); n = 18; a = 10; % angle in 10 degree classes elseif strcmp(dist,'Zen') Par = branch.zenith(2:end); n = 18; a = 10; % zenith direction in 10 degree angle classes elseif strcmp(dist,'Azi') Par = branch.azimuth(2:end)+180; n = 36; a = 10; % azimuth direction in 10 degree angle classes end BranchDist = zeros(8,n); for i = 1:n I = Par >= (i-1)*a & Par < i*a; BranchDist(1,i) = sum(BVol(I)); % volume (all branches) BranchDist(2,i) = sum(BVol(I & BOrd == 1)); % volume (1st-branches) BranchDist(3,i) = sum(BAre(I)); % area (all branches) BranchDist(4,i) = sum(BAre(I & BOrd == 1)); % area (1st-branches) BranchDist(5,i) = sum(BLen(I)); % length (all branches) BranchDist(6,i) = sum(BLen(I & BOrd == 1)); % length (1st-branches) BranchDist(7,i) = nnz(I); % number (all branches) BranchDist(8,i) = nnz(I & BOrd == 1); % number (1st-branches) end treedata.(['VolBranch',dist]) = BranchDist(1,:); treedata.(['VolBranch1',dist]) = BranchDist(2,:); treedata.(['AreBranch',dist]) = BranchDist(3,:); treedata.(['AreBranch1',dist]) = BranchDist(4,:); treedata.(['LenBranch',dist]) = BranchDist(5,:); treedata.(['LenBranch1',dist]) = BranchDist(6,:); treedata.(['NumBranch',dist]) = BranchDist(7,:); treedata.(['NumBranch1',dist]) = BranchDist(8,:); end function treedata = branch_order_distribution(treedata,branch) %% Branch order distributions % Volume, area, length and number of branches as a function of branch order BO = max(branch.order); BranchOrdDist = zeros(BO,4); for i = 1:max(1,BO) I = branch.order == i; BranchOrdDist(i,1) = sum(branch.volume(I)); % volumes BranchOrdDist(i,2) = sum(branch.area(I)); % areas BranchOrdDist(i,3) = sum(branch.length(I)); % lengths BranchOrdDist(i,4) = nnz(I); % number of ith-order branches end treedata.VolBranchOrd = BranchOrdDist(:,1)'; treedata.AreBranchOrd = BranchOrdDist(:,2)'; treedata.LenBranchOrd = BranchOrdDist(:,3)'; treedata.NumBranchOrd = BranchOrdDist(:,4)'; end ================================================ FILE: src/tools/verticalcat.m ================================================ function [Vector,IndElements] = verticalcat(CellArray) % Vertical concatenation of the given cell-array into a vector. CellSize = cellfun('length',CellArray); % determine the size of each cell nc = max(size(CellArray)); % number of cells IndElements = ones(nc,2); % indexes for elements in each cell IndElements(:,2) = cumsum(CellSize); IndElements(2:end,1) = IndElements(2:end,1)+IndElements(1:end-1,2); Vector = zeros(sum(CellSize),1); % concatenation of the cell-array into a vector for j = 1:nc Vector(IndElements(j,1):IndElements(j,2)) = CellArray{j}; end ================================================ FILE: src/treeqsm.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function QSM = treeqsm(P,inputs) % --------------------------------------------------------------------- % TREEQSM.M Reconstructs quantitative structure tree models from point % clouds containing a tree. % % Version 2.4.1 % Latest update 2 May 2022 % % Copyright (C) 2013-2022 Pasi Raumonen % --------------------------------------------------------------------- % % INPUTS: % % P (Filtered) point cloud, (m_points x 3)-matrix, the rows % give the coordinates of the points. % % inputs Structure field defining reconstruction parameters. % Created with the "create_input.m" script. Contains % the following main fields: % PatchDiam1 Patch size of the first uniform-size cover % % PatchDiam2Min Minimum patch size of the cover sets in the second cover % % PatchDiam2Max Maximum cover set size in the stem's base in the % second cover % % BallRad1 Ball size used for the first cover generation % % BallRad2 Maximum ball radius used for the second cover generation % % nmin1 Minimum number of points in BallRad1-balls, % default value is 3. % % nmin2 Minimum number of points in BallRad2-balls, % default value is 1. % % OnlyTree If "1", the point cloud contains only points from the % tree and the trunk's base is defined as the lowest % part of the point cloud. Default value is "1". % % Tria If "1", tries to make triangulation for the stem up % to first main branch. Default value is "0". % % Dist If "1", compute the point-model distances. % Default value is "1". % % MinCylRad Minimum cylinder radius, used particularly in the % taper corrections % % ParentCor If "1", child branch cylinders radii are always % smaller than the parent branche's cylinder radii % % TaperCor If "1", use partially linear (stem) and parabola % (branches) taper corrections % % GrowthVolCor If "1", use growth volume correction introduced % by Jan Hackenberg % % GrowthVolFac fac-parameter of the growth volume approach, % defines upper and lower bound % % name Name string for saving output files and name for the % model in the output object % % tree Numerical id/index given to the tree % % model Model number of the tree, e.g. with the same inputs % % savemat If "1", saves the output struct QSM as a matlab-file % into \result folder % % savetxt If "1", saves the models in .txt-files into % \result folder % % plot Defines what is plotted during the reconstruction: % 2 = same as below plus distributions % 1 = plots the segmented point cloud and QSMs % 0 = plots nothing % % disp Defines what is displayed during the reconstruction: % 2 = same as below plus times and tree attributes; % 1 = display name, parameters and fit metrics; % 0 = display only the name % --------------------------------------------------------------------- % OUTPUT: % % QSM Structure array with the following fields: % cylinder Cylinder data % branch Branch data % treedata Tree attributes % rundata Information about the modelling run % pmdistances Point-to-model distance statistics % triangulation Triangulation of the stem (if inputs.Tria = 1) % --------------------------------------------------------------------- % cylinder (structure-array) contains the following fields: % radius % length % start xyz-coordinates of the starting point % axis xyz-component of the cylinder axis % parent index (in this file) of the parent cylinder % extension index (in this file) of the extension cylinder % added is cylinder added after normal cylinder fitting (= 1 if added) % UnmodRadius unmodified radius of the cylinder % branch branch (index in the branch structure array) of the cylinder % BranchOrder branch order of the branch the cylinder belongs % PositionInBranch running number of the cylinder in the branch it belongs % % branch (structure-array) contains the following fields: % order branch order (0 for trunk, 1 for branches originating from % the trunk, etc.) % parent index (in this file) of the parent branch % volume volume (L) of the branch (sum of the volumes of the cylinders % forming the branch) % length length (m) of the branch (sum of the lengths of the cylinders) % angle branching angle (deg) (angle between the branch and its parent % at the branching point) % height height (m) of the base of the branch % azimuth azimuth (deg) of the branch at the base % diameter diameter (m) of the branch at the base % % treedata (structure-array) contains the following fields: % TotalVolume % TrunkVolume % BranchVolume % TreeHeight % TrunkLength % BranchLength % NumberBranches Total number of branches % MaxBranchOrder % TotalArea % DBHqsm From the cylinder of the QSM at the right heigth % DBHcyl From the cylinder fitted to the section 1.1-1.5m % location (x,y,z)-coordinates of the base of the tree % StemTaper Stem taper function/curve from the QSM % VolumeCylDiam Distribution of the total volume in diameter classes % LengthCylDiam Distribution of the total length in diameter classes % VolumeBranchOrder Branch volume per branching order % LengthBranchOrder Branch length per branching order % NumberBranchOrder Number of branches per branching order % treedata from mixed model (cylinders and triangulation) contains also % the following fields: % DBHtri Computed from triangulation model % TriaTrunkVolume Triangulated trunk volume (up to first branch) % MixTrunkVolume Mixed trunk volume, bottom (triang.) + top (cylinders) % MixTotalVolume Mixed total volume, mixed trunk volume + branch volume % TriaTrunkLength Triangulated trunk length % % pmdistances (structure-array) contains the following fields (and others): % CylDists Average point-model distance for each cylinder % median median of CylDist for all, stem, 1branch, 2branch cylinder % mean mean of CylDist for all, stem, 1branch, 2branch cylinder % max max of CylDist for all, stem, 1branch, 2branch cylinder % std standard dev. of CylDist for all, stem, 1branch, 2branch cylinder % % rundata (structure-array) contains the following fields: % inputs The input parameters in a structure-array % time Computation times for each step % date Starting and stopping dates (year,month,day,hour,minute,second) % of the computation % % triangulation (structure-array) contains the following fields: % vert Vertices (xyz-coordinates) of the triangulation % facet Facet information % fvd Color information for plotting the model % volume Volume enclosed by the triangulation % bottom Z-coordinate of the bottom plane of the triangulation % top Z-coordinate of the top plane of the triangulation % triah Height of the triangles % triah Width of the triangles % cylind Cylinder index in the stem where the triangulation stops % --------------------------------------------------------------------- % Changes from version 2.4.0 to 2.4.1, 2 May 2022: % Minor update. New filtering options, new code ("define_input") for % selecting automatically PatchDiam and BallRad parameter values for % the optimization process, added sensitivity estimates of the results, % new smoother plotting of QSMs, corrected some bugs, rewrote some % functions (e.g. "branches"). % Particular changes in treeqsm.m file: % 1) Deleted the remove of the field "ChildCyls" and "CylsInSegment". % Changes from version 2.3.2 to 2.4.0, 17 Aug 2020: % First major update. Cylinder fitting process and the taper correction % has changed. The fitting is adaptive and no more “lcyl” and “FilRad” % parameters. Treedata has many new outputs: Branch and cylinder % distributions; surface areas; crown dimensions. More robust triangulation % of stem. Branch, cylinder and triangulation structures have new fields. % More optimisation metrics, more plots of the results and more plotting % functions. % Particular changes in treeqsm.m file: % 1) Removed the for-loops for lcyl and FilRad. % 2) Changes what is displayed about the quality of QSMs % (point-model-distances and surface coverage) during reconstruction % 3) Added version number to rundata % 4) Added remove of the field "ChildCyls" and "CylsInSegment" of "cylinder" % from "branches" to "treeqsm". % Changes from version 2.3.1 to 2.3.2, 2 Dec 2019: % Small changes in the subfunction to allow trees without branches % Changes from version 2.3.0 to 2.3.1, 8 Oct 2019: % 1) Some changes in the subfunctions, particularly in "cylinders" and % "tree_sets" % 2) Changed how "treeqsm" displays things during the running of the % function %% Code starts --> Time = zeros(11,1); % Save computation times for modelling steps Date = zeros(2,6); % Starting and stopping dates of the computation Date(1,:) = clock; % Names of the steps to display name = ['Cover sets '; 'Tree sets '; 'Initial segments'; 'Final segments '; 'Cylinders '; 'Branch & data '; 'Distances ']; if inputs.disp > 0 disp('---------------') disp([' ',inputs.name,', Tree = ',num2str(inputs.tree),... ', Model = ',num2str(inputs.model)]) end % Input parameters PatchDiam1 = inputs.PatchDiam1; PatchDiam2Min = inputs.PatchDiam2Min; PatchDiam2Max = inputs.PatchDiam2Max; BallRad1 = inputs.BallRad1; BallRad2 = inputs.BallRad2; nd = length(PatchDiam1); ni = length(PatchDiam2Min); na = length(PatchDiam2Max); if inputs.disp == 2 % Display parameter values disp([' PatchDiam1 = ',num2str(PatchDiam1)]) disp([' BallRad1 = ',num2str(BallRad1)]) disp([' PatchDiam2Min = ',num2str(PatchDiam2Min)]) disp([' PatchDiam2Max = ',num2str(PatchDiam2Max)]) disp([' BallRad2 = ',num2str(BallRad2)]) disp([' Tria = ',num2str(inputs.Tria),... ', OnlyTree = ',num2str(inputs.OnlyTree)]) disp('Progress:') end %% Make the point cloud into proper form % only 3-dimensional data if size(P,2) > 3 P = P(:,1:3); end % Only double precision data if ~isa(P,'double') P = double(P); end %% Initialize the output file QSM = struct('cylinder',{},'branch',{},'treedata',{},'rundata',{},... 'pmdistance',{},'triangulation',{}); %% Reconstruct QSMs nmodel = 0; for h = 1:nd tic Inputs = inputs; Inputs.PatchDiam1 = PatchDiam1(h); Inputs.BallRad1 = BallRad1(h); if nd > 1 && inputs.disp >= 1 disp(' -----------------') disp([' PatchDiam1 = ',num2str(PatchDiam1(h))]); disp(' -----------------') end %% Generate cover sets cover1 = cover_sets(P,Inputs); Time(1) = toc; if inputs.disp == 2 display_time(Time(1),Time(1),name(1,:),1) end %% Determine tree sets and update neighbors [cover1,Base,Forb] = tree_sets(P,cover1,Inputs); Time(2) = toc-Time(1); if inputs.disp == 2 display_time(Time(2),sum(Time(1:2)),name(2,:),1) end %% Determine initial segments segment1 = segments(cover1,Base,Forb); Time(3) = toc-sum(Time(1:2)); if inputs.disp == 2 display_time(Time(3),sum(Time(1:3)),name(3,:),1) end %% Correct segments % Don't remove small segments and add the modified base to the segment segment1 = correct_segments(P,cover1,segment1,Inputs,0,1,1); Time(4) = toc-sum(Time(1:3)); if inputs.disp == 2 display_time(Time(4),sum(Time(1:4)),name(4,:),1) end for i = 1:na % Modify inputs Inputs.PatchDiam2Max = PatchDiam2Max(i); Inputs.BallRad2 = BallRad2(i); if na > 1 && inputs.disp >= 1 disp(' -----------------') disp([' PatchDiam2Max = ',num2str(PatchDiam2Max(i))]); disp(' -----------------') end for j = 1:ni tic % Modify inputs Inputs.PatchDiam2Min = PatchDiam2Min(j); if ni > 1 && inputs.disp >= 1 disp(' -----------------') disp([' PatchDiam2Min = ',num2str(PatchDiam2Min(j))]); disp(' -----------------') end %% Generate new cover sets % Determine relative size of new cover sets and use only tree points RS = relative_size(P,cover1,segment1); % Generate new cover cover2 = cover_sets(P,Inputs,RS); Time(5) = toc; if inputs.disp == 2 display_time(Time(5),sum(Time(1:5)),name(1,:),1) end %% Determine tree sets and update neighbors [cover2,Base,Forb] = tree_sets(P,cover2,Inputs,segment1); Time(6) = toc-Time(5); if inputs.disp == 2 display_time(Time(6),sum(Time(1:6)),name(2,:),1) end %% Determine segments segment2 = segments(cover2,Base,Forb); Time(7) = toc-sum(Time(5:6)); if inputs.disp == 2 display_time(Time(7),sum(Time(1:7)),name(3,:),1) end %% Correct segments % Remove small segments and the extended bases. segment2 = correct_segments(P,cover2,segment2,Inputs,1,1,0); Time(8) = toc-sum(Time(5:7)); if inputs.disp == 2 display_time(Time(8),sum(Time(1:8)),name(4,:),1) end %% Define cylinders cylinder = cylinders(P,cover2,segment2,Inputs); Time(9) = toc; if inputs.disp == 2 display_time(Time(9),sum(Time(1:9)),name(5,:),1) end if ~isempty(cylinder.radius) %% Determine the branches branch = branches(cylinder); %% Compute (and display) model attributes T = segment2.segments{1}; T = vertcat(T{:}); T = vertcat(cover2.ball{T}); trunk = P(T,:); % point cloud of the trunk % Compute attributes and distibutions from the cylinder model % and possibly some from a triangulation [treedata,triangulation] = tree_data(cylinder,branch,trunk,inputs); Time(10) = toc-Time(9); if inputs.disp == 2 display_time(Time(10),sum(Time(1:10)),name(6,:),1) end %% Compute point model distances if inputs.Dist pmdis = point_model_distance(P,cylinder); % Display the mean point-model distances and surface coverages % for stem, branch, 1branc and 2branch cylinders if inputs.disp >= 1 D = [pmdis.TrunkMean pmdis.BranchMean ... pmdis.Branch1Mean pmdis.Branch2Mean]; D = round(10000*D)/10; T = cylinder.branch == 1; B1 = cylinder.BranchOrder == 1; B2 = cylinder.BranchOrder == 2; SC = 100*cylinder.SurfCov; S = [mean(SC(T)) mean(SC(~T)) mean(SC(B1)) mean(SC(B2))]; S = round(10*S)/10; disp(' ----------') str = [' PatchDiam1 = ',num2str(PatchDiam1(h)), ... ', PatchDiam2Max = ',num2str(PatchDiam2Max(i)), ... ', PatchDiam2Min = ',num2str(PatchDiam2Min(j))]; disp(str) str = [' Distances and surface coverages for ',... 'trunk, branch, 1branch, 2branch:']; disp(str) str = [' Average cylinder-point distance: '... num2str(D(1)),' ',num2str(D(2)),' ',... num2str(D(3)),' ',num2str(D(4)),' mm']; disp(str) str = [' Average surface coverage: '... num2str(S(1)),' ',num2str(S(2)),' ',... num2str(S(3)),' ',num2str(S(4)),' %']; disp(str) disp(' ----------') end Time(11) = toc-sum(Time(9:10)); if inputs.disp == 2 display_time(Time(11),sum(Time(1:11)),name(7,:),1) end end %% Reconstruct the output "QSM" Date(2,:) = clock; Time(12) = sum(Time(1:11)); clear qsm qsm = struct('cylinder',{},'branch',{},'treedata',{},'rundata',{},... 'pmdistance',{},'triangulation',{}); qsm(1).cylinder = cylinder; qsm(1).branch = branch; qsm(1).treedata = treedata; qsm(1).rundata.inputs = Inputs; qsm(1).rundata.time = single(Time); qsm(1).rundata.date = single(Date); qsm(1).rundata.version = '2.4.1'; if inputs.Dist qsm(1).pmdistance = pmdis; end if inputs.Tria qsm(1).triangulation = triangulation; end nmodel = nmodel+1; QSM(nmodel) = qsm; %% Save the output into results-folder % matlab-format (.mat) if inputs.savemat str = [inputs.name,'_t',num2str(inputs.tree),'_m',... num2str(inputs.model)]; save(['results/QSM_',str],'QSM') end % text-format (.txt) if inputs.savetxt if nd > 1 || na > 1 || ni > 1 str = [inputs.name,'_t',num2str(inputs.tree),'_m',... num2str(inputs.model)]; if nd > 1 str = [str,'_D',num2str(PatchDiam1(h))]; end if na > 1 str = [str,'_DA',num2str(PatchDiam2Max(i))]; end if ni > 1 str = [str,'_DI',num2str(PatchDiam2Min(j))]; end else str = [inputs.name,'_t',num2str(inputs.tree),'_m',... num2str(inputs.model)]; end save_model_text(qsm,str) end %% Plot models and segmentations if inputs.plot >= 1 if inputs.Tria plot_models_segmentations(P,cover2,segment2,cylinder,trunk,... triangulation) else plot_models_segmentations(P,cover2,segment2,cylinder) end if nd > 1 || na > 1 || ni > 1 pause end end end end end end ================================================ FILE: src/triangulation/boundary_curve.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function [Curve,Ind] = boundary_curve(P,Curve0,rball,dmax) % --------------------------------------------------------------------- % BOUNDARY_CURVE.M Determines the boundary curve based on the % previously defined boundary curve. % % Version 1.1.0 % Latest update 3 May 2022 % % Copyright (C) 2015-2022 Pasi Raumonen % --------------------------------------------------------------------- % % Inputs: % P Point cloud of the cross section % Curve0 Seed points from previous cross section curve % rball Radius of the balls centered at seed points % dmax Maximum distance between concecutive curve points, if larger, % then create a new one between the points % --------------------------------------------------------------------- % Changes from version 1.0.0 to 1.1.0, 3 May 2022: % 1) Increased the cubical neighborhood in the generation of the segments %% Partition the point cloud into cubes Min = double(min([P(:,1:2); Curve0(:,1:2)])); Max = double(max([P(:,1:2); Curve0(:,1:2)])); N = double(ceil((Max-Min)/rball)+5); % cube coordinates of the section points CC = floor([P(:,1)-Min(1) P(:,2)-Min(2)]/rball)+3; % Sorts the points according a lexicographical order S = [CC(:,1) CC(:,2)-1]*[1 N(1)]'; [S,I] = sort(S); % Define "partition" np = size(P,1); partition = cell(N(1),N(2)); p = 1; % The index of the point under comparison while p <= np t = 1; while (p+t <= np) && (S(p) == S(p+t)) t = t+1; end q = I(p); partition{CC(q,1),CC(q,2)} = I(p:p+t-1); p = p+t; end %% Define segments using the previous points % cube coordinates of the seed points: CC = floor([Curve0(:,1)-Min(1) Curve0(:,2)-Min(2)]/rball)+3; I = CC < 3; CC(I) = 3; nc = size(Curve0,1); % number of sets Dist = 1e8*ones(np,1); % distance of point to the closest center SoP = zeros(np,1); % the segment the points belong to Radius = rball^2; for i = 1:nc points = partition(CC(i,1)-2:CC(i,1)+2,CC(i,2)-2:CC(i,2)+2); points = vertcat(points{:}); V = [P(points,1)-Curve0(i,1) P(points,2)-Curve0(i,2)]; dist = sum(V.*V,2); PointsInBall = dist < Radius; points = points(PointsInBall); dist = dist(PointsInBall); D = Dist(points); L = dist < D; I = points(L); Dist(I) = dist(L); SoP(I) = i; end %% Finalise the segments % Number of points in each segment and index of each point in its segment Num = zeros(nc,1); IndPoints = zeros(np,1); for i = 1:np if SoP(i) > 0 Num(SoP(i)) = Num(SoP(i))+1; IndPoints(i) = Num(SoP(i)); end end % Continue if enough non-emtpy segments if nnz(Num) > 0.05*nc % Initialization of the "Seg" Seg = cell(nc,1); for i = 1:nc Seg{i} = zeros(Num(i),1); end % Define the "Seg" for i = 1:np if SoP(i) > 0 Seg{SoP(i),1}(IndPoints(i),1) = i; end end %% Define the new curve points as the average of the segments Curve = zeros(nc,3); % the new boundary curve Empty = false(nc,1); for i = 1:nc S = Seg{i}; if ~isempty(S) Curve(i,:) = mean(P(S,:),1); if norm(Curve(i,:)-Curve0(i,:)) > 1.25*dmax Curve(i,:) = Curve0(i,:); end else Empty(i) = true; end end %% Interpolate for empty segments % For empty segments create points by interpolation from neighboring % non-empty segments if any(Empty) for i = 1:nc if Empty(i) if i > 1 && i < nc k = 0; while i+k <= nc && Empty(i+k) k = k+1; end if i+k <= nc LineEle = Curve(i+k,:)-Curve(i-1,:); else LineEle = Curve(1,:)-Curve(i-1,:); end if k < 5 for j = 1:k Curve(i+j-1,:) = Curve(i-1,:)+j/(k+1)*LineEle; end else Curve(i:i+k-1,:) = Curve0(i:i+k-1,:); end elseif i == 1 a = 0; while Empty(end-a) a = a+1; end b = 1; while Empty(b) b = b+1; end LineEle = Curve(b,:)-Curve(nc-a,:); n = a+b-1; if n < 5 for j = 1:a-1 Curve(nc-a+1+j,:) = Curve(nc-a,:)+j/n*LineEle; end for j = 1:b-1 Curve(j,:) = Curve(nc-a,:)+(j+a-1)/n*LineEle; end else Curve(nc-a+2:nc,1:2) = Curve0(nc-a+2:nc,1:2); Curve(nc-a+2:nc,3) = Curve0(nc-a+2:nc,3); Curve(1:b-1,1:2) = Curve0(1:b-1,1:2); Curve(1:b-1,3) = Curve0(1:b-1,3); end elseif i == nc LineEle = Curve(1,:)-Curve(nc-1,:); Curve(i,:) = Curve(nc-1,:)+0.5*LineEle; end end end end % Correct the height Curve(:,3) = min(Curve(:,3)); % Check self-intersection [Intersect,IntersectLines] = check_self_intersection(Curve(:,1:2)); % If self-intersection, try to modify the curve j = 1; while Intersect && j <= 5 n = size(Curve,1); InterLines = (1:1:n)'; NumberOfIntersections = cellfun('length',IntersectLines(:,1)); I = NumberOfIntersections > 0; InterLines = InterLines(I); CrossLen = vertcat(IntersectLines{I,2}); if length(CrossLen) == length(InterLines) LineEle = Curve([2:end 1],:)-Curve(1:end,:); d = sqrt(sum(LineEle.*LineEle,2)); m = length(InterLines); for i = 1:2:m if InterLines(i) ~= n Curve(InterLines(i)+1,:) = Curve(InterLines(i),:)+... 0.9*CrossLen(i)/d(InterLines(i))*LineEle(InterLines(i),:); else Curve(1,:) = Curve(InterLines(i),:)+... 0.9*CrossLen(i)/d(InterLines(i))*LineEle(InterLines(i),:); end end [Intersect,IntersectLines] = check_self_intersection(Curve(:,1:2)); j = j+1; else j = 6; end end %% Add new points if too large distances LineEle = Curve([2:end 1],:)-Curve(1:end,:); d = sum(LineEle.*LineEle,2); Large = d > dmax^2; m = nnz(Large); if m > 0 Curve0 = zeros(nc+m,3); Ind = zeros(nc+m,2); t = 0; for i = 1:nc if Large(i) t = t+1; Curve0(t,:) = Curve(i,:); if i < nc Ind(t,:) = [i i+1]; else Ind(t,:) = [i 1]; end t = t+1; Curve0(t,:) = Curve(i,:)+0.5*LineEle(i,:); if i < nc Ind(t,:) = [i+1 0]; else Ind(t,:) = [1 0]; end else t = t+1; Curve0(t,:) = Curve(i,:); if i < nc Ind(t,:) = [i i+1]; else Ind(t,:) = [i 1]; end end end Curve = Curve0; else Ind = [(1:1:nc)' [(2:1:nc)'; 1]]; end %% Remove new points if too small distances nc = size(Curve,1); LineEle = Curve([2:end 1],:)-Curve(1:end,:); d = sum(LineEle.*LineEle,2); Small = d < (0.333*dmax)^2; m = nnz(Small); if m > 0 for i = 1:nc-1 if ~Small(i) && Small(i+1) Ind(i,2) = -1; elseif Small(i) && Small(i+1) Small(i+1) = false; end end if ~Small(nc) && Small(1) Ind(nc,2) = -1; Ind(1,2) = -1; Small(1) = false; Small(nc) = true; I = Ind(:,2) > 0; Ind(2:end,1) = Ind(2:end,1)+1; Ind(I,2) = Ind(I,2)+1; end Ind = Ind(~Small,:); Curve = Curve(~Small,:); end else % If not enough new points, return the old curve Ind = [(1:1:nc)' [(2:1:nc)'; 1]]; Curve = Curve0; end ================================================ FILE: src/triangulation/boundary_curve2.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function Curve = boundary_curve2(P,Curve0,rball,dmax) % --------------------------------------------------------------------- % BOUNDARY_CURVE2.M Determines the boundary curve based on the % previously defined boundary curve. % % Version 1.0 % Latest update 16 Aug 2017 % % Copyright (C) 2015-2017 Pasi Raumonen % --------------------------------------------------------------------- % % Inputs: % P Point cloud of the cross section % Curve0 Seed points from previous cross section curve % rball Radius of the balls centered at seed points % dmax Maximum distance between concecutive curve points, if larger, % then create a new one between the points %% Partition the point cloud into cubes Min = double(min([P(:,1:2); Curve0(:,1:2)])); Max = double(max([P(:,1:2); Curve0(:,1:2)])); N = double(ceil((Max-Min)/rball)+5); CC = floor([P(:,1)-Min(1) P(:,2)-Min(2)]/rball)+3; % cube coordinates of the section points % Sorts the points according a lexicographical order S = [CC(:,1) CC(:,2)-1]*[1 N(1)]'; [S,I] = sort(S); % Define "partition" np = size(P,1); partition = cell(N(1),N(2)); p = 1; % The index of the point under comparison while p <= np t = 1; while (p+t <= np) && (S(p) == S(p+t)) t = t+1; end q = I(p); partition{CC(q,1),CC(q,2)} = I(p:p+t-1); p = p+t; end %% Define segments using the previous points CC = floor([Curve0(:,1)-Min(1) Curve0(:,2)-Min(2)]/rball)+3; % cube coordinates of the seed points I = CC < 3; CC(I) = 3; nc = size(Curve0,1); % number of sets Dist = 1e8*ones(np,1); % distance of point to the closest center SoP = zeros(np,1); % the segment the points belong to Radius = rball^2; for i = 1:nc points = partition(CC(i,1)-1:CC(i,1)+1,CC(i,2)-1:CC(i,2)+1); points = vertcat(points{:}); V = [P(points,1)-Curve0(i,1) P(points,2)-Curve0(i,2)]; dist = sum(V.*V,2); PointsInBall = dist < Radius; points = points(PointsInBall); dist = dist(PointsInBall); D = Dist(points); L = dist < D; I = points(L); Dist(I) = dist(L); SoP(I) = i; end %% Finalise the segments % Number of points in each segment and index of each point in its segment Num = zeros(nc,1); IndPoints = zeros(np,1); for i = 1:np if SoP(i) > 0 Num(SoP(i)) = Num(SoP(i))+1; IndPoints(i) = Num(SoP(i)); end end % Continue if enough non-emtpy segments if nnz(Num) > 0.05*nc % Initialization of the "Seg" Seg = cell(nc,1); for i = 1:nc Seg{i} = zeros(Num(i),1); end % Define the "Seg" for i = 1:np if SoP(i) > 0 Seg{SoP(i),1}(IndPoints(i),1) = i; end end %% Define the new curve points as the average of the segments Curve = zeros(nc,3); % the new boundary curve for i = 1:nc S = Seg{i}; if ~isempty(S) Curve(i,:) = mean(P(S,:),1); if norm(Curve(i,:)-Curve0(i,:)) > 1.25*dmax Curve(i,:) = Curve0(i,:); end else Curve(i,:) = Curve0(i,:); end end %% Add new points if too large distances V = Curve([2:end 1],:)-Curve(1:end,:); d = sum(V.*V,2); Large = d > dmax^2; m = nnz(Large); if m > 0 Curve0 = zeros(nc+m,3); t = 0; for i = 1:nc if Large(i) t = t+1; Curve0(t,:) = Curve(i,:); t = t+1; Curve0(t,:) = Curve(i,:)+0.5*V(i,:); else t = t+1; Curve0(t,:) = Curve(i,:); end end Curve = Curve0; end %% Remove new points if too small distances nc = size(Curve,1); V = Curve([2:end 1],:)-Curve(1:end,:); d = sum(V.*V,2); Small = d < (0.333*dmax)^2; m = nnz(Small); if m > 0 for i = 1:nc-1 if Small(i) && Small(i+1) Small(i+1) = false; end end if ~Small(nc) && Small(1) Small(1) = false; Small(nc) = true; end Curve = Curve(~Small,:); end else % If not enough new points, return the old curve Curve = Curve0; end ================================================ FILE: src/triangulation/check_self_intersection.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function [Intersect,IntersectLines] = check_self_intersection(Curve) % The function takes in a curve (the coordinates of the vertices, in the % right order) and checks if the curve intersects itself % % Outputs: % Intersect Logical value indicating if the curve self-intersects % IntersectLines Cell array containing for each line element which are % the intersecting elements and how far away along % the line the intersection point is if ~isempty(Curve) dim = size(Curve,2); % two or three dimensional curve n = size(Curve,1); % number of points in the curve V = Curve([(2:n)'; 1],:)-Curve; % line elements forming the curve L = sqrt(sum(V.*V,2)); % the lengths of the line elements i = 1; % the line element under inspection Ind = (1:1:n)'; % indexes of the line elements if dim == 2 % 2d curves % directions (unit vectors) of the line elements: DirLines = [1./L.*V(:,1) 1./L.*V(:,2)]; Intersect = false; if nargout == 1 % check only if the curve intersects while i <= n-1 && ~Intersect % Select the line elements that can intersect element i if i > 1 I = Ind > i+1 | Ind < i-1; else I = Ind > i+1 & Ind < n; end ind = Ind(I)'; for j = ind % Solve for the crossing points of every line element A = [DirLines(j,:)' -DirLines(i,:)']; b = Curve(i,:)'-Curve(j,:)'; Ainv = 1/(A(1,1)*A(2,2)-A(1,2)*A(2,1))*[A(2,2) -A(1,2); -A(2,1) A(1,1)]; x = Ainv*b; % signed length along the line elements to the crossing if x(1) >= 0 && x(1) <= L(j) && x(2) >= 0 && x(2) <= L(i) Intersect = true; end end i = i+1; % study the next line element end else % determine also all intersection points (line elements) IntersectLines = cell(n,2); for i = 1:n-1 % Select the line elements that can intersect element i if i > 1 I = Ind > i+1 | Ind < i-1; else I = Ind > i+1 & Ind < n; end ind = Ind(I)'; for j = ind % Solve for the crossing points of every line element A = [DirLines(j,:)' -DirLines(i,:)']; b = Curve(i,:)'-Curve(j,:)'; Ainv = 1/(A(1,1)*A(2,2)-A(1,2)*A(2,1))*[A(2,2) -A(1,2); -A(2,1) A(1,1)]; x = Ainv*b; if x(1) >= 0 && x(1) <= L(j) && x(2) >= 0 && x(2) <= L(i) Intersect = true; % which line elements cross element i: IntersectLines{i,1} = [IntersectLines{i,1}; j]; % which line elements cross element j: IntersectLines{j,1} = [IntersectLines{j,1}; i]; % distances along element i to intersection points: IntersectLines{i,2} = [IntersectLines{i,2}; x(1)]; % distances along element j to intersection points: IntersectLines{j,2} = [IntersectLines{j,2}; x(2)]; end end end % remove possible multiple values for i = 1:n IntersectLines{i,1} = unique(IntersectLines{i,1}); IntersectLines{i,2} = min(IntersectLines{i,2}); end end elseif dim == 3 % 3d curves % directions (unit vectors) of the line elements DirLines = [1./L.*V(:,1) 1./L.*V(:,2) 1./L.*V(:,3)]; Intersect = false; if nargout == 1 % check only if the curve intersects while i <= n-1 % Select the line elements that can intersect element i if i > 1 I = Ind > i+1 | Ind < i-1; else I = Ind > i+1 & Ind < n; end % Solve for possible intersection points [~,DistOnRay,DistOnLines] = distances_between_lines(... Curve(i,:),DirLines(i,:),Curve(I,:),DirLines(I,:)); if any(DistOnRay >= 0 & DistOnRay <= L(i) &... DistOnLines > 0 & DistOnLines <= L(I)) Intersect = true; i = n; else i = i+1; % study the next line element end end else % determine also all intersection points (line elements) IntersectLines = cell(n,2); for i = 1:n-1 % Select the line elements that can intersect element i if i > 1 I = Ind > i+1 | Ind < i-1; else I = Ind > i+1 & Ind < n; end % Solve for possible intersection points [D,DistOnRay,DistOnLines] = distances_between_lines(... Curve(i,:),DirLines(i,:),Curve(I,:),DirLines(I,:)); if any(DistOnRay >= 0 & DistOnRay <= L(i) & ... DistOnLines > 0 & DistOnLines <= L(I)) Intersect = true; J = DistOnRay >= 0 & DistOnRay <= L(i) & ... DistOnLines > 0 & DistOnLines <= L(I); ind = Ind(I); ind = ind(J); DistOnLines = DistOnLines(J); IntersectLines{i,1} = ind; IntersectLines{i,2} = DistOnRay(J); % Record the elements intersecting for j = 1:length(ind) IntersectLines{ind(j),1} = [IntersectLines{ind(j),1}; i]; IntersectLines{ind(j),2} = [IntersectLines{ind(j),2}; DistOnLines(j)]; end end end % remove possible multiple values for i = 1:n IntersectLines{i} = unique(IntersectLines{i}); IntersectLines{i,2} = min(IntersectLines{i,2}); end end end else % Empty curve Intersect = false; IntersectLines = cell(1,1); end ================================================ FILE: src/triangulation/curve_based_triangulation.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function triangulation = curve_based_triangulation(P,TriaHeight,TriaWidth) % --------------------------------------------------------------------- % CURVE_BASED_TRIANGULATION.M Reconstructs a triangulation for the % stem-buttress surface based on boundary curves % % Version 1.1.0 % Latest update 3 May 2022 % % Copyright (C) 2015-2022 Pasi Raumonen % --------------------------------------------------------------------- % % Inputs: % P Point cloud of the stem to be triangulated % TriaHeight Height of the triangles % TriaWidth Width of the triangles % % Output: % triangulation Structure field defining the triangulation. Contains % the following main fields: % vert Vertices of the triangulation model (nv x 3)-matrix % facet Facets (triangles) of the triangulation % (the vertices forming the facets) % fvd Color information of the facets for plotting with "patch" % volume Volume enclosed by the facets in liters % bottom The z-coordinate of the bottom of the model % top The z-coordinate of the top of the model % triah TriaHeight % triaw TriaWidth % --------------------------------------------------------------------- % Changes from version 1.0.2 to 1.1.0, 3 May 2022: % 1) Increased the radius of the balls at seed points from TriaWidth to % 2*TriaWidth in the input of "boundary_curve" % 2) Added triangle orientation check after the side is covered with % triangles so that the surface normals are pointing outward % 3) Modified the check if the new boundary curve changes only a little and % then stop reconstruction % 4) Added halving the triangle height if the boundary curve length has % increased three times. % 5) Changed the bottom level from the smallest z-coordinate to the % average of the lowest 100 z-coordinates. % 6) Minor streamlining the code and added more comments % Changes from version 1.0.2 to 1.0.3, 11 Aug 2020: % 1) Small changes in the code when computing the delaunay triangulation % of the top layer % Changes from version 1.0.1 to 1.0.2, 15 Jan 2020: % 1) Added side surface areas (side, top, bottom) to output as fields % Changes from version 1.0.0 to 1.0.1, 26 Nov 2019: % 1) Removed the plotting of the triangulation model at the end of the code %% Determine the first boundary curve np = size(P,1); [~,I] = sort(P(:,3),'descend'); P = P(I,:); Hbot = mean(P(end-100:end,3)); Htop = P(1,3); N = ceil((Htop-Hbot)/TriaHeight); Vert = zeros(1e5,3); Tria = zeros(1e5,3); TriaLay = zeros(1e5,1); VertLay = zeros(1e5,1,'uint16'); Curve = zeros(0,3); i = 0; % the layer whose cross section is under reconstruction ps = 1; while P(ps,3) > Htop-i*TriaHeight ps = ps+1; end pe = ps; while i < N/4 && isempty(Curve) % Define thin horizontal cross section of the stem i = i+1; ps = pe+1; k = 1; while P(ps+k,3) > Htop-i*TriaHeight k = k+1; end pe = ps+k-1; PSection = P(ps:pe,:); % Create initial boundary curve: iter = 0; while iter <= 15 && isempty(Curve) iter = iter+1; Curve = initial_boundary_curve(PSection,TriaWidth); end end if isempty(Curve) triangulation = zeros(0,1); disp(' No triangulation: Problem with the first curve') return end % make the height of the curve even: Curve(:,3) = max(Curve(:,3)); % Save vertices: nv = size(Curve,1); % number of vertices in the curve Vert(1:nv,:) = Curve; VertLay(1:nv) = i; t = 0; m00 = size(Curve,1); %% Determine the other boundary curves and the triangulation downwards i0 = i; i = i0+1; nv0 = 0; LayerBottom = Htop-i*TriaHeight; while i <= N && pe < np %% Define thin horizontal cross section of the stem ps = pe+1; k = 1; while ps+k <= np && P(ps+k,3) > LayerBottom k = k+1; end pe = ps+k-1; PSection = P(ps:pe,:); %% Create boundary curves using the previous curves as seeds if i > i0+1 nv0 = nv1; end % Define seed points: Curve(:,3) = Curve(:,3)-TriaHeight; Curve0 = Curve; % Create new boundary curve [Curve,Ind] = boundary_curve(PSection,Curve,2*TriaWidth,1.5*TriaWidth); if isempty(Curve) disp(' No triangulation: Empty curve') triangulation = zeros(0,1); return end Curve(:,3) = max(Curve(:,3)); %% Check if the curve intersects itself [Intersect,IntersectLines] = check_self_intersection(Curve(:,1:2)); %% If self-intersection, try to modify the curve j = 1; while Intersect && j <= 10 n = size(Curve,1); CrossLines = (1:1:n)'; NumberOfIntersections = cellfun('length',IntersectLines(:,1)); I = NumberOfIntersections > 0; CrossLines = CrossLines(I); CrossLen = vertcat(IntersectLines{I,2}); if length(CrossLen) == length(CrossLines) LineEle = Curve([2:end 1],:)-Curve(1:end,:); d = sqrt(sum(LineEle.*LineEle,2)); m = length(CrossLines); for k = 1:2:m if CrossLines(k) ~= n Curve(CrossLines(k)+1,:) = Curve(CrossLines(k),:)+... 0.9*CrossLen(k)/d(CrossLines(k))*LineEle(CrossLines(k),:); else Curve(1,:) = Curve(CrossLines(k),:)+... 0.9*CrossLen(k)/d(CrossLines(k))*LineEle(CrossLines(k),:); end end [Intersect,IntersectLines] = check_self_intersection(Curve(:,1:2)); j = j+1; else j = 11; end end m = size(Curve,1); if Intersect %% Curve self-intersects, use previous curve to extrapolate to the bottom H = Curve0(1,3)-Hbot; if H > 0.75 && Intersect triangulation = zeros(0,1); disp([' No triangulation: Self-intersection at ',... num2str(H),' m from the bottom']) return end Curve = Curve0; Curve(:,3) = Curve(:,3)-TriaHeight; Nadd = floor(H/TriaHeight)+1; m = size(Curve,1); Ind = [(1:1:m)' [(2:1:m)'; 1]]; T = H/Nadd; for k = 1:Nadd if k > 1 Curve(:,3) = Curve(:,3)-T; end Vert(nv+1:nv+m,:) = Curve; VertLay(nv+1:nv+m) = i; %% Define the triangulation between two boundary curves nv1 = nv; nv = nv+m; t0 = t+1; pass = false; for j = 1:m if Ind(j,2) > 0 && j < m t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,:)]; t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,2) nv1+j+1]; elseif Ind(j,2) > 0 && ~pass t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,:)]; t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,2) nv1+1]; elseif Ind(j,2) == 0 && j < m t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1) nv1+j+1]; elseif Ind(j,2) == 0 && ~pass t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1) nv1+1]; elseif j == 1 && Ind(j,2) == -1 t = t+1; Tria(t,:) = [nv nv1 nv0+1]; t = t+1; Tria(t,:) = [nv nv0+1 nv1+1]; t = t+1; Tria(t,:) = [nv0+1 nv0+2 nv1+1]; t = t+1; Tria(t,:) = [nv1+1 nv0+2 nv0+3]; t = t+1; Tria(t,:) = [nv1+1 nv0+3 nv1+2]; pass = true; elseif Ind(j,2) == -1 && j < m t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1) nv0+Ind(j,1)+1]; t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1)+1 nv1+j+1]; t = t+1; Tria(t,:) = [nv0+Ind(j,1)+1 nv0+Ind(j,1)+2 nv1+j+1]; elseif Ind(j,2) == -1 && ~pass t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1) nv0+Ind(j,1)+1]; t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1)+1 nv1+1]; t = t+1; Tria(t,:) = [nv0+Ind(j,1)+1 nv0+1 nv1+1]; end end TriaLay(t0:t) = i; i = i+1; nv0 = nv1; end i = N+1; else %% No self-intersection, proceed with triangulation and new curves Vert(nv+1:nv+m,:) = Curve; VertLay(nv+1:nv+m) = i; %% If little change between Curve and Curve0, stop the reconstruction C = intersect(Curve0,Curve,"rows"); if size(C,1) > 0.7*size(Curve,1) N = i; end %% If the boundary curve has grown much longer than originally, then % decrease the triangle height if m > 3*m00 TriaHeight = TriaHeight/2; % use half the height N = N+ceil((N-i)/2); % update the number of layers m00 = m; end %% Define the triangulation between two boundary curves nv1 = nv; nv = nv+m; t0 = t+1; pass = false; for j = 1:m if Ind(j,2) > 0 && j < m t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,:)]; t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,2) nv1+j+1]; elseif Ind(j,2) > 0 && ~pass t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,:)]; t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,2) nv1+1]; elseif Ind(j,2) == 0 && j < m t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1) nv1+j+1]; elseif Ind(j,2) == 0 && ~pass t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1) nv1+1]; elseif j == 1 && Ind(j,2) == -1 t = t+1; Tria(t,:) = [nv nv1 nv0+1]; t = t+1; Tria(t,:) = [nv nv0+1 nv1+1]; t = t+1; Tria(t,:) = [nv0+1 nv0+2 nv1+1]; t = t+1; Tria(t,:) = [nv1+1 nv0+2 nv0+3]; t = t+1; Tria(t,:) = [nv1+1 nv0+3 nv1+2]; pass = true; elseif Ind(j,2) == -1 && j < m t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1) nv0+Ind(j,1)+1]; t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1)+1 nv1+j+1]; t = t+1; Tria(t,:) = [nv0+Ind(j,1)+1 nv0+Ind(j,1)+2 nv1+j+1]; elseif Ind(j,2) == -1 && ~pass t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1) nv0+Ind(j,1)+1]; t = t+1; Tria(t,:) = [nv1+j nv0+Ind(j,1)+1 nv1+1]; t = t+1; Tria(t,:) = [nv0+Ind(j,1)+1 nv0+1 nv1+1]; end end TriaLay(t0:t) = i; i = i+1; LayerBottom = LayerBottom-TriaHeight; end end Vert = Vert(1:nv,:); VertLay = VertLay(1:nv); Tria = Tria(1:t,:); TriaLay = TriaLay(1:t); %% Check the orientation of the triangles % so that surface normals are outward pointing a = round(t/10); % select the top triangles U = Vert(Tria(1:a,2),:)-Vert(Tria(1:a,1),:); V = Vert(Tria(1:a,3),:)-Vert(Tria(1:a,1),:); Center = mean(Vert(1:nv-1,:)); % the center of the stem C = Vert(Tria(1:a,1),:)+0.25*V+0.25*U; W = C(:,1:2)-Center(1:2); % vectors from the triagles to the stem's center Normals = cross(U,V); if nnz(sum(Normals(:,1:2).*W,2) < 0) > 0.5*length(C) Tria(1:t,1:2) = [Tria(1:t,2) Tria(1:t,1)]; end % U = Vert(Tria(1:t,2),:)-Vert(Tria(1:t,1),:); % V = Vert(Tria(1:t,3),:)-Vert(Tria(1:t,1),:); % Normals = cross(U,V); % Normals = normalize(Normals); % C = Vert(Tria(1:t,1),:)+0.25*V+0.25*U; % fvd = ones(t,1); % figure(5) % point_cloud_plotting(P(1,:),5,6) % patch('Vertices',Vert,'Faces',Tria,'FaceVertexCData',fvd,'FaceColor','flat') % alpha(1) % hold on % arrow_plot(C,0.1*Normals,5) % hold off % axis equal % pause %% Remove possible double triangles nt = size(Tria,1); Keep = true(nt,1); Scoord = Vert(Tria(:,1),:)+Vert(Tria(:,2),:)+Vert(Tria(:,3),:); S = sum(Scoord,2); [part,CC] = cubical_partition(Scoord,2*TriaWidth); for j = 1:nt-1 if Keep(j) points = part(CC(j,1)-1:CC(j,1)+1,CC(j,2)-1:CC(j,2)+1,CC(j,3)-1:CC(j,3)+1); points = vertcat(points{:}); I = S(j) == S(points); J = points ~= j; I = I&J&Keep(points); if any(I) p = points(I); I = intersect(Tria(j,:),Tria(p,:)); if length(I) == 3 Keep(p) = false; end end end end Tria = Tria(Keep,:); TriaLay = TriaLay(Keep); %% Generate triangles for the horizontal layers and compute the volumes % Triangles of the ground layer % Select the boundary curve: N = double(max(VertLay)); I = VertLay == N; Vert(I,3) = Hbot; ind = (1:1:nv)'; ind = ind(I); Curve = Vert(I,:); % Boundary curve of the bottom n = size(Curve,1); if n < 10 triangulation = zeros(0,1); disp(' No triangulation: Ground layer boundary curve too small') return end % Define Delaunay triangulation for the bottom C = zeros(n,2); C(:,1) = (1:1:n)'; C(1:n-1,2) = (2:1:n)'; C(n,2) = 1; warning off dt = delaunayTriangulation(Curve(:,1),Curve(:,2),C); In = dt.isInterior(); GroundTria = dt(In,:); Points = dt.Points; warning on if size(Points,1) > size(Curve,1) disp(' No triangulation: Problem with delaunay in the bottom layer') triangulation = zeros(0,1); return end GroundTria0 = GroundTria; GroundTria(:,1) = ind(GroundTria(:,1)); GroundTria(:,2) = ind(GroundTria(:,2)); GroundTria(:,3) = ind(GroundTria(:,3)); % Compute the normals and areas U = Curve(GroundTria0(:,2),:)-Curve(GroundTria0(:,1),:); V = Curve(GroundTria0(:,3),:)-Curve(GroundTria0(:,1),:); Cg = Curve(GroundTria0(:,1),:)+0.25*V+0.25*U; Ng = cross(U,V); I = Ng(:,3) > 0; % Check orientation Ng(I,:) = -Ng(I,:); Ag = 0.5*sqrt(sum(Ng.*Ng,2)); Ng = 0.5*[Ng(:,1)./Ag Ng(:,2)./Ag Ng(:,3)./Ag]; % Remove possible negative area triangles: I = Ag > 0; Ag = Ag(I); Cg = Cg(I,:); Ng = Ng(I,:); GroundTria = GroundTria(I,:); % Update the triangles: Tria = [Tria; GroundTria]; TriaLay = [TriaLay; (N+1)*ones(size(GroundTria,1),1)]; if abs(sum(Ag)-polyarea(Curve(:,1),Curve(:,2))) > 0.001*sum(Ag) disp(' No triangulation: Problem with delaunay in the bottom layer') triangulation = zeros(0,1); return end % Triangles of the top layer % Select the top curve: N = double(min(VertLay)); I = VertLay == N; ind = (1:1:nv)'; ind = ind(I); Curve = Vert(I,:); CenterTop = mean(Curve); % Delaunay triangulation of the top: n = size(Curve,1); C = zeros(n,2); C(:,1) = (1:1:n)'; C(1:n-1,2) = (2:1:n)'; C(n,2) = 1; warning off dt = delaunayTriangulation(Curve(:,1),Curve(:,2),C); Points = dt.Points; warning on if min(size(dt)) == 0 || size(Points,1) > size(Curve,1) disp(' No triangulation: Problem with delaunay in the top layer') triangulation = zeros(0,1); return end In = dt.isInterior(); TopTria = dt(In,:); TopTria0 = TopTria; TopTria(:,1) = ind(TopTria(:,1)); TopTria(:,2) = ind(TopTria(:,2)); TopTria(:,3) = ind(TopTria(:,3)); % Compute the normals and areas: U = Curve(TopTria0(:,2),:)-Curve(TopTria0(:,1),:); V = Curve(TopTria0(:,3),:)-Curve(TopTria0(:,1),:); Ct = Curve(TopTria0(:,1),:)+0.25*V+0.25*U; Nt = cross(U,V); I = Nt(:,3) < 0; Nt(I,:) = -Nt(I,:); At = 0.5*sqrt(sum(Nt.*Nt,2)); Nt = 0.5*[Nt(:,1)./At Nt(:,2)./At Nt(:,3)./At]; % Remove possible negative area triangles: I = At > 0; At = At(I); Ct = Ct(I,:); Nt = Nt(I,:); TopTria = TopTria(I,:); % Update the triangles: Tria = [Tria; TopTria]; TriaLay = [TriaLay; N*ones(size(TopTria,1),1)]; if abs(sum(At)-polyarea(Curve(:,1),Curve(:,2))) > 0.001*sum(At) disp(' No triangulation: Problem with delaunay in the top layer') triangulation = zeros(0,1); return end % Triangles of the side B = TriaLay <= max(VertLay) & TriaLay > 1; U = Vert(Tria(B,2),:)-Vert(Tria(B,1),:); V = Vert(Tria(B,3),:)-Vert(Tria(B,1),:); Cs = Vert(Tria(B,1),:)+0.25*V+0.25*U; Ns = cross(U,V); As = 0.5*sqrt(sum(Ns.*Ns,2)); Ns = 0.5*[Ns(:,1)./As Ns(:,2)./As Ns(:,3)./As]; I = As > 0; Ns = Ns(I,:); As = As(I); Cs = Cs(I,:); % Volumes in liters VTotal = sum(At.*sum(Ct.*Nt,2))+sum(As.*sum(Cs.*Ns,2))+sum(Ag.*sum(Cg.*Ng,2)); VTotal = round(10000*VTotal/3)/10; if VTotal < 0 disp(' No triangulation: Problem with volume') triangulation = zeros(0,1); return end V = Vert(Tria(:,1),1:2)-CenterTop(1:2); fvd = sqrt(sum(V.*V,2)); triangulation.vert = single(Vert); triangulation.facet = uint16(Tria); triangulation.fvd = single(fvd); triangulation.volume = VTotal; triangulation.SideArea = sum(As); triangulation.BottomArea = sum(Ag); triangulation.TopArea = sum(At); triangulation.bottom = min(Vert(:,3)); triangulation.top = max(Vert(:,3)); triangulation.triah = TriaHeight; triangulation.triaw = TriaWidth; % figure(5) % point_cloud_plotting(P,5,6) % patch('Vertices',Vert,'Faces',Tria,'FaceVertexCData',fvd,'FaceColor','flat') % % hold on % % arrow_plot(Cs,0.2*Ns,5) % % hold off % % axis equal % alpha(1) ================================================ FILE: src/triangulation/initial_boundary_curve.m ================================================ % This file is part of TREEQSM. % % TREEQSM is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % TREEQSM is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with TREEQSM. If not, see . function Curve = initial_boundary_curve(P,TriaWidth) % --------------------------------------------------------------------- % INITIAL_BOUNDARY_CURVE.M Determines the boundary curve adaptively. % % Version 1.0.1 % Latest update 26 Nov 2019 % % Copyright (C) 2015-2017 Pasi Raumonen % --------------------------------------------------------------------- % Changes from version 1.0.0 to 1.0.1, 26 Nov 2019: % 1) Bug fix: Added "return" if the "Curve" is empty after it is first defined. %% Define suitable center % Use xy-data and even the z-coordinate to the top Top = max(P(:,3)); P = [P(:,1:2) Top*ones(size(P,1),1)]; % Define the "center" of points as the mean Center = mean(P); Center0 = Center; % If the center is outside or close to the boundary, define new center i = 0; A0 = 61; ShortestDist = 0; while ShortestDist < 0.075 && i < 100 Center = Center0+[3*ShortestDist*randn(1,2) 0]; % Randomly move the center % Compute angles of points as seen from the center V = mat_vec_subtraction(P(:,1:2),Center(1:2)); angle = 180/pi*atan2(V(:,2),V(:,1))+180; % % Check if the center is outside or near the boundary of the cross section A = false(70,1); a = ceil(angle/5); I = a > 0; A(a(I)) = true; if i == 0 ShortestDist = 0.025; elseif nnz(A) < A0 ShortestDist = 0.05; else PointDist = sqrt(sum(V.*V,2)); [ShortestDist,FirstPoint] = min(PointDist); end i = i+1; if i == 100 && ShortestDist < 0.075 i = 0; A0 = A0-2; end end %% Define first boundary curve based on the center Curve = zeros(18,1); % the boundary curve, contains indexed of the point cloud rows Curve(1) = FirstPoint; % start the curve from the point the closest the center % Modify the angles so that first point has the angle 0 a0 = angle(FirstPoint); I = angle < a0; angle(I) = angle(I)+(360-a0); angle(~I) = angle(~I)-a0; % Select the rest of the points as the closest point in 15 deg sectors % centered at 20 deg intervals np = size(P,1); Ind = (1:1:np)'; t = 0; for i = 2:18 J = angle > 12.5+20*(i-2) & angle < 27.5+20*(i-2); if ~any(J) % if no points, try 18 deg sector J = angle > 11+20*(i-2) & angle < 29+20*(i-2); end if any(J) % if sector has points, select the closest point as the curve point D = PointDist(J); ind = Ind(J); [~,J] = min(D); t = t+1; Curve(t) = ind(J); end end Curve = Curve(1:t); if isempty(Curve) return end I = true(np,1); I(Curve) = false; Ind = Ind(I); %% Adapt the initial curve to the data V = P(Curve([(2:t)'; 1]),:)-P(Curve,:); D = sqrt(sum(V(:,1:2).*V(:,1:2),2)); n = t; n0 = 1; % Continue adding new points as long as too long edges exists while any(D > 1.25*TriaWidth) && n > n0 N = [V(:,2) -V(:,1) V(:,3)]; M = P(Curve,:)+0.5*V; Curve1 = Curve; t = 0; for i = 1:n if D(i) > 1.25*TriaWidth [d,~,hc] = distances_to_line(P(Curve1,:),N(i,:),M(i,:)); I = hc > 0.01 & d < D(i)/2; if any(I) H = min(hc(I)); else H = 1; end [d,~,h] = distances_to_line(P(Ind,:),N(i,:),M(i,:)); I = d < D(i)/3 & h > -TriaWidth/2 & h < H; if any(I) ind = Ind(I); h = h(I); [h,J] = min(h); I = ind(J); t = t+1; if i < n Curve1 = [Curve1(1:t); I; Curve1(t+1:end)]; else Curve1 = [Curve1(1:t); I]; end J = Ind ~= I; Ind = Ind(J); t = t+1; else t = t+1; end else t = t+1; end end Curve = Curve1(1:t); n0 = n; n = size(Curve,1); V = P(Curve([(2:n)'; 1]),:)-P(Curve,:); D = sqrt(sum(V.*V,2)); end %% Refine the curve for longer edges if far away points n0 = n-1; while n > n0 N = [V(:,2) -V(:,1) V(:,3)]; M = P(Curve,:)+0.5*V; Curve1 = Curve; t = 0; for i = 1:n if D(i) > 0.5*TriaWidth [d,~,hc] = distances_to_line(P(Curve1,:),N(i,:),M(i,:)); I = hc > 0.01 & d < D(i)/2; if any(I) H = min(hc(I)); else H = 1; end [d,~,h] = distances_to_line(P(Ind,:),N(i,:),M(i,:)); I = d < D(i)/3 & h > -TriaWidth/3 & h < H; ind = Ind(I); h = h(I); [h,J] = min(h); if h > TriaWidth/10 I = ind(J); t = t+1; if i < n Curve1 = [Curve1(1:t); I; Curve1(t+1:end)]; else Curve1 = [Curve1(1:t); I]; end J = Ind ~= I; Ind = Ind(J); t = t+1; else t = t+1; end else t = t+1; end end Curve = Curve1(1:t); n0 = n; n = size(Curve,1); V = P(Curve([(2:n)'; 1]),:)-P(Curve,:); D = sqrt(sum(V.*V,2)); end %% Smooth the curve by defining the points by means of neighbors Curve = P(Curve,:); % Change the curve from point indexes to coordinates Curve = boundary_curve2(P,Curve,0.04,TriaWidth); if isempty(Curve) return end %% Add points for too long edges n = size(Curve,1); V = Curve([(2:n)'; 1],:)-Curve; D = sqrt(sum(V.*V,2)); Curve1 = Curve; t = 0; for i = 1:n if D(i) > TriaWidth m = floor(D(i)/TriaWidth); t = t+1; W = zeros(m,3); for j = 1:m W(j,:) = Curve(i,:)+j/(m+1)*V(i,:); end Curve1 = [Curve1(1:t,:); W; Curve1(t+1:end,:)]; t = t+m ; else t = t+1; end end Curve = Curve1; n = size(Curve,1); %% Define the curve again by equalising the point distances along the curve V = Curve([(2:n)'; 1],:)-Curve; D = sqrt(sum(V.*V,2)); L = cumsum(D); m = ceil(L(end)/TriaWidth); TriaWidth = L(end)/m; Curve1 = zeros(m,3); Curve1(1,:) = Curve(1,:); b = 1; for i = 2:m while L(b) < (i-1)*TriaWidth b = b+1; end if b > 1 a = ((i-1)*TriaWidth-L(b-1))/D(b); Curve1(i,:) = Curve(b,:)+a*V(b,:); else a = (L(b)-(i-1)*TriaWidth)/D(b); Curve1(i,:) = Curve(b,:)+a*V(b,:); end end Curve = Curve1; Intersect = check_self_intersection(Curve(:,1:2)); if Intersect Curve = zeros(0,3); end