Showing preview only (512K chars total). Download the full file or copy to clipboard to get everything.
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. <http://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/philosophy/why-not-lgpl.html>.
================================================
FILE: README.md
================================================
# TreeQSM
**Version 2.4.1**
**Reconstruction of quantitative structure models for trees from point cloud data**
[](https://zenodo.org/badge/latestdoi/100592530)

### 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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/licenses/>.
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 class
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
Condensed preview — 89 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (519K chars).
[
{
"path": ".gitignore",
"chars": 11,
"preview": ".DS_Store\r\n"
},
{
"path": "LICENSE.md",
"chars": 35335,
"preview": "TreeQSM Version 2.4.0\nCopyright (C) 2013-2020 Pasi Raumonen\n\nTreeQSM is free software: you can redistribute it and/or mo"
},
{
"path": "README.md",
"chars": 3021,
"preview": "# TreeQSM\n\n**Version 2.4.1**\n**Reconstruction of quantitative structure models for trees from point cloud data**\n\n[![DOI"
},
{
"path": "src/create_input.m",
"chars": 5360,
"preview": "\n% Creates input parameter structure array needed to run \"treeqsm\" function\n% and \"filtering\" function.\n% NOTE: use this"
},
{
"path": "src/estimate_precision.m",
"chars": 5602,
"preview": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms"
},
{
"path": "src/least_squares_fitting/form_rotation_matrices.m",
"chars": 1449,
"preview": "% This file is part of TREEQSM.\r\n% \r\n% TREEQSM is free software: you can redistribute it and/or modify\r\n% it under the t"
},
{
"path": "src/least_squares_fitting/func_grad_axis.m",
"chars": 3013,
"preview": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the term"
},
{
"path": "src/least_squares_fitting/func_grad_circle.m",
"chars": 1232,
"preview": "function [dist,J] = func_grad_circle(P,par,weight)\n\n% ------------------------------------------------------------------"
},
{
"path": "src/least_squares_fitting/func_grad_circle_centre.m",
"chars": 1172,
"preview": "function [dist,J] = func_grad_circle_centre(P,par,weight)\n\n% -----------------------------------------------------------"
},
{
"path": "src/least_squares_fitting/func_grad_cylinder.m",
"chars": 3370,
"preview": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the term"
},
{
"path": "src/least_squares_fitting/least_squares_axis.m",
"chars": 3918,
"preview": "\nfunction cyl = least_squares_axis(P,Axis,Point0,Rad0,weight)\n\n% -------------------------------------------------------"
},
{
"path": "src/least_squares_fitting/least_squares_circle.m",
"chars": 3093,
"preview": "function cir = least_squares_circle(P,Point0,Rad0,weight)\n% ------------------------------------------------------------"
},
{
"path": "src/least_squares_fitting/least_squares_circle_centre.m",
"chars": 2991,
"preview": "function cir = least_squares_circle_centre(P,Point0,Rad0)\n% ------------------------------------------------------------"
},
{
"path": "src/least_squares_fitting/least_squares_cylinder.m",
"chars": 6889,
"preview": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the term"
},
{
"path": "src/least_squares_fitting/nlssolver.m",
"chars": 2534,
"preview": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the term"
},
{
"path": "src/least_squares_fitting/rotate_to_z_axis.m",
"chars": 1206,
"preview": "% This file is part of TREEQSM.\r\n% \r\n% TREEQSM is free software: you can redistribute it and/or modify\r\n% it under the t"
},
{
"path": "src/main_steps/branches.m",
"chars": 4480,
"preview": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms"
},
{
"path": "src/main_steps/correct_segments.m",
"chars": 30167,
"preview": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms"
},
{
"path": "src/main_steps/cover_sets.m",
"chars": 10655,
"preview": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms"
},
{
"path": "src/main_steps/cylinders.m",
"chars": 34496,
"preview": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms"
},
{
"path": "src/main_steps/filtering.m",
"chars": 8700,
"preview": "% This file is part of TREEQSM.\r\n% \r\n% TREEQSM is free software: you can redistribute it and/or modify\r\n% it under the t"
},
{
"path": "src/main_steps/point_model_distance.m",
"chars": 5875,
"preview": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the term"
},
{
"path": "src/main_steps/relative_size.m",
"chars": 3969,
"preview": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the term"
},
{
"path": "src/main_steps/segments.m",
"chars": 13369,
"preview": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the term"
},
{
"path": "src/main_steps/tree_data.m",
"chars": 31615,
"preview": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms"
},
{
"path": "src/main_steps/tree_sets.m",
"chars": 28345,
"preview": "% This file is part of TREEQSM.\r\n%\r\n% TREEQSM is free software: you can redistribute it and/or modify\r\n% it under the te"
},
{
"path": "src/make_models.m",
"chars": 7381,
"preview": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms"
},
{
"path": "src/make_models_parallel.m",
"chars": 8030,
"preview": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms"
},
{
"path": "src/plotting/plot2d.m",
"chars": 6179,
"preview": "function h = plot2d(X,Y,fig,strtit,strx,stry,leg,E)\n\n% 2D-plots, where the data (X and Y), figure number, title, xlabel,"
},
{
"path": "src/plotting/plot_branch_segmentation.m",
"chars": 3644,
"preview": "function plot_branch_segmentation(P,cover,segment,Color,fig,ms,segind,BO)\n\n% -------------------------------------------"
},
{
"path": "src/plotting/plot_branches.m",
"chars": 1207,
"preview": "function plot_branches(P,cover,segment,fig,ms,segind,BO)\n\nn = nargin;\nif n < 7\n BO = 1000;\n if n < 6\n segin"
},
{
"path": "src/plotting/plot_comparison.m",
"chars": 782,
"preview": "function plot_comparison(P1,P2,fig,ms1,ms2)\r\n\r\n% Plots two point clouds \"P1\" and \"P2\" so that those points of \"P2\" which"
},
{
"path": "src/plotting/plot_cone_model.m",
"chars": 4236,
"preview": "function plot_cone_model(cylinder,fig,nf,alp,Ind)\n\n% Plots the given cylinder model as truncated cones defined by the cy"
},
{
"path": "src/plotting/plot_cylinder_model.m",
"chars": 4609,
"preview": "function plot_cylinder_model(cylinder,Color,fig,nf,alp,Ind)\n\n% ---------------------------------------------------------"
},
{
"path": "src/plotting/plot_cylinder_model2.m",
"chars": 2756,
"preview": "function plot_cylinder_model2(cylinder,fig,nf,alp,Ind)\n\n% Plots the cylinder model.\n% cylinder Structure array containi"
},
{
"path": "src/plotting/plot_distribution.m",
"chars": 5312,
"preview": "function plot_distribution(QSM,fig,rela,cumu,dis,dis2,dis3,dis4)\n\n% ----------------------------------------------------"
},
{
"path": "src/plotting/plot_large_point_cloud.m",
"chars": 503,
"preview": "function plot_large_point_cloud(P,fig,ms,rel)\n\n% Plots a random subset of a large point cloud. The user specifies the\n% "
},
{
"path": "src/plotting/plot_models_segmentations.m",
"chars": 3161,
"preview": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the term"
},
{
"path": "src/plotting/plot_point_cloud.m",
"chars": 937,
"preview": "function plot_point_cloud(P,fig,ms,col)\r\n\r\n% Plots the given point cloud.\r\n%\r\n% PLOT_POINT_CLOUD(P,FIG,MS,col) plots p"
},
{
"path": "src/plotting/plot_scatter.m",
"chars": 673,
"preview": "function plot_scatter(P,C,fig,ms)\n\n% A scatter plot where the color of each 2d or 3d point is specified by a\n% number. \n"
},
{
"path": "src/plotting/plot_segments.m",
"chars": 2888,
"preview": "function plot_segments(P,Bal,fig,ms,seg1,seg2,seg3,seg4,seg5)\r\n\r\n% Plots point cloud segments/subsets defined as subsets"
},
{
"path": "src/plotting/plot_segs.m",
"chars": 1912,
"preview": "function plot_segs(P,comps,fig,ms,Bal)\r\n\r\n% Plots the point cloud segments given in the cell array \"comps\".\r\n% If 4 inpu"
},
{
"path": "src/plotting/plot_spreads.m",
"chars": 980,
"preview": "function plot_spreads(treedata,fig,lw,rel)\n\n% Plots the spreads as a polar plot with different height layers presented\n%"
},
{
"path": "src/plotting/plot_tree_structure.m",
"chars": 2983,
"preview": "function plot_tree_structure(P,cover,segment,fig,ms,segind,BO)\r\n\r\n% ----------------------------------------------------"
},
{
"path": "src/plotting/plot_tree_structure2.m",
"chars": 2305,
"preview": "function plot_tree_structure2(P,Bal,Segs,SChi,fig,ms,BO,segind)\r\n\r\n% Plots the branch-segmented tree point cloud so that"
},
{
"path": "src/plotting/plot_triangulation.m",
"chars": 948,
"preview": "function plot_triangulation(QSM,fig,nf,AllTree)\n\n% Plots the triangulation model of the stem's bottom part and the cylin"
},
{
"path": "src/plotting/point_cloud_plotting.m",
"chars": 1093,
"preview": "function point_cloud_plotting(P,fig,ms,Bal,Sub)\r\n\r\n% Plots the given point cloud \"P\". With additional inputs one can plo"
},
{
"path": "src/select_optimum.m",
"chars": 41288,
"preview": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms"
},
{
"path": "src/tools/average.m",
"chars": 137,
"preview": "function A = average(X)\n\n% Computes the average of columns of the matrix X\n\nn = size(X,1);\nif n > 1\n A = sum(X)/n;\nel"
},
{
"path": "src/tools/change_precision.m",
"chars": 565,
"preview": "function v = change_precision(v)\n\n% Decrease the number of nonzero decimals in the vector v according to the\n% exponent "
},
{
"path": "src/tools/connected_components.m",
"chars": 5720,
"preview": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the term"
},
{
"path": "src/tools/cross_product.m",
"chars": 163,
"preview": "function C = cross_product(A,B)\n\n% Calculates the cross product C of the 3-vectors A and B\n\nC = [A(2)*B(3)-A(3)*B(2); A"
},
{
"path": "src/tools/cubical_averaging.m",
"chars": 1154,
"preview": "function DSP = cubical_averaging(P,CubeSize)\n\ntic\n% Downsamples the given point cloud by averaging points from each \n% c"
},
{
"path": "src/tools/cubical_downsampling.m",
"chars": 1463,
"preview": "function Pass = cubical_downsampling(P,CubeSize)\n\n% Downsamples the given point cloud by selecting one point from each \n"
},
{
"path": "src/tools/cubical_partition.m",
"chars": 4085,
"preview": "% This file is part of TREEQSM.\r\n%\r\n% TREEQSM is free software: you can redistribute it and/or modify\r\n% it under the te"
},
{
"path": "src/tools/define_input.m",
"chars": 4812,
"preview": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms"
},
{
"path": "src/tools/dimensions.m",
"chars": 979,
"preview": "function [D,dir] = dimensions(points,varargin)\r\n\r\n% Calculates the box-dimensions and dimension estimates of the point s"
},
{
"path": "src/tools/display_time.m",
"chars": 1339,
"preview": "function display_time(T1,T2,string,display)\n\n% Display the two times given. \"T1\" is the time named with the \"string\" and"
},
{
"path": "src/tools/distances_between_lines.m",
"chars": 1246,
"preview": "function [DistLines,DistOnRay,DistOnLines] = distances_between_lines(PointRay,DirRay,PointLines,DirLines)\r\n\r\n% Calculate"
},
{
"path": "src/tools/distances_to_line.m",
"chars": 405,
"preview": "function [d,V,h,B] = distances_to_line(Q,LineDirec,LinePoint)\r\n\r\n% Calculates the distances of the points, given in the "
},
{
"path": "src/tools/dot_product.m",
"chars": 125,
"preview": "function C = dot_product(A,B)\n\n% Computes the dot product of the corresponding rows of the matrices A and B\n\nC = sum(A.*"
},
{
"path": "src/tools/expand.m",
"chars": 615,
"preview": "function C = expand(Nei,C,n,Forb)\n\n% Expands the given subset \"C\" of cover sets \"n\" times with their neighbors, \n% and o"
},
{
"path": "src/tools/growth_volume_correction.m",
"chars": 5308,
"preview": "function cylinder = growth_volume_correction(cylinder,inputs)\n\n% -------------------------------------------------------"
},
{
"path": "src/tools/intersect_elements.m",
"chars": 238,
"preview": "function Set = intersect_elements(Set1,Set2,False1,False2)\n\n% Determines the intersection of Set1 and Set2.\n\nSet = uniqu"
},
{
"path": "src/tools/mat_vec_subtraction.m",
"chars": 207,
"preview": "function A = mat_vec_subtraction(A,v)\r\n\r\n% Subtracts from each row of the matrix A the vector v.\r\n% If A is (n x m)-matr"
},
{
"path": "src/tools/median2.m",
"chars": 276,
"preview": "function y = median2(X)\n\n% Computes the median of the given vector.\n\nn = size(X,1);\nif n > 1\n X = sort(X);\n m = fl"
},
{
"path": "src/tools/normalize.m",
"chars": 141,
"preview": "function [A,L] = normalize(A)\n\n% Normalize rows of the matrix\n\nL = sqrt(sum(A.*A,2));\nn = size(A,2);\nfor i = 1:n\n A(:"
},
{
"path": "src/tools/optimal_parallel_vector.m",
"chars": 457,
"preview": "function [v,mean_res,sigmah,residual] = optimal_parallel_vector(V)\r\n\r\n% For a given set of unit vectors (the rows of the"
},
{
"path": "src/tools/orthonormal_vectors.m",
"chars": 373,
"preview": "function [V,W] = orthonormal_vectors(U)\n\n% Generate vectors V and W that are unit vectors orthogonal to themselves \n% an"
},
{
"path": "src/tools/rotation_matrix.m",
"chars": 429,
"preview": "function R = rotation_matrix(A,angle)\r\n\r\n% Returns the rotation matrix for the given axis A and angle (in radians)\r\n\r\nA "
},
{
"path": "src/tools/save_model_text.m",
"chars": 4758,
"preview": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the term"
},
{
"path": "src/tools/sec2min.m",
"chars": 163,
"preview": "function [Tmin,Tsec] = sec2min(T)\n\n% Transforms the given number of seconds into minutes and residual seconds\n\nTmin = fl"
},
{
"path": "src/tools/select_cylinders.m",
"chars": 170,
"preview": "function cylinder = select_cylinders(cylinder,Ind)\n\nNames = fieldnames(cylinder);\nn = size(Names,1);\nfor i = 1:n\n cyl"
},
{
"path": "src/tools/set_difference.m",
"chars": 306,
"preview": "function Set1 = set_difference(Set1,Set2,False)\n\n% Performs the set difference so that the common elements of Set1 and S"
},
{
"path": "src/tools/simplify_qsm.m",
"chars": 10948,
"preview": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the term"
},
{
"path": "src/tools/surface_coverage.m",
"chars": 4458,
"preview": "function [SurfCov,Dis,CylVol,dis] = surface_coverage(P,Axis,Point,nl,ns,Dmin,Dmax)\n \n% ---------------------------------"
},
{
"path": "src/tools/surface_coverage2.m",
"chars": 548,
"preview": "function SurfCov = surface_coverage2(Axis,Len,Vec,height,nl,ns)\n\n% Computes surface coverage (number between 0 and 1) of"
},
{
"path": "src/tools/surface_coverage_filtering.m",
"chars": 3535,
"preview": "function [Pass,c] = surface_coverage_filtering(P,c,lh,ns)\n\n% -----------------------------------------------------------"
},
{
"path": "src/tools/unique2.m",
"chars": 197,
"preview": "function SetUni = unique2(Set)\n\n\nn = length(Set);\nif n > 0\n Set = sort(Set);\n d = Set(2:n)-Set(1:n-1);\n A = Set"
},
{
"path": "src/tools/unique_elements.m",
"chars": 312,
"preview": "function Set = unique_elements(Set,False)\n\nn = length(Set);\nif n > 2\n I = true(n,1);\n for j = 1:n\n if ~Fals"
},
{
"path": "src/tools/update_tree_data.m",
"chars": 22826,
"preview": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms"
},
{
"path": "src/tools/verticalcat.m",
"chars": 566,
"preview": "function [Vector,IndElements] = verticalcat(CellArray)\n\n% Vertical concatenation of the given cell-array into a vector.\n"
},
{
"path": "src/treeqsm.m",
"chars": 19249,
"preview": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the term"
},
{
"path": "src/triangulation/boundary_curve.m",
"chars": 8054,
"preview": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms"
},
{
"path": "src/triangulation/boundary_curve2.m",
"chars": 4546,
"preview": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms"
},
{
"path": "src/triangulation/check_self_intersection.m",
"chars": 6103,
"preview": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms"
},
{
"path": "src/triangulation/curve_based_triangulation.m",
"chars": 16621,
"preview": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms"
},
{
"path": "src/triangulation/initial_boundary_curve.m",
"chars": 6528,
"preview": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms"
}
]
// ... and 1 more files (download for full content)
About this extraction
This page contains the full source code of the InverseTampere/TreeQSM GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 89 files (484.2 KB), approximately 153.1k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.