[
  {
    "path": ".gitignore",
    "content": ".DS_Store\r\n"
  },
  {
    "path": "LICENSE.md",
    "content": "TreeQSM Version 2.4.0\nCopyright (C) 2013-2020 Pasi Raumonen\n\nTreeQSM 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.\n\nTreeQSM 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.\n\n\n\n## GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007\n\n\nCopyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\nEveryone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.\n\nPreamble\n\nThe GNU General Public License is a free, copyleft license for software and other kinds of works.\n\nThe 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\nyour programs, too.\n\nWhen 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.\n\nTo 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.\n\nFor 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.\n\nDevelopers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.\n\nFor 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.\n\nSome 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.\n\nFinally, 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.\n\nThe precise terms and conditions for copying, distribution and modification follow.\n\nTERMS AND CONDITIONS\n\n0. Definitions.\n\n\"This License\" refers to version 3 of the GNU General Public License.\n\n\"Copyright\" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.\n\n\"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.\n\nTo \"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.\n\nA \"covered work\" means either the unmodified Program or a work based on the Program.\n\nTo \"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\npublic, and in some countries other activities as well.\n\nTo \"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.\n\nAn 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.\n\n  1. Source Code.\n\n  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.\n\n  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.\n\n  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.\n\n  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\nprograms 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,\nsuch as by intimate data communication or control flow between those subprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.\n\n  The Corresponding Source for a work in source code form is that same work.\n\n  2. Basic Permissions.\n\n  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\nrights of fair use or other equivalent, as provided by copyright law.\n\n  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\nfor 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.\n\n  Conveying under any other circumstances is permitted solely under the conditions stated below.  Sublicensing is not allowed; section 10 makes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  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.\n\n  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.\n\n  4. Conveying Verbatim Copies.\n\n  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;\nkeep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.\n\n  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.\n\n  5. Conveying Modified Source Versions.\n\n  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:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is released under this License and any conditions added under section\n   7.  This requirement modifies the requirement in section 4 to \"keep intact all notices\".\n\n    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.\n\n    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.\n\n  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\nused 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.\n\n  6. Conveying Non-Source Forms.\n\n  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:\n\n    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.\n\n    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.\n\n    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.\n\n    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.\n\n    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.\n\n  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.\n\n  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.\n\n  \"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.\n\n  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\nCorresponding 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).\n\n  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.\n\n  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.\n\n  7. Additional Terms.\n\n  \"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\nunder those permissions, but the entire Program remains governed by this License without regard to the additional permissions.\n\n  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.\n\n  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:\n\n    a) Disclaiming warranty or limiting liability differently from the  terms of sections 15 and 16 of this License; or\n\n    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\n\n    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\n\n    d) Limiting the use for publicity purposes of names of licensors or authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or\n\n    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.\n\n  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\na 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.\n\n  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.\n\n  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.\n\n  8. Termination.\n\n  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).\n\n  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\nprior to 60 days after the cessation.\n\n  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.\n\n  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.\n\n  9. Acceptance Not Required for Having Copies.\n\n  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\nnot accept this License.  Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  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.\n\n  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\nlicenses 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.\n\n  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\nany patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  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\".\n\n  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\nconsequence 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.\n\n  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.\n\n  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.\n\n  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\npatent 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\ncountry that you have reason to believe are valid.\n\n  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\nwork and works based on it.\n\n  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\nin 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\nconveyed 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.\n\n  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.\n\n  12. No Surrender of Others' Freedom.\n\n  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.\n\n  13. Use with the GNU Affero General Public License.\n\n  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\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  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.\n\n  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.\n\n  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.\n\n  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.\n\n  15. Disclaimer of Warranty.\n\n  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.\n\n  16. Limitation of Liability.\n\n  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.\n\n  17. Interpretation of Sections 15 and 16.\n\n  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.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  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.\n\n  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.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    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.\n\n    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.\n\n    You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it  under certain conditions; type `show c' for details.\n\nThe 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\".\n\n  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.\nFor more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.\n\n  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>.\n"
  },
  {
    "path": "README.md",
    "content": "# TreeQSM\n\n**Version 2.4.1**\n**Reconstruction of quantitative structure models for trees from point cloud data**\n\n[![DOI](https://zenodo.org/badge/100592530.svg)](https://zenodo.org/badge/latestdoi/100592530)\n\n![QSM image](https://github.com/InverseTampere/TreeQSM/blob/master/Manual/fig_point_cloud_qsm.png)\n\n\n### Description\n\nTreeQSM 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.\n\nThe TreeQSM is written in Matlab.\nThe 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.\n\n### References\n\nWeb: https://research.tuni.fi/inverse/\nSome published papers about the method and applications:  \nRaumonen et al. 2013, Remote Sensing https://www.mdpi.com/2072-4292/5/2/491  \nCalders et al. 2015, Methods in Ecology and Evolution https://besjournals.onlinelibrary.wiley.com/doi/full/10.1111/2041-210X.12301  \nRaumonen et al. 2015, ISPRS Annals https://www.isprs-ann-photogramm-remote-sens-spatial-inf-sci.net/II-3-W4/189/2015/  \nÅkerblom et al. 2015, Remote Sensing https://www.mdpi.com/2072-4292/7/4/4581  \nÅkerblom et al. 2017, Remote Sensing of Environment https://www.sciencedirect.com/science/article/abs/pii/S0034425716304746  \nde Tanago Menaca et al. 2017, Methods in Ecology and Evolution https://besjournals.onlinelibrary.wiley.com/doi/10.1111/2041-210X.12904  \nÅkerblom et al. 2018, Interface Focus http://dx.doi.org/10.1098/rsfs.2017.0045   \nDisney et al. 2018, Interface Focus http://dx.doi.org/10.1098/rsfs.2017.0048   \n\n\n### Quick guide\n\nHere 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.  \n\n1) Start MATLAB and set the main path to the root folder, where _treeqsm.m_ is located.\\\n2) 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.\\\n3) Import a point cloud of a tree into the workspace. Let us name it P.\\\n4) Define suitable inputs:\\\n  &nbsp; &nbsp; >> inputs = define_input(P,1,1,1);\\\n5) Reconstruct QSMs:\\\n  &nbsp; &nbsp; >> QSM = treeqsm(P,inputs);  \n"
  },
  {
    "path": "src/create_input.m",
    "content": "\n% Creates input parameter structure array needed to run \"treeqsm\" function\n% and \"filtering\" function.\n% NOTE: use this code to define all the parameters but the PatchDiam and\n% BallRad parameters can be conveniently defined by \"define_input\"\n% function.\n% \n% Last update 11 May 2022\n\nclear inputs\n\n%% QSM reconstruction parameters\n%%% THE THREE INPUT PARAMETERS TO BE OPTIMIZED.\n% These CAN BE VARIED AND SHOULD BE OPTIMIZED \n% One possibility to define these is to use \"define_input\" code\n% (These can have multiple values given as vectors, e.g. [0.01 0.02]).\n% Patch size of the first uniform-size cover:\ninputs.PatchDiam1 = [0.08 0.12]; \n% Minimum patch size of the cover sets in the second cover:\ninputs.PatchDiam2Min = [0.02 0.03]; \n% Maximum cover set size in the stem's base in the second cover:\ninputs.PatchDiam2Max = [0.07 0.1]; \n\n%%% ADDITIONAL PATCH GENERATION PARAMETERS.\n% The following parameters CAN BE VARIED BUT CAN BE USUALLY KEPT AS SHOWN\n% (i.e. little bigger than PatchDiam parameters).\n% One possibility to define these is to use \"define_input\" code\n% Ball radius in the first uniform-size cover generation:\ninputs.BallRad1 = inputs.PatchDiam1+0.015; \n% Maximum ball radius in the second cover generation:\ninputs.BallRad2 = inputs.PatchDiam2Max+0.01; \n\n% The following parameters CAN BE USUALLY KEPT FIXED as shown.\n% Minimum number of points in BallRad1-balls, generally good value is 3:\ninputs.nmin1 = 3; \n% Minimum number of points in BallRad2-balls, generally good value is 1:\ninputs.nmin2 = 1; \n% Does the point cloud contain points only from the tree (if 1, then yes):\ninputs.OnlyTree = 1; \n% Produce a triangulation of the stem's bottom part up to the first main\n% branch (if 1, then yes):\ninputs.Tria = 0; \n% Compute the point-model distances (if 1, then yes):\ninputs.Dist = 1; \n\n%%% RADIUS CORRECTION OPTIONS FOR MODIFYING TOO LARGE AND TOO SMALL CYLINDERS.\n% These parameters CAN BE USUALLY KEPT FIXED as shown.\n% Traditional TreeQSM choices:\n% Minimum cylinder radius, used particularly in the taper corrections:\ninputs.MinCylRad = 0.0025; \n% Radius correction based on radius of the parent. If 1, radii in a branch \n% are always smaller than the radius of the parent in the parent branch:\ninputs.ParentCor = 1; \n% Parabola taper correction of radii inside branches. If 1, use the\n% correction:\ninputs.TaperCor = 1; \n\n% Growth volume correction approach introduced by Jan Hackenberg, \n% allometry: Radius = a*GrowthVol^b+c\ninputs.GrowthVolCor = 0; % If 1, use growth volume (GV) correction \n% fac-parameter of the GV-approach, defines upper and lower bound. When \n% using GV-approach, consider setting TaperCorr = 0, ParentCorr = 0, \n% MinCylinderRadius = 0.\ninputs.GrowthVolFac = 1.5; % Defines the allowed radius: \n%  1/fac*predicted_radius <= radius <= fac*predicted_radius\n%  However, the radii of the branch tip cylinders are not increased.\n\n%% Filtering parameters\n% NOTE: These are all optional, but needed to run the \"filtering\" function.\n% Statistical k-nearest neighbor distance outlier filtering, applied if \n% filter.k > 0. The value filter.k is the number of nearest neighbors. \ninputs.filter.k = 10;\n% Statistical point density outlier filtering, applied if filter.radius > 0. \n% The value filter.radius is the radius of the ball neighborhood. This is\n% usually meant as alternative to the above knn-filtering.\ninputs.filter.radius = 0.00;\n% The value filter.nsigma is the multiplier of the standard deviation of\n% the kth-nearest neighbor distance/point density and points whose \n% kth-nearest neighbor distance/point density is larger/lower than the \n% average +/- filter.nsigma * std are removed:\ninputs.filter.nsigma = 1.5;\n% Small component filtering is applied if filter.ncomp > 0. This filter is\n% based on cover whose patches are defined by filter.PatchDiam1 and \n% filter.BallRad1. The points which are included in components that have\n% less than filter.ncomp patches are removed:\ninputs.filter.PatchDiam1 = 0.05;\ninputs.filter.BallRad1 = 0.075;\ninputs.filter.ncomp = 2;\n% Cubical downsampling is applied if filter.EdgeLength > 0. \n% The value filter.EdgeLength is the length of the cube edges:\ninputs.filter.EdgeLength = 0.004;\n% Plot the filtering results automatically after the filtering if\n% filter.plot > 0\ninputs.filter.plot = 1;\n\n%% Other inputs\n% These parameters don't affect the QSM-reconstruction but define what is\n% saved, plotted, and displayed and how the models are named/indexed\n% Name string for saving output files and naming models:\ninputs.name = 'tree'; \n% Tree index. If modelling multiple trees, then they can be indexed uniquely:\ninputs.tree = 1;\n% Model index, can separate models if multiple models with the same inputs:\ninputs.model = 1; \n% Save the output struct QSM as a matlab-file into \\result folder. \n% If name = 'pine', tree = 2, model = 5, the name of the saved file is \n% 'QSM_pine_t2_m5.mat':\ninputs.savemat = 1; \n% Save the models in .txt-files (check \"save_model_text.m\"):\ninputs.savetxt = 1; \n% What are plotted during reconstruction process: \n% 2 = plots the QSM, the segmentated point cloud and distributions, \n% 1 = plots the QSM and the segmentated point cloud\n% 0 = plots nothing\ninputs.plot = 2; \n% What are displayed during the reconstruction: 2 = display all; \n% 1 = display name, parameters and distances; 0 = display only the name:\ninputs.disp = 2; \n"
  },
  {
    "path": "src/estimate_precision.m",
    "content": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction [TreeData,OptQSMs,OptQSM] = ...\n  estimate_precision(QSMs,NewQSMs,TreeData,OptModels,savename)\n\n% ---------------------------------------------------------------------\n% ESTIMATE_PRECISION.M      Combines additional QSMs with optimal inputs\n%                             with previously generated QSMs to estimate the\n%                             precision (standard deviation) better.\n%\n% Version 1.1.0\n% Latest update     10 May 2022\n%\n% Copyright (C) 2016-2022 Pasi Raumonen\n% ---------------------------------------------------------------------\n\n% Uses models with the same inputs to estimate the precision (standard\n% deviation) of the results. Has two sets of models as its inputs:\n% 1) QSMs can contain models with many different input parameters for each tree\n% and OptModels contain the indexes of the models that are used here (\"optimal\n% models\"); 2) NewQSMs contains only models with the optimal inputs.\n%\n% Inputs:\n% QSMs          Contain all the models, possibly from multiple trees\n% NewQSMs       Contains the additional models with optimal inputs, for all trees\n% TreeData      Similar structure array as the \"treedata\" in QSMs but now each\n%                   single-number attribute contains the mean and std computed\n%                   from the models with the optimal inputs, and the\n%                   sensitivities for PatchDiam-parameters\n% OptModels     Indexes of the optimal models for each tree in \"QSMs\"\n% savename      Optional input, name string specifying the name of the saved\n%                   file containing the outputs\n% Outputs:\n% TreeData      Updated with new mean and std computed from all the QSMs\n%                 with the optimal inputs\n% OptQSMs       Contains all the models with the optimal inputs, for all trees\n% OptQSM        The best model (minimum point-model distance) among the models\n%                   with the optimal inputs, for all trees\n% ---------------------------------------------------------------------\n\n% Changes from version 1.0.2 to 1.1.0, 10 May 2022:\n% 1) Added \"TreeData\", the output of \"select_optimum\", as an input, and now\n%     it is updated\n\n% Changes from version 1.0.1 to 1.0.2, 26 Nov 2019:\n% 1) Added the \"name\" of the point cloud from the inputs.name to the output\n%    TreeData as a field. Also now displays the name together with the tree\n%    number.\n\n% Changes from version 1.0.0 to 1.0.1, 08 Oct 2019:\n% 1) Small change for how the output \"TreeData\" is initialised\n\n\n%% Reconstruct the outputs\nOptQSMs = QSMs(vertcat(OptModels{:,1})); % Optimal models from the optimization process\nOptQSMs = [OptQSMs NewQSMs]; % Combine all the optimal QSMs\n\nm = max(size(OptQSMs)); % number of models\nIndAll = (1:1:m)';\n% Find the first non-empty model\ni = 1;\nwhile isempty(OptQSMs(i).cylinder)\n  i = i+1;\nend\n% Determine how many single-number attributes there are in treedata\nnames = fieldnames(OptQSMs(i).treedata);\nn = 1;\nwhile numel(OptQSMs(i).treedata.(names{n})) == 1\n  n = n+1;\nend\nn = n-1;\n\ntreedata = zeros(n,m); % Collect all single-number tree attributes from all models\nTreeId = zeros(m,1); % Collect tree and model indexes from all models\nDist = zeros(m,1); % Collect the distances\nKeep = true(m,1); % Non-empty models\nfor i = 1:m\n  if ~isempty(OptQSMs(i).cylinder)\n    for j = 1:n\n      treedata(j,i) = OptQSMs(i).treedata.(names{j});\n    end\n    TreeId(i) = OptQSMs(i).rundata.inputs.tree;\n    Dist(i) = OptQSMs(i).pmdistance.mean;\n  else\n    Keep(i) = false;\n  end\nend\ntreedata = treedata(:,Keep);\nTreeId = TreeId(Keep,:);\nDist = Dist(Keep);\nIndAll = IndAll(Keep);\nTreeIds = unique(TreeId);\nnt = length(TreeIds); % number of trees\n\n% Compute the means and standard deviations\nOptModel = zeros(nt,1);\nDataM = zeros(n,nt);\nDataS = zeros(n,nt);\nfor t = 1:nt\n  I = TreeId == TreeIds(t);\n  ind = IndAll(I);\n  dist = vertcat(Dist(ind));\n  [~,J] = min(dist);\n  OptModel(t) = ind(J);\n  DataM(:,t) = mean(treedata(:,ind),2);\n  DataS(:,t) = std(treedata(:,ind),[],2);\nend\nOptQSM = OptQSMs(OptModel);\nDataCV = DataS./DataM*100;\n\n%% Display some data about optimal models\n% Decrease the number of non-zero decimals\nfor j = 1:nt\n  DataM(:,j) = change_precision(DataM(:,j));\n  DataS(:,j) = change_precision(DataS(:,j));\n  DataCV(:,j) = change_precision(DataCV(:,j));\nend\n\n% Display optimal inputs, model and attributes for each tree\nfor t = 1:nt\n  disp(['  Tree: ',num2str(t),', ',OptQSM(t).rundata.inputs.name])\n  disp('    Attributes (mean, std, CV(%)):')\n  for i = 1:n\n    str = (['     ',names{i},': ',num2str([DataM(i,t) DataS(i,t) DataCV(i,t)])]);\n    disp(str)\n  end\n  disp('------')\nend\n\n%% Generate TreeData structure for optimal models\n%TreeData = vertcat(OptQSM(:).treedata);\nfor t = 1:nt\n  for i = 1:n\n    TreeData(t).(names{i})(1:2) = [DataM(i,t) DataS(i,t)];\n  end\n  TreeData(t).name = OptQSM(t).rundata.inputs.name;\nend\n\n%% Save results\nif nargin == 5\n  str = ['results/OptimalQSMs_',savename];\n  save(str,'TreeData','OptQSMs','OptQSM')\nend\n"
  },
  {
    "path": "src/least_squares_fitting/form_rotation_matrices.m",
    "content": "% 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 terms of the GNU General Public License as published by\r\n% the Free Software Foundation, either version 3 of the License, or\r\n% (at your option) any later version.\r\n% \r\n% TREEQSM is distributed in the hope that it will be useful,\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n% GNU General Public License for more details.\r\n% \r\n% You should have received a copy of the GNU General Public License\r\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\r\n\r\nfunction [R,dR1,dR2] = form_rotation_matrices(theta)\r\n  \r\n% --------------------------------------------------------------------------\r\n% FORM_ROTATION_MATRICES.M      Forms rotation matrices R = R2*R1 and its\r\n%                                   derivatives\r\n%\r\n% Input \r\n% theta    Plane rotation angles (t1, t2) \r\n%\r\n% Output \r\n% R        Rotation matrix\r\n% R1       Plane rotation [1 0 0; 0 c1 -s1; 0 s1 c1]\r\n% R2       Plane rotation [c2 0 s2; 0 1 0; -s2 0 c2]\r\n\r\nc = cos(theta);\r\ns = sin(theta);\r\n\r\nR1 = [1 0 0; 0 c(1) -s(1); 0 s(1) c(1)];\r\nR = R1;\r\n\r\nR2 = [c(2) 0 s(2); 0 1 0; -s(2) 0 c(2)];\r\nR = R2*R;\r\n\r\nif nargout > 1\r\n    dR1 = [0 0 0; 0 -R1(3,2) -R1(2,2); 0 R1(2,2) -R1(3,2)];\r\nend\r\n\r\nif nargout > 2\r\n    dR2 = [-R2(1,3) 0 R2(1,1); 0 0 0; -R2(1,1) 0 -R2(1,3)];\r\nend"
  },
  {
    "path": "src/least_squares_fitting/func_grad_axis.m",
    "content": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction [dist,J] = func_grad_axis(P,par,weight)\n\n% ---------------------------------------------------------------------\n% FUNC_GRAD_CYLINDER.M   Function and gradient calculation for \n%                least-squares cylinder fit.\n%\n% Version 2.1.0\n% Latest update     14 July 2020\n%\n% Copyright (C) 2013-2020 Pasi Raumonen\n% ---------------------------------------------------------------------\n%\n% Input \n% par       Cylinder parameters [x0 y0 alpha beta r]'\n% P         Point cloud\n% weight    (Optional) Weights for the points\n% \n% Output\n% dist      Signed distances of points to the cylinder surface:\n%               dist(i) = sqrt(xh(i)^2 + yh(i)^2) - r, where \n%               [xh yh zh]' = Ry(beta) * Rx(alpha) * ([x y z]' - [x0 y0 0]')\n% J         Jacobian matrix d dist(i)/d par(j).\n\n% Changes from version 2.0.0 to 2.1.0, 14 July 2020:\n% 1) Added optional input for weights of the points\n\n\n% Five cylinder parameters: \n% Location = axis point intersects xy-plane: x0 and y0 (z0 == 0)\n% Rotation angles around x and y axis = alpha and beta\n% Radius = r\n%\n% Transformed points:\n% Pt = [xh yx zh] = Ry(beta) * Rx(alpha) * (P - [x0 y0 0])\n%\n% \"Plane points\":\n% Qt = Pt * I2 = [xh yh];\n%\n% Distance:\n% D(x0,y0,alpha,beta,r) = sqrt( dot(Qt,Qt) )-r = sqrt( Qt*Qt' )-r\n%\n% Least squares = minimize Sum( D^2 ) over x0, y0, alpha, beta and r\n%\n% rt = sqrt( dot(Qt,Qt) )\n% N = Qt/rt\n%\n% Jacobian for D with respect to x0, y0, alpha, beta:\n% dD/di = dot( N,dQt/di ) = dot( Qt/rt,dQt/di )\n%\n% R = Ry*Rx\n% dQt/dx0 = R*[-1 0 0]'\n% dQt/dy0 = R*[0 -1 0]'\n% dQt/dalpha = (P-[x0 y0 0])*DRx';\n% dQt/dalpha = (P-[x0 y0 0])*DRy';\n  \nx0 = par(1);\ny0 = par(2);\nalpha = par(3);\nbeta = par(4);\nr = par(5);\n\n% Determine the rotation matrices and their derivatives\n[R,DR1,DR2] = form_rotation_matrices([alpha beta]);\n\n% Calculate the distances\nPt = (P-[x0 y0 0])*R';\nxt = Pt(:,1);\nyt = Pt(:,2);\nrt = sqrt(xt.*xt + yt.*yt);\ndist = rt-r; % Distances to the cylinder surface\nif nargin == 3\n  dist = weight.*dist; % Weighted distances\nend\n\n% form the Jacobian matrix\nif nargout > 1\n  \n  N = [xt./rt yt./rt];\n  m = size(P,1);\n  J = zeros(m,2);\n  \n  A3 = (P-[x0 y0 0])*DR1';\n  J(:,1) = sum(N(:,1:2).*A3(:,1:2),2);\n  \n  A4 = (P-[x0 y0 0])*DR2';\n  J(:,2) = sum(N(:,1:2).*A4(:,1:2),2);\n  \n  if nargin == 3\n    % Weighted Jacobian\n    J = [weight.*J(:,1) weight.*J(:,2)];\n  end\nend\n"
  },
  {
    "path": "src/least_squares_fitting/func_grad_circle.m",
    "content": "function [dist,J] = func_grad_circle(P,par,weight)\n\n% ---------------------------------------------------------------------\n% FUNC_GRAD_CIRCLE.M   Function and gradient calculation for \n%                           least-squares circle fit.\n%\n% Version 1.0\n% Latest update     20 Oct 2017\n%\n% Copyright (C) 2017 Pasi Raumonen\n% ---------------------------------------------------------------------\n%\n% Input \n% P         Point cloud\n% par       Circle parameters [x0 y0 r]'\n% weight    Weights for the points. Weight the distances.\n% \n% Output\n% dist      Signed distances of points to the circle:\n%               dist(i) = sqrt((xi-x0)^2 + (yi-y0)^2) - r, where \n%               \n% J         Jacobian matrix d dist(i)/d par(j).\n\n\n% Calculate the distances\nVx = P(:,1)-par(1);\nVy = P(:,2)-par(2);\nrt = sqrt(Vx.*Vx + Vy.*Vy);\nif nargin == 3\n    dist = weight.*(rt-par(3)); % Weighted distances to the circle\nelse\n    dist = rt-par(3); % Distances to the circle\nend\n\n% form the Jacobian matrix\nif nargout > 1\n    m = size(P, 1);\n    J = zeros(m,3);\n    J(:,1) = -Vx./rt;\n    J(:,2) = -Vy./rt;\n    J(:,3) = -1*ones(m,1);\n    % apply the weights\n    if nargin == 3\n        J = [weight.*J(:,1) weight.*J(:,2) weight.*J(:,3)];\n    end\nend\n"
  },
  {
    "path": "src/least_squares_fitting/func_grad_circle_centre.m",
    "content": "function [dist,J] = func_grad_circle_centre(P,par,weight)\n\n% ---------------------------------------------------------------------\n% FUNC_GRAD_CIRCLE.M   Function and gradient calculation for \n%                           least-squares circle fit.\n%\n% Version 1.0\n% Latest update     20 Oct 2017\n%\n% Copyright (C) 2017 Pasi Raumonen\n% ---------------------------------------------------------------------\n%\n% Input \n% P         Point cloud\n% par       Circle parameters [x0 y0 r]'\n% weight    Weights for the points. Weight the distances.\n% \n% Output\n% dist      Signed distances of points to the circle:\n%               dist(i) = sqrt((xi-x0)^2 + (yi-y0)^2) - r, where \n%               \n% J         Jacobian matrix d dist(i)/d par(j).\n\n\n% Calculate the distances\nVx = P(:,1)-par(1);\nVy = P(:,2)-par(2);\nrt = sqrt(Vx.*Vx+Vy.*Vy);\nif nargin == 3\n  dist = weight.*(rt-par(3)); % Weighted distances to the circle\nelse\n  dist = rt-par(3); % Distances to the circle\nend\n\n% form the Jacobian matrix\nif nargout > 1\n  m = size(P,1);\n  J = zeros(m,2);\n  J(:,1) = -Vx./rt;\n  J(:,2) = -Vy./rt;\n  % apply the weights\n  if nargin == 3\n    J = [weight.*J(:,1) weight.*J(:,2)];\n  end\nend\n"
  },
  {
    "path": "src/least_squares_fitting/func_grad_cylinder.m",
    "content": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction [dist,J] = func_grad_cylinder(par,P,weight)\n\n% ---------------------------------------------------------------------\n% FUNC_GRAD_CYLINDER.M   Function and gradient calculation for \n%                least-squares cylinder fit.\n%\n% Version 2.2.0\n% Latest update     5 Oct 2021\n%\n% Copyright (C) 2013-2021 Pasi Raumonen\n% ---------------------------------------------------------------------\n%\n% Input \n% par       Cylinder parameters [x0 y0 alpha beta r]'\n% P         Point cloud\n% weight    (Optional) Weights for the points\n% \n% Output\n% dist      Signed distances of points to the cylinder surface:\n%               dist(i) = sqrt(xh(i)^2 + yh(i)^2) - r, where \n%               [xh yh zh]' = Ry(beta) * Rx(alpha) * ([x y z]' - [x0 y0 0]')\n% J         Jacobian matrix d dist(i)/d par(j).\n\n% Five cylinder parameters: \n% Location = axis point intersects xy-plane: x0 and y0 (z0 == 0)\n% Rotation angles around x and y axis = alpha and beta\n% Radius = r\n%\n% Transformed points:\n% Pt = [xh yx zh] = Ry(beta) * Rx(alpha) * (P - [x0 y0 0])\n%\n% \"Plane points\":\n% Qt = Pt * I2 = [xh yh];\n%\n% Distance:\n% D(x0,y0,alpha,beta,r) = sqrt( dot(Qt,Qt) )-r = sqrt( Qt*Qt' )-r\n%\n% Least squares = minimize Sum( D^2 ) over x0, y0, alpha, beta and r\n%\n% rt = sqrt( dot(Qt,Qt) )\n% N = Qt/rt\n%\n% Jacobian for D with respect to x0, y0, alpha, beta:\n% dD/di = dot( N,dQt/di ) = dot( Qt/rt,dQt/di )\n%\n% R = Ry*Rx\n% dQt/dx0 = R*[-1 0 0]'\n% dQt/dy0 = R*[0 -1 0]'\n% dQt/dalpha = (P-[x0 y0 0])*DRx';\n% dQt/dalpha = (P-[x0 y0 0])*DRy';\n\n% Changes from version 2.1.0 to 2.2.0, 5 Oct 20201:\n% 1) Minor changes in syntax\n\n% Changes from version 2.0.0 to 2.1.0, 14 July 2020:\n% 1) Added optional input for weights of the points\n\nx0 = par(1);\ny0 = par(2);\nalpha = par(3);\nbeta = par(4);\nr = par(5);\n\n% Determine the rotation matrices and their derivatives\n[R,DR1,DR2] = form_rotation_matrices([alpha beta]);\n\n% Calculate the distances\nPt = (P-[x0 y0 0])*R';\nxt = Pt(:,1);\nyt = Pt(:,2);\nrt = sqrt(xt.*xt + yt.*yt);\ndist = rt-r; % Distances to the cylinder surface\nif nargin == 3\n    dist = weight.*dist; % Weighted distances\nend\n\n% form the Jacobian matrix\nif nargout > 1 \n  N = [xt./rt yt./rt];\n  m = size(P,1);\n  J = zeros(m,5);\n  \n  A1 = (R*[-1 0 0]')';\n  A = eye(2);\n  A(1,1) = A1(1);  A(2,2) = A1(2);\n  J(:,1) = sum(N(:,1:2)*A,2);\n  \n  A2 = (R*[0 -1 0]')';\n  A(1,1) = A2(1);  A(2,2) = A2(2);\n  J(:,2) = sum(N(:,1:2)*A,2);\n  \n  A3 = (P-[x0 y0 0])*DR1';\n  J(:,3) = sum(N(:,1:2).*A3(:,1:2),2);\n  \n  A4 = (P-[x0 y0 0])*DR2';\n  J(:,4) = sum(N(:,1:2).*A4(:,1:2),2);\n  \n  J(:,5) = -1*ones(m,1);\n  if nargin == 3\n    % Weighted Jacobian\n    J = [weight.*J(:,1) weight.*J(:,2) weight.*J(:,3) ...\n      weight.*J(:,4) weight.*J(:,5)];\n  end\nend\n"
  },
  {
    "path": "src/least_squares_fitting/least_squares_axis.m",
    "content": "\nfunction cyl = least_squares_axis(P,Axis,Point0,Rad0,weight)\n\n% ---------------------------------------------------------------------\n% LEAST_SQUARES_AXIS.M   Least-squares cylinder axis fitting using \n%                         Gauss-Newton when radius and point are given\n%\n% Version 1.0\n% Latest update     1 Oct 2021\n%\n% Copyright (C) 2017-2021 Pasi Raumonen\n% ---------------------------------------------------------------------\n% Input    \n% P         3d point cloud\n% Axis0     Initial axis estimate (1 x 3)\n% Point0    Initial estimate of axis point (1 x 3)\n% Rad0      Initial estimate of the cylinder radius\n% weight    (Optional) Weights for each point\n% \n% Output\n% cyl       Structure array with the following fields\n%   axis      Cylinder axis (optimized here)\n%   radius    Radius of the cylinder (from the input)\n%   start     Axis point (from the input)\n%   mad       Mean absolute distance of the points to the cylinder surface\n%   SurfCov   Surface coverage, how much of the cylinder surface is covered \n%               with points\n%   conv      If conv = 1, the algorithm has converged \n%   rel       If rel = 1, the algorithm has reliable answer in terms of\n%               matrix inversion with a good enough condition number\n% ---------------------------------------------------------------------\n\n\n%% Initial estimates and other settings\nres = 0.03; % \"Resolution level\" for computing surface coverage\npar = [0 0]';\nmaxiter = 50; % maximum number of Gauss-Newton iteration\niter = 0; % number of iterations so far\nconv = false; % converge of Gauss-Newton algorithm\nrel = true; % are the results reliable, system matrix not badly conditioned\nif nargin == 4\n    weight = ones(size(P,1),1);\nend\nRot0 = rotate_to_z_axis(Axis);\nPt = (P-Point0)*Rot0';\n\nPar = [0 0 0 0 Rad0]';\n\n%% Gauss-Newton iterations\nwhile iter < maxiter && ~conv && rel\n    \n    % Calculate the distances and Jacobian\n    [dist,J] = func_grad_axis(Pt,Par);\n    \n    % Calculate update step and gradient.\n    SS0 = norm(dist); % Squared sum of the distances\n    % solve for the system of equations: \n    % par(i+1) = par(i) - (J'J)^(-1)*J'd(par(i))\n    A = J'*J;\n    b = J'*dist;\n    warning off\n    p = -A\\b; % solve for the system of equations\n    warning on\n    \n    % Update\n    par = par+p;\n    \n    % Check if the updated parameters lower the squared sum value\n    Par = [0; 0; par; Rad0];\n    dist = func_grad_axis(Pt,Par);\n    SS1 = norm(dist);\n    if SS1 > SS0\n        % Update did not decreased the squared sum, use update with much\n        % shorter update step\n        par = par-0.95*p;\n        Par = [0; 0; par; Rad0];\n        dist = func_grad_axis(Pt,Par);\n        SS1 = norm(dist);\n    end\n    \n    % Check reliability\n    rel = true;\n    if rcond(A) < 10000*eps\n        rel = false;\n    end\n    \n    % Check convergence\n    if abs(SS0-SS1) < 1e-5\n        conv = true;\n    end\n    \n    iter = iter+1;\nend\n\n%% Output\n% Inverse transformation to find axis and point on axis \n% corresponding to original data\nRot = form_rotation_matrices(par);\nAxis = Rot0'*Rot'*[0 0 1]'; % axis direction\n\n% Compute the point distances to the axis\n[dist,~,h] = distances_to_line(P,Axis,Point0); \ndist = dist-Rad0; % distances without weights\nLen = max(h)-min(h);\n\n% Compute mad (for points with maximum weights)\nif nargin <= 4\n  mad = mean(abs(dist)); % mean absolute distance to the circle\nelse\n  I = weight == max(weight);\n  mad = mean(abs(dist(I))); % mean absolute distance to the circle\nend\n\n% Compute SurfCov, minimum 3*8 grid\nif ~any(isnan(par)) && rel && conv\n  nl = ceil(Len/res);\n  nl = max(nl,3);\n  ns = ceil(2*pi*Rad0/res);\n  ns = max(ns,8);\n  ns = min(36,ns);\n  SurfCov = single(surface_coverage(P,Axis,Point0,nl,ns,0.8*Rad0));\nelse\n  SurfCov = single(0);\nend\n\n\n%% Define the output \nclear cir\ncyl.radius = Rad0;\ncyl.start = Point0;\ncyl.axis = Axis';\ncyl.mad = mad;\ncyl.SurfCov = SurfCov;\ncyl.conv = conv;\ncyl.rel = rel;\n"
  },
  {
    "path": "src/least_squares_fitting/least_squares_circle.m",
    "content": "function cir = least_squares_circle(P,Point0,Rad0,weight)\n% ---------------------------------------------------------------------\n% LEAST_SQUARES_CIRCLE.M   Least-squares circle fitting using Gauss-Newton.\n%\n% Version 1.1.0\n% Latest update     6 Oct 2021\n%\n% Copyright (C) 2017-2021 Pasi Raumonen\n% ---------------------------------------------------------------------\n% Input    \n% P         2d point cloud\n% Point0    Initial estimate of centre (1 x 2)\n% Rad0      Initial estimate of the circle radius\n% weight    Optional, weights for each point\n% \n% Output  \n% Rad       Radius of the cylinder\n% Point     Centre point (1 x 2)\n% ArcCov    Arc point coverage (%), how much of the circle arc is covered with points\n% conv      If conv = 1, the algorithm has converged \n% rel       If rel = 1, the algorithm has reliable answer in terms of\n%               matrix inversion with a good enough condition number\n% ---------------------------------------------------------------------\n\n\n%% Initial estimates and other settings\npar = [Point0 Rad0]'; \nmaxiter = 200; % maximum number of Gauss-Newton iteration\niter = 0; % number of iterations so far\nconv = false; % converge of Gauss-Newton algorithm\nrel = true; % are the reusults reliable in the sense that system matrix was not badly conditioned\nif nargin == 3\n  weight = ones(size(P,1),1);\nend\n\n%% Gauss-Newton iterations\nwhile iter < maxiter && ~conv && rel\n  \n  % Calculate the distances and Jacobian\n  [dist,J] = func_grad_circle(P,par,weight);\n  \n  % Calculate update step and gradient.\n  SS0 = norm(dist); % Squared sum of the distances\n  % solve for the system of equations: par(i+1) = par(i) - (J'J)^(-1)*J'd(par(i))\n  A = J'*J;\n  b = J'*dist;\n  warning off\n  p = -A\\b; % solve for the system of equations\n  warning on\n  \n  % Update\n  par = par+p;\n  \n  % Check if the updated parameters lower the squared sum value\n  dist = func_grad_circle(P,par,weight);\n  SS1 = norm(dist);\n  if SS1 > SS0\n    % Update did not decreased the squared sum, use update with much\n    % shorter update step\n    par = par-0.95*p;\n    dist = func_grad_circle(P,par,weight);\n    SS1 = norm(dist);\n  end\n  \n  % Check reliability\n  if rcond(A) < 10000*eps\n    rel = false;\n  end\n  \n  % Check convergence\n  if abs(SS0-SS1) < 1e-5\n    conv = true;\n  end\n  \n  iter = iter+1;\nend\n\n%% Output\nRad = par(3);\nPoint = par(1:2);\nU = P(:,1)-Point(1);\nV = P(:,2)-Point(2);\ndist = sqrt(U.*U+V.*V)-Rad;\nif nargin <= 3\n  mad = mean(abs(dist)); % mean absolute distance to the circle\nelse\n  I = weight == max(weight);\n  mad = mean(abs(dist(I))); % mean absolute distance to the circle\nend\n% Calculate ArcCov, how much of the circle arc is covered with points\nif ~any(isnan(par))\n  if nargin <= 3\n    I = dist > -0.2*Rad;\n  else\n    I = dist > -0.2*Rad & weight == max(weight);\n  end\n  U = U(I,:);   V = V(I,:);\n  ang = atan2(V,U)+pi;\n  ang = ceil(ang/2/pi*100);\n  ang(ang <= 0) = 1;\n  Arc = false(100,1);\n  Arc(ang) = true;\n  ArcCov = nnz(Arc)/100;\nelse\n  ArcCov = 0;\nend\n\ncir.radius = Rad;\ncir.point = Point';\ncir.mad = mad;\ncir.ArcCov = ArcCov;\ncir.conv = conv;\ncir.rel = rel;"
  },
  {
    "path": "src/least_squares_fitting/least_squares_circle_centre.m",
    "content": "function cir = least_squares_circle_centre(P,Point0,Rad0)\n% ---------------------------------------------------------------------\n% LEAST_SQUARES_CIRCLE_CENTRE.M   Least-squares circle fitting such that\n%                                   radius is given (fits the centre)\n%\n% Version 1.0.0\n% Latest update     6 Oct 2021\n%\n% Copyright (C) 2017-2021 Pasi Raumonen\n% ---------------------------------------------------------------------\n% Input    \n% P         2d point cloud\n% Point0    Initial estimate of centre (1 x 2)\n% Rad0      The circle radius\n% weight    Optional, weights for each point\n% \n% Output  \n% cir     Structure array with the following fields\n%   Rad       Radius of the cylinder\n%   Point     Centre point (1 x 2)\n%   ArcCov    Arc point coverage (%), how much of the circle arc is covered \n%               with points\n%   conv      If conv = 1, the algorithm has converged \n%   rel       If rel = 1, the algorithm has reliable answer in terms of\n%               matrix inversion with a good enough condition number\n% ---------------------------------------------------------------------\n\n% Changes from version 1.0.0 to 1.1.0, 6 Oct 2021:  \n% 1) Streamlining code and some computations\n\n%% Initial estimates and other settings\npar = [Point0 Rad0]'; \nmaxiter = 200; % maximum number of Gauss-Newton iteration\niter = 0; % number of iterations so far\nconv = false; % converge of Gauss-Newton algorithm\nrel = true; % the results reliable (system matrix was not badly conditioned)\n\n%% Gauss-Newton iterations\nwhile iter < maxiter && ~conv && rel\n  \n  % Calculate the distances and Jacobian\n  [dist,J] = func_grad_circle_centre(P,par);\n  \n  % Calculate update step and gradient.\n  SS0 = norm(dist); % Squared sum of the distances\n  % solve for the system of equations: par(i+1) = par(i) - (J'J)^(-1)*J'd(par(i))\n  A = J'*J;\n  b = J'*dist;\n  warning off\n  p = -A\\b; % solve for the system of equations\n  warning on\n  \n  % Update\n  par(1:2,1) = par(1:2,1)+p;\n  \n  % Check if the updated parameters lower the squared sum value\n  dist = func_grad_circle_centre(P,par);\n  SS1 = norm(dist);\n  if SS1 > SS0\n    % Update did not decreased the squared sum, use update with much\n    % shorter update step\n    par(1:2,1) = par(1:2,1)-0.95*p;\n    dist = func_grad_circle_centre(P,par);\n    SS1 = norm(dist);\n  end\n  \n  % Check reliability\n  if rcond(A) < 10000*eps\n    rel = false;\n  end\n  \n  % Check convergence\n  if abs(SS0-SS1) < 1e-5\n    conv = true;\n  end\n  \n  iter = iter+1;\nend\n\n%% Output\nPoint = par(1:2);\nif conv && rel\n  % Calculate ArcCov, how much of the circle arc is covered with points\n  U = P(:,1)-par(1);\n  V = P(:,2)-par(2);\n  ang = atan2(V,U)+pi;\n  I = false(100,1);\n  ang = ceil(ang/2/pi*100);\n  I(ang) = true;\n  ArcCov = nnz(I)/100;\n  % mean absolute distance to the circle\n  d = sqrt(U.*U+V.*V)-Rad0;\n  mad = mean(abs(d)); \nelse\n  mad = 0;\n  ArcCov = 0;\nend\n\ncir.radius = Rad0;\ncir.point = Point';\ncir.mad = mad;\ncir.ArcCov = ArcCov;\ncir.conv = conv;\ncir.rel = rel;"
  },
  {
    "path": "src/least_squares_fitting/least_squares_cylinder.m",
    "content": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction cyl = least_squares_cylinder(P,cyl0,weight,Q)\n% ---------------------------------------------------------------------\n% LEAST_SQUARES_CYLINDER.M   Least-squares cylinder using Gauss-Newton.\n%\n% Version 2.0.0\n% Latest update     5 Oct 2021\n%\n% Copyright (C) 2013-2021 Pasi Raumonen\n% ---------------------------------------------------------------------\n% Input    \n% P         Point cloud\n% cyl0      Initial estimates of the cylinder parameters\n% weight    (Optional) Weights of the points for fitting\n% Q         (Optional) Subset of \"P\" where the cylinder is intended\n% \n% Output  \n% cyl       Structure array containing the following fields:\n%   radius      Radius of the cylinder\n%   length      Length of the cylinder\n%   start       Point on the axis at the bottom of the cylinder (1 x 3)\n%   axis        Axis direction of the cylinder (1 x 3) \n%   mad         Mean absolute distance between points and cylinder surface\n%   SurfCov     Relative cover of the cylinder's surface by the points \n%   dist        Radial distances from the points to the cylinder (m x 1) \n%   conv        If conv = 1, the algorithm has converged \n%   rel         If rel = 1, the algorithm has reliable answer in terms of\n%                   matrix inversion with a good enough condition number\n% ---------------------------------------------------------------------\n\n% Changes from version 1.3.0 to 2.0.0, 5 Oct 2021:  \n% 1) Included the Gauss-Newton iterations into this function (removed the \n%      call to nlssolver function)\n% 2) Changed how the updata step is solved from the Jacobian\n% 3) Simplified some expressions and added comments\n% 4) mad is computed only from the points along the cylinder length in the\n%     case of the optional input \"Q\" is given.  \n% 5) Changed the surface coverage estimation by filtering out points whose \n%     distance to the axis is less than 80% of the radius \n\n% Changes from version 1.2.0 to 1.3.0, 14 July 2020:  \n% 1) Changed the input parameters of the cylinder to the struct format.\n% 2) Added optional input for weights\n% 3) Added optional input \"Q\", a subset of \"P\", the cylinder is intended\n%    to be fitted in this subset but it is fitted to \"P\" to get better\n%    estimate of the axis direction and radius\n\n% Changes from version 1.1.0 to 1.2.0, 14 Jan 2020:  \n% 1) Changed the outputs and optionally the inputs to the struct format.\n% 2) Added new output, \"mad\", which is the mean absolute distance of the\n%    points from the surface of the cylinder.\n% 3) Added new output, \"SurfCov\", that measures how well the surface of the\n%    cylinder is covered by the points.\n% 4) Added new output, \"SurfCovDis\", which is a matrix of mean point distances \n%    from layer/sector-intersections to the axis.\n% 5) Added new output, \"SurfCovVol\", which is an estimate of the cylinder's \n%    volume based on the radii in \"SurfCovDis\" and \"cylindrical sectors\".\n% 6) Added new optional input \"res\" which gives the point resolution level\n%    for computing SurfCov: the width and length of sectors/layers.\n\n% Changes from version 1.0.0 to 1.1.0, 3 Oct 2019:  \n% 1) Bug fix: --> \"Point = Rot0'*([par(1) par(2) 0]')...\"\n\n\n%% Initialize data and values\nres = 0.03; % \"Resolution level\" for computing surface coverage\nmaxiter = 50; % maximum number of Gauss-Newton iterations\niter = 0; \nconv = false; % Did the iterations converge\nrel = true; % Are the results reliable (condition number was not very bad)\nif nargin == 2\n  NoWeights = true; % No point weight given for the fitting\nelse\n  NoWeights = false;\nend\n\n% Transform the data to close to standard position via a translation  \n% followed by a rotation\nRot0 = rotate_to_z_axis(cyl0.axis);\nPt = (P-cyl0.start)*Rot0';\n\n% Initial estimates\npar = [0 0 0 0 cyl0.radius]'; \n\n\n%% Gauss-Newton algorithm \n% find estimate of rotation-translation-radius parameters that transform\n% the data so that the best-fit cylinder is one in standard position\nwhile iter < maxiter && ~conv && rel\n  \n  %% Calculate the distances and Jacobian\n  if NoWeights\n    [d0,J] = func_grad_cylinder(par,Pt);\n  else\n    [d0,J] = func_grad_cylinder(par,Pt,weight);\n  end\n  \n  %% Calculate update step\n  SS0 = norm(d0); % Squared sum of the distances\n  % solve for the system of equations:\n  % par(i+1) = par(i) - (J'J)^(-1)*J'd0(par(i))\n  A = J'*J;\n  b = J'*d0;\n  warning off\n  p = -A\\b; % solve for the system of equations\n  warning on\n  par = par+p; % update the parameters\n\n  %% Check reliability\n  if rcond(-A) < 10000*eps\n    rel = false;\n  end\n  \n  %% Check convergence:\n  % The distances with the new parameter values:\n  if NoWeights\n    dist = func_grad_cylinder(par,Pt);\n  else\n    dist = func_grad_cylinder(par,Pt,weight);\n  end\n  SS1 = norm(dist); % Squared sum of the distances\n  if abs(SS0-SS1) < 1e-4\n    conv = true;\n  end\n  \n  iter = iter + 1;\nend\n\n%% Compute the cylinder parameters and other outputs\ncyl.radius = single(par(5)); % radius\n\n% Inverse transformation to find axis and point on axis \n% corresponding to original data\nRot = form_rotation_matrices(par(3:4));\nAxis = Rot0'*Rot'*[0 0 1]'; % axis direction\nPoint = Rot0'*([par(1) par(2) 0]')+cyl0.start'; % axis point\n\n% Compute the start, length and mad, translate the axis point to the \n% cylinder's bottom:\n% If the fourth input (point cloud Q) is given, use it for the start, \n% length, mad, and SurfCov\nif nargin == 4\n  if size(Q,1) > 5\n    P = Q;\n  end\nend\nH = P*Axis; % heights along the axis\nhmin = min(H);\ncyl.length = single(abs(max(H)-hmin));\nhpoint = Axis'*Point;\nPoint = Point-(hpoint-hmin)*Axis; % axis point at the cylinder's bottom\ncyl.start = single(Point');\ncyl.axis = single(Axis');\n% Compute mad for the points along the cylinder length:\nif nargin >= 6\n  I = weight == max(weight);\n  cyl.mad = single(average(abs(dist(I)))); % mean absolute distance\nelse\n  cyl.mad = single(average(abs(dist))); % mean absolute distance\nend\ncyl.conv = conv;\ncyl.rel = rel;\n\n% Compute SurfCov, minimum 3*8 grid\nif ~any(isnan(Axis)) && ~any(isnan(Point)) && rel && conv\n  nl = max(3,ceil(cyl.length/res));\n  ns = ceil(2*pi*cyl.radius/res);\n  ns = min(36,max(ns,8));\n  SurfCov = surface_coverage(P,Axis',Point',nl,ns,0.8*cyl.radius);\n  \n  cyl.SurfCov = single(SurfCov);\nelse\n  cyl.SurfCov = single(0);\nend\n"
  },
  {
    "path": "src/least_squares_fitting/nlssolver.m",
    "content": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction [par,d,conv,rel] = nlssolver(par,P,weight)\n\n% ---------------------------------------------------------------------\n% NLSSOLVER.M   Nonlinear least squares solver for cylinders.\n%\n% Version 2.1.0\n% Latest update     14 July 2020\n%\n% Copyright (C) 2013-2020 Pasi Raumonen\n% ---------------------------------------------------------------------\n%\n% Input \n% par       Intial estimates of the parameters\n% P         Point cloud\n%           \n% Output \n% par       Optimised parameter values\n% d         Distances of points to cylinder\n% conv      True if fitting converged\n% rel       True if condition number was not very bad, fit was reliable\n\n% Changes from version 2.0.0 to 2.1.0, 14 July 2020:\n% 1) Added optional input for weights of the points\n\nmaxiter = 50;\niter = 0;\nconv = false;\nrel = true;\n\nif nargin == 2\n    NoWeights = true;\nelse\n    NoWeights = false;\nend\n\n%% Gauss-Newton iterations\nwhile iter < maxiter && ~conv && rel\n    \n    %% Calculate the distances and Jacobian\n    if NoWeights\n        [d0, J] = func_grad_cylinder(par,P);\n    else\n        [d0, J] = func_grad_cylinder(par,P,weight);\n    end\n    \n    %% Calculate update step\n    SS0 = norm(d0); % Squared sum of the distances\n    % solve for the system of equations: \n    % par(i+1) = par(i) - (J'J)^(-1)*J'd0(par(i))\n    A = J'*J;\n    b = J'*d0;\n    warning off\n    p = -A\\b; % solve for the system of equations\n    warning on\n    par = par+p; % update the parameters\n    \n    %% Check reliability\n    if rcond(-R) < 10000*eps\n        rel = false;\n    end\n    \n    %% Check convergence:\n    % The distances with the new parameter values:\n    if NoWeights\n        d = func_grad_cylinder(par,P); \n    else\n        d = func_grad_cylinder(par,P,weight); \n    end\n    SS1 = norm(d); % Squared sum of the distances\n    if abs(SS0-SS1) < 1e-4\n        conv = true;\n    end\n    \n    iter = iter + 1;\nend\n"
  },
  {
    "path": "src/least_squares_fitting/rotate_to_z_axis.m",
    "content": "% 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 terms of the GNU General Public License as published by\r\n% the Free Software Foundation, either version 3 of the License, or\r\n% (at your option) any later version.\r\n% \r\n% TREEQSM is distributed in the hope that it will be useful,\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n% GNU General Public License for more details.\r\n% \r\n% You should have received a copy of the GNU General Public License\r\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\r\n\r\nfunction [R,D,a] = rotate_to_z_axis(Vec)\r\n\r\n% --------------------------------------------------------------------------\r\n% ROTATE_TO_Z_AXIS.M   Forms the rotation matrix to rotate the vector to \r\n%                           a point along the positive z-axis. \r\n%\r\n% Input \r\n% Vec      Vector (3 x 1)\r\n%\r\n% Output \r\n% R        Rotation matrix, with R * Vec = [0 0 z]', z > 0 \r\n\r\n\r\nD = cross(Vec,[0 0 1]);\r\nif norm(D) > 0\r\n    a = acos(Vec(3));\r\n    R = rotation_matrix(D,a);\r\nelse\r\n    R = eye(3);\r\n    a = 0;\r\n    D = [1 0 0];\r\nend\r\n"
  },
  {
    "path": "src/main_steps/branches.m",
    "content": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction branch = branches(cylinder)\n\n% ---------------------------------------------------------------------\n% BRANCHES.M        Determines the branching structure and computes branch\n%                       attributes\n%\n% Version 3.0.0\n% Latest update     2 May 2022\n%\n% Copyright (C) 2013-2022 Pasi Raumonen\n% ---------------------------------------------------------------------\n\n% Determines the branches (cylinders in a segment define a branch), their order\n% and topological parent-child-relation. Branch number one is the trunk and\n% its order is zero. Notice that branch number does not tell its age in the\n% sense that branch number two would be the oldest branch and the number\n% three the second oldest.\n%\n% Inputs:\n% cylinder  Cylinders, structure array\n%\n% Outputs:\n% branch    Branch structure array, contains fields:\n%             Branch order, parent, volume, length, angle, height, azimuth\n%             and diameter\n% ---------------------------------------------------------------------\n\n% Changes from version 2.1.0 to 3.0.0, 2 May 2022:\n% 1) Changed the code such that the input \"segment\" and output \"cylinder\"\n%    are not needed anymore, which simplified the code in many places.\n%    Cylinder info is now computed in \"cylinders\" function.\n\n% Changes from version 2.0.0 to 2.1.0, 25 Jan 2020:\n% 1) Chanced the coding to simplify and shorten the code\n% 2) Added branch area and zenith direction as new fields in the\n%    branch-structure array\n% 3) Removed the line were 'ChildCyls' and'CylsInSegment' fields are\n%    removed from the cylinder-structure array\n\nRad = cylinder.radius;\nLen = cylinder.length;\nAxe = cylinder.axis;\n\n%% Branches\nnc = size(Rad,1);  % number of cylinder\nns = max(cylinder.branch);  % number of segments\nBData = zeros(ns,9); % branch ord, dia, vol, are, len, ang, hei, azi, zen\nind = (1:1:nc)';\nCiB = cell(ns,1);\nfor i = 1:ns\n  C = ind(cylinder.branch == i);\n  CiB{i} = C;\n  if ~isempty(C)\n\n    BData(i,1) = cylinder.BranchOrder(C(1)); % branch order\n    BData(i,2) = 2*Rad(C(1)); % branch diameter\n    BData(i,3) = 1000*pi*sum(Len(C).*Rad(C).^2); % branch volume\n    BData(i,4) = 2*pi*sum(Len(C).*Rad(C)); % branch area\n    BData(i,5) = sum(Len(C)); % branch length\n\n    % if the first cylinder is added to fill a gap, then\n    % use the second cylinder to compute the angle:\n    if cylinder.added(C(1)) && length(C) > 1\n      FC = C(2);  % first cyl in the branch\n      PC = cylinder.parent(C(1)); % parent cylinder of the branch\n    else\n      FC = C(1);\n      PC = cylinder.parent(FC);\n    end\n    if PC > 0\n      BData(i,6) = 180/pi*acos(Axe(FC,:)*Axe(PC,:)'); % branch angle\n    end\n\n    BData(i,7) = cylinder.start(C(1),3)-cylinder.start(1,3); % branch height\n    BData(i,8) = 180/pi*atan2(Axe(C(1),2),Axe(C(1),1)); % branch azimuth\n    BData(i,9) = 180/pi*acos(Axe(C(1),3)); % branch zenith\n  end\nend\nBData = single(BData);\n\n%% Branching structure (topology, parent-child-relation)\nbranch.order = uint8(BData(:,1));\nBPar = zeros(ns,1);\nChi = cell(nc,1);\nfor i = 1:nc\n  c = ind(cylinder.parent == i);\n  c = c(c ~= cylinder.extension(i));\n  Chi{i} = c;\nend\nfor i = 1:ns\n  C = CiB{i};\n  ChildCyls = unique(vertcat(Chi{C}));\n  CB = unique(cylinder.branch(ChildCyls));  % Child branches\n  BPar(CB) = i;\nend\nif ns <= 2^16\n  branch.parent = uint16(BPar);\nelse\n  branch.parent = uint32(BPar);\nend\n\n%% Finish the definition of branch\nbranch.diameter = BData(:,2);   % diameters in meters\nbranch.volume = BData(:,3);     % volumes in liters\nbranch.area = BData(:,4);       % areas in square meters\nbranch.length = BData(:,5);     % lengths in meters\nbranch.angle = BData(:,6);      % angles in degrees\nbranch.height = BData(:,7);     % heights in meters\nbranch.azimuth = BData(:,8);    % azimuth directions in angles\nbranch.zenith = BData(:,9);     % zenith directions in angles\n"
  },
  {
    "path": "src/main_steps/correct_segments.m",
    "content": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction segment = correct_segments(P,cover,segment,inputs,RemSmall,ModBases,AddChild)\n\n% ---------------------------------------------------------------------\n% CORRECT_SEGMENTS.M        Corrects the given segmentation.\n%\n% Version 2.0.2\n% Latest update     2 May 2022\n%\n% Copyright (C) 2013-2022 Pasi Raumonen\n% ---------------------------------------------------------------------\n\n% First segments are modified by making them as long as possible. Here the\n% stem and 1-st order branches are handled differently as there is also\n% restriction to how \"curved\" they can be in the sense of ratio\n% total_length/base_tip_distance. Then, optionally, small segments that\n% are close to their parent and have no children are removed as unclear\n% (are they part of the parent or real segments?).\n% Then, optionally, the bases of branches are modified by\n% expanding them into parent segment in order to remove ledges from the\n% parent from locations of the branches.\n\n% Inputs:\n% P             Point cloud\n% cover         Cover sets\n% segment       Segments\n% inputs        The input structure\n% RemSmall      If True, small unclear segments are removed\n% ModBase       If True, bases of the segments are modified\n% AddChild      If True, the expanded (modified) base is added to the child segment.\n%               If AddChild = false and ModBase = true, then the expanded part is\n%               removed from both the child and the parent.\n% Outputs:\n% segment       Segments\n% ---------------------------------------------------------------------\n\n% Changes from version 2.0.1 to 2.0.2, 2 May 2022:\n% 1) Added \"if ~isempty(SegChildren)... \" statement to the\n%    \"modify_topology\" subfunction where next branch is selected based on \n%    the increasing branching order to prevent a rare bug \n\n% Changes from version 2.0.0 to 2.0.1, 2 Oct 2019:\n% 1) Main function: added \"if SPar(i,1) > 1\"-statement to ModBase -->\n%    NotAddChild\n\nif nargin == 4\n  RemSmall = true;\n  ModBases = false;\nelseif nargin == 5\n  ModBases = false;\nelseif nargin == 6\n  AddChild = false;\nend\n\nBal = cover.ball;\nSegs = segment.segments;\nSPar = segment.ParentSegment;\nSChi = segment.ChildSegment;\nCe = P(cover.center,:);\n\n%% Make stem and branches as long as possible\nif RemSmall\n  [Segs,SPar,SChi] = modify_topology(P,Ce,Bal,Segs,SPar,SChi,inputs.PatchDiam2Max);\nelse\n  [Segs,SPar,SChi] = modify_topology(P,Ce,Bal,Segs,SPar,SChi,inputs.PatchDiam1);\nend\n\n%% Remove small child segments\nif RemSmall\n  [Segs,SPar,SChi] = remove_small(Ce,Segs,SPar,SChi);\nend\n\n% Check the consistency of empty vector sizes\nns = size(Segs,1);\nfor i = 1:ns\n  if isempty(SChi{i})\n    SChi{i} = zeros(0,1,'uint32');\n  end\nend\n\nif ModBases\n  %% Modify the base of the segments\n  ns = size(Segs,1);\n  base = cell(200,1);\n  if AddChild\n    % Add the expanded base to the child and remove it from the parent\n    for i = 2:ns\n      SegC = Segs{i};\n      SegP = Segs{SPar(i,1)};\n      [SegP,Base] = modify_parent(P,Bal,Ce,SegP,SegC,SPar(i,2),inputs.PatchDiam1,base);\n      Segs{SPar(i,1)} = SegP;\n      SegC{1} = Base;\n      Segs{i} = SegC;\n    end\n  else\n    % Only remove the expanded base from the parent\n    for i = 2:ns\n      if SPar(i,1) > 1\n        SegC = Segs{i};\n        SegP = Segs{SPar(i,1)};\n        SegP = modify_parent(P,Bal,Ce,SegP,SegC,SPar(i,2),inputs.PatchDiam2Max,base);\n        Segs{SPar(i,1)} = SegP;\n      end\n    end\n  end\nend\nSPar = SPar(:,1);\n\n% Modify the size and type of SChi and Segs, if necessary\nns = size(Segs,1);\nfor i = 1:ns\n  C = SChi{i};\n  if size(C,2) > size(C,1) && size(C,1) > 0\n    SChi{i} = uint32(C');\n  elseif size(C,1) == 0 || size(C,2) == 0\n    SChi{i} = zeros(0,1,'uint32');\n  else\n    SChi{i} = uint32(C);\n  end\n  S = Segs{i};\n  for j = 1:size(S,1)\n    S{j} = uint32(S{j});\n  end\n  Segs{i} = S;\nend\nsegment.segments = Segs;\nsegment.ParentSegment = SPar;\nsegment.ChildSegment = SChi;\n\n%% Generate segment data for the points\nnp = size(P,1);\nns = size(Segs,1);\n% Define for each point its segment\nif ns <= 2^16\n  SegmentOfPoint = zeros(np,1,'uint16');\nelse\n  SegmentOfPoint = zeros(np,1,'uint32');\nend\nfor i = 1:ns\n  S = Segs{i};\n  S = vertcat(S{:});\n  SegmentOfPoint(vertcat(Bal{S})) = i;\nend\nsegment.SegmentOfPoint = SegmentOfPoint;\n% Define the indexes of the segments up to 3rd-order\nC = SChi{1};\nsegment.branch1indexes = C;\nif ~isempty(C)\n  C = vertcat(SChi{C});\n  segment.branch2indexes = C;\n  if ~isempty(C)\n    C = vertcat(SChi{C});\n    segment.branch3indexes = C;\n  else\n    segment.branch3indexes = zeros(0,1);\n  end\nelse\n  segment.branch2indexes = zeros(0,1);\n  segment.branch3indexes = zeros(0,1);\nend\n\nend % End of main function\n\n\nfunction StemTop = search_stem_top(P,Ce,Bal,Segs,SPar,dmin)\n\n% Search the stem's top segment such that the resulting stem\n% 1) is one the highest segments (goes to the top of the tree)\n% 2) is horizontally close to the bottom of the stem (goes straigth up)\n% 3) has length close to the distance between its bottom and top (is not too curved)\nnseg = size(Segs,1);\nSegHeight = zeros(nseg,1); % heights of the tips of the segments\nHorDist = zeros(nseg,1); % horizontal distances of the tips from stem's center\ns = Segs{1}{1};\nStemCen = average(Ce(s,:)); % center (x,y) of stem base\nfor i = 1:nseg\n  S = Segs{i}{end}(1);\n  SegHeight(i) = Ce(S,3);\n  HorDist(i) = norm(Ce(S,1:2)-StemCen(1:2));\nend\nTop = max(SegHeight); % the height of the highest tip\nHeiDist = Top-SegHeight; % the height difference to \"Top\"\nDist = sqrt((HorDist.^2+HeiDist.^2)); % Distance to the top\nLenDisRatio = 2;\nSearchDist = 0.5;\nMaxLenDisRatio = 1.05; % the maximum acceptable length/distance ratio of segments\nSubSegs = zeros(100,1); % Segments to be combined to form the stem\nwhile LenDisRatio > MaxLenDisRatio\n  StemTops = (1:1:nseg)';\n  I = Dist < SearchDist; % only segments with distance to the top < 0.5m\n  while ~any(I)\n    SearchDist = SearchDist+0.5;\n    I = Dist < SearchDist;\n  end\n  StemTops = StemTops(I);\n\n  % Define i-1 alternative stems from StemTops\n  n = length(StemTops);\n  Stems = cell(n,1);\n  Segment = cell(3000,1);\n  for j = 1:n\n    Seg = Segs{1};\n    spar = SPar;\n    if StemTops(j) ~= 1\n      % Tip point was not in the current segment, modify segments\n      SubSegs(1) = StemTops(j);\n      nsegs = 1;\n      segment = StemTops(j);\n      while segment ~= 1\n        segment = SPar(segment,1);\n        nsegs = nsegs+1;\n        SubSegs(nsegs) = segment;\n      end\n      % Modify stem\n      a = size(Seg,1);\n      Segment(1:a) = Seg;\n      a = a+1;\n      for i = 1:nsegs-2\n        I = SubSegs(nsegs-i); % segment to be combined to the first segment\n        J = SubSegs(nsegs-i-1); % above segment's child to be combined next\n        SP = spar(I,2);  % layer index of the child in the parent\n        SegC = Segs{I};\n        sp = spar(J,2);  % layer index of the child's child in the child\n        if SP >= a-2 % Use the whole parent\n          Segment(a:a+sp-1) = SegC(1:sp);\n          spar(J,2) = a+sp-1;\n          a = a+sp;\n        else % Use only bottom part of the parent\n          Segment(SP+1:SP+sp) = SegC(1:sp);\n          a = SP+sp+1;\n          spar(J,2) = SP+sp;\n        end\n        SubSegs(nsegs-i) = 1;\n      end\n\n      % Combine the last segment to the branch\n      I = SubSegs(1);\n      SP = spar(I,2);\n      SegC = Segs{I};\n      nc = size(SegC,1);\n      if SP >= a-2 % Use the whole parent\n        Segment(a:a+nc-1) = SegC;\n        a = a+nc-1;\n      else % divide the parent segment into two parts\n        Segment(SP+1:SP+nc) = SegC;\n        a = SP+nc;\n      end\n      Stems{j,1} = Segment(1:a);\n    else\n      Stems{j,1} = Seg;\n    end\n\n  end\n\n  % Calculate the lengths of the candidate stems\n  N = ceil(0.5/dmin/1.4); % number of layers used for linear length approximation\n  Lengths = zeros(n,1);\n  Heights = zeros(n,1);\n  for i = 1:n\n    Seg = Stems{i,1};\n    ns = size(Seg,1);\n    if ceil(ns/N) > floor(ns/N)\n      m = ceil(ns/N);\n    else\n      m = ceil(ns/N)+1;\n    end\n    Nodes = zeros(m,3);\n    for j = 1:m\n      I = (j-1)*N+1;\n      if I > ns\n        I = ns;\n      end\n      S = Seg{I};\n      if length(S) > 1\n        Nodes(j,:) = average(Ce(S,:));\n      else\n        S = Bal{S};\n        Nodes(j,:) = average(P(S,:));\n      end\n    end\n    V = Nodes(2:end,:)-Nodes(1:end-1,:);\n    Lengths(i) = sum(sqrt(sum(V.*V,2)));\n    V = Nodes(end,:)-Nodes(1,:);\n    Heights(i) = norm(V);\n  end\n\n  LenDisRatio = Lengths./Heights;\n  [LenDisRatio,I] = min(LenDisRatio);\n  StemTop = StemTops(I);\n  SearchDist = SearchDist+1;\n  if SearchDist > 3\n    MaxLenDisRatio = 1.1;\n    if SearchDist > 5\n      MaxLenDisRatio = 1.15;\n      if SearchDist > 7\n        MaxLenDisRatio = 5;\n      end\n    end\n  end\nend\n\nend % End subfunction\n\n\nfunction BranchTop = search_branch_top(P,Ce,Bal,Segs,SPar,SChi,dmin,BI)\n\n% Search the end segment for branch such that the resulting branch\n% 1) has length close to the distance between its bottom and top\n% 2) has distance close to the farthest segment end\n\n% Inputs\n% BI    Branch (segment) index\n\n% Outputs\n% BranchTop     The index of the segment forming the tip of the branch\n%                   originating from the base of the given segment BI\n\n% Define all the sub-segments of the given segments\nns = size(Segs,1);\nSegments = zeros(ns,1); % the given segment and its sub-segments\nSegments(1) = BI;\nt = 2;\nC = SChi{BI};\nwhile ~isempty(C)\n  n = length(C);\n  Segments(t:t+n-1) = C;\n  C = vertcat(SChi{C});\n  t = t+n;\nend\nif t > 2\n  t = t-n;\nend\nSegments = Segments(1:t);\n\n% Determine linear distances from the segment tips to the base of the given\n% segment\nLinearDist = zeros(t,1); % linear distances from the\nSeg = Segs{Segments(1)};\nBranchBase = average(Ce(Seg{1},:)); % center of branch's base\nfor i = 1:t\n  Seg = Segs{Segments(i)};\n  C = average(Ce(Seg{end},:)); % tip\n  LinearDist(i) = norm(C-BranchBase);\nend\nLinearDist = LinearDist(1:t);\n\n% Sort the segments according their linear distance, from longest to\n% shortest\n[LinearDist,I] = sort(LinearDist,'descend');\nSegments = Segments(I);\n\n% Define alternative branches from Segments\nBranches = cell(t,1); % the alternative segments as cell layers\nSubSegs = zeros(100,1); % Segments to be combined\nSegment = cell(3000,1);\nfor j = 1:t\n  Seg = Segs{BI};\n  spar = SPar;\n  if Segments(j) ~= BI\n    % Tip point was not in the current segment, modify segments\n    SubSegs(1) = Segments(j);\n    k = 1;\n    S = Segments(j);\n    while S ~= BI\n      S = SPar(S,1);\n      k = k+1;\n      SubSegs(k) = S;\n    end\n    % Modify branch\n    a = size(Seg,1);\n    Segment(1:a) = Seg;\n    a = a+1;\n    for i = 1:k-2\n      I = SubSegs(k-i); % segment to be combined to the first segment\n      J = SubSegs(k-i-1); % above segment's child to be combined next\n      SP = spar(I,2);  % layer index of the child in the parent\n      SegC = Segs{I};\n      sp = spar(J,2);  % layer index of the child's child in the child\n      if SP >= a-2 % Use the whole parent\n        Segment(a:a+sp-1) = SegC(1:sp);\n        spar(J,2) = a+sp-1;\n        a = a+sp;\n      else % Use only bottom part of the parent\n        Segment(SP+1:SP+sp) = SegC(1:sp);\n        a = SP+sp+1;\n        spar(J,2) = SP+sp;\n      end\n      SubSegs(k-i) = 1;\n    end\n\n    % Combine the last segment to the branch\n    I = SubSegs(1);\n    SP = spar(I,2);\n    SegC = Segs{I};\n    L = size(SegC,1);\n    if SP >= a-2 % Use the whole parent\n      Segment(a:a+L-1) = SegC;\n      a = a+L-1;\n    else % divide the parent segment into two parts\n      Segment(SP+1:SP+L) = SegC;\n      a = SP+L;\n    end\n    Branches{j,1} = Segment(1:a);\n  else\n    Branches{j,1} = Seg;\n  end\n\nend\n\n% Calculate the lengths of the candidate branches. Stop, if possible, when\n% the ratio length/linear distance is less 1.2 (branch is quite straight)\nN = ceil(0.25/dmin/1.4); % number of layers used for linear length approximation\ni = 1; % running index for while loop\nContinue = true; % continue while loop as long as \"Continue\" is true\nLengths = zeros(t,1);  % linear lengths of the branches\nwhile i <= t && Continue\n  % Approximate the length with line segments connecting nodes along\n  % the segment\n  Seg = Branches{i,1};\n  ns = size(Seg,1);\n  if ceil(ns/N) > floor(ns/N)\n    m = ceil(ns/N);\n  else\n    m = ceil(ns/N)+1;\n  end\n  Nodes = zeros(m,3);\n  for j = 1:m\n    I = (j-1)*N+1;\n    if I > ns\n      I = ns;\n    end\n    S = Seg{I};\n    if length(S) > 1\n      Nodes(j,:) = average(Ce(S,:));\n    else\n      S = Bal{S};\n      Nodes(j,:) = average(P(S,:));\n    end\n  end\n  V = Nodes(2:end,:)-Nodes(1:end-1,:); % line segments\n  Lengths(i) = sum(sqrt(sum(V.*V,2)));\n\n  % Continue as long as the length is less than 20% longer than the linear dist.\n  % and the linear distance is over 75% of the maximum\n  if Lengths(i)/LinearDist(i) < 1.20 && LinearDist(i) > 0.75*LinearDist(1)\n    Continue = false;\n    BranchTop = Segments(i);\n  end\n  i = i+1;\nend\n\n% If no suitable segment was found, try first with less strict conditions,\n% and if that does not work, then select the one with the largest linear distance\nif Continue\n  L = Lengths./LinearDist;\n  i = 1;\n  while i <= t && L(i) > 1.4 && LinearDist(i) > 0.75*LinearDist(1)\n    i = i+1;\n  end\n  if i <= t\n    BranchTop = Segments(i);\n  else\n    BranchTop = Segments(1);\n  end\nend\n\nend % End subfunction\n\n\nfunction [Segs,SPar,SChi] = modify_topology(P,Ce,Bal,Segs,SPar,SChi,dmin)\n\n% Make stem and branches as long as possible\nns = size(Segs,1);\nFal = false(2*ns,1);\nnc = ceil(ns/5);\nSubSegments = zeros(nc,1); % for searching sub-segments\nSegInd = 1; % the segment under modification\nUnMod = true(ns,1);\nUnMod(SegInd) = false;\nBranchOrder = 0;\nChildSegInd = 1; % index of the child segments under modification\nwhile any(UnMod)\n  ChildSegs = SChi{SegInd}; % child segments of the segment under modification\n  if size(ChildSegs,1) < size(ChildSegs,2)\n    ChildSegs = ChildSegs';\n    SChi{SegInd} = ChildSegs;\n  end\n\n  if ~isempty(Segs(SegInd)) && ~isempty(ChildSegs)\n\n    if SegInd > 1 && BranchOrder > 1 % 2nd-order and higher branches\n      % Search the tip of the sub-branches with biggest linear\n      % distance from the current branch's base\n      SubSegments(1) = SegInd;\n      NSubSegs = 2;\n      while ~isempty(ChildSegs)\n        n = length(ChildSegs);\n        SubSegments(NSubSegs:NSubSegs+n-1) = ChildSegs;\n        ChildSegs = vertcat(SChi{ChildSegs});\n        NSubSegs = NSubSegs+n;\n      end\n      if NSubSegs > 2\n        NSubSegs = NSubSegs-n;\n      end\n\n      % Find tip-points\n      Top = zeros(NSubSegs,3);\n      for i = 1:NSubSegs\n        Top(i,:) = Ce(Segs{SubSegments(i)}{end}(1),:);\n      end\n\n      % Define bottom of the branch\n      BotLayer = Segs{SegInd}{1};\n      Bottom = average(Ce(BotLayer,:));\n\n      % End segment is the segment whose tip has greatest distance to\n      % the bottom of the branch\n      V = mat_vec_subtraction(Top,Bottom);\n      d = sum(V.*V,2);\n      [~,I] = max(d);\n      TipSeg = SubSegments(I(1));\n\n    elseif SegInd > 1 && BranchOrder <= 1 % first order branches\n\n      TipSeg = search_branch_top(P,Ce,Bal,Segs,SPar,SChi,dmin,SegInd);\n\n    else % Stem\n\n      TipSeg = search_stem_top(P,Ce,Bal,Segs,SPar,dmin);\n\n    end\n\n    if TipSeg ~= SegInd\n      % Tip point was not in the current segment, modify segments\n      SubSegments(1) = TipSeg;\n      NSubSegs = 1;\n      while TipSeg ~= SegInd\n        TipSeg = SPar(TipSeg,1);\n        NSubSegs = NSubSegs+1;\n        SubSegments(NSubSegs) = TipSeg;\n      end\n\n      % refine branch\n      for i = 1:NSubSegs-2\n        I = SubSegments(NSubSegs-i); % segment to be combined to the first segment\n        J = SubSegments(NSubSegs-i-1); % above segment's child to be combined next\n        SP = SPar(I,2);  % layer index of the child in the parent\n        SegP = Segs{SegInd};\n        SegC = Segs{I};\n        N = size(SegP,1);\n        sp = SPar(J,2);  % layer index of the child's child in the child\n        if SP >= N-2 % Use the whole parent\n          Segs{SegInd} = [SegP; SegC(1:sp)];\n          if sp < size(SegC,1) % use only part of the child segment\n            Segs{I} = SegC(sp+1:end);\n            SPar(I,2) = N+sp;\n\n            ChildSegs = SChi{I};\n            K = SPar(ChildSegs,2) <= sp;\n            c = ChildSegs(~K);\n            SChi{I} = c;\n            SPar(c,2) = SPar(c,2)-sp;\n            ChildSegs = ChildSegs(K);\n            SChi{SegInd} = [SChi{SegInd}; ChildSegs];\n            SPar(ChildSegs,1) = SegInd;\n            SPar(ChildSegs,2) = N+SPar(ChildSegs,2);\n\n          else % use the whole child segment\n            Segs{I} = cell(0,1);\n            SPar(I,1) = 0;\n            UnMod(I) = false;\n\n            ChildSegs = SChi{I};\n            SChi{I} = zeros(0,1);\n            c = set_difference(SChi{SegInd},I,Fal);\n            SChi{SegInd} = [c; ChildSegs];\n            SPar(ChildSegs,1) = SegInd;\n            SPar(ChildSegs,2) = N+SPar(ChildSegs,2);\n\n          end\n\n          SubSegments(NSubSegs-i) = SegInd;\n        else % divide the parent segment into two parts\n          ns = ns+1;\n          Segs{ns} = SegP(SP+1:end); % the top part of the parent forms a new segment\n          SPar(ns,1) = SegInd;\n          SPar(ns,2) = SP;\n          UnMod(ns) = true;\n\n          Segs{SegInd} = [SegP(1:SP); SegC(1:sp)];\n\n          ChildSegs = SChi{SegInd};\n          if size(ChildSegs,1) < size(ChildSegs,2)\n            ChildSegs = ChildSegs';\n          end\n          K = SPar(ChildSegs,2) > SP;\n          SChi{SegInd} = ChildSegs(~K);\n          ChildSegs = ChildSegs(K);\n          SChi{ns} = ChildSegs;\n          SPar(ChildSegs,1) = ns;\n          SPar(ChildSegs,2) = SPar(ChildSegs,2)-SP;\n          SChi{SegInd} = [SChi{SegInd}; ns];\n          if sp < size(SegC,1) % use only part of the child segment\n            Segs{I} = SegC(sp+1:end);\n            SPar(I,2) = SP+sp;\n\n            ChildSegs = SChi{I};\n            K = SPar(ChildSegs,2) <= sp;\n            SChi{I} = ChildSegs(~K);\n            SPar(ChildSegs(~K),2) = SPar(ChildSegs(~K),2)-sp;\n            ChildSegs = ChildSegs(K);\n            SChi{SegInd} = [SChi{SegInd}; ChildSegs];\n            SPar(ChildSegs,1) = SegInd;\n            SPar(ChildSegs,2) = SP+SPar(ChildSegs,2);\n\n          else % use the whole child segment\n            Segs{I} = cell(0,1);\n            SPar(I,1) = 0;\n            UnMod(I) = false;\n\n            ChildSegs = SChi{I};\n            c = set_difference(SChi{SegInd},I,Fal);\n            SChi{SegInd} = [c; ChildSegs];\n            SPar(ChildSegs,1) = SegInd;\n            SPar(ChildSegs,2) = SP+SPar(ChildSegs,2);\n\n          end\n          SubSegments(NSubSegs-i) = SegInd;\n        end\n\n      end\n\n      % Combine the last segment to the branch\n      I = SubSegments(1);\n      SP = SPar(I,2);\n      SegP = Segs{SegInd};\n      SegC = Segs{I};\n      N = size(SegP,1);\n      if SP >= N-3 % Use the whole parent\n        Segs{SegInd} = [SegP; SegC];\n        Segs{I} = cell(0);\n        SPar(I,1) = 0;\n        UnMod(I) = false;\n\n        ChildSegs = SChi{I};\n        if size(ChildSegs,1) < size(ChildSegs,2)\n          ChildSegs = ChildSegs';\n        end\n        c = set_difference(SChi{SegInd},I,Fal);\n        SChi{SegInd} = [c; ChildSegs];\n        SPar(ChildSegs,1) = SegInd;\n        SPar(ChildSegs,2) = N+SPar(ChildSegs,2);\n\n      else % divide the parent segment into two parts\n        ns = ns+1;\n        Segs{ns} = SegP(SP+1:end);\n        SPar(ns,:) = [SegInd SP];\n        Segs{SegInd} = [SegP(1:SP); SegC];\n        Segs{I} = cell(0);\n        SPar(I,1) = 0;\n        UnMod(ns) = true;\n        UnMod(I) = false;\n\n        ChildSegs = SChi{SegInd};\n        K = SPar(ChildSegs,2) > SP;\n        SChi{SegInd} = [ChildSegs(~K); ns];\n        ChildSegs = ChildSegs(K);\n        SChi{ns} = ChildSegs;\n        SPar(ChildSegs,1) = ns;\n        SPar(ChildSegs,2) = SPar(ChildSegs,2)-SP;\n\n        ChildSegs = SChi{I};\n        c = set_difference(SChi{SegInd},I,Fal);\n        SChi{SegInd} = [c; ChildSegs];\n        SPar(ChildSegs,1) = SegInd;\n        SPar(ChildSegs,2) = SP+SPar(ChildSegs,2);\n\n      end\n\n    end\n    UnMod(SegInd) = false;\n  else\n    UnMod(SegInd) = false;\n  end\n\n  % Select the next branch, use increasing branching order\n  if BranchOrder > 0 && any(UnMod(SegChildren))\n    ChildSegInd = ChildSegInd+1;\n    SegInd = SegChildren(ChildSegInd);\n  elseif BranchOrder == 0\n    BranchOrder = BranchOrder+1;\n    SegChildren = SChi{1};\n    if ~isempty(SegChildren)\n      SegInd = SegChildren(1);\n    else\n      UnMod = false;\n    end\n  else\n    BranchOrder = BranchOrder+1;\n    i = 1;\n    SegChildren = SChi{1};\n    while i < BranchOrder && ~isempty(SegChildren)\n      i = i+1;\n      L = cellfun('length',SChi(SegChildren));\n      Keep = L > 0;\n      SegChildren = SegChildren(Keep);\n      SegChildren = vertcat(SChi{SegChildren});\n    end\n    I = UnMod(SegChildren);\n    if any(I)\n      SegChildren = SegChildren(I);\n      SegInd = SegChildren(1);\n      ChildSegInd = 1;\n    end\n  end\nend\n\n% Modify indexes by removing empty segments\nEmpty = true(ns,1);\nfor i = 1:ns\n  if isempty(Segs{i})\n    Empty(i) = false;\n  end\nend\nSegs = Segs(Empty);\nInd = (1:1:ns)';\nn = nnz(Empty);\nI = (1:1:n)';\nInd(Empty) = I;\nSPar = SPar(Empty,:);\nJ = SPar(:,1) > 0;\nSPar(J,1) = Ind(SPar(J,1));\nfor i = 1:ns\n  if Empty(i)\n    ChildSegs = SChi{i};\n    if ~isempty(ChildSegs)\n      ChildSegs = Ind(ChildSegs);\n      SChi{i} = ChildSegs;\n    end\n  end\nend\nSChi = SChi(Empty);\nns = n;\n\n% Modify SChi\nfor i = 1:ns\n  ChildSegs = SChi{i};\n  if size(ChildSegs,2) > size(ChildSegs,1) && size(ChildSegs,1) > 0\n    SChi{i} = ChildSegs';\n  elseif size(ChildSegs,1) == 0 || size(ChildSegs,2) == 0\n    SChi{i} = zeros(0,1);\n  end\n  Seg = Segs{i};\n  n = max(size(Seg));\n  for j = 1:n\n    ChildSegs = Seg{j};\n    if size(ChildSegs,2) > size(ChildSegs,1) && size(ChildSegs,1) > 0\n      Seg{j} = ChildSegs';\n    elseif size(ChildSegs,1) == 0 || size(ChildSegs,2) == 0\n      Seg{j} = zeros(0,1);\n    end\n  end\n  Segs{i} = Seg;\nend\nend % End of function\n\n\nfunction [Segs,SPar,SChi] = remove_small(Ce,Segs,SPar,SChi)\n\n% Removes small child segments\n\n% computes and estimate for stem radius at the base\nSegment = Segs{1};  % current or parent segment\nns = size(Segment,1);  % layers in the parent\nif ns > 10\n  EndL = 10;  % ending layer index in parent\nelse\n  EndL = ns;\nend\nEnd = average(Ce(Segment{EndL},:)); % Center of end layer\nStart = average(Ce(Segment{1},:));  % Center of starting layer\nV = End-Start;  % Vector between starting and ending centers\nV = V/norm(V);  % normalize\nSets = vertcat(Segment{1:EndL});\nMaxRad = max(distances_to_line(Ce(Sets,:),V,Start));\n\nNseg = size(Segs,1);\nFal = false(Nseg,1);\nKeep = true(Nseg,1);\nSets = zeros(2000,1);\nfor i = 1:Nseg\n  if Keep(i)\n    ChildSegs = SChi{i};  % child segments\n    if ~isempty(ChildSegs) % child segments exists\n      n = length(ChildSegs); % number of children\n      Segment = Segs{i};  % current or parent segment\n      ns = size(Segment,1);  % layers in the parent\n      for j = 1:n % check each child separately\n        nl = SPar(ChildSegs(j),2);  % the index of the layer in the parent the child begins\n        if nl > 10\n          StartL = nl-10; % starting layer index in parent\n        else\n          StartL = 1;\n        end\n        if ns-nl > 10\n          EndL = nl+10;  % end layer index in parent\n        else\n          EndL = ns;\n        end\n        End = average(Ce(Segment{EndL},:));\n        Start = average(Ce(Segment{StartL},:));\n        V = End-Start;  % Vector between starting and ending centers\n        V = V/norm(V);  % normalize\n\n        % cover sets of the child\n        ChildSets = Segs{ChildSegs(j)};\n        NL = size(ChildSets,1);\n        a = 1;\n        for k = 1:NL\n          S = ChildSets{k};\n          Sets(a:a+length(S)-1) = S;\n          a = a+length(S);\n        end\n        ChildSets = Sets(1:a-1);\n\n        % maximum distance in child\n        distChild = max(distances_to_line(Ce(ChildSets,:),V,Start));\n\n        if distChild < MaxRad+0.06\n\n          % Select the cover sets of the parent between centers\n          NL = EndL-StartL+1;\n          a = 1;\n          for k = 1:NL\n            S = Segment{StartL+(k-1)};\n            Sets(a:a+length(S)-1) = S;\n            a = a+length(S);\n          end\n          ParentSets = Sets(1:a-1);\n\n          % maximum distance in parent\n          distPar = max(distances_to_line(Ce(ParentSets,:),V,Start));\n          if (distChild-distPar < 0.02) || (distChild/distPar < 1.2 && distChild-distPar < 0.06)\n            ChildChildSegs = SChi{ChildSegs(j)};\n            nc = length(ChildChildSegs);\n            if nc == 0\n              % Remove, no child segments\n              Keep(ChildSegs(j)) = false;\n              Segs{ChildSegs(j)} = zeros(0,1);\n              SPar(ChildSegs(j),:) = zeros(1,2);\n              SChi{i} = set_difference(ChildSegs,ChildSegs(j),Fal);\n            else\n              L = SChi(ChildChildSegs);\n              L = vertcat(L{:}); % child child segments\n              if isempty(L)\n                J = false(nc,1);\n                for k = 1:nc\n                  segment = Segs{ChildChildSegs(k)};\n                  if isempty(segment)\n                    J(k) = true;\n                  else\n                    segment1 = [vertcat(segment{:}); ParentSets];\n                    distSeg = max(distances_to_line(Ce(segment1,:),V,Start));\n                    if (distSeg-distPar < 0.02) || (distSeg/distPar < 1.2 && distSeg-distPar < 0.06)\n                      J(k) = true;\n                    end\n                  end\n                end\n                if all(J)\n                  % Remove\n                  ChildChildSegs1 = [ChildChildSegs; ChildSegs(j)];\n                  nc = length(ChildChildSegs1);\n                  Segs(ChildChildSegs1) = cell(nc,1);\n                  Keep(ChildChildSegs1) = false;\n                  SPar(ChildChildSegs1,:) = zeros(nc,2);\n                  d = set_difference(ChildSegs,ChildSegs(j),Fal);\n                  SChi{i} = d;\n                  SChi(ChildChildSegs1) = cell(nc,1);\n                end\n              end\n            end\n          end\n        end\n      end\n    end\n    if i == 1\n      MaxRad = MaxRad/2;\n    end\n  end\nend\n% Modify segments and their indexing\nSegs = Segs(Keep);\nn = nnz(Keep);\nInd = (1:1:Nseg)';\nJ = (1:1:n)';\nInd(Keep) = J;\nInd(~Keep) = 0;\nSPar = SPar(Keep,:);\nJ = SPar(:,1) > 0;\nSPar(J,1) = Ind(SPar(J,1));\n% Modify SChi\nfor i = 1:Nseg\n  if Keep(i)\n    ChildSegs = SChi{i};\n    if ~isempty(ChildSegs)\n      ChildSegs = nonzeros(Ind(ChildSegs));\n      if size(ChildSegs,1) < size(ChildSegs,2)\n        SChi{i} = ChildSegs';\n      else\n        SChi{i} = ChildSegs;\n      end\n    else\n      SChi{i} = zeros(0,1);\n    end\n  end\nend\nSChi = SChi(Keep);\nend % End of function\n\n\nfunction [SegP,Base] = modify_parent(P,Bal,Ce,SegP,SegC,nl,PatchDiam,base)\n\n% Expands the base of the branch backwards into its parent segment and\n% then removes the expansion from the parent segment.\n\nBase = SegC{1};\nif ~isempty(Base)\n\n  % Define the directions of the segments\n  DirChi = segment_direction(Ce,SegC,1);\n  DirPar = segment_direction(Ce,SegP,nl);\n\n  if length(Base) > 1\n    BaseCent = average(Ce(Base,:));\n    db = distances_to_line(Ce(Base,:), DirChi', BaseCent); % distances of the sets in the base to the axis of the branch\n    DiamBase = 2*max(db);  % diameter of the base\n  elseif length(Bal{Base}) > 1\n    BaseCent = average(P(Bal{Base},:));\n    db = distances_to_line(P(Bal{Base},:), DirChi', BaseCent);\n    DiamBase = 2*max(db);\n  else\n    BaseCent = Ce(Base,:);\n    DiamBase = 0;\n  end\n\n  % Determine the number of cover set layers \"n\" to be checked\n  Angle = abs(DirChi'*DirPar);  % abs of cosine of the angle between component and segment directions\n  Nlayer = max([3,ceil(Angle*2*DiamBase/PatchDiam)]);\n  if Nlayer > nl  % can go only to the bottom of the segment\n    Nlayer = nl;\n  end\n\n  % Check the layers\n  layer = 0;\n  base{1} = Base;\n  while layer < Nlayer\n    Sets = SegP{nl-layer};\n    Seg = average(Ce(Sets,:)); % mean of the cover sets' centers\n\n    VBase = mat_vec_subtraction(Ce(Sets,:),BaseCent);  % vectors from base's center to sets in the segment\n    h = VBase*DirChi;\n    B = repmat(DirChi',length(Sets),1);\n    B = [h.*B(:,1) h.*B(:,2) h.*B(:,3)];\n    V = VBase-B;\n    distSets = sqrt(sum(V.*V,2)); % distances of the sets in the segment to the axis of the branch\n\n    VSeg = mat_vec_subtraction(Ce(Sets,:),Seg);  % vectors from segments's center to sets in the segment\n    lenBase = sqrt(sum(VBase.*VBase,2)); % lengths of VBase\n    lenSeg = sqrt(sum(VSeg.*VSeg,2)); % lengths of VSeg\n    if Angle < 0.9\n      K = lenBase < 1.1/(1-0.5*Angle^2)*lenSeg;     % sets closer to the base's center than segment's center\n      J = distSets < 1.25*DiamBase;   % sets close enough to the axis of the branch\n      I = K&J;\n    else % branch almost parallel to parent\n      I = distSets < 1.25*DiamBase; % only the distance to the branch axis counts\n    end\n\n    if all(I) || ~any(I) % stop the process if all the segment's or no segment's sets\n      layer = Nlayer;\n    else\n      SegP{nl-layer} = Sets(not(I));\n      base{layer+2} = Sets(I);\n      layer = layer+1;\n    end\n  end\n  Base = vertcat(base{1:Nlayer+1});\nend\n\nend % End of function\n\n\nfunction D = segment_direction(Ce,Seg,nl)\n\n% Defines the direction of the segment\n\n% Define bottom and top layers\nif nl-3 > 0\n  bot = nl-3;\nelse\n  bot = 1;\nend\nj = 1;\nwhile j < 3 && isempty(Seg{bot})\n  bot = bot+1;\n  j = j+1;\nend\nif nl+2 <= size(Seg,1)\n  top = nl+2;\nelse\n  top = size(Seg,1);\nend\nj = 1;\nwhile j < 3 && isempty(Seg{top})\n  top = top-1;\n  j = j+1;\nend\n\n% Direction\nif top > bot\n  Bot = average(Ce(Seg{bot},:));\n  Top = average(Ce(Seg{top},:));\n  V = Top-Bot;\n  D = V'/norm(V);\nelse\n  D = zeros(3,1);\nend\n\n\nend % End of function\n"
  },
  {
    "path": "src/main_steps/cover_sets.m",
    "content": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction cover = cover_sets(P,inputs,RelSize)\n\n% ---------------------------------------------------------------------\n% COVER_SETS.M          Creates cover sets (surface patches) and their\n%                       neighbor-relation for a point cloud\n%\n% Version 2.0.1\n% Latest update     2 May 2022\n%\n% Copyright (C) 2013-2022 Pasi Raumonen\n% ---------------------------------------------------------------------\n\n% Covers the point cloud with small sets, which are along the surface,\n% such that each point belongs at most one cover set; i.e. the cover is\n% a partition of the point cloud.\n%\n% The cover is generated such that at first the point cloud is covered\n% with balls with radius \"BallRad\". This first cover is such that\n% 1) the minimum distance between the centers is \"PatchDiam\", and\n% 2) the maximum distance from any point to nearest center is also \"PatchDiam\".\n% Then the first cover of BallRad-balls is used to define a second cover:\n% each BallRad-ball \"A\" defines corresponding cover set \"B\" in the second cover\n% such that \"B\" contains those points of \"A\" that are nearer to the center of\n% \"A\" than any other center of BallRad-balls. The BallRad-balls also define\n% the neighbors for the second cover: Let CA and CB denote cover sets in\n% the second cover, and BA and BB their BallRad-balls. Then CB is\n% a neighbor of CA, and vice versa, if BA and CB intersect or\n% BB and CA intersect.\n%\n% Inputs:\n% P         Point cloud\n% inputs    Input stucture, the following fields are needed:\n%   PatchDiam1   Minimum distance between centers of cover sets; i.e. the\n%                   minimum diameter of cover set in uniform covers. Does\n%                   not need nor use the third optional input \"RelSize\".\n%   PatchDiam2Min   Minimum diameter of cover sets for variable-size\n%                     covers. Needed if \"RelSize\" is given as input.\n%   PatchDiam2Max   Maximum diameter of cover sets for variable-size\n%                     covers. Needed if \"RelSize\" is given as input.\n% \tBallRad1    Radius of the balls used to generate the uniform cover. \n%                   These balls are also used to determine the neighbors\n%   BallRad2    Maximum radius of the balls used to generate the \n%                   varibale-size cover. \n%   nmin1, nmin2    Minimum number of points in a BallRad1- and\n%                       BallRad2-balls\n% RelSize   Relative cover set size for each point\n%\n% Outputs:\n% cover     Structure array containing the followin fields:\n%   ball        Cover sets, (n_sets x 1)-cell\n%   center      Center points of the cover sets, (n_sets x 1)-vector\n%   neighbor    Neighboring cover sets of each cover set, (n_sets x 1)-cell\n\n% Changes from version 2.0.0 to 2.0.1, 2 May 2022:\n% 1) Added comments and changed some variable names\n% 2) Enforced that input parameters are type double\n\nif ~isa(P,'double')\n  P = double(P);\nend\n\n%% Large balls and centers\nnp = size(P,1);\nBall = cell(np,1); % Large balls for generation of the cover sets and their neighbors\nCen = zeros(np,1,'uint32'); % the center points of the balls/cover sets\nNotExa = true(np,1); % the points not yet examined\nDist = 1e8*ones(np,1);  % distance of point to the closest center\nBoP = zeros(np,1,'uint32');  % the balls/cover sets the points belong\nnb = 0;             % number of sets generated\nif nargin == 2\n  %% Same size cover sets everywhere\n  BallRad = double(inputs.BallRad1);\n  PatchDiamMax = double(inputs.PatchDiam1);\n  nmin = double(inputs.nmin1);\n  % Partition the point cloud into cubes for quick neighbor search\n  [partition,CC] = cubical_partition(P,BallRad);\n\n  % Generate the balls\n  Radius = BallRad^2;\n  MaxDist = PatchDiamMax^2;\n  % random permutation of points, produces different covers for the same inputs:\n  RandPerm = randperm(np); \n  for i = 1:np\n    if NotExa(RandPerm(i))\n      Q = RandPerm(i); % the center/seed point of the current cover set\n      % Select the points in the cubical neighborhood of the seed:\n      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);\n      points = vertcat(points{:});\n      % Compute distances of the points to the seed:\n      V = [P(points,1)-P(Q,1) P(points,2)-P(Q,2) P(points,3)-P(Q,3)];\n      dist = sum(V.*V,2);\n      % Select the points inside the ball:\n      Inside = dist < Radius;\n      if nnz(Inside) >= nmin\n        ball = points(Inside); % the points forming the ball\n        d = dist(Inside); % the distances of the ball's points\n        core = (d < MaxDist); % the core points of the cover set\n        NotExa(ball(core)) = false; % mark points as examined\n        % define new ball:\n        nb = nb+1; \n        Ball{nb} = ball;\n        Cen(nb) = Q;\n        % Select which points belong to this ball, i.e. are closer this\n        % seed than previously tested seeds:\n        D = Dist(ball); % the previous distances\n        closer = d < D; % which points are closer to this seed\n        ball = ball(closer); % define the ball\n        % update the ball and distance information of the points\n        Dist(ball) = d(closer); \n        BoP(ball) = nb; \n      end\n    end\n  end\nelse\n  %% Use relative sizes (the size varies)\n  % Partition the point cloud into cubes\n  BallRad = double(inputs.BallRad2);\n  PatchDiamMin = double(inputs.PatchDiam2Min);\n  PatchDiamMax = double(inputs.PatchDiam2Max);\n  nmin = double(inputs.nmin2);\n  MRS = PatchDiamMin/PatchDiamMax;\n  % minimum radius\n  r = double(1.5*(double(min(RelSize))/256*(1-MRS)+MRS)*BallRad+1e-5); \n  NE = 1+ceil(BallRad/r);\n  if NE > 4\n    r = PatchDiamMax/4;\n    NE = 1+ceil(BallRad/r);\n  end\n  [Partition,CC,~,Cubes] = cubical_partition(P,r,NE);\n\n  I = RelSize == 0; % Don't use points with no size determined\n  NotExa(I) = false;\n\n  % Define random permutation of points (results in different covers for \n  % same input) so that first small sets are generated\n  RandPerm = zeros(np,1,'uint32');\n  I = RelSize <= 32;\n  ind = uint32(1:1:np)';\n  I = ind(I);\n  t1 = length(I);\n  RandPerm(1:1:t1) = I(randperm(t1));\n  I = RelSize <= 128 & RelSize > 32;\n  I = ind(I);\n  t2 = length(I);\n  RandPerm(t1+1:1:t1+t2) = I(randperm(t2));\n  t2 = t2+t1;\n  I = RelSize > 128;\n  I = ind(I);\n  t3 = length(I);\n  RandPerm(t2+1:1:t2+t3) = I(randperm(t3));\n  clearvars ind I\n\n  Point = zeros(round(np/1000),1,'uint32');\n  e = BallRad-PatchDiamMax;\n  for i = 1:np\n    if NotExa(RandPerm(i))\n      Q = RandPerm(i); % the center/seed point of the current cover set\n      % Compute the set size and the cubical neighborhood of the seed point:\n      rs = double(RelSize(Q))/256*(1-MRS)+MRS; % relative radius\n      MaxDist = PatchDiamMax*rs; % diameter of the cover set\n      Radius = MaxDist+sqrt(rs)*e; % radius of the ball including the cover set\n      N = ceil(Radius/r); % = number of cells needed to include the ball\n      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);\n      I = cubes > 0;\n      cubes = cubes(I); % Cubes forming the neighborhood\n      Par = Partition(cubes); % cell-array of the points in the neighborhood\n      % vertical catenation of the points from the cell-array\n      S = cellfun('length',Par);\n      stop = cumsum(S);\n      start = [0; stop]+1;\n      for k = 1:length(stop)\n        Point(start(k):stop(k)) = Par{k};\n      end\n      points = Point(1:stop(k));\n      % Compute the distance of the \"points\" to the seed:\n      V = [P(points,1)-P(Q,1) P(points,2)-P(Q,2) P(points,3)-P(Q,3)];\n      dist = sum(V.*V,2);\n      % Select the points inside the ball:\n      Inside = dist < Radius^2;\n      if nnz(Inside) >= nmin\n        ball = points(Inside); % the points forming the ball\n        d = dist(Inside); % the distances of the ball's points\n        core = (d < MaxDist^2); % the core points of the cover set\n        NotExa(ball(core)) = false; % mark points as examined\n        % define new ball:\n        nb = nb+1; \n        Ball{nb} = ball;\n        Cen(nb) = Q;\n        % Select which points belong to this ball, i.e. are closer this\n        % seed than previously tested seeds:\n        D = Dist(ball); % the previous distances\n        closer = d < D; % which points are closer to this seed\n        ball = ball(closer); % define the ball\n        % update the ball and distance information of the points\n        Dist(ball) = d(closer); \n        BoP(ball) = nb; \n      end\n    end\n  end\nend\nBall = Ball(1:nb,:);\nCen = Cen(1:nb);\nclearvars RandPerm NotExa Dist\n\n%% Cover sets\n% Number of points in each ball and index of each point in its ball\nNum = zeros(nb,1,'uint32');\nInd = zeros(np,1,'uint32');\nfor i = 1:np\n  if BoP(i) > 0\n    Num(BoP(i)) = Num(BoP(i))+1;\n    Ind(i) = Num(BoP(i));\n  end\nend\n\n% Initialization of the \"PointsInSets\"\nPointsInSets = cell(nb,1);\nfor i = 1:nb\n  PointsInSets{i} = zeros(Num(i),1,'uint32');\nend\n\n% Define the \"PointsInSets\"\nfor i = 1:np\n  if BoP(i) > 0\n    PointsInSets{BoP(i),1}(Ind(i)) = i;\n  end\nend\n\n%% Neighbors\n% Define neighbors. Sets A and B are neighbors if the large ball of A\n% contains points of B. Notice that this is not a symmetric relation.\nNei = cell(nb,1);\nFal = false(nb,1);\nfor i = 1:nb\n  B = Ball{i};        % the points in the big ball of cover set \"i\"\n  I = (BoP(B) ~= i);\n  N = B(I);           % the points of B not in the cover set \"i\"\n  N = BoP(N);\n\n  % select the unique elements of N:\n  n = length(N);\n  if n > 2\n    Include = true(n,1);\n    for j = 1:n\n      if ~Fal(N(j))\n        Fal(N(j)) = true;\n      else\n        Include(j) = false;\n      end\n    end\n    Fal(N) = false;\n    N = N(Include);\n  elseif n == 2\n    if N(1) == N(2)\n      N = N(1);\n    end\n  end\n\n  Nei{i} = uint32(N);\nend\n\n% Make the relation symmetric by adding, if needed, A as B's neighbor\n% in the case B is A's neighbor\nfor i = 1:nb\n  N = Nei{i};\n  for j = 1:length(N)\n    K = (Nei{N(j)} == i);\n    if ~any(K)\n      Nei{N(j)} = uint32([Nei{N(j)}; i]);\n    end\n  end\nend\n\n% Define output\ncover.ball = PointsInSets;\ncover.center = Cen;\ncover.neighbor = Nei;\n\n%% Display statistics\n%disp(['    ',num2str(nb),' cover sets, points not covered: ',num2str(np-nnz(BoP))])"
  },
  {
    "path": "src/main_steps/cylinders.m",
    "content": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction cylinder = cylinders(P,cover,segment,inputs)\n\n% ---------------------------------------------------------------------\n% CYLINDERS.M       Fits cylinders to the branch-segments of the point cloud\n%\n% Version 3.0.0\n% Latest update     1 Now 2018\n%\n% Copyright (C) 2013-2018 Pasi Raumonen\n% ---------------------------------------------------------------------\n%\n% Reconstructs the surface and volume of branches of input tree with\n% cylinders. Subdivides each segment to smaller regions to which cylinders\n% are fitted in least squares sense. Returns the cylinder information and\n% in addition the child-relation of the cylinders plus the cylinders in\n% each segment.\n% ---------------------------------------------------------------------\n% Inputs:\n% P         Point cloud, matrix\n% cover     Cover sets\n% segment   Segments\n% input     Input parameters of the reconstruction:\n%   MinCylRad   Minimum cylinder radius, used in the taper corrections\n%   ParentCor   Radius correction based on radius of the parent: radii in\n%                 a branch are usually smaller than the radius of the parent\n%                 cylinder in the parent branch\n%   TaperCor    Parabola taper correction of radii inside branches.\n%   GrowthVolCor  If 1, use growth volume correction\n%   GrowthVolFac  Growth volume correction factor\n%\n% Outputs:\n% cylinder  Structure array containing the following cylinder info:\n%   radius        Radii of the cylinders, vector\n%   length        Lengths of the cylinders, vector\n%   axis          Axes of the cylinders, matrix\n%   start         Starting points of the cylinders, matrix\n%   parent        Parents of the cylinders, vector\n%   extension     Extensions of the cylinders, vector\n%   branch        Branch of the cylinder\n%   BranchOrder   Branching order of the cylinder\n%   PositionInBranch    Position of the cylinder inside the branch\n%   mad           Mean absolute distances of points from the cylinder\n%                           surface, vector\n%   SurfCov       Surface coverage measure, vector\n%   added         Added cylinders, logical vector\n%   UnModRadius   Unmodified radii\n% ---------------------------------------------------------------------\n\n% Changes from version 3.0.0 to 3.1.0, 6 Oct 2021:\n% 1) Added the growth volume correction option (\"growth_volume_correction\")\n%    back, which was removed from the previous version by a mistake. The\n%    \"growth_volume_correction\" function was also corrected.\n% 2) Added the fields \"branch\", \"BranchOrder\", \"PositionInBranch\" to the\n%    output structure \"cylinder\"\n% 3) Removed the fields \"CylsInSegment\" and \"ChildCyls\" from the output\n%    structure \"cylinder\"\n\n% Changes from version 2.0.0 to 3.0.0, 13 Aug 2020:\n% Many comprehensive and small changes:\n% 1) \"regions\" and \"cylinder_fitting\" are combined into \"cylinder_fitting\"\n%   and the process is more adaptive as it now fits at least 3 (up to 10)\n%   cylinders of different lengths for each region.\n% 2) \"lcyl\" and \"FilRad\" parameters are not used anymore\n% 3) Surface coverage (\"SurfCov\") and mean absolute distance (\"mad\") are\n%   added to the cylinder structure as fields.\n% 4) Surface coverage filtering is used in the definition of the regions\n%   and removing outliers\n% 5) \"adjustments\" has many changes, particularly in the taper corrections\n%   where the parabola-taper curve is fitted to all the data with surface\n%   coverage as a weight. Adjustment of radii based on the parabola is\n%   closer the parabola the smaller the surface coverage. For the stem the\n%   taper correction is the same as for the branches. The minimum and\n%   maximum radii corrections are also modified.\n% 6) Syntax has changed, particularly for the \"cyl\"-structure\n\n% Changes from version 2.1.0 to 2.1.1, 26 Nov 2019:\n% 1) Increased the minimum number \"n\" of estimated cylinders for\n%    initialization of vectors at the beginning of the code. This is done\n%    to make sure that trees without branches will not cause errors.\n\n% Changes from version 2.0.0 to 2.1.0, 3 Oct 2019:\n% 1) Bug fix: UnmodRadius is now defined as it should, as the radius after\n%    least squares fitting but without parent, taper or growth vol. corrections\n% 2) Bug fix: Correction in \"least_squares_cylinder.m\", calculates the\n%    starting point of the cylinder now correctly.\n% 3) Bug fix: Correct errors related to combining data when a fitted\n%    cylinder is replaced with two shorter ones, in \"cylinder_fitting\"\n% 4) Removed some unnecessary command lines for computing radius estimates\n%    in \"regions\"\n\n%% Initialization of variables\nSegs = segment.segments;\nSPar = segment.ParentSegment;\nSChi = segment.ChildSegment;\nNumOfSeg = max(size(Segs));   % number of segments\nn = max(2000,min(40*NumOfSeg,2e5));\nc = 1;  % number of cylinders determined\nCChi = cell(n,1); % Children of the cylinders\nCiS = cell(NumOfSeg,1); % Cylinders in the segment\ncylinder.radius = zeros(n,1,'single');\ncylinder.length = zeros(n,1,'single');\ncylinder.start = zeros(n,3,'single');\ncylinder.axis = zeros(n,3,'single');\ncylinder.parent = zeros(n,1,'uint32');\ncylinder.extension = zeros(n,1,'uint32');\ncylinder.added = false(n,1);\ncylinder.UnmodRadius = zeros(n,1,'single');\ncylinder.branch = zeros(n,1,'uint16');\ncylinder.SurfCov = zeros(n,1,'single');\ncylinder.mad = zeros(n,1,'single');\n\n%% Determine suitable order of segments (from trunk to the \"youngest\" child)\nbases = (1:1:NumOfSeg)';\nbases = bases(SPar(:,1) == 0);\nnb = length(bases);\nSegmentIndex = zeros(NumOfSeg,1);\nnc = 0;\nfor i = 1:nb\n  nc = nc+1;\n  SegmentIndex(nc) = bases(i);\n  S = vertcat(SChi{bases(i)});\n  while ~isempty(S)\n    n = length(S);\n    SegmentIndex(nc+1:nc+n) = S;\n    nc = nc+n;\n    S = vertcat(SChi{S});\n  end\nend\n\n%% Fit cylinders individually for each segment\nfor k = 1:NumOfSeg\n  si = SegmentIndex(k);\n  if si > 0\n    %% Some initialization about the segment\n    Seg = Segs{si};      % the current segment under analysis\n    nl = max(size(Seg));  % number of cover set layers in the segment\n    [Sets,IndSets] = verticalcat(Seg); % the cover sets in the segment\n\n    ns = length(Sets);   % number of cover sets in the current segment\n    Points = vertcat(cover.ball{Sets}); % the points in the segments\n    np = length(Points);         % number of points in the segment\n\n    % Determine indexes of points for faster definition of regions\n    BallSize = cellfun('length',cover.ball(Sets));\n    IndPoints = ones(nl,2); % indexes for points in each layer of the segment\n    for j = 1:nl\n      IndPoints(j,2) = sum(BallSize(IndSets(j,1):IndSets(j,2)));\n    end\n    IndPoints(:,2) = cumsum(IndPoints(:,2));\n    IndPoints(2:end,1) = IndPoints(2:end,1)+IndPoints(1:end-1,2);\n    Base = Seg{1};          % the base of the segment\n    nb = IndPoints(1,2); % number of points in the base\n\n    % Reconstruct only large enough segments\n    if nl > 1 && np > nb && ns > 2 && np > 20 && ~isempty(Base)\n\n      %% Cylinder fitting\n      [cyl,Reg] = cylinder_fitting(P,Points,IndPoints,nl,si);\n      nc = numel(cyl.radius);\n\n      %% Search possible parent cylinder\n      if nc > 0 && si > 1\n        [PC,cyl,added] = parent_cylinder(SPar,SChi,CiS,cylinder,cyl,si);\n        nc = numel(cyl.radius);\n      elseif si == 1\n        PC = zeros(0,1);\n        added = false;\n      else\n        added = false;\n      end\n      cyl.radius0 = cyl.radius;\n\n      %% Modify cylinders\n      if nc > 0\n        % Define parent cylinder:\n        parcyl.radius = cylinder.radius(PC);\n        parcyl.length = cylinder.length(PC);\n        parcyl.start = cylinder.start(PC,:);\n        parcyl.axis = cylinder.axis(PC,:);\n        % Modify the cylinders\n        cyl = adjustments(cyl,parcyl,inputs,Reg);\n      end\n\n      %% Save the cylinders\n      % if at least one acceptable cylinder, then save them\n      Accept = nc > 0 & min(cyl.radius(1:nc)) > 0;\n      if Accept\n        % If the parent cylinder exists, set the parent-child relations\n        if ~isempty(PC)\n          cylinder.parent(c) = PC;\n          if cylinder.extension(PC) == c\n            I = cylinder.branch(PC);\n            cylinder.branch(c:c+nc-1) = I;\n            CiS{I} = [CiS{I}; linspace(c,c+nc-1,nc)'];\n          else\n            CChi{PC} = [CChi{PC}; c];\n            cylinder.branch(c:c+nc-1) = si;\n            CiS{si} = linspace(c,c+nc-1,nc)';\n          end\n        else\n          cylinder.branch(c:c+nc-1) = si;\n          CiS{si} = linspace(c,c+nc-1,nc)';\n        end\n\n        cylinder.radius(c:c+nc-1) = cyl.radius(1:nc);\n        cylinder.length(c:c+nc-1) = cyl.length(1:nc);\n        cylinder.axis(c:c+nc-1,:) = cyl.axis(1:nc,:);\n        cylinder.start(c:c+nc-1,:) = cyl.start(1:nc,:);\n        cylinder.parent(c+1:c+nc-1) = linspace(c,c+nc-2,nc-1);\n        cylinder.extension(c:c+nc-2) = linspace(c+1,c+nc-1,nc-1);\n        cylinder.UnmodRadius(c:c+nc-1) = cyl.radius0(1:nc);\n        cylinder.SurfCov(c:c+nc-1) = cyl.SurfCov(1:nc);\n        cylinder.mad(c:c+nc-1) = cyl.mad(1:nc);\n        if added\n          cylinder.added(c) = true;\n          cylinder.added(c) = true;\n        end\n        c = c+nc; % number of cylinders so far (plus one)\n\n      end\n    end\n  end\nend\nc = c-1; % number of cylinders\n\n\n%% Define outputs\nnames = fieldnames(cylinder);\nn = max(size(names));\nfor k = 1:n\n  cylinder.(names{k}) = single(cylinder.(names{k})(1:c,:));\nend\nif c <= 2^16\n  cylinder.parent = uint16(cylinder.parent);\n  cylinder.extension = uint16(cylinder.extension);\nend\nnb = max(cylinder.branch);\nif nb <= 2^8\n  cylinder.branch = uint8(cylinder.branch);\nelseif nb <= 2^16\n  cylinder.branch = uint16(cylinder.branch);\nend\ncylinder.added = logical(cylinder.added);\n\n% Define the branching order:\nBOrd = zeros(c,1);\nfor i = 1:c\n  if cylinder.parent(i) > 0\n    p = cylinder.parent(i);\n    if cylinder.extension(p) == i\n      BOrd(i) = BOrd(p);\n    else\n      BOrd(i) = BOrd(p)+1;\n    end\n  end\nend\ncylinder.BranchOrder = uint8(BOrd);\n% Define the cylinder position inside the branch\nPiB = ones(c,1);\nfor i = 1:NumOfSeg\n  C = CiS{i};\n  if ~isempty(C)\n    n = length(C);\n    PiB(C) = (1:1:n)';\n  end\nend\nif max(PiB) <= 2^8\n  cylinder.PositionInBranch = uint8(PiB);\nelse\n  cylinder.PositionInBranch = uint16(PiB);\nend\n\n% Growth volume correction\nif inputs.GrowthVolCor && c > 0\n  cylinder = growth_volume_correction(cylinder,inputs);\nend\n\nend % End of main function\n\n\nfunction [cyl,Reg] = cylinder_fitting(P,Points,Ind,nl,si)\n\nif nl > 6\n  i0 = 1;     i = 4; % indexes of the first and last layers of the region\n  t = 0;\n  Reg = cell(nl,1);\n  cyls = cell(11,1);\n  regs = cell(11,1);\n  data = zeros(11,4);\n  while i0 < nl-2\n    %% Fit at least three cylinders of different lengths\n    bot = Points(Ind(i0,1):Ind(i0+1,2));\n    Bot = average(P(bot,:)); % Bottom axis point of the region\n    again = true;\n    j = 0;\n    while i+j <= nl && j <= 10 && (j <= 2 || again)\n      %% Select points and estimate axis\n      RegC = Points(Ind(i0,1):Ind(i+j,2)); % candidate region\n      % Top axis point of the region:\n      top = Points(Ind(i+j-1,1):Ind(i+j,2));\n      Top = average(P(top,:));\n      % Axis of the cylinder:\n      Axis = Top-Bot;\n      c0.axis = Axis/norm(Axis);\n      % Compute the height along the axis:\n      h = (P(RegC,:)-Bot)*c0.axis';\n      minh = min(h);\n      % Correct Bot to correspond to the real bottom\n      if j == 0\n        Bot = Bot+minh*c0.axis;\n        c0.start = Bot;\n        h = (P(RegC,:)-Bot)*c0.axis';\n        minh = min(h);\n      end\n      if i+j >= nl\n        ht = (Top-c0.start)*c0.axis';\n        Top = Top+(max(h)-ht)*c0.axis;\n      end\n      % Compute the height of the Top:\n      ht = (Top-c0.start)*c0.axis';\n      Sec = h <= ht & h >= minh; % only points below the Top\n      c0.length = ht-minh; % length of the region/cylinder\n      % The region for the cylinder fitting:\n      reg = RegC(Sec);\n      Q0 = P(reg,:);\n\n      %% Filter points and estimate radius\n      if size(Q0,1) > 20\n        [Keep,c0] = surface_coverage_filtering(Q0,c0,0.02,20);\n        reg = reg(Keep);\n        Q0 = Q0(Keep,:);\n      else\n        c0.radius = 0.01;\n        c0.SurfCov = 0.05;\n        c0.mad = 0.01;\n        c0.conv = 1;\n        c0.rel = 1;\n      end\n\n      %% Fit cylinder\n      if size(Q0,1) > 9\n        if i >= nl && t == 0\n          c = least_squares_cylinder(Q0,c0);\n        elseif i >= nl && t > 0\n          h = (Q0-CylTop)*c0.axis';\n          I = h >= 0;\n          Q = Q0(I,:); % the section\n          reg = reg(I);\n          n2 = size(Q,1);     n1 = nnz(~I);\n          if n2 > 9 && n1 > 5\n            Q0 = [Q0(~I,:); Q]; % the point cloud for cylinder fitting\n            W = [1/3*ones(n2,1); 2/3*ones(n1,1)]; % the weights\n            c = least_squares_cylinder(Q0,c0,W,Q);\n          else\n            c = least_squares_cylinder(Q0,c0);\n          end\n        elseif t == 0\n          top = Points(Ind(i+j-3,1):Ind(i+j-2,2));\n          Top = average(P(top,:)); % Top axis point of the region\n          ht = (Top-Bot)*c0.axis';\n          h = (Q0-Bot)*c0.axis';\n          I = h <= ht;\n          Q = Q0(I,:); % the section\n          reg = reg(I);\n          n2 = size(Q,1);     n3 = nnz(~I);\n          if n2 > 9 && n3 > 5\n            Q0 = [Q; Q0(~I,:)]; % the point cloud for cylinder fitting\n            W = [2/3*ones(n2,1); 1/3*ones(n3,1)]; % the weights\n            c = least_squares_cylinder(Q0,c0,W,Q);\n          else\n            c = least_squares_cylinder(Q0,c0);\n          end\n        else\n          top = Points(Ind(i+j-3,1):Ind(i+j-2,2));\n          Top = average(P(top,:)); % Top axis point of the region\n          ht = (Top-CylTop)*c0.axis';\n          h = (Q0-CylTop)*c0.axis';\n          I1 = h < 0; % the bottom\n          I2 = h >= 0 & h <= ht; % the section\n          I3 = h > ht; % the top\n          Q = Q0(I2,:);\n          reg = reg(I2);\n          n1 = nnz(I1);   n2 = size(Q,1);     n3 = nnz(I3);\n          if n2 > 9\n            Q0 = [Q0(I1,:); Q; Q0(I3,:)];\n            W = [1/4*ones(n1,1); 2/4*ones(n2,1); 1/4*ones(n3,1)];\n            c = least_squares_cylinder(Q0,c0,W,Q);\n          else\n            c = c0;\n            c.rel = 0;\n          end\n        end\n\n        if c.conv == 0\n          c = c0;\n          c.rel = 0;\n        end\n        if c.SurfCov < 0.2\n          c.rel = 0;\n        end\n      else\n        c = c0;\n        c.rel = 0;\n      end\n\n      % Collect fit data\n      data(j+1,:) = [c.rel c.conv c.SurfCov c.length/c.radius];\n      cyls{j+1} = c;\n      regs{j+1} = reg;\n      j = j+1;\n      % If reasonable cylinder fitted, then stop fitting new ones\n      % (but always fit at least three cylinders)\n      RL = c.length/c.radius; % relative length of the cylinder\n      if again && c.rel && c.conv && RL > 2\n        if si == 1 && c.SurfCov > 0.7\n          again = false;\n        elseif si > 1 && c.SurfCov > 0.5\n          again = false;\n        end\n      end\n    end\n\n    %% Select the best of the fitted cylinders\n    % based on maximum surface coverage\n    OKfit = data(1:j,1) & data(1:j,2) & data(1:j,4) > 1.5;\n\n    J = (1:1:j)';\n    t = t+1;\n    if any(OKfit)\n      J = J(OKfit);\n    end\n    [~,I] = max(data(J,3)-0.01*data(J,4));\n    J = J(I);\n    c = cyls{J};\n\n    %% Update the indexes of the layers for the next region:\n    CylTop = c.start+c.length*c.axis;\n    i0 = i0+1;\n    bot = Points(Ind(i0,1):Ind(i0+1,2));\n    Bot = average(P(bot,:)); % Bottom axis point of the region\n    h = (Bot-CylTop)*c.axis';\n    i00 = i0;\n    while i0+1 < nl && i0 < i00+5 && h < -c.radius/3\n      i0 = i0+1;\n      bot = Points(Ind(i0,1):Ind(i0+1,2));\n      Bot = average(P(bot,:)); % Bottom axis point of the region\n      h = (Bot-CylTop)*c.axis';\n    end\n    i = i0+5;\n    i = min(i,nl);\n\n    %% If the next section is very short part of the end of the branch\n    % then simply increase the length of the current cylinder\n    if nl-i0+2 < 4\n      reg = Points(Ind(nl-5,1):Ind(nl,2));\n      Q0 = P(reg,:);\n      ht = (c.start+c.length*c.axis)*c.axis';\n      h = Q0*c.axis';\n      maxh = max(h);\n      if maxh > ht\n        c.length = c.length+(maxh-ht);\n      end\n      i0 = nl;\n    end\n    Reg{t} = regs{J};\n\n    if t == 1\n      cyl = c;\n      names = fieldnames(cyl);\n      n = max(size(names));\n    else\n      for k = 1:n\n        cyl.(names{k}) = [cyl.(names{k}); c.(names{k})];\n      end\n    end\n\n    %% compute cylinder top for the definition of the next section\n    CylTop = c.start+c.length*c.axis;\n  end\n  Reg = Reg(1:t);\n\nelse\n  %% Define a region for small segments\n  Q0 = P(Points,:);\n  if size(Q0,1) > 10\n    %% Define the direction\n    bot = Points(Ind(1,1):Ind(1,2));\n    Bot = average(P(bot,:));\n    top = Points(Ind(nl,1):Ind(nl,2));\n    Top = average(P(top,:));\n    Axis = Top-Bot;\n    c0.axis = Axis/norm(Axis);\n    h = Q0*c0.axis';\n    c0.length = max(h)-min(h);\n    hpoint = Bot*c0.axis';\n    c0.start = Bot-(hpoint-min(h))*c0.axis;\n\n    %% Define other outputs\n    [Keep,c0] = surface_coverage_filtering(Q0,c0,0.02,20);\n    Reg = cell(1,1);\n    Reg{1} = Points(Keep);\n    Q0 = Q0(Keep,:);\n    cyl = least_squares_cylinder(Q0,c0);\n    if ~cyl.conv || ~cyl.rel\n      cyl = c0;\n    end\n    t = 1;\n  else\n    cyl = 0;\n    t = 0;\n  end\nend\n% Define Reg as coordinates\nfor i = 1:t\n  Reg{i} = P(Reg{i},:);\nend\nReg = Reg(1:t);\n% End of function\nend\n\n\nfunction [PC,cyl,added] = parent_cylinder(SPar,SChi,CiS,cylinder,cyl,si)\n\n% Finds the parent cylinder from the possible parent segment.\n% Does this by checking if the axis of the cylinder, if continued, will\n% cross the nearby cylinders in the parent segment.\n% Adjust the cylinder so that it starts from the surface of its parent.\n\nrad = cyl.radius;\nlen = cyl.length;\nsta = cyl.start;\naxe = cyl.axis;\n\n% PC     Parent cylinder\nnc = numel(rad);\nadded = false;\nif SPar(si) > 0 % parent segment exists, find the parent cylinder\n  s = SPar(si);\n  PC = CiS{s}; % the cylinders in the parent segment\n  % select the closest cylinders for closer examination\n  if length(PC) > 1\n    D = mat_vec_subtraction(-cylinder.start(PC,:),-sta(1,:));\n    d = sum(D.*D,2);\n    [~,I] = sort(d);\n    if length(PC) > 3\n      I = I(1:4);\n    end\n    pc = PC(I);\n    ParentFound = false;\n  elseif length(PC) == 1\n    ParentFound = true;\n  else\n    PC = zeros(0,1);\n    ParentFound = true;\n  end\n\n  %% Check possible crossing points\n  if ~ParentFound\n    pc0 = pc;\n    n = length(pc);\n    % Calculate the possible crossing points of the cylinder axis, when\n    % extended, on the surfaces of the parent candidate cylinders\n    x = zeros(n,2);  % how much the starting point has to move to cross\n    h = zeros(n,2);  % the crossing point height in the parent\n    Axe = cylinder.axis(pc,:);\n    Sta = cylinder.start(pc,:);\n    for j = 1:n\n      % Crossing points solved from a quadratic equation\n      A = axe(1,:)-(axe(1,:)*Axe(j,:)')*Axe(j,:);\n      B = sta(1,:)-Sta(j,:)-(sta(1,:)*Axe(j,:)')*Axe(j,:)...\n        +(Sta(j,:)*Axe(j,:)')*Axe(j,:);\n      e = A*A';\n      f = 2*A*B';\n      g = B*B'-cylinder.radius(pc(j))^2;\n      di = sqrt(f^2 - 4*e*g);  % the discriminant\n      s1 = (-f + di)/(2*e);\n      % how much the starting point must be moved to cross:\n      s2 = (-f - di)/(2*e);\n      if isreal(s1) %% cylinders can cross\n        % the heights of the crossing points\n        x(j,:) = [s1 s2];\n        h(j,1) = sta(1,:)*Axe(j,:)'+x(j,1)*axe(1,:)*Axe(j,:)'-...\n          Sta(j,:)*Axe(j,:)';\n        h(j,2) = sta(1,:)*Axe(j,:)'+x(j,2)*axe(1,:)*Axe(j,:)'-...\n          Sta(j,:)*Axe(j,:)';\n      end\n    end\n\n    %% Extend to crossing point in the (extended) parent\n    I = x(:,1) ~= 0; % Select only candidates with crossing points\n    pc = pc0(I);    x = x(I,:);     h = h(I,:);\n    j = 1;      n = nnz(I);\n    X = zeros(n,3); %\n    Len = cylinder.length(pc);\n    while j <= n && ~ParentFound\n      if x(j,1) > 0 && x(j,2) < 0\n        % sp inside the parent and crosses its surface\n        if h(j,1) >= 0 && h(j,1) <= Len(j) && len(1)-x(j,1) > 0\n          PC = pc(j);\n          sta(1,:) = sta(1,:)+x(j,1)*axe(1,:);\n          len(1) = len(1)-x(j,1);\n          ParentFound = true;\n        elseif len(1)-x(j,1) > 0\n          if h(j,1) < 0\n            X(j,:) = [x(j,1) abs(h(j,1)) 0];\n          else\n            X(j,:) = [x(j,1) h(j,1)-Len(j) 0];\n          end\n        else\n          X(j,:) = [x(j,1) h(j,1) 1];\n        end\n      elseif x(j,1) < 0 && x(j,2) > 0 && len(1)-x(j,2) > 0\n        % sp inside the parent and crosses its surface\n        if h(j,2) >= 0 && h(j,2) <= Len(j) && len(1)-x(j,2) > 0\n          PC = pc(j);\n          sta(1,:) = sta(1,:)+x(j,2)*axe(1,:);\n          len(1) = len(1)-x(j,2);\n          ParentFound = true;\n        elseif len(1)-x(j,2) > 0\n          if h(j,2) < 0\n            X(j,:) = [x(j,2) abs(h(j,2)) 0];\n          else\n            X(j,:) = [x(j,2) h(j,2)-Len(j) 0];\n          end\n        else\n          X(j,:) = [x(j,2) h(j,2) 1];\n        end\n      elseif x(j,1) < 0 && x(j,2) < 0 && x(j,2) < x(j,1) && len(1)-x(j,1) > 0\n        % sp outside the parent and crosses its surface when extended\n        % backwards\n        if h(j,1) >= 0 && h(j,1) <= Len(j) && len(1)-x(j,1) > 0\n          PC = pc(j);\n          sta(1,:) = sta(1,:)+x(j,1)*axe(1,:);\n          len(1) = len(1)-x(j,1);\n          ParentFound = true;\n        elseif len(1)-x(j,1) > 0\n          if h(j,1) < 0\n            X(j,:) = [x(j,1) abs(h(j,1)) 0];\n          else\n            X(j,:) = [x(j,1) h(j,1)-Len(j) 0];\n          end\n        else\n          X(j,:) = [x(j,1) h(j,1) 1];\n        end\n      elseif x(j,1) < 0 && x(j,2) < 0 && x(j,2) > x(j,1) && len(1)-x(j,2) > 0\n        % sp outside the parent and crosses its surface when extended\n        % backwards\n        if h(j,2) >= 0 && h(j,2) <= Len(j) && len(1)-x(j,2) > 0\n          PC = pc(j);\n          sta(1,:) = sta(1,:)+x(j,2)*axe(1,:);\n          len(1) = len(1)-x(j,2);\n          ParentFound = true;\n        elseif len(1)-x(j,2) > 0\n          if h(j,2) < 0\n            X(j,:) = [x(j,2) abs(h(j,2)) 0];\n          else\n            X(j,:) = [x(j,2) h(j,2)-Len(j) 0];\n          end\n        else\n          X(j,:) = [x(j,2) h(j,2) 1];\n        end\n      elseif x(j,1) > 0 && x(j,2) > 0 && x(j,2) < x(j,1) && len(1)-x(j,1) > 0\n        % sp outside the parent but crosses its surface when extended forward\n        if h(j,1) >= 0 && h(j,1) <= Len(j) && len(1)-x(j,1) > 0\n          PC = pc(j);\n          sta(1,:) = sta(1,:)+x(j,1)*axe(1,:);\n          len(1) = len(1)-x(j,1);\n          ParentFound = true;\n        elseif len(1)-x(j,1) > 0\n          if h(j,1) < 0\n            X(j,:) = [x(j,1) abs(h(j,1)) 0];\n          else\n            X(j,:) = [x(j,1) h(j,1)-Len(j) 0];\n          end\n        else\n          X(j,:) = [x(j,1) h(j,1) 1];\n        end\n      elseif x(j,1) > 0 && x(j,2) > 0 && x(j,2) > x(j,1) && len(1)-x(j,2) > 0\n        % sp outside the parent and crosses its surface when extended forward\n        if h(j,2) >= 0 && h(j,2) <= Len(j) && len(1)-x(j,2) > 0\n          PC = pc(j);\n          sta(1,:) = sta(1,:)+x(j,2)*axe(1,:);\n          len(1) = len(1)-x(j,2);\n          ParentFound = true;\n        elseif len(1)-x(j,2) > 0\n          if h(j,1) < 0\n            X(j,:) = [x(j,2) abs(h(j,2)) 0];\n          else\n            X(j,:) = [x(j,2) h(j,2)-Len(j) 0];\n          end\n        else\n          X(j,:) = [x(j,2) h(j,2) 1];\n        end\n      end\n      j = j+1;\n    end\n\n    if ~ParentFound && n > 0\n      [H,I] = min(X(:,2));\n      X = X(I,:);\n      if X(3) == 0 && H < 0.1*Len(I)\n        PC = pc(I);\n        sta(1,:) = sta(1,:)+X(1)*axe(1,:);\n        len(1) = len(1)-X(1);\n        ParentFound = true;\n      else\n        PC = pc(I);\n\n        if nc > 1 && X(1) <= rad(1) && abs(X(2)) <= 1.25*cylinder.length(PC)\n          % Remove the first cylinder and adjust the second\n          S = sta(1,:)+X(1)*axe(1,:);\n          V = sta(2,:)+len(2)*axe(2,:)-S;\n          len(2) = norm(V);         len = len(2:nc);\n          axe(2,:) = V/norm(V);      axe = axe(2:nc,:);\n          sta(2,:) = S;            sta = sta(2:nc,:);\n          rad = rad(2:nc);\n          cyl.mad = cyl.mad(2:nc);\n          cyl.SurfCov = cyl.SurfCov(2:nc);\n          nc = nc-1;\n          ParentFound = true;\n        elseif nc > 1\n          % Remove the first cylinder\n          sta = sta(2:nc,:);    len = len(2:nc);\n          axe = axe(2:nc,:);        rad = rad(2:nc);\n          cyl.mad = cyl.mad(2:nc);\n          cyl.SurfCov = cyl.SurfCov(2:nc);\n          nc = nc-1;\n        elseif isempty(SChi{si})\n          % Remove the cylinder\n          nc = 0;\n          PC = zeros(0,1);\n          ParentFound = true;\n          rad = zeros(0,1);\n        elseif X(1) <= rad(1) && abs(X(2)) <= 1.5*cylinder.length(PC)\n          % Adjust the cylinder\n          sta(1,:) = sta(1,:)+X(1)*axe(1,:);\n          len(1) = abs(X(1));\n          ParentFound = true;\n        end\n      end\n    end\n\n    if ~ParentFound\n      % The parent is the cylinder in the parent segment whose axis\n      % line is the closest to the axis line of the first cylinder\n      % Or the parent cylinder is the one whose base, when connected\n      % to the first cylinder is the most parallel.\n      % Add new cylinder\n      pc = pc0;\n\n      [Dist,~,DistOnLines] = distances_between_lines(...\n        sta(1,:),axe(1,:),cylinder.start(pc,:),cylinder.axis(pc,:));\n\n      I = DistOnLines >= 0;\n      J = DistOnLines <= cylinder.length(pc);\n      I = I&J;\n      if ~any(I)\n        I = DistOnLines >= -0.2*cylinder.length(pc);\n        J = DistOnLines <= 1.2*cylinder.length(pc);\n        I = I&J;\n      end\n      if any(I)\n        pc = pc(I);     Dist = Dist(I);     DistOnLines = DistOnLines(I);\n        [~,I] = min(Dist);\n        DistOnLines = DistOnLines(I);       PC = pc(I);\n        Q = cylinder.start(PC,:)+DistOnLines*cylinder.axis(PC,:);\n        V = sta(1,:)-Q;      L = norm(V);        V = V/L;\n        a = acos(V*cylinder.axis(PC,:)');\n        h = sin(a)*L;\n        S = Q+cylinder.radius(PC)/h*L*V;\n        L = (h-cylinder.radius(PC))/h*L;\n        if L > 0.01 && L/len(1) > 0.2\n          nc = nc+1;\n          sta = [S; sta];   rad = [rad(1); rad];\n          axe = [V; axe];       len = [L; len];\n          cyl.mad = [cyl.mad(1); cyl.mad];\n          cyl.SurfCov = [cyl.SurfCov(1); cyl.SurfCov];\n          cyl.rel = [cyl.rel(1); cyl.rel];\n          cyl.conv = [cyl.conv(1); cyl.conv];\n          added = true;\n        end\n      else\n        V = -mat_vec_subtraction(cylinder.start(pc,:),sta(1,:));\n        L0 = sqrt(sum(V.*V,2));\n        V = [V(:,1)./L0 V(:,2)./L0 V(:,3)./L0];\n        A = V*axe(1,:)';\n        [A,I] = max(A);\n        L1 = L0(I);       PC = pc(I);     V = V(I,:);\n        a = acos(V*cylinder.axis(PC,:)');\n        h = sin(a)*L1;\n        S = cylinder.start(PC,:)+cylinder.radius(PC)/h*L1*V;\n        L = (h-cylinder.radius(PC))/h*L1;\n        if L > 0.01 && L/len(1) > 0.2\n          nc = nc+1;\n          sta = [S; sta];   rad = [rad(1); rad];\n          axe = [V; axe];   len = [L; len];\n          cyl.mad = [cyl.mad(1); cyl.mad];\n          cyl.SurfCov = [cyl.SurfCov(1); cyl.SurfCov];\n          cyl.rel = [cyl.rel(1); cyl.rel];\n          cyl.conv = [cyl.conv(1); cyl.conv];\n          added = true;\n        end\n      end\n    end\n  end\nelse\n  % no parent segment exists\n  PC = zeros(0,1);\nend\n\n% define the output\ncyl.radius = rad(1:nc);     cyl.length = len(1:nc,:);\ncyl.start = sta(1:nc,:);    cyl.axis = axe(1:nc,:);\ncyl.mad = cyl.mad(1:nc);    cyl.SurfCov = cyl.SurfCov(1:nc);\ncyl.conv = cyl.conv(1:nc);  cyl.rel = cyl.rel(1:nc);\n% End of function\nend\n\n\nfunction cyl = adjustments(cyl,parcyl,inputs,Regs)\n\nnc = size(cyl.radius,1);\nMod = false(nc,1); % cylinders modified\nSC = cyl.SurfCov;\n\n%% Determine the maximum and the minimum radius\n% The maximum based on parent branch\nif ~isempty(parcyl.radius)\n  MaxR = 0.95*parcyl.radius;\n  MaxR = max(MaxR,inputs.MinCylRad);\nelse\n  % use the maximum from the bottom cylinders\n  a = min(3,nc);\n  MaxR = 1.25*max(cyl.radius(1:a));\nend\nMinR = min(cyl.radius(SC > 0.7));\nif ~isempty(MinR) && min(cyl.radius) < MinR/2\n  MinR = min(cyl.radius(SC > 0.4));\nelseif isempty(MinR)\n  MinR = min(cyl.radius(SC > 0.4));\n  if isempty(MinR)\n    MinR = inputs.MinCylRad;\n  end\nend\n\n%% Check maximum and minimum radii\nI = cyl.radius < MinR;\ncyl.radius(I) = MinR;\nMod(I) = true;\nif inputs.ParentCor || nc <= 3\n  I = (cyl.radius > MaxR & SC < 0.7) | (cyl.radius > 1.2*MaxR);\n  cyl.radius(I) = MaxR;\n  Mod(I) = true;\n  % For short branches modify with more restrictions\n  if nc <= 3\n    I = (cyl.radius > 0.75*MaxR & SC < 0.7);\n    if any(I)\n      r = max(SC(I)/0.7.*cyl.radius(I),MinR);\n      cyl.radius(I) = r;\n      Mod(I) = true;\n    end\n  end\nend\n\n%% Use taper correction to modify radius of too small and large cylinders\n% Adjust radii if a small SurfCov and high SurfCov in the previous and\n% following cylinders\nfor i = 2:nc-1\n  if SC(i) < 0.7 && SC(i-1) >= 0.7 && SC(i+1) >= 0.7\n    cyl.radius(i) = 0.5*(cyl.radius(i-1)+cyl.radius(i+1));\n    Mod(i) = true;\n  end\nend\n\n%% Use taper correction to modify radius of too small and large cylinders\nif inputs.TaperCor\n  if max(cyl.radius) < 0.001\n\n    %% Adjust radii of thin branches to be linearly decreasing\n    if nc > 2\n      r = sort(cyl.radius);\n      r = r(2:end-1);\n      a = 2*mean(r);\n      if a > max(r)\n        a = min(0.01,max(r));\n      end\n      b = min(0.5*min(cyl.radius),0.001);\n      cyl.radius = linspace(a,b,nc)';\n    elseif nc > 1\n      r = max(cyl.radius);\n      cyl.radius = [r; 0.5*r];\n    end\n    Mod = true(nc,1);\n\n  elseif nc > 4\n    %% Parabola adjustment of maximum and minimum\n    % Define parabola taper shape as maximum (and minimum) radii for\n    % the cylinders with low surface coverage\n    branchlen = sum(cyl.length(1:nc)); % branch length\n    L = cyl.length/2+[0; cumsum(cyl.length(1:nc-1))];\n    Taper = [L; branchlen];\n    Taper(:,2) = [1.05*cyl.radius; MinR];\n    sc = [SC; 1];\n\n    % Least square fitting of parabola to \"Taper\":\n    A = [sum(sc.*Taper(:,1).^4) sum(sc.*Taper(:,1).^2); ...\n      sum(sc.*Taper(:,1).^2) sum(sc)];\n    y = [sum(sc.*Taper(:,2).*Taper(:,1).^2); sum(sc.*Taper(:,2))];\n    warning off\n    x = A\\y;\n    warning on\n    x(1) = min(x(1),-0.0001); % tapering from the base to the tip\n    Ru = x(1)*L.^2+x(2); % upper bound parabola\n    Ru( Ru < MinR ) = MinR;\n    if max(Ru) > MaxR\n      a = max(Ru);\n      Ru = MaxR/a*Ru;\n    end\n    Rl = 0.75*Ru; % lower bound parabola\n    Rl( Rl < MinR ) = MinR;\n\n    % Modify radii based on parabola:\n    % change values larger than the parabola-values when SC < 70%:\n    I = cyl.radius > Ru & SC < 0.7;\n    cyl.radius(I) = Ru(I)+(cyl.radius(I)-Ru(I)).*SC(I)/0.7;\n    Mod(I) = true;\n    % change values larger than the parabola-values when SC > 70% and\n    % radius is over 33% larger than the parabola-value:\n    I = cyl.radius > 1.333*Ru & SC >= 0.7;\n    cyl.radius(I) = Ru(I)+(cyl.radius(I)-Ru(I)).*SC(I);\n    Mod(I) = true;\n    % change values smaller than the downscaled parabola-values:\n    I = (cyl.radius < Rl & SC < 0.7) | (cyl.radius < 0.5*Rl);\n    cyl.radius(I) = Rl(I);\n    Mod(I) = true;\n\n  else\n    %% Adjust radii of short branches to be linearly decreasing\n    R = cyl.radius;\n    if nnz(SC >= 0.7) > 1\n      a = max(R(SC >= 0.7));\n      b = min(R(SC >= 0.7));\n    elseif nnz(SC >= 0.7) == 1\n      a = max(R(SC >= 0.7));\n      b = min(R);\n    else\n      a = sum(R.*SC/sum(SC));\n      b = min(R);\n    end\n    Ru = linspace(a,b,nc)';\n    I = SC < 0.7 & ~Mod;\n    cyl.radius(I) = Ru(I)+(R(I)-Ru(I)).*SC(I)/0.7;\n    Mod(I) = true;\n\n  end\nend\n\n%% Modify starting points by optimising them for given radius and axis\nnr = size(Regs,1);\nfor i = 1:nc\n  if Mod(i)\n    if nr == nc\n      Reg = Regs{i};\n    elseif i > 1\n      Reg = Regs{i-1};\n    end\n    if abs(cyl.radius(i)-cyl.radius0(i)) > 0.005 && ...\n        (nr == nc || (nr < nc && i > 1))\n      P = Reg-cyl.start(i,:);\n      [U,V] = orthonormal_vectors(cyl.axis(i,:));\n      P = P*[U V];\n      cir = least_squares_circle_centre(P,[0 0],cyl.radius(i));\n      if cir.conv && cir.rel\n        cyl.start(i,:) = cyl.start(i,:)+cir.point(1)*U'+cir.point(2)*V';\n        cyl.mad(i,1) = cir.mad;\n        [~,V,h] = distances_to_line(Reg,cyl.axis(i,:),cyl.start(i,:));\n        if min(h) < -0.001\n          cyl.length(i) = max(h)-min(h);\n          cyl.start(i,:) = cyl.start(i,:)+min(h)*cyl.axis(i,:);\n          [~,V,h] = distances_to_line(Reg,cyl.axis(i,:),cyl.start(i,:));\n        end\n        a = max(0.02,0.2*cyl.radius(i));\n        nl = ceil(cyl.length(i)/a);\n        nl = max(nl,4);\n        ns = ceil(2*pi*cyl.radius(i)/a);\n        ns = max(ns,10);\n        ns = min(ns,36);\n        cyl.SurfCov(i,1) = surface_coverage2(...\n          cyl.axis(i,:),cyl.length(i),V,h,nl,ns);\n      end\n    end\n  end\nend\n\n%% Continuous branches\n% Make cylinders properly \"continuous\" by moving the starting points\n% Move the starting point to the plane defined by parent cylinder's top\nif nc > 1\n  for j = 2:nc\n    U = cyl.start(j,:)-cyl.start(j-1,:)-cyl.length(j-1)*cyl.axis(j-1,:);\n    if (norm(U) > 0.0001)\n      % First define vector V and W which are orthogonal to the\n      % cylinder axis N\n      N = cyl.axis(j,:)';\n      if norm(N) > 0\n        [V,W] = orthonormal_vectors(N);\n        % Now define the new starting point\n        x = [N V W]\\U';\n        cyl.start(j,:) = cyl.start(j,:)-x(1)*N';\n        if x(1) > 0\n          cyl.length(j) = cyl.length(j)+x(1);\n        elseif cyl.length(j)+x(1) > 0\n          cyl.length(j) = cyl.length(j)+x(1);\n        end\n      end\n    end\n  end\nend\n\n%% Connect far away first cylinder to the parent\nif ~isempty(parcyl.radius)\n  [d,V,h,B] = distances_to_line(cyl.start(1,:),parcyl.axis,parcyl.start);\n  d = d-parcyl.radius;\n  if d > 0.001\n    taper = cyl.start(1,:);\n    E = taper+cyl.length(1)*cyl.axis(1,:);\n    V = parcyl.radius*V/norm(V);\n    if h >= 0 && h <= parcyl.length\n      cyl.start(1,:) = parcyl.start+B+V;\n    elseif h < 0\n      cyl.start(1,:) = parcyl.start+V;\n    else\n      cyl.start(1,:) = parcyl.start+parcyl.length*parcyl.axis+V;\n    end\n    cyl.axis(1,:) = E-cyl.start(1,:);\n    cyl.length(1) = norm(cyl.axis(1,:));\n    cyl.axis(1,:) = cyl.axis(1,:)/cyl.length(1);\n  end\nend\n\n% End of function\nend\n"
  },
  {
    "path": "src/main_steps/filtering.m",
    "content": "% 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 terms of the GNU General Public License as published by\r\n% the Free Software Foundation, either version 3 of the License, or\r\n% (at your option) any later version.\r\n% \r\n% TREEQSM is distributed in the hope that it will be useful,\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n% GNU General Public License for more details.\r\n% \r\n% You should have received a copy of the GNU General Public License\r\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\r\n\r\nfunction Pass = filtering(P,inputs)\r\n\r\n% ---------------------------------------------------------------------\r\n% FILTERING.M       Filters noise from point clouds.\r\n%\r\n% Version 3.0.0\r\n% Latest update     3 May 2022\r\n%\r\n% Copyright (C) 2013-2022 Pasi Raumonen\r\n% ---------------------------------------------------------------------\r\n\r\n% Filters the point cloud as follows:\r\n% \r\n% 1) the possible NaNs are removed.\r\n% \r\n% 2) (optional, done if filter.k > 0) Statistical kth-nearest neighbor \r\n% distance outlier filtering based on user defined \"k\" (filter.k) and\r\n% multiplier for standard deviation (filter.nsigma): Determines the \r\n% kth-nearest neighbor distance for all points and then removes the points \r\n% whose distances are over average_distance + nsigma*std. Computes the \r\n% statistics for each meter layer in vertical direction so that the\r\n% average distances and SDs can change as the point density decreases.\r\n% \r\n% 3) (optional, done if filter.radius > 0) Statistical point density \r\n% filtering based on user defined ball radius (filter.radius) and multiplier \r\n% for standard deviation (filter.nsigma): Balls of radius \"filter.radius\"\r\n% centered at each point are defined for all points and the number of\r\n% points included (\"point density\") are computed and then removes the points \r\n% whose density is smaller than average_density - nsigma*std. Computes the \r\n% statistics for each meter layer in vertical direction so that the\r\n% average densities and SDs can change as the point density decreases.\r\n% \r\n% 4) (optional, done if filter.ncomp > 0) Small component filtering based\r\n% on user defined cover (filter.PatchDiam1, filter.BallRad1) and threshold\r\n% (filter.ncomp): Covers the point cloud and determines the connected\r\n% components of the cover and removes the points from the small components\r\n% that have less than filter.ncomp cover sets.\r\n%\r\n% 5) (optional, done if filter.EdgeLength > 0) cubical downsampling of the \r\n% point cloud based on user defined cube size (filter.EdgeLength): \r\n% selects randomly one point from each cube\r\n%\r\n% Does the filtering in the above order and thus always applies the next \r\n% fitering to the point cloud already filtered by the previous methods. \r\n% Statistical kth-nearest neighbor distance outlier filtering and the \r\n% statistical point density filtering are meant to be exlusive to each\r\n% other.\r\n%\r\n% Inputs:\r\n% P         Point cloud\r\n% inputs    Inputs structure with the following subfields:\r\n%   filter.EdgeLength   Edge length of the cubes in the cubical downsampling\r\n%   filter.k            k of knn method\r\n%   filter.radius       Radius of the balls in the density filtering\r\n%   filter.nsigma       Multiplier for standard deviation, determines how\r\n%                         far from the mean the threshold is in terms of SD.\r\n%                         Used in both the knn and the density filtering\r\n%   filter.ncomp        Threshold number of components in the small\r\n%                         component filtering\r\n%   filter.PatchDiam1   Defines the patch/cover set size for the component \r\n%                         filtering\r\n%   filter.BallRad1     Defines the neighbors for the component filtering\r\n%   filter.plot         If true, plots the filtered point cloud\r\n% Outputs:\r\n% Pass      Logical vector indicating points passing the filtering\r\n% ---------------------------------------------------------------------\r\n\r\n% Changes from version 2.0.0 to 3.0.0, 3 May 2022:\r\n% Major changes and additions.\r\n% 1) Added two new filtering options: statistical kth-nearest neighbor \r\n%    distance outlier filtering and cubical downsampling.\r\n% 2) Changed the old point density filtering, which was based on given\r\n%    threshold, into statistical point density filtering, where the\r\n%    threshold is based on user defined statistical measure\r\n% 3) All the input parameters are given by \"inputs\"-structure that can be\r\n%    defined by \"create_input\" script   \r\n% 4) Streamlined the coding and what is displayed\r\n\r\n%% Initial data processing\r\n% Only double precision data\r\nif ~isa(P,'double')\r\n  P = double(P);\r\nend\r\n% Only x,y,z-data\r\nif size(P,2) > 3\r\n  P = P(:,1:3);\r\nend\r\nnp = size(P,1);\r\nnp0 = np;\r\nind = (1:1:np)';\r\nPass = false(np,1);\r\n\r\ndisp('----------------------')\r\ndisp(' Filtering...')\r\ndisp(['  Points before filtering:  ',num2str(np)])\r\n\r\n%% Remove possible NaNs\r\nF = ~any(isnan(P),2);\r\nif nnz(F) < np\r\n  disp(['  Points with NaN removed:  ',num2str(np-nnz(Pass))])\r\n  ind = ind(F);\r\nend \r\n\r\n%% Statistical kth-nearest neighbor distance outlier filtering\r\nif inputs.filter.k > 0\r\n  % Compute the knn distances\r\n  Q = P(ind,:);\r\n  np = size(Q,1);\r\n  [~, kNNdist] = knnsearch(Q,Q,'dist','euclidean','k',inputs.filter.k);\r\n  kNNdist = kNNdist(:,end);\r\n\r\n  % Change the threshold kNNdistance according the average and standard \r\n  % deviation for every vertical layer of 1 meter in height\r\n  hmin = min(Q(:,3));\r\n  hmax = max(Q(:,3));\r\n  H = ceil(hmax-hmin);\r\n  F = false(np,1);\r\n  ind = (1:1:np)';\r\n  for i = 1:H\r\n    I = Q(:,3) < hmin+i & Q(:,3) >= hmin+i-1;\r\n    points = ind(I);\r\n    d = kNNdist(points);\r\n    J = d < mean(d)+inputs.filter.nsigma*std(d);\r\n    points = points(J);\r\n    F(points) = 1;\r\n  end\r\n  ind = ind(F);\r\n  disp(['  Points removed as statistical outliers:  ',num2str(np-length(ind))])\r\nend\r\n\r\n%% Statistical point density filtering\r\nif inputs.filter.radius > 0\r\n  Q = P(ind,:);\r\n  np = size(Q,1);\r\n\r\n  % Partition the point cloud into cubes\r\n  [partition,CC] = cubical_partition(Q,inputs.filter.radius);\r\n\r\n  % Determine the number of points inside a ball for each point\r\n  NumOfPoints = zeros(np,1);\r\n  r1 = inputs.filter.radius^2;\r\n  for i = 1:np\r\n    if NumOfPoints(i) == 0\r\n      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);\r\n      points = vertcat(points{:,:});\r\n      cube = Q(points,:);\r\n      p = partition{CC(i,1),CC(i,2),CC(i,3)};\r\n      for j = 1:length(p)\r\n        dist = (Q(p(j),1)-cube(:,1)).^2+(Q(p(j),2)-cube(:,2)).^2+(Q(p(j),3)-cube(:,3)).^2;\r\n        J = dist < r1;\r\n        NumOfPoints(p(j)) = nnz(J);\r\n      end\r\n    end\r\n  end\r\n\r\n  % Change the threshold point density according the average and standard \r\n  % deviation for every vertical layer of 1 meter in height\r\n  hmin = min(Q(:,3));\r\n  hmax = max(Q(:,3));\r\n  H = ceil(hmax-hmin);\r\n  F = false(np,1);\r\n  ind = (1:1:np)';\r\n  for i = 1:H\r\n    I = Q(:,3) < hmin+i & Q(:,3) >= hmin+i-1;\r\n    points = ind(I);\r\n    N = NumOfPoints(points);\r\n    J = N > mean(N)-inputs.filter.nsigma*std(N);\r\n    points = points(J);\r\n    F(points) = 1;\r\n  end\r\n  ind = ind(F);\r\n  disp(['  Points removed as statistical outliers:  ',num2str(np-length(ind))])\r\nend\r\n\r\n%% Small component filtering\r\nif inputs.filter.ncomp > 0\r\n  % Cover the point cloud with patches\r\n  input.BallRad1 = inputs.filter.BallRad1;\r\n  input.PatchDiam1 = inputs.filter.PatchDiam1;\r\n  input.nmin1 = 0;\r\n  Q = P(ind,:);\r\n  np = size(Q,1);\r\n  cover = cover_sets(Q,input);\r\n\r\n  % Determine the separate components\r\n  Components = connected_components(cover.neighbor,0,inputs.filter.ncomp);\r\n\r\n  % The filtering\r\n  B = vertcat(Components{:}); % patches in the components\r\n  points = vertcat(cover.ball{B}); % points in the components\r\n  F = false(np,1);\r\n  F(points) = true;\r\n  ind = ind(F);\r\n  disp(['  Points with small components removed:  ',num2str(np-length(ind))])\r\nend\r\n\r\n%% Cubical downsampling\r\nif inputs.filter.EdgeLength > 0\r\n  Q = P(ind,:);\r\n  np = size(Q,1);\r\n  F = cubical_downsampling(Q,inputs.filter.EdgeLength);\r\n  ind = ind(F);\r\n  disp(['  Points removed with downsampling:  ',num2str(np-length(ind))])\r\nend\r\n\r\n%% Define the output and display summary results\r\nPass(ind) = true;\r\nnp = nnz(Pass);\r\ndisp(['  Points removed in total: ',num2str(np0-np)])\r\ndisp(['  Points removed in total (%): ',num2str(round((1-np/np0)*1000)/10)])\r\ndisp(['  Points left: ',num2str(np)])\r\n\r\n%% Plot the filtered and unfiltered point clouds\r\nif inputs.filter.plot\r\n  plot_comparison(P(Pass,:),P(~Pass,:),1,1,1)\r\n  plot_point_cloud(P(Pass,:),2,1)\r\nend\r\n"
  },
  {
    "path": "src/main_steps/point_model_distance.m",
    "content": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction pmdistance = point_model_distance(P,cylinder)\n\n% ---------------------------------------------------------------------\n% POINT_MODEL_DISTANCE.M    Computes the distances of the points to the \n%                               cylinder model\n%\n% Version 2.1.1\n% Latest update     8 Oct 2021\n%\n% Copyright (C) 2015-2021 Pasi Raumonen\n% ---------------------------------------------------------------------\n\n% Changes from version 2.1.0 to 2.1.1, 8 Oct 2021:  \n% 1) Changed the determinationa NE, the number of empty edge layers, so \n%     that is now limited in size, before it is given as input for \n%     cubical_partition function.\n\n% Changes from version 2.0.0 to 2.1.0, 26 Nov 2019:  \n% 1) Bug fix: Corrected the computation of the output at the end of the\n%    code so that trees without branches are computed correctly.\n\n% Cylinder data\nRad = cylinder.radius;\nLen = cylinder.length;\nSta = cylinder.start;\nAxe = cylinder.axis;\nBOrd = cylinder.BranchOrder;\n\n% Select randomly 25 % or max one million points for the distance comput.\nnp0 = size(P,1);\na = min(0.25*np0,1000000);\nI = logical(round(0.5/(1-a/np0)*rand(np0,1)));\nP = P(I,:);\n\n% Partition the points into cubes \nL = 2*median(Len);\nNE = max(3,min(10,ceil(max(Len)/L)))+3;\n[Partition,~,Info] = cubical_partition(P,L,NE);\nMin = Info(1:3);\nEL = Info(7);\nNE = Info(8);\n\n% Calculates the cube-coordinates of the starting points\nCC = floor([Sta(:,1)-Min(1) Sta(:,2)-Min(2) Sta(:,3)-Min(3)]/EL)+NE+1;\n\n% Compute the number of cubes needed for each starting point\nN = ceil(Len/L);\n\n% Correct N so that cube indexes are not too small or large\nI = CC(:,1) < N+1;\nN(I) = CC(I,1)-1;\nI = CC(:,2) < N+1;\nN(I) = CC(I,2)-1;\nI = CC(:,3) < N+1;\nN(I) = CC(I,3)-1;\nI = CC(:,1)+N+1 > Info(4);\nN(I) = Info(4)-CC(I,1)-1;\nI = CC(:,2)+N+1 > Info(5);\nN(I) = Info(5)-CC(I,2)-1;\nI = CC(:,3)+N+1 > Info(6);\nN(I) = Info(6)-CC(I,3)-1;\n\n% Calculate the distances to the cylinders\nn = size(Rad,1);\nnp = size(P,1);\nDist = zeros(np,2); % Distance and the closest cylinder of each points\nDist(:,1) = 2; % Large distance initially\nPoints = zeros(ceil(np/10),1,'int32'); % Auxiliary variable\nData = cell(n,1);\nfor i = 1:n\n  Par = Partition(CC(i,1)-N(i):CC(i,1)+N(i),CC(i,2)-N(i):CC(i,2)+N(i),...\n    CC(i,3)-N(i):CC(i,3)+N(i));\n  if N(i) > 1\n    S = cellfun('length',Par);\n    I = S > 0;\n    S = S(I);\n    Par = Par(I);\n    stop = cumsum(S);\n    start = [0; stop]+1;\n    for k = 1:length(stop)\n      Points(start(k):stop(k)) = Par{k}(:);\n    end\n    points = Points(1:stop(k));\n  else\n    points = vertcat(Par{:});\n  end\n  [d,~,h] = distances_to_line(P(points,:),Axe(i,:),Sta(i,:));\n  d = abs(d-Rad(i));\n  Data{i} = [d h double(points)];\n  I = d < Dist(points,1);\n  J = h >= 0;\n  K = h <= Len(i);\n  L = d < 0.5;\n  M = I&J&K&L;\n  points = points(M);\n  Dist(points,1) = d(M);\n  Dist(points,2) = i;\nend\n\n% Calculate the distances to the cylinders for points not yet calculated\n% because they are not \"on side of cylinder\nfor i = 1:n\n  if ~isempty(Data{i})\n    d = Data{i}(:,1);\n    h = Data{i}(:,2);\n    points = Data{i}(:,3);\n    I = d < Dist(points,1);\n    J = h >= -0.1 & h <= 0;\n    K = h <= Len(i)+0.1 & h >= Len(i);\n    L = d < 0.5;\n    M = I&(J|K)&L;\n    points = points(M);\n    Dist(points,1) = d(M);\n    Dist(points,2) = i;\n  end\nend\n\n% Select only the shortest 95% of distances for each cylinder\nN = zeros(n,1);\nO = zeros(np,1);\nfor i = 1:np\n  if Dist(i,2) > 0\n    N(Dist(i,2)) = N(Dist(i,2))+1;\n    O(i) = N(Dist(i,2));\n  end\nend\nCyl = cell(n,1);\nfor i = 1:n\n  Cyl{i} = zeros(N(i),1);\nend\nfor i = 1:np\n  if Dist(i,2) > 0\n    Cyl{Dist(i,2)}(O(i)) = i;\n  end\nend\nDistCyl = zeros(n,1); % Average point distance to each cylinder\nfor i = 1:n\n  I = Cyl{i};\n  m = length(I);\n  if m > 19 % select the smallest 95% of distances\n    d = sort(Dist(I,1));\n    DistCyl(i) = mean(d(1:floor(0.95*m)));\n  elseif m > 0\n    DistCyl(i) = mean(Dist(I,1));\n  end\nend\n\n% Define the output\npmdistance.CylDist = single(DistCyl);\npmdistance.median = median(DistCyl(:,1));\npmdistance.mean = mean(DistCyl(:,1));\npmdistance.max = max(DistCyl(:,1));\npmdistance.std = std(DistCyl(:,1));\n\nT = BOrd == 0;\nB1 = BOrd == 1;\nB2 = BOrd == 2;\nB = DistCyl(~T,1);\nT = DistCyl(T,1);\nB1 = DistCyl(B1,1);\nB2 = DistCyl(B2,1);\n\npmdistance.TrunkMedian = median(T);\npmdistance.TrunkMean = mean(T);\npmdistance.TrunkMax = max(T);\npmdistance.TrunkStd = std(T);\n\nif ~isempty(B)\n  pmdistance.BranchMedian = median(B);\n  pmdistance.BranchMean = mean(B);\n  pmdistance.BranchMax = max(B);\n  pmdistance.BranchStd = std(B);\nelse\n  pmdistance.BranchMedian = 0;\n  pmdistance.BranchMean = 0;\n  pmdistance.BranchMax = 0;\n  pmdistance.BranchStd = 0;\nend\n\nif ~isempty(B1)\n  pmdistance.Branch1Median = median(B1);\n  pmdistance.Branch1Mean = mean(B1);\n  pmdistance.Branch1Max = max(B1);\n  pmdistance.Branch1Std = std(B1);\nelse\n  pmdistance.Branch1Median = 0;\n  pmdistance.Branch1Mean = 0;\n  pmdistance.Branch1Max = 0;\n  pmdistance.Branch1Std = 0;\nend\n\nif ~isempty(B2)\n  pmdistance.Branch2Median = median(B2);\n  pmdistance.Branch2Mean = mean(B2);\n  pmdistance.Branch2Max = max(B2);\n  pmdistance.Branch2Std = std(B2);\nelse\n  pmdistance.Branch2Median = 0;\n  pmdistance.Branch2Mean = 0;\n  pmdistance.Branch2Max = 0;\n  pmdistance.Branch2Std = 0;\nend\n"
  },
  {
    "path": "src/main_steps/relative_size.m",
    "content": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction RS = relative_size(P,cover,segment)\n\n% ---------------------------------------------------------------------\n% RELATIVE_SIZE.M   Determines relative cover set size for points in new covers\n%\n% Version 2.00\n% Latest update     16 Aug 2017\n%\n% Copyright (C) 2014-2017 Pasi Raumonen\n% ---------------------------------------------------------------------\n% \n% Uses existing segmentation and its branching structure to determine\n% relative size of the cover sets distributed over new covers. The idea is \n% to decrease the relative size as the branch size decreases. This is \n% realised so that the relative size at the base of a branch is\n% proportional to the size of the stem's base, measured as number of\n% cover sets in the first few layers. Also when we approach the\n% tip of the branch, the relative size decreases to the minimum. \n% Maximum relative size is 256 at the bottom of the\n% stem and the minimum is 1 at the tip of every branch.\n%\n% Output:\n% RS    Relative size (1-256), uint8-vector, (n_points x 1)\n\nBal = cover.ball;\nCen = cover.center;\nNei = cover.neighbor;\nSegs = segment.segments;\nSChi = segment.ChildSegment;\nnp = size(P,1);     % number of points\nns = size(Segs,1);  % number of segments\n\n%% Use branching order and height as apriori info\n% Determine the branch orders of the segments\nOrd = zeros(ns,1);\nC = SChi{1};\norder = 0;\nwhile ~isempty(C)\n    order = order+order;\n    Ord(C) = order;\n    C = vertcat(SChi{C});\nend\nmaxO = order+1; % maximum branching order (plus one)\n\n% Determine tree height\nTop = max(P(Cen,3));\nBot = min(P(Cen,3));\nH = Top-Bot;\n\n%% Determine \"base size\" compared to the stem base\n% BaseSize is the relative size of the branch base compared to the stem\n% base, measured as number of cover sets in the first layers of the cover\n% sets. If it is larger than apriori upper limit based on branching order\n% and branch height, then correct to the apriori limit \nBaseSize = zeros(ns,1);\n% Determine first the base size at the stem\nS = Segs{1};\nn = size(S,1);\nif n >= 2\n    m = min([6 n]);\n    BaseSize(1) = mean(cellfun(@length,S(2:m)));\nelse\n    BaseSize(1) = length(S{1});\nend\n% Then define base size for other segments\nfor i = 2:ns\n    S = Segs{i};\n    n = size(S,1);\n    if n >= 2\n        m = min([6 n]);\n        BaseSize(i) = ceil(mean(cellfun(@length,S(2:m)))/BaseSize(1)*256);\n    else\n        BaseSize(i) = length(S{1})/BaseSize(1)*256;\n    end\n    bot = min(P(Cen(S{1}),3)); \n    h = bot-Bot; % height of the segment's base\n    BS = ceil(256*(maxO-Ord(i))/maxO*(H-h)/H); % maximum apriori base size\n    if BaseSize(i) > BS\n        BaseSize(i) = BS;\n    end\nend\nBaseSize(1) = 256;\n\n%% Determine relative size for points\nTS = 1;\nRS = zeros(np,1,'uint8');\nfor i = 1:ns\n    S = Segs{i};\n    s = size(S,1);\n    for j = 1:s\n        Q = S{j};\n        RS(vertcat(Bal{Q})) = BaseSize(i)-(BaseSize(i)-TS)*sqrt((j-1)/s);\n    end\nend\n\n%% Adjust the relative size at the base of child segments\nRS0 = RS;\nfor i = 1:ns\n    C = SChi{i};\n    n = length(C);\n    if n > 0\n        for j = 1:n\n            S = Segs{C(j)};\n            B = S{1};\n            N = vertcat(Nei{B});\n            if size(S,1) > 1\n                N = setdiff(N,S{2});\n            end\n            N = union(N,B);\n            N = vertcat(Bal{N});\n            RS(N) = RS0(N)/2;\n        end\n    end\nend\n"
  },
  {
    "path": "src/main_steps/segments.m",
    "content": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction segment = segments(cover,Base,Forb)\n\n% ---------------------------------------------------------------------\n% SEGMENTS.M        Segments the covered point cloud into branches.\n%\n% Version 2.10\n% Latest update     16 Aug 2017\n%\n% Copyright (C) 2013-2017 Pasi Raumonen\n% ---------------------------------------------------------------------\n\n% Segments the tree into branches and records their parent-child-relations. \n% Bifurcations are recognized by studying connectivity of a \"study\"\n% region moving along the tree. In case of multiple connected components \n% in \"study\", the components are classified as the continuation and branches.\n%\n% Inputs:\n% cover         Cover sets\n% Base          Base of the tree\n% Forb          Cover sets not part of the tree\n%\n% Outputs:\n% segment       Structure array containing the followin fields:\n%   segments          Segments found, (n_seg x 1)-cell, each cell contains a cell array the cover sets\n%   ParentSegment     Parent segment of each segment, (n_seg x 1)-vector,\n%                       equals to zero if no parent segment\n%   ChildSegment      Children segments of each segment, (n_seg x 1)-cell\n\nNei = cover.neighbor;\nnb = size(Nei,1);           % The number of cover sets\na = max([200000 nb/100]);   % Estimate for maximum number of segments\nSBas = cell(a,1);           % The segment bases found\nSegs = cell(a,1);           % The segments found\nSPar = zeros(a,2,'uint32'); % The parent segment of each segment\nSChi = cell(a,1);           % The children segments of each segment\n\n% Initialize SChi\nSChi{1} = zeros(5000,1,'uint32');\nC = zeros(200,1);\nfor i = 2:a\n    SChi{i} = C;\nend\nNChi = zeros(a,1);      % Number of child segments found for each segment\n\nFal = false(nb,1);      % Logical false-vector for cover sets\ns = 1;                  % The index of the segment under expansion\nb = s;                  % The index of the latest found base\n\nSBas{s} = Base;\nSeg = cell(1000,1);    % The cover set layers in the current segment\nSeg{1} = Base;\n\nForbAll = Fal;       % The forbidden sets\nForbAll(Forb) = true;\nForbAll(Base) = true;\nForb = ForbAll;      % The forbidden sets for the segment under expansion\n\nContinue = true; % True as long as the component can be segmented further \nNewSeg = true;   % True if the first Cut for the current segment\nnl = 1;          % The number of cover set layers currently in the segment\n\n% Segmenting stops when there are no more segments to be found\nwhile Continue && (b < nb)\n    \n    % Update the forbidden sets\n    Forb(Seg{nl}) = true;\n    \n    % Define the study\n    Cut = define_cut(Nei,Seg{nl},Forb,Fal);\n    CutSize = length(Cut);\n    \n    if NewSeg\n        NewSeg = false;\n        ns = min(CutSize,6);\n    end\n    \n    % Define the components of cut and study regions\n    if CutSize > 0\n        CutComps = cut_components(Nei,Cut,CutSize,Fal,Fal);\n        nc = size(CutComps,1);\n        if nc > 1\n            [StudyComps,Bases,CompSize,Cont,BaseSize] = ...\n                study_components(Nei,ns,Cut,CutComps,Forb,Fal,Fal);\n            nc = length(Cont);\n        end\n    else\n        nc = 0;\n    end\n    \n    % Classify study region components\n    if nc == 1\n        % One component, continue expansion of the current segment\n        nl = nl+1;\n        if size(Cut,2) > 1\n            Seg{nl} = Cut';\n        else\n            Seg{nl} = Cut;\n        end\n    elseif nc > 1\n        % Classify the components of the Study region\n        Class = component_classification(CompSize,Cont,BaseSize,CutSize);\n        \n        for i = 1:nc\n            if Class(i) == 1\n                Base = Bases{i};\n                ForbAll(Base) = true;\n                Forb(StudyComps{i}) = true;\n                J = Forb(Cut);\n                Cut = Cut(~J);\n                b = b+1;\n                SBas{b} = Base;\n                SPar(b,:) = [s nl];\n                NChi(s) = NChi(s)+1;\n                SChi{s}(NChi(s)) = b;\n            end\n        end\n        \n        % Define the new cut.\n        % If the cut is empty, determine the new base\n        if isempty(Cut)\n            Segs{s} = Seg(1:nl);\n            S = vertcat(Seg{1:nl});\n            ForbAll(S) = true;\n\n            if s < b\n                s = s+1;\n                Seg{1} = SBas{s};\n                Forb = ForbAll;\n                NewSeg = true;\n                nl = 1;\n            else\n                Continue = false;\n            end\n        else\n            if size(Cut,2) > 1\n                Cut = Cut';\n            end\n            nl = nl+1;\n            Seg{nl} = Cut;\n        end\n    \n    else\n        % If the study region has zero size, then the current segment is\n        % complete and determine the base of the next segment\n        Segs{s} = Seg(1:nl);\n        S = vertcat(Seg{1:nl});\n        ForbAll(S) = true;\n        \n        if s < b\n            s = s+1;\n            Seg{1} = SBas{s};\n            Forb = ForbAll;\n            NewSeg = true;\n            nl = 1;\n        else\n            Continue = false;\n        end\n    end\nend\nSegs = Segs(1:b);\nSPar = SPar(1:b,:);\nschi = SChi(1:b);\n\n% Define output\nSChi = cell(b,1);\nfor i = 1:b\n    if NChi(i) > 0\n        SChi{i} = uint32(schi{i}(1:NChi(i)));\n    else\n        SChi{i} = zeros(0,1,'uint32');\n    end\n    S = Segs{i};\n    for j = 1:size(S,1)\n        S{j} = uint32(S{j});\n    end\n    Segs{i} = S;\nend\nclear Segment\nsegment.segments = Segs;\nsegment.ParentSegment = SPar;\nsegment.ChildSegment = SChi;\n\nend % End of the main function\n\n\n% Define subfunctions\n\nfunction Cut = define_cut(Nei,CutPre,Forb,Fal)\n\n% Defines the \"Cut\" region\nCut = vertcat(Nei{CutPre});\nCut = unique_elements(Cut,Fal);\nI = Forb(Cut);\nCut = Cut(~I);\nend % End of function \n\n\nfunction [Components,CompSize] = cut_components(Nei,Cut,CutSize,Fal,False)\n\n% Define the connected components of the Cut\nif CutSize == 1\n    % Cut is connected and therefore Study is also\n    CompSize = 1;\n    Components = cell(1,1);\n    Components{1} = Cut;\nelseif CutSize == 2\n    I = Nei{Cut(1)} == Cut(2);\n    if any(I)\n        Components = cell(1,1);\n        Components{1} = Cut;\n        CompSize = 1;\n    else\n        Components = cell(2,1);\n        Components{1} = Cut(1);\n        Components{2} = Cut(2);\n        CompSize = [1 1];\n    end\nelseif CutSize == 3\n    I = Nei{Cut(1)} == Cut(2);\n    J = Nei{Cut(1)} == Cut(3);\n    K = Nei{Cut(2)} == Cut(3);\n    if any(I)+any(J)+any(K) >= 2\n        CompSize = 1;\n        Components = cell(1,1);\n        Components{1} = Cut;\n    elseif any(I)\n        Components = cell(2,1);\n        Components{1} = Cut(1:2);\n        Components{2} = Cut(3);\n        CompSize = [2 1];\n    elseif any(J)\n        Components = cell(2,1);\n        Components{1} = Cut([1 3]');\n        Components{2} = Cut(2);\n        CompSize = [2 1];\n    elseif any(K)\n        Components = cell(2,1);\n        Components{1} = Cut(2:3);\n        Components{2} = Cut(1);\n        CompSize = [2 1];\n    else\n        CompSize = [1 1 1];\n        Components = cell(3,1);\n        Components{1} = Cut(1);\n        Components{2} = Cut(2);\n        Components{3} = Cut(3);\n    end\nelse\n    Components = cell(CutSize,1);\n    CompSize = zeros(CutSize,1);\n    Comp = zeros(CutSize,1);\n    Fal(Cut) = true;\n    nc = 0;      % number of components found\n    m = Cut(1);\n    i = 0;\n    while i < CutSize\n        Added = Nei{m};\n        I = Fal(Added);\n        Added = Added(I);\n        a = length(Added);\n        Comp(1) = m;\n        Fal(m) = false;\n        t = 1;\n        while a > 0\n            Comp(t+1:t+a) = Added;\n            Fal(Added) = false;\n            t = t+a;\n            Ext = vertcat(Nei{Added});\n            Ext = unique_elements(Ext,False);\n            I = Fal(Ext);\n            Added = Ext(I);\n            a = length(Added);\n        end\n        i = i+t;\n        nc = nc+1;\n        Components{nc} = Comp(1:t);\n        CompSize(nc) = t;\n        if i < CutSize\n            J = Fal(Cut);\n            m = Cut(J);\n            m = m(1);\n        end\n    end\n    Components = Components(1:nc);\n    CompSize = CompSize(1:nc);\nend\n\nend % End of function\n\n\nfunction [Components,Bases,CompSize,Cont,BaseSize] = ...\n    study_components(Nei,ns,Cut,CutComps,Forb,Fal,False)\n\n% Define Study as a cell-array\nStudy = cell(ns,1);\nStudySize = zeros(ns,1);\nStudy{1} = Cut;\nStudySize(1) = length(Cut);\nif ns >= 2\n    N = Cut;\n    i = 1;\n    while i < ns\n        Forb(N) = true;\n        N = vertcat(Nei{N});\n        N = unique_elements(N,Fal);\n        I = Forb(N);\n        N = N(~I);\n        if ~isempty(N)\n            i = i+1;\n            Study{i} = N;\n            StudySize(i) = length(N);\n        else\n            Study = Study(1:i);\n            StudySize = StudySize(1:i);\n            i = ns+1;\n        end\n    end\nend\n\n% Define study as a vector\nns = length(StudySize);\nstudysize = sum(StudySize);\nstudy = vertcat(Study{:});\n\n% Determine the components of study\nnc = size(CutComps,1);\ni = 1; % index of cut component\nj = 0; % number of elements attributed to components\nk = 0; % number of study components\nFal(study) = true;\nComponents = cell(nc,1);\nCompSize = zeros(nc,1);\nComp = zeros(studysize,1);\nwhile i <= nc\n    C = CutComps{i};\n    while j < studysize\n        a = length(C);\n        Comp(1:a) = C;\n        Fal(C) = false;\n        if a > 1\n            Add = unique_elements(vertcat(Nei{C}),False);\n        else\n            Add = Nei{C};\n        end\n        t = a;\n        I = Fal(Add);\n        Add = Add(I);\n        a = length(Add);\n        while a > 0\n            Comp(t+1:t+a) = Add;\n            Fal(Add) = false;\n            t = t+a;\n            Add = vertcat(Nei{Add});\n            Add = unique_elements(Add,False);\n            I = Fal(Add);\n            Add = Add(I);\n            a = length(Add);\n        end\n        j = j+t;\n        k = k+1;\n        Components{k} = Comp(1:t);\n        CompSize(k) = t;\n        if j < studysize\n            C = zeros(0,1);\n            while i < nc && isempty(C)\n                i = i+1;\n                C = CutComps{i};\n                J = Fal(C);\n                C = C(J);\n            end\n            if i == nc && isempty(C)\n                j = studysize;\n                i = nc+1;\n            end\n        else\n            i = nc+1;\n        end\n    end\n    Components = Components(1:k);\n    CompSize = CompSize(1:k);\nend\n\n% Determine BaseSize and Cont\nCont = true(k,1);\nBaseSize = zeros(k,1);\nBases = cell(k,1);\nif k > 1\n    Forb(study) = true;\n    Fal(study) = false;\n    Fal(Study{1}) = true;\n    for i = 1:k\n        % Determine the size of the base of the components\n        Set = unique_elements([Components{i}; Study{1}],False);\n        False(Components{i}) = true;\n        I = False(Set)&Fal(Set);\n        False(Components{i}) = false;\n        Set = Set(I);\n        Bases{i} = Set;\n        BaseSize(i) = length(Set);\n    end\n    Fal(Study{1}) = false;\n    Fal(Study{ns}) = true;\n    Forb(study) = true;\n    for i = 1:k\n        % Determine if the component can be extended\n        Set = unique_elements([Components{i}; Study{ns}],False);\n        False(Components{i}) = true;\n        I = False(Set)&Fal(Set);\n        False(Components{i}) = false;\n        Set = Set(I);\n        if ~isempty(Set)\n            N = vertcat(Nei{Set});\n            N = unique_elements(N,False);\n            I = Forb(N);\n            N = N(~I);\n            if isempty(N)\n                Cont(i) = false;\n            end\n        else\n            Cont(i) = false;\n        end\n    end\nend\n\nend % End of function\n\n\nfunction Class = component_classification(CompSize,Cont,BaseSize,CutSize)\n\n% Classifies study region components:\n% Class(i) == 0 continuation\n% Class(i) == 1 branch\n\nnc = size(CompSize,1);\nStudySize = sum(CompSize);\nClass = ones(nc,1);     % true if a component is a branch to be further segmented\nContiComp = 0;\n% Simple initial classification\nfor i = 1:nc\n    if BaseSize(i) == CompSize(i) && ~Cont(i)\n        % component has no expansion, not a branch\n        Class(i) = 0;\n    elseif BaseSize(i) == 1 && CompSize(i) <= 2 && ~Cont(i)\n        % component has very small expansion, not a branch\n        Class(i) = 0;\n    elseif BaseSize(i)/CutSize < 0.05 && 2*BaseSize(i) >= CompSize(i) && ~Cont(i)\n        % component has very small expansion or is very small, not a branch\n        Class(i) = 0;\n    elseif CompSize(i) <= 3 && ~Cont(i)\n        % very small component, not a branch\n        Class(i) = 0;\n    elseif BaseSize(i)/CutSize >= 0.7 || CompSize(i) >= 0.7*StudySize\n        % continuation of the segment\n        Class(i) = 0;\n        ContiComp = i;\n    else\n        % Component is probably a branch\n    end\nend\n\nBranches = Class == 1;\nif ContiComp == 0 && any(Branches)\n    Ind = (1:1:nc)';\n    Branches = Ind(Branches);\n    [~,I] = max(CompSize(Branches));\n    Class(Branches(I)) = 0;\nend\n\nend % End of function\n"
  },
  {
    "path": "src/main_steps/tree_data.m",
    "content": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction [treedata,triangulation] = tree_data(cylinder,branch,trunk,inputs)\n\n% ---------------------------------------------------------------------\n% TREE_DATA.M       Calculates some tree attributes from cylinder QSM.\n%\n% Version 3.0.1\n% Latest update     2 May 2022\n%\n% Copyright (C) 2013-2022 Pasi Raumonen\n% ---------------------------------------------------------------------\n\n% Inputs:\n% cylinder:\n%   radius (Rad)    Radii of the cylinders\n%   length (Len)    Lengths of the cylinders\n%   start (Sta)     Starting points of the cylinders\n%   axis (Axe)      Axes of the cylinders\n% branch:\n%   order (BOrd)    Branch order data\n%   volume (BVol)   Branch volume data\n%   length (BLen)   Branch length data\n% trunk     Point cloud of the trunk\n% inputs            Input structure, defines if results are displayed and\n%                     plotted and if triangulation results are computed\n%\n% Output:\n% treedata     Tree data/attributes in a struct\n% ---------------------------------------------------------------------\n\n% Changes from version 3.0.0 to 3.0.1, 2 May 2022:\n% 1) Small changes in \"crown_measures\" when computing crown base to prevent\n%    errors in special cases.\n% 2) Small change for how to compute the \"first major branch\" in \n%    \"triangulate_stem\".\n% 3) Modified code so that \"n\" cannot be empty in \"branch_distribution\" and\n%    cause warning\n% 4) Decreased the minimum triangle sizes in \"triangulate_stem\"\n% 5) The triangulation code has some changes.\n% 6) Minor streamlining of the code\n\n% Changes from version 2.0.2 to 3.0.0, 13 Feb 2020:\n% 1) Changed the setup for triangulation:\n%     - The size of the triangles is more dependent on the dbh\n%     - The height of the stem section is defined up to the first major branch\n%       (branch diameter > 0.1*dbh or maximum branch diameter) but keeping\n%       the stem diameter above 25% of dbh.\n% 2) Makes now more tries for triangulation, also changes triangle size\n%    and the length of the stem section if necessary.\n% 3) Changed the names of some fields in the output:\n%     - VolumeCylDiam --> VolCylDia\n%     - LengthCylDiam --> LenCylDia\n%     - VolumeBranchOrder --> VolBranchOrd\n%     - LengthBranchOrder --> LenBranchOrd\n%     - NumberBranchOrder --> NumBranchOrd\n% 3) Added many new fields into the output treedata, particularly distributions:\n%     - Total length (trunk length + branch length) (\"TotalLength\")\n%     - Trunk area and branch area (\"TrunkArea\" and \"BranchArea\")\n%     - Crown dimensions: \"CrownDiamAve\", \"CrownDiamMax\",\"CrownAreaConv\",\n%       \"CrownAreaAlpha\", \"CrownBaseHeight\", \"CrownLength\", \"CrownRatio\",\n%       \"CrownVolumeConv\", \"CrownVolumeAlpha\".\n%     - Vertical tree profile \"VerticalProfile\" and tree diameters in\n%       18 directions at 20 height layers \"spreads\".\n%     - Branch area as functions of diameter class and branch order\n%           (\"AreCylDia\" and \"AreBranchOrd\")\n%     - Volume, area and length of CYLINDERS (tree segments) in 1 meter\n%           HEIGHT classes (\"VolCylHei\", \"AreCylHei\", \"LenCylHei\")\n%     - Volume, area and length of CYLINDERS (tree segments) in 10 deg\n%           ZENITH DIRECTION classes (\"VolCylZen\", \"AreCylZen\", \"LenCylZen\")\n%     - Volume, area and length of CYLINDERS (tree segments) in 10 deg\n%           AZIMUTH DIRECTION classes (\"VolCylAzi\", \"AreCylAzi\", \"LenCylAzi\")\n%     - Volume, area, length and number of all and 1st-order BRANCHES\n%           in 1 cm DIAMETER classes (\"AreBranchDia\", \"AreBranch1Dia\", etc.)\n%     - Volume, area, length and number of all and 1st-order BRANCHES\n%           in 1 meter HEIGHT classes (\"AreBranchDia\", \"AreBranch1Dia\", etc.)\n%     - Volume, area, length and number of all and 1st-order BRANCHES\n%           in 10 degree BRANCHING ANGLE classes\n%           (\"AreBranchAng\", \"AreBranch1Ang\", etc.)\n%     - Volume, area, length and number of all and 1st-order BRANCHES\n%           in 22.5 degree branch AZIMUTH ANGLE classes\n%           (\"AreBranchAzi\", \"AreBranch1Azi\", etc.)\n%     - Volume, area, length and number of all and 1st-order BRANCHES\n%           in 10 degree branch ZENITH ANGLE classes\n%           (\"AreBranchZen\", \"AreBranch1Zen\", etc.)\n% 4) Added new area-related fields into the output triangulation:\n%       - side area, top area and bottom area\n% 5) Added new triangulation related fields to the output treedata:\n%      - TriaTrunkArea      side area of the triangulation\n%      - MixTrunkArea       trunk area from triangulation and cylinders\n%      - MixTotalArea       total area where the MixTrunkArea used instead\n%                               of TrunkArea\n% 6) Structure has more subfunctions.\n% 7) Changed the coding for cylinder fitting of DBH to conform new output\n%    of the least_square_cylinder.\n\n% Changes from version 2.0.1 to 2.0.2, 26 Nov 2019:\n% 1) Bug fix: Added a statement \"C < nc\" for a while command that makes sure\n%    that the index \"C\" does not exceed the number of stem cylinders, when\n%    determining the index of cylinders up to first branch.\n% 2) Bug fix: Changed \"for i = 1:BO\" to \"for i = 1:max(1,BO)\" where\n%    computing branch order data.\n% 3) Added the plotting of the triangulation model\n\n% Changes from version 2.0.0 to 2.0.1, 9 Oct 2019:\n% 1) Bug fix: Changed the units (from 100m to 1m) for computing the branch\n%    length distribution: branch length per branch order.\n\n% Define some variables from cylinder:\nRad = cylinder.radius;\nLen = cylinder.length;\nnc = length(Rad);\nind = (1:1:nc)';\nTrunk = cylinder.branch == 1; % Trunk cylinders\n\n%% Tree attributes from cylinders\n% Volumes, areas, lengths, branches\ntreedata.TotalVolume = 1000*pi*Rad.^2'*Len;\ntreedata.TrunkVolume = 1000*pi*Rad(Trunk).^2'*Len(Trunk);\ntreedata.BranchVolume = 1000*pi*Rad(~Trunk).^2'*Len(~Trunk);\nbottom = min(cylinder.start(:,3));\n[top,i] = max(cylinder.start(:,3));\nif cylinder.axis(i,3) > 0\n  top = top+Len(i)*cylinder.axis(i,3);\nend\ntreedata.TreeHeight = top-bottom;\ntreedata.TrunkLength = sum(Len(Trunk));\ntreedata.BranchLength = sum(Len(~Trunk));\ntreedata.TotalLength = treedata.TrunkLength+treedata.BranchLength;\nNB = length(branch.order)-1; % number of branches\ntreedata.NumberBranches = NB;\nBO = max(branch.order); % maximum branch order\ntreedata.MaxBranchOrder = BO;\ntreedata.TrunkArea = 2*pi*sum(Rad(Trunk).*Len(Trunk));\ntreedata.BranchArea = 2*pi*sum(Rad(~Trunk).*Len(~Trunk));\ntreedata.TotalArea = 2*pi*sum(Rad.*Len);\n\n%% Diameter at breast height (dbh)\n% Dbh from the QSM and from a cylinder fitted particularly to the correct place\ntreedata = dbh_cylinder(treedata,trunk,Trunk,cylinder,ind);\n\n%% Crown measures,Vertical profile and spreads\n[treedata,spreads] = crown_measures(treedata,cylinder,branch);\n\n%% Trunk volume and DBH from triangulation\nif inputs.Tria\n  [treedata,triangulation] = triangulate_stem(...\n    treedata,cylinder,branch,trunk);\nelse\n  triangulation = 0;\nend\n\n%% Tree Location\ntreedata.location = cylinder.start(1,:);\n\n%% Stem taper\nR = Rad(Trunk);\nn = length(R);\nTaper = zeros(n+1,2);\nTaper(1,2) = 2*R(1);\nTaper(2:end,1) = cumsum(Len(Trunk));\nTaper(2:end,2) = [2*R(2:end); 2*R(n)];\ntreedata.StemTaper = Taper';\n\n%% Vertical profile and spreads\ntreedata.VerticalProfile = mean(spreads,2);\ntreedata.spreads = spreads;\n\n%% CYLINDER DISTRIBUTIONS:\n%% Wood part diameter distributions\n% Volume, area and length of wood parts as functions of cylinder diameter\n% (in 1cm diameter classes)\ntreedata = cylinder_distribution(treedata,cylinder,'Dia');\n\n%% Wood part height distributions\n% Volume, area and length of cylinders as a function of height\n% (in 1 m height classes)\ntreedata = cylinder_height_distribution(treedata,cylinder,ind);\n\n%% Wood part zenith direction distributions\n% Volume, area and length of wood parts as functions of cylinder zenith\n% direction (in 10 degree angle classes)\ntreedata = cylinder_distribution(treedata,cylinder,'Zen');\n\n%% Wood part azimuth direction distributions\n% Volume, area and length of wood parts as functions of cylinder zenith\n% direction (in 10 degree angle classes)\ntreedata = cylinder_distribution(treedata,cylinder,'Azi');\n\n%% BRANCH DISTRIBUTIONS:\n%% Branch order distributions\n% Volume, area, length and number of branches as a function of branch order\ntreedata = branch_order_distribution(treedata,branch);\n\n%% Branch diameter distributions\n% Volume, area, length and number of branches as a function of branch diameter\n% (in 1cm diameter classes)\ntreedata = branch_distribution(treedata,branch,'Dia');\n\n%% Branch height distribution\n% Volume, area, length and number of branches as a function of branch height\n% (in 1 meter classes) for all and 1st-order branches\ntreedata = branch_distribution(treedata,branch,'Hei');\n\n%% Branch angle distribution\n% Volume, area, length and number of branches as a function of branch angle\n% (in 10 deg angle classes) for all and 1st-order branches\ntreedata = branch_distribution(treedata,branch,'Ang');\n\n%% Branch azimuth distribution\n% Volume, area, length and number of branches as a function of branch azimuth\n% (in 22.5 deg angle classes) for all and 1st-order branches\ntreedata = branch_distribution(treedata,branch,'Azi');\n\n%% Branch zenith distribution\n% Volume, area, length and number of branches as a function of branch zenith\n% (in 10 deg angle classes) for all and 1st-order branches\ntreedata = branch_distribution(treedata,branch,'Zen');\n\n%% change into single-format\nNames = fieldnames(treedata);\nn = size(Names,1);\nfor i = 1:n\n  treedata.(Names{i}) = single(treedata.(Names{i}));\nend\n\nif inputs.disp == 2\n  %% Generate units for displaying the treedata\n  Units = zeros(n,3);\n  for i = 1:n\n    if ~inputs.Tria && strcmp(Names{i},'CrownVolumeAlpha')\n      m = i;\n    elseif inputs.Tria && strcmp(Names{i},'TriaTrunkLength')\n      m = i;\n    end\n    if strcmp(Names{i}(1:3),'DBH')\n      Units(i,:) = 'm  ';\n    elseif strcmp(Names{i}(end-2:end),'ume')\n      Units(i,:) = 'L  ';\n    elseif strcmp(Names{i}(end-2:end),'ght')\n      Units(i,:) = 'm  ';\n    elseif strcmp(Names{i}(end-2:end),'gth')\n      Units(i,:) = 'm  ';\n    elseif strcmp(Names{i}(1:3),'vol')\n      Units(i,:) = 'L  ';\n    elseif strcmp(Names{i}(1:3),'len')\n      Units(i,:) = 'm  ';\n    elseif strcmp(Names{i}(end-2:end),'rea')\n      Units(i,:) = 'm^2';\n    elseif strcmp(Names{i}(1:3),'loc')\n      Units(i,:) = 'm  ';\n    elseif strcmp(Names{i}(end-4:end),'aConv')\n      Units(i,:) = 'm^2';\n    elseif strcmp(Names{i}(end-5:end),'aAlpha')\n      Units(i,:) = 'm^2';\n    elseif strcmp(Names{i}(end-4:end),'eConv')\n      Units(i,:) = 'm^3';\n    elseif strcmp(Names{i}(end-5:end),'eAlpha')\n      Units(i,:) = 'm^3';\n    elseif strcmp(Names{i}(end-2:end),'Ave')\n      Units(i,:) = 'm  ';\n    elseif strcmp(Names{i}(end-2:end),'Max')\n      Units(i,:) = 'm  ';\n    end\n  end\n  %% Display treedata\n  disp('------------')\n  disp('  Tree attributes:')\n  for i = 1:m\n    v = change_precision(treedata.(Names{i}));\n    if strcmp(Names{i},'DBHtri')\n      disp('  -----')\n      disp('  Tree attributes from triangulation:')\n    end\n    disp(['  ',Names{i},' = ',num2str(v),' ',Units(i,:)])\n  end\n  disp('  -----')\nend\n\nif inputs.plot > 1\n  %% Plot distributions\n  figure(6)\n  subplot(2,4,1)\n  plot(Taper(:,1),Taper(:,2),'-b')\n  title('Stem taper')\n  xlabel('Distance from base (m)')\n  ylabel('Diameter (m)')\n  axis tight\n  grid on\n  \n  Q.treedata = treedata;\n  subplot(2,4,2)\n  plot_distribution(Q,6,0,0,'VolCylDia')\n  \n  subplot(2,4,3)\n  plot_distribution(Q,6,0,0,'AreCylDia')\n  \n  subplot(2,4,4)\n  plot_distribution(Q,6,0,0,'LenCylDia')\n  \n  subplot(2,4,5)\n  plot_distribution(Q,6,0,0,'VolBranchOrd')\n  \n  subplot(2,4,6)\n  plot_distribution(Q,6,0,0,'LenBranchOrd')\n  \n  subplot(2,4,7)\n  plot_distribution(Q,6,0,0,'AreBranchOrd')\n  \n  subplot(2,4,8)\n  plot_distribution(Q,6,0,0,'NumBranchOrd')\n  \n  figure(7)\n  subplot(3,3,1)\n  plot_distribution(Q,7,0,0,'VolCylHei')\n  \n  subplot(3,3,2)\n  plot_distribution(Q,7,0,0,'AreCylHei')\n  \n  subplot(3,3,3)\n  plot_distribution(Q,7,0,0,'LenCylHei')\n  \n  subplot(3,3,4)\n  plot_distribution(Q,7,0,0,'VolCylZen')\n  \n  subplot(3,3,5)\n  plot_distribution(Q,7,0,0,'AreCylZen')\n  \n  subplot(3,3,6)\n  plot_distribution(Q,7,0,0,'LenCylZen')\n  \n  subplot(3,3,7)\n  plot_distribution(Q,7,0,0,'VolCylAzi')\n  \n  subplot(3,3,8)\n  plot_distribution(Q,7,0,0,'AreCylAzi')\n  \n  subplot(3,3,9)\n  plot_distribution(Q,7,0,0,'LenCylAzi')\n  \n  figure(8)\n  subplot(3,4,1)\n  %if %%%%%% !!!!!!!!\n  plot_distribution(Q,8,1,0,'VolBranchDia','VolBranch1Dia')\n  \n  subplot(3,4,2)\n  plot_distribution(Q,8,1,0,'AreBranchDia','AreBranch1Dia')\n  \n  subplot(3,4,3)\n  plot_distribution(Q,8,1,0,'LenBranchDia','LenBranch1Dia')\n  \n  subplot(3,4,4)\n  plot_distribution(Q,8,1,0,'NumBranchDia','NumBranch1Dia')\n  \n  subplot(3,4,5)\n  plot_distribution(Q,8,1,0,'VolBranchHei','VolBranch1Hei')\n  \n  subplot(3,4,6)\n  plot_distribution(Q,8,1,0,'AreBranchHei','AreBranch1Hei')\n  \n  subplot(3,4,7)\n  plot_distribution(Q,8,1,0,'LenBranchHei','LenBranch1Hei')\n  \n  subplot(3,4,8)\n  plot_distribution(Q,8,1,0,'NumBranchHei','NumBranch1Hei')\n  \n  subplot(3,4,9)\n  plot_distribution(Q,8,1,0,'VolBranchAng','VolBranch1Ang')\n  \n  subplot(3,4,10)\n  plot_distribution(Q,8,1,0,'AreBranchAng','AreBranch1Ang')\n  \n  subplot(3,4,11)\n  plot_distribution(Q,8,1,0,'LenBranchAng','LenBranch1Ang')\n  \n  subplot(3,4,12)\n  plot_distribution(Q,8,1,0,'NumBranchAng','NumBranch1Ang')\n  \n  figure(9)\n  subplot(2,4,1)\n  plot_distribution(Q,9,1,0,'VolBranchZen','VolBranch1Zen')\n  \n  subplot(2,4,2)\n  plot_distribution(Q,9,1,0,'AreBranchZen','AreBranch1Zen')\n \n  subplot(2,4,3)\n  plot_distribution(Q,9,1,0,'LenBranchZen','LenBranch1Zen')\n  \n  subplot(2,4,4)\n  plot_distribution(Q,9,1,0,'NumBranchZen','NumBranch1Zen')\n  \n  subplot(2,4,5)\n  plot_distribution(Q,9,1,0,'VolBranchAzi','VolBranch1Azi')\n  \n  subplot(2,4,6)\n  plot_distribution(Q,9,1,0,'AreBranchAzi','AreBranch1Azi')\n  \n  subplot(2,4,7)\n  plot_distribution(Q,9,1,0,'LenBranchAzi','LenBranch1Azi')\n  \n  subplot(2,4,8)\n  plot_distribution(Q,9,1,0,'NumBranchAzi','NumBranch1Azi')\nend\n\nend % End of main function\n\n\nfunction treedata = dbh_cylinder(treedata,trunk,Trunk,cylinder,ind)\n\n% Dbh from the QSM\ni = 1;\nn = nnz(Trunk);\nT = ind(Trunk);\nwhile i < n && sum(cylinder.length(T(1:i))) < 1.3\n  i = i+1;\nend\nDBHqsm = 2*cylinder.radius(T(i));\ntreedata.DBHqsm = DBHqsm;\n\n% Determine DBH from cylinder fitted particularly to the correct place\n% Select the trunk point set\nV = trunk-cylinder.start(1,:);\nh = V*cylinder.axis(1,:)';\nI = h < 1.5;\nJ = h > 1.1;\nI = I&J;\nif nnz(I) > 100\n  T = trunk(I,:);\n  % Fit cylinder\n  cyl0 = select_cylinders(cylinder,i);\n  cyl = least_squares_cylinder(T,cyl0);\n  RadiusOK = 2*cyl.radius > 0.8*DBHqsm & 2*cyl.radius < 1.2*DBHqsm;\n  \n  if RadiusOK && abs(cylinder.axis(i,:)*cyl.axis') > 0.9 && cyl.conv && cyl.rel\n    treedata.DBHcyl = 2*cyl.radius;\n  else\n    treedata.DBHcyl = DBHqsm;\n  end\nelse\n  treedata.DBHcyl = DBHqsm;\nend\n% End of function\nend\n\n\nfunction [treedata,spreads] = crown_measures(treedata,cylinder,branch)\n\n%% Generate point clouds from the cylinder model\nAxe = cylinder.axis;\nLen = cylinder.length;\nSta = cylinder.start;\nTip = Sta+[Len.*Axe(:,1) Len.*Axe(:,2) Len.*Axe(:,3)]; % tips of the cylinders\nnc = length(Len);\nP = zeros(5*nc,3); % four mid points on the cylinder surface\nt = 0;\nfor i = 1:nc\n  [U,V] = orthonormal_vectors(Axe(i,:));\n  U = cylinder.radius(i)*U;\n  if cylinder.branch(i) == 1\n    % For stem cylinders generate more points\n    R = rotation_matrix(Axe(i,:),pi/12);\n    for k = 1:4\n      M = Sta(i,:)+k/4*Len(i)*Axe(i,:);\n      for j = 1:12\n        if j > 1\n          U = R*U;\n        end\n        t = t+1;\n        P(t,:) = M+U';\n      end\n    end\n  else\n    M = Sta(i,:)+0.5*Len(i)*Axe(i,:);\n    R = rotation_matrix(Axe(i,:),pi/4);\n    for j = 1:4\n      if j > 1\n        U = R*U;\n      end\n      t = t+1;\n      P(t,:) = M+U';\n    end\n  end\nend\nP = P(1:t,:);\nI = ~isnan(P(:,1));\nP = P(I,:);\nP = double([P; Sta; Tip]);\nP = unique(P,'rows');\n\n%% Vertical profiles (layer diameters/spreads), mean:\nbot = min(P(:,3));\ntop = max(P(:,3));\nHei = top-bot;\nif Hei > 10\n  m = 20;\nelseif Hei > 2\n  m = 10;\nelse\n  m = 5;\nend\nspreads = zeros(m,18);\nfor j = 1:m\n  I = P(:,3) >= bot+(j-1)*Hei/m & P(:,3) < bot+j*Hei/m;\n  X = unique(P(I,:),'rows');\n  if size(X,1) > 5\n    [K,A] = convhull(X(:,1),X(:,2));\n    % compute center of gravity for the convex hull and use it as\n    % center for computing average diameters\n    n = length(K);\n    x = X(K,1);\n    y = X(K,2);\n    CX = sum((x(1:n-1)+x(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A;\n    CY = sum((y(1:n-1)+y(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A;\n    \n    V = mat_vec_subtraction(X(:,1:2),[CX CY]);\n    ang = atan2(V(:,2),V(:,1))+pi;\n    [ang,I] = sort(ang);\n    L = sqrt(sum(V.*V,2));\n    L = L(I);\n    for i = 1:18\n      I = ang >= (i-1)*pi/18 & ang < i*pi/18;\n      if any(I)\n        L1 = max(L(I));\n      else\n        L1 = 0;\n      end\n      J = ang >= (i-1)*pi/18+pi & ang < i*pi/18+pi;\n      if any(J)\n        L2 = max(L(J));\n      else\n        L2 = 0;\n      end\n      spreads(j,i) = L1+L2;\n    end\n  end\nend\n\n%% Crown diameters (spreads), mean and maximum:\nX = unique(P(:,1:2),'rows');\n[K,A] = convhull(X(:,1),X(:,2));\n% compute center of gravity for the convex hull and use it as center for\n% computing average diameters\nn = length(K);\nx = X(K,1);\ny = X(K,2);\nCX = sum((x(1:n-1)+x(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A;\nCY = sum((y(1:n-1)+y(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A;\nV = Tip(:,1:2)-[CX CY];\nang = atan2(V(:,2),V(:,1))+pi;\n[ang,I] = sort(ang);\nL = sqrt(sum(V.*V,2));\nL = L(I);\nS = zeros(18,1);\nfor i = 1:18\n  I = ang >= (i-1)*pi/18 & ang < i*pi/18;\n  if any(I)\n    L1 = max(L(I));\n  else\n    L1 = 0;\n  end\n  J = ang >= (i-1)*pi/18+pi & ang < i*pi/18+pi;\n  if any(J)\n    L2 = max(L(J));\n  else\n    L2 = 0;\n  end\n  S(i) = L1+L2;\nend\ntreedata.CrownDiamAve = mean(S);\nMaxDiam = 0;\nfor i = 1:n\n  V = mat_vec_subtraction([x y],[x(i) y(i)]);\n  L = max(sqrt(sum(V.*V,2)));\n  if L > MaxDiam\n    MaxDiam = L;\n  end\nend\ntreedata.CrownDiamMax = L;\n\n%% Crown areas from convex hull and alpha shape:\ntreedata.CrownAreaConv = A;\nalp = max(0.5,treedata.CrownDiamAve/10);\nshp = alphaShape(X(:,1),X(:,2),alp);\ntreedata.CrownAreaAlpha = shp.area;\n\n%% Crown base\n% Define first major branch as the branch whose diameter > min(0.05*dbh,5cm)\n% and whose horizontal relative reach is more than the median reach of 1st-ord.\n% branches (or at maximum 10). The reach is defined as the horizontal\n% distance from the base to the tip divided by the dbh.\ndbh = treedata.DBHcyl;\nnb = length(branch.order);\nHL = zeros(nb,1); % horizontal reach\nbranches1 = (1:1:nb)';\nbranches1 = branches1(branch.order == 1); % 1st-order branches\nnb = length(branches1);\nnc = size(Sta,1);\nind = (1:1:nc)';\nfor i = 1:nb\n  C = ind(cylinder.branch == branches1(i));\n  if ~isempty(C)\n    base = Sta(C(1),:);\n    C = C(end);\n    tip = Sta(C,:)+Len(C)*Axe(C);\n    V = tip(1:2)-base(1:2);\n    HL(branches1(i)) = sqrt(V*V')/dbh*2;\n  end\nend\nM = min(10,median(HL));\n\n% Sort the branches according to the their heights\nHei = branch.height(branches1);\n[Hei,SortOrd] = sort(Hei);\nbranches1 = branches1(SortOrd);\n\n% Search the first/lowest branch:  \nd = min(0.05,0.05*dbh);\nb = 0;\nif nb > 1\n  i = 1;\n  while i < nb\n    i = i+1;\n    if branch.diameter(branches1(i)) > d && HL(branches1(i)) > M\n      b = branches1(i);\n      i = nb+2;\n    end\n  end\n  if i == nb+1 && nb > 1\n    b = branches1(1);\n  end\nend\n\nif b > 0\n  % search all the children of the first major branch:\n  nb = size(branch.parent,1);\n  Ind = (1:1:nb)';\n  chi = Ind(branch.parent == b);\n  B = b;\n  while ~isempty(chi)\n    B = [B; chi];\n    n = length(chi);\n    C = cell(n,1);\n    for i = 1:n\n      C{i} = Ind(branch.parent == chi(i));\n    end\n    chi = vertcat(C{:});\n  end\n  \n  % define crown base height from the ground:\n  BaseHeight = max(Sta(:,3)); % Height of the crown base\n  for i = 1:length(B)\n    C = ind(cylinder.branch == B(i));\n    ht = min(Tip(C,3));\n    hb = min(Sta(C,3));\n    h = min(hb,ht);\n    if h < BaseHeight\n      BaseHeight = h;\n    end\n  end\n  treedata.CrownBaseHeight = BaseHeight-Sta(1,3);\n  \n  %% Crown length and ratio\n  treedata.CrownLength = treedata.TreeHeight-treedata.CrownBaseHeight;\n  treedata.CrownRatio = treedata.CrownLength/treedata.TreeHeight;\n  \n  %% Crown volume from convex hull and alpha shape:\n  I = P(:,3) >= BaseHeight;\n  X = P(I,:);\n  [K,V] = convhull(X(:,1),X(:,2),X(:,3));\n  treedata.CrownVolumeConv = V;\n  alp = max(0.5,treedata.CrownDiamAve/5);\n  shp = alphaShape(X(:,1),X(:,2),X(:,3),alp,'HoleThreshold',10000);\n  treedata.CrownVolumeAlpha = shp.volume;\n\nelse \n  % No branches\n  treedata.CrownBaseHeight = treedata.TreeHeight;\n  treedata.CrownLength = 0;\n  treedata.CrownRatio = 0;\n  treedata.CrownVolumeConv = 0;\n  treedata.CrownVolumeAlpha = 0;\nend\n% End of function\nend\n\n\nfunction [treedata,triangulation] = ...\n  triangulate_stem(treedata,cylinder,branch,trunk)\n\nSta = cylinder.start;\nRad = cylinder.radius;\nLen = cylinder.length;\nDBHqsm = treedata.DBHqsm;\n% Determine the first major branch (over 10% of dbh or the maximum\n% diameter branch):\nnb = size(branch.diameter,1);\nind = (1:1:nb)';\nind = ind(branch.order == 1);\n[~,I] = sort(branch.height(ind));\nind = ind(I);\nn = length(ind);\nb = 1;\nwhile b <= n && branch.diameter(ind(b)) < 0.1*DBHqsm\n  b = b+1;\nend\nb = ind(b);\nif b > n\n  [~,b] = max(branch.diameter);\nend\n\n% Determine suitable cylinders up to the first major branch but keep the\n% stem diameter above one quarter (25%) of dbh:\nC = 1;\nnc = size(Sta,1);\nwhile C < nc && cylinder.branch(C) < b\n  C = C+1;\nend\nn = nnz(cylinder.branch == 1);\ni = 2;\nwhile i < n && Sta(i,3) < Sta(C,3) && Rad(i) > 0.125*DBHqsm\n  i = i+1;\nend\nCylInd = max(i,3);\nTrunkLenTri = Sta(CylInd,3)-Sta(1,3);\n\nEmptyTriangulation = false;\n% Calculate the volumes\nif size(trunk,1) > 1000 && TrunkLenTri >= 1\n  \n  % Set the parameters for triangulation:\n  % Compute point density, which is used to increase the triangle\n  % size if the point density is very small\n  PointDensity = zeros(CylInd-1,1);\n  for i = 1:CylInd-1\n    I = trunk(:,3) >= Sta(i,3) & trunk(:,3) < Sta(i+1,3);\n    PointDensity(i) = pi*Rad(i)*Len(i)/nnz(I);\n  end\n  PointDensity = PointDensity(PointDensity < inf);\n  d = max(PointDensity);\n  \n  % Determine minimum triangle size based on dbh\n  if DBHqsm > 1\n    MinTriaHeight = 0.1;\n  elseif DBHqsm > 0.50\n    MinTriaHeight = 0.075;\n  elseif DBHqsm > 0.10\n    MinTriaHeight = 0.05;\n  else\n    MinTriaHeight = 0.02;\n  end\n  TriaHeight0 = max(MinTriaHeight,4*sqrt(d));\n  \n  % Select the trunk point set used for triangulation\n  I = trunk(:,3) <= Sta(CylInd,3);\n  Stem = trunk(I,:);\n  \n  % Do the triangulation:\n  triangulation = zeros(1,0);\n  l = 0;\n  while isempty(triangulation) && l < 4 && CylInd > 2\n    l = l+1;\n    TriaHeight = TriaHeight0;\n    TriaWidth = TriaHeight;\n    k = 0;\n    while isempty(triangulation) && k < 3\n      k = k+1;\n      j = 0;\n      while isempty(triangulation) && j < 5\n        triangulation = curve_based_triangulation(Stem,TriaHeight,TriaWidth);\n        j = j+1;\n      end\n      % try different triangle sizes if necessary\n      if isempty(triangulation) && k < 3\n        TriaHeight = TriaHeight+0.03;\n        TriaWidth = TriaHeight;\n      end\n    end\n    % try different length of stem sections if necessary\n    if isempty(triangulation) && l < 4 && CylInd > 2\n      CylInd = CylInd-1;\n      I = trunk(:,3) <= Sta(CylInd,3);\n      Stem = trunk(I,:);\n    end\n  end\n  \n  if ~isempty(triangulation)\n    triangulation.cylind = CylInd;\n    % Dbh from triangulation\n    Vert = triangulation.vert;\n    h = Vert(:,3)-triangulation.bottom;\n    [~,I] = min(abs(h-1.3));\n    H = h(I);\n    I = abs(h-H) < triangulation.triah/2;\n    V = Vert(I,:);\n    V = V([2:end 1],:)-V(1:end,:);\n    d = sqrt(sum(V.*V,2));\n    treedata.DBHtri = sum(d)/pi;\n    % volumes from the triangulation\n    treedata.TriaTrunkVolume = triangulation.volume;\n    TrunkVolMix = treedata.TrunkVolume-...\n      1000*pi*sum(Rad(1:CylInd-1).^2.*Len(1:CylInd-1))+triangulation.volume;\n    TrunkAreaMix = treedata.TrunkArea-...\n      2*pi*sum(Rad(1:CylInd-1).*Len(1:CylInd-1))+triangulation.SideArea;\n    treedata.MixTrunkVolume = TrunkVolMix;\n    treedata.MixTotalVolume = TrunkVolMix+treedata.BranchVolume;\n    treedata.TriaTrunkArea = triangulation.SideArea;\n    treedata.MixTrunkArea = TrunkAreaMix;\n    treedata.MixTotalArea = TrunkAreaMix+treedata.BranchArea;\n    treedata.TriaTrunkLength = TrunkLenTri;\n    \n  else\n    EmptyTriangulation = true;\n  end\nelse\n  EmptyTriangulation = true;\nend\n\nif EmptyTriangulation\n  disp('  No triangulation model produced')\n  clear triangulation\n  treedata.DBHtri = DBHqsm;\n  treedata.TriaTrunkVolume = treedata.TrunkVolume;\n  treedata.TriaTrunkArea = treedata.TrunkArea;\n  treedata.MixTrunkVolume = treedata.TrunkVolume;\n  treedata.MixTrunkArea = treedata.TrunkArea;\n  treedata.MixTotalVolume = treedata.TotalVolume;\n  treedata.MixTotalArea = treedata.TotalArea;\n  treedata.TriaTrunkLength = 0;\n  triangulation.vert = zeros(0,3);\n  triangulation.facet = zeros(0,3);\n  triangulation.fvd = zeros(0,1);\n  triangulation.volume = 0;\n  triangulation.SideArea = 0;\n  triangulation.BottomArea = 0;\n  triangulation.TopArea = 0;\n  triangulation.bottom = 0;\n  triangulation.top = 0;\n  triangulation.triah = 0;\n  triangulation.triaw = 0;\n  triangulation.cylind = 0;\nend\nend\n\n\nfunction treedata = cylinder_distribution(treedata,cyl,dist)\n%% Wood part diameter, zenith and azimuth direction distributions\n% Volume, area and length of wood parts as functions of cylinder\n% diameter, zenith, and azimuth\nif strcmp(dist,'Dia')\n  Par = cyl.radius;\n  n = ceil(max(200*cyl.radius));\n  a = 0.005; % diameter in 1 cm classes\nelseif strcmp(dist,'Zen')\n  Par = 180/pi*acos(cyl.axis(:,3));\n  n = 18;\n  a = 10; % zenith direction in 10 degree angle classes\nelseif strcmp(dist,'Azi')\n  Par = 180/pi*atan2(cyl.axis(:,2),cyl.axis(:,1))+180;\n  n = 36;\n  a = 10; % azimuth direction in 10 degree angle classes\nend\n\nCylDist = zeros(3,n);\nfor i = 1:n\n  K = Par >= (i-1)*a & Par < i*a;\n  CylDist(1,i) = 1000*pi*sum(cyl.radius(K).^2.*cyl.length(K)); % vol in L\n  CylDist(2,i) = 2*pi*sum(cyl.radius(K).*cyl.length(K)); % area in m^2\n  CylDist(3,i) = sum(cyl.length(K)); % length in m\nend\ntreedata.(['VolCyl',dist]) = CylDist(1,:);\ntreedata.(['AreCyl',dist]) = CylDist(2,:);\ntreedata.(['LenCyl',dist]) = CylDist(3,:);\nend\n\n\nfunction treedata = cylinder_height_distribution(treedata,cylinder,ind)\n\nRad = cylinder.radius;\nLen = cylinder.length;\nAxe = cylinder.axis;\n\n%% Wood part height distributions\n% Volume, area and length of cylinders as a function of height\n% (in 1 m height classes)\nMaxHei= ceil(treedata.TreeHeight);\ntreedata.VolCylHei = zeros(1,MaxHei);\ntreedata.AreCylHei = zeros(1,MaxHei);\ntreedata.LenCylHei = zeros(1,MaxHei);\nEnd = cylinder.start+[Len.*Axe(:,1) Len.*Axe(:,2) Len.*Axe(:,3)];\nbot = min(cylinder.start(:,3));\nB = cylinder.start(:,3)-bot;\nT = End(:,3)-bot;\nfor j = 1:MaxHei\n  I1 = B >= (j-2) & B < (j-1); % base below this bin\n  J1 = B >= (j-1) & B < j; % base in this bin\n  K1 = B >= j & B < (j+1); % base above this bin\n  I2 = T >= (j-2) & T < (j-1); % top below this bin\n  J2 = T >= (j-1) & T < j; % top in this bin\n  K2 = T >= j & T < (j+1); % top above this bin\n  C1 = ind(J1&J2); % base and top in this bin\n  C2 = ind(J1&K2); % base in this bin, top above\n  C3 = ind(J1&I2); % base in this bin, top below\n  C4 = ind(I1&J2); % base in bin below, top in this\n  C5 = ind(K1&J2); % base in bin above, top in this\n  v1 = 1000*pi*sum(Rad(C1).^2.*Len(C1));\n  a1 = 2*pi*sum(Rad(C1).*Len(C1));\n  l1 = sum(Len(C1));\n  r2 = (j-B(C2))./(T(C2)-B(C2)); % relative portion in this bin\n  v2 = 1000*pi*sum(Rad(C2).^2.*Len(C2).*r2);\n  a2 = 2*pi*sum(Rad(C2).*Len(C2).*r2);\n  l2 = sum(Len(C2).*r2);\n  r3 = (B(C3)-j+1)./(B(C3)-T(C3)); % relative portion in this bin\n  v3 = 1000*pi*sum(Rad(C3).^2.*Len(C3).*r3);\n  a3 = 2*pi*sum(Rad(C3).*Len(C3).*r3);\n  l3 = sum(Len(C3).*r3);\n  r4 = (T(C4)-j+1)./(T(C4)-B(C4)); % relative portion in this bin\n  v4 = 1000*pi*sum(Rad(C4).^2.*Len(C4).*r4);\n  a4 = 2*pi*sum(Rad(C4).*Len(C4).*r4);\n  l4 = sum(Len(C4).*r4);\n  r5 = (j-T(C5))./(B(C5)-T(C5)); % relative portion in this bin\n  v5 = 1000*pi*sum(Rad(C5).^2.*Len(C5).*r5);\n  a5 = 2*pi*sum(Rad(C5).*Len(C5).*r5);\n  l5 = sum(Len(C5).*r5);\n  treedata.VolCylHei(j) = v1+v2+v3+v4+v5;\n  treedata.AreCylHei(j) = a1+a2+a3+a4+a5;\n  treedata.LenCylHei(j) = l1+l2+l3+l4+l5;\nend\nend\n\n\nfunction treedata = branch_distribution(treedata,branch,dist)\n%% Branch diameter, height, angle, zenith and azimuth distributions\n% Volume, area, length and number of branches as a function of branch\n% diamater, height, angle, zenith and aximuth\nBOrd = branch.order(2:end);\nBVol = branch.volume(2:end);\nBAre = branch.area(2:end);\nBLen = branch.length(2:end);\nif strcmp(dist,'Dia')\n  Par = branch.diameter(2:end);\n  n = ceil(max(100*Par));\n  a = 0.005; % diameter in 1 cm classes\nelseif strcmp(dist,'Hei')\n  Par = branch.height(2:end);\n  n = ceil(treedata.TreeHeight);\n  a = 1; % height in 1 m classes\nelseif strcmp(dist,'Ang')\n  Par = branch.angle(2:end);\n  n = 18;\n  a = 10; % angle in 10 degree classes\nelseif strcmp(dist,'Zen')\n  Par = branch.zenith(2:end);\n  n = 18;\n  a = 10; % zenith direction in 10 degree angle classes\nelseif strcmp(dist,'Azi')\n  Par = branch.azimuth(2:end)+180;\n  n = 36;\n  a = 10; % azimuth direction in 10 degree angle classes\nend\nif isempty(n)\n  n = 0;\nend\n\nBranchDist = zeros(8,n);\nfor i = 1:n\n  I = Par >= (i-1)*a & Par < i*a;\n  BranchDist(1,i) = sum(BVol(I)); % volume (all branches)\n  BranchDist(2,i) = sum(BVol(I & BOrd == 1)); % volume (1st-branches)\n  BranchDist(3,i) = sum(BAre(I)); % area (all branches)\n  BranchDist(4,i) = sum(BAre(I & BOrd == 1)); % area (1st-branches)\n  BranchDist(5,i) = sum(BLen(I)); % length (all branches)\n  BranchDist(6,i) = sum(BLen(I & BOrd == 1)); % length (1st-branches)\n  BranchDist(7,i) = nnz(I); % number (all branches)\n  BranchDist(8,i) = nnz(I & BOrd == 1); % number (1st-branches)\nend\ntreedata.(['VolBranch',dist]) = BranchDist(1,:);\ntreedata.(['VolBranch1',dist]) = BranchDist(2,:);\ntreedata.(['AreBranch',dist]) = BranchDist(3,:);\ntreedata.(['AreBranch1',dist]) = BranchDist(4,:);\ntreedata.(['LenBranch',dist]) = BranchDist(5,:);\ntreedata.(['LenBranch1',dist]) = BranchDist(6,:);\ntreedata.(['NumBranch',dist]) = BranchDist(7,:);\ntreedata.(['NumBranch1',dist]) = BranchDist(8,:);\nend\n\n\nfunction treedata = branch_order_distribution(treedata,branch)\n%% Branch order distributions\n% Volume, area, length and number of branches as a function of branch order\nBO = max(branch.order);\nBranchOrdDist = zeros(BO,4);\nfor i = 1:max(1,BO)\n  I = branch.order == i;\n  BranchOrdDist(i,1) = sum(branch.volume(I)); % volumes\n  BranchOrdDist(i,2) = sum(branch.area(I)); % areas\n  BranchOrdDist(i,3) = sum(branch.length(I)); % lengths\n  BranchOrdDist(i,4) = nnz(I); % number of ith-order branches\nend\ntreedata.VolBranchOrd = BranchOrdDist(:,1)';\ntreedata.AreBranchOrd = BranchOrdDist(:,2)';\ntreedata.LenBranchOrd = BranchOrdDist(:,3)';\ntreedata.NumBranchOrd = BranchOrdDist(:,4)';\nend\n"
  },
  {
    "path": "src/main_steps/tree_sets.m",
    "content": "% 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 terms of the GNU General Public License as published by\r\n% the Free Software Foundation, either version 3 of the License, or\r\n% (at your option) any later version.\r\n%\r\n% TREEQSM is distributed in the hope that it will be useful,\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n% GNU General Public License for more details.\r\n%\r\n% You should have received a copy of the GNU General Public License\r\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\r\n\r\nfunction [cover,Base,Forb] = tree_sets(P,cover,inputs,segment)\r\n\r\n% ---------------------------------------------------------------------\r\n% TREE_SETS.M       Determines the base of the trunk and the cover sets\r\n%                   belonging to the tree, updates the neighbor-relation\r\n%\r\n% Version 2.3.0\r\n% Latest update     2 May 2022\r\n%\r\n% Copyright (C) 2013-2022 Pasi Raumonen\r\n% ---------------------------------------------------------------------\r\n%\r\n% Determines the cover sets that belong to the tree. Determines also the\r\n% base of the tree and updates the neighbor-relation such that all of the\r\n% tree is connected, i.e., the cover sets belonging to the tree form a\r\n% single connected component. Optionally uses information from existing\r\n% segmentation to make sure that stem and 1st-, 2nd-, 3rd-order branches\r\n% are properly connnected.\r\n% ---------------------------------------------------------------------\r\n% Inputs:\r\n% P             Point cloud\r\n% cover         Cover sets, their centers and neighbors\r\n% PatchDiam     Minimum diameter of the cover sets\r\n% OnlyTree      Logical value indicating if the point cloud contains only\r\n%                   points from the tree to be modelled\r\n% segment       Previous segments\r\n%\r\n% Outputs:\r\n% cover     Cover sets with updated neigbors\r\n% Base      Base of the trunk (the cover sets forming the base)\r\n% Forb      Cover sets not part of the tree\r\n% ---------------------------------------------------------------------\r\n\r\n% Changes from version 2.2.0 to 2.3.0, 2 May 2022:\r\n% 1) Added new lines of code at the end of the \"define_main_branches\" to\r\n%    make sure that the \"Trunk\" variable defines connected stem\r\n\r\n% Changes from version 2.1.0 to 2.2.0, 13 Aug 2020:\r\n% 1) \"define_base_forb\": Changed the base height specification from\r\n%     0.1*aux.Height to 0.02*aux.Height\r\n% 2) \"define_base_forb\": changed the cylinder fitting syntax corresponding\r\n%     to the new input and outputs of \"least_squares_cylinder\"\r\n% 3) \"make_tree_connected”: Removed \"Trunk(Base) = false;\" at the beginning\r\n%     of the function as unnecessary and to prevent errors in a special case\r\n%     where the Trunk is equal to Base.\r\n%\t4) \"make_tree_connected”: Removed from the end the generation of \"Trunk\"\r\n%     again and the new call for the function\r\n%\t5) \"make_tree_connected”: Increased the minimum distance of a component\r\n%     to be removed from 8m to 12m.\r\n\r\n% Changes from version 2.0.0 to 2.1.0, 11 Oct 2019:\r\n% 1) \"define_main_branches\": modified the size of neighborhood \"balls0\",\r\n%    added seven lines of code, prevents possible error of too low or big\r\n%    indexes on \"Par\"\r\n% 2) Increased the maximum base height from 0.5m to 1.5m\r\n% 3) \"make_tree_connected\": added at the end a call for the function itself,\r\n%    if the tree is not yet connected, thus running the function again if\r\n%    necessary\r\n\r\n%% Define auxiliar object\r\nclear aux\r\naux.nb = max(size(cover.center));   % number of cover sets\r\naux.Fal = false(aux.nb,1);\r\naux.Ind = (1:1:aux.nb)';\r\naux.Ce = P(cover.center,1:3); % Coordinates of the center points\r\naux.Hmin = min(aux.Ce(:,3));\r\naux.Height = max(aux.Ce(:,3))-aux.Hmin;\r\n\r\n%% Define the base of the trunk and the forbidden sets\r\nif nargin == 3\r\n  [Base,Forb,cover] = define_base_forb(P,cover,aux,inputs);\r\nelse\r\n  inputs.OnlyTree = true;\r\n  [Base,Forb,cover] = define_base_forb(P,cover,aux,inputs,segment);\r\nend\r\n\r\n%% Define the trunk (and the main branches)\r\nif nargin == 3\r\n  [Trunk,cover] = define_trunk(cover,aux,Base,Forb,inputs);\r\nelse\r\n  [Trunk,cover] = define_main_branches(cover,segment,aux,inputs);\r\nend\r\n\r\n%% Update neighbor-relation to make the whole tree connected\r\n[cover,Forb] = make_tree_connected(cover,aux,Forb,Base,Trunk,inputs);\r\n\r\nend % End of the main function\r\n\r\n\r\nfunction [Base,Forb,cover] = define_base_forb(P,cover,aux,inputs,segment)\r\n\r\n% Defines the base of the stem and the forbidden sets (the sets containing\r\n% points not from the tree, i.e, ground, understory, etc.)\r\nCe = aux.Ce;\r\nif inputs.OnlyTree && nargin == 4\r\n  % No ground in the point cloud, the base is the lowest part\r\n  BaseHeight = min(1.5,0.02*aux.Height);\r\n  I = Ce(:,3) < aux.Hmin+BaseHeight;\r\n  Base = aux.Ind(I);\r\n  Forb = aux.Fal;\r\n  % Make sure the base, as the bottom of point cloud, is not in multiple parts\r\n  Wb = max(max(Ce(Base,1:2))-min(Ce(Base,1:2)));\r\n  Wt = max(max(Ce(:,1:2))-min(Ce(:,1:2)));\r\n  k = 1;\r\n  while k <= 5 && Wb > 0.3*Wt\r\n    BaseHeight = BaseHeight-0.05;\r\n    BaseHeight = max(BaseHeight,0.05);\r\n    if BaseHeight > 0\r\n      I = Ce(:,3) < aux.Hmin+BaseHeight;\r\n    else\r\n      [~,I] = min(Ce(:,3));\r\n    end\r\n    Base = aux.Ind(I);\r\n    Wb = max(max(Ce(Base,1:2))-min(Ce(Base,1:2)));\r\n    k = k+1;\r\n  end\r\nelseif inputs.OnlyTree\r\n  % Select the stem sets from the previous segmentation and define the\r\n  % base\r\n  BaseHeight = min(1.5,0.02*aux.Height);\r\n  SoP = segment.SegmentOfPoint(cover.center);\r\n  stem = aux.Ind(SoP == 1);\r\n  I = Ce(stem,3) < aux.Hmin+BaseHeight;\r\n  Base = stem(I);\r\n  Forb = aux.Fal;\r\nelse\r\n  % Point cloud contains non-tree points.\r\n  % Determine the base from the \"height\" and \"density\" of cover sets\r\n  % by projecting the sets to the xy-plane\r\n  Bal = cover.ball;\r\n  Nei = cover.neighbor;\r\n\r\n  % The vertices of the rectangle containing C\r\n  Min = double(min(Ce));\r\n  Max = double(max(Ce(:,1:2)));\r\n\r\n  % Number of rectangles with edge length \"E\" in the plane\r\n  E = min(0.1,0.015*aux.Height);\r\n  n = double(ceil((Max(1:2)-Min(1:2))/E)+1);\r\n\r\n  % Calculates the rectangular-coordinates of the points\r\n  px = floor((Ce(:,1)-Min(1))/E)+1;\r\n  py = floor((Ce(:,2)-Min(2))/E)+1;\r\n\r\n  % Sorts the points according a lexicographical order\r\n  LexOrd = [px py-1]*[1 n(1)]';\r\n  [LexOrd,SortOrd] = sort(LexOrd);\r\n\r\n  Partition = cell(n(1),n(2));\r\n  hei = zeros(n(1),n(2)); % \"height\" of the cover sets in the squares\r\n  den = hei;  % density of the cover sets in the squares\r\n  baseden = hei;\r\n  p = 1; % The index of the point under comparison\r\n  while p <= aux.nb\r\n    t = 1;\r\n    while (p+t <= aux.nb) && (LexOrd(p) == LexOrd(p+t))\r\n      t = t+1;\r\n    end\r\n    q = SortOrd(p);\r\n    J = SortOrd(p:p+t-1);\r\n    Partition{px(q),py(q)} = J;\r\n    p = p+t;\r\n    K = ceil(10*(Ce(J,3)-Min(3)+0.01)/(aux.Height-0.01));\r\n    B = K <= 2;\r\n    K = unique(K);\r\n    hei(px(q),py(q)) = length(K)/10;\r\n    den(px(q),py(q)) = t;\r\n    baseden(px(q),py(q)) = nnz(B);\r\n  end\r\n  den = den/max(max(den));  % normalize\r\n  baseden = baseden/max(max(baseden));\r\n\r\n  % function whose maximum determines location of the trunk\r\n  f = den.*hei.*baseden;\r\n  % smooth the function by averaging over 8-neighbors\r\n  x = zeros(n(1),n(2));\r\n  y = zeros(n(1),n(2));\r\n  for i = 2:n(1)-1\r\n    for j = 2:n(2)-1\r\n      f(i,j) = mean(mean(f(i-1:i+1,j-1:j+1)));\r\n      x(i,j) = Min(1)+i*E;\r\n      y(i,j) = Min(2)+j*E;\r\n    end\r\n  end\r\n  f = f/max(max(f));\r\n\r\n  % Trunk location is around the maximum f-value\r\n  I = f > 0.5;\r\n  Trunk0 = Partition(I); % squares that contain the trunk\r\n  Trunk0 = vertcat(Trunk0{:});\r\n  HBottom = min(Ce(Trunk0,3));\r\n  I = Ce(Trunk0,3) > HBottom+min(0.02*aux.Height,0.3);\r\n  J = Ce(Trunk0,3) < HBottom+min(0.08*aux.Height,1.5);\r\n  I = I&J; % slice close to bottom should contain the trunk\r\n  Trunk = Trunk0(I);\r\n  Trunk = union(Trunk,vertcat(Nei{Trunk})); % Expand with neighbors\r\n  Trunk = union(Trunk,vertcat(Nei{Trunk})); % Expand with neighbors\r\n  Trunk = union(Trunk,vertcat(Nei{Trunk})); % Expand with neighbors\r\n\r\n  % Define connected components of Trunk and select the largest component\r\n  [Comp,CS] = connected_components(Nei,Trunk,0,aux.Fal);\r\n  [~,I] = max(CS);\r\n  Trunk = Comp{I};\r\n\r\n  % Fit cylinder to Trunk\r\n  I = Ce(Trunk,3) < HBottom+min(0.1*aux.Height,2); % Select the bottom part\r\n  Trunk = Trunk(I);\r\n  Trunk = union(Trunk,vertcat(Nei{Trunk}));\r\n  Points = Ce(Trunk,:);\r\n  c.start = mean(Points);\r\n  c.axis = [0 0 1];\r\n  c.radius = mean(distances_to_line(Points,c.axis,c.start));\r\n  c = least_squares_cylinder(Points,c);\r\n\r\n  % Remove far away points and fit new cylinder\r\n  dis = distances_to_line(Points,c.axis,c.start);\r\n  [~,I] = sort(abs(dis));\r\n  I = I(1:ceil(0.9*length(I)));\r\n  Points = Points(I,:);\r\n  Trunk = Trunk(I);\r\n  c = least_squares_cylinder(Points,c);\r\n\r\n  % Select the sets in the bottom part of the trunk and remove sets too\r\n  % far away form the cylinder axis (also remove far away points from sets)\r\n  I = Ce(Trunk0,3) < HBottom+min(0.04*aux.Height,0.6);\r\n  TrunkBot = Trunk0(I);\r\n  TrunkBot = union(TrunkBot,vertcat(Nei{TrunkBot}));\r\n  TrunkBot = union(TrunkBot,vertcat(Nei{TrunkBot}));\r\n  n = length(TrunkBot);\r\n  Keep = true(n,1); % Keep sets that are close enough the axis\r\n  a = max(0.06,0.2*c.radius);\r\n  b = max(0.04,0.15*c.radius);\r\n  for i = 1:n\r\n    d = distances_to_line(Ce(TrunkBot(i),:),c.axis,c.start);\r\n    if d < c.radius+a\r\n      B = Bal{Trunk(i)};\r\n      d = distances_to_line(P(B,:),c.axis,c.start);\r\n      I = d < c.radius+b;\r\n      Bal{Trunk(i)} = B(I);\r\n    else\r\n      Keep(i) = false;\r\n    end\r\n  end\r\n  TrunkBot = TrunkBot(Keep);\r\n\r\n  % Select the above part of the trunk and combine with the bottom\r\n  I = Ce(Trunk0,3) > HBottom+min(0.03*aux.Height,0.45);\r\n  Trunk = Trunk0(I);\r\n  Trunk = union(Trunk,vertcat(Nei{Trunk}));\r\n  Trunk = union(Trunk,TrunkBot);\r\n\r\n  BaseHeight = min(1.5,0.02*aux.Height);\r\n  % Determine the base\r\n  Bot = min(Ce(Trunk,3));\r\n  J = Ce(Trunk,3) < Bot+BaseHeight;\r\n  Base = Trunk(J);\r\n\r\n  % Determine \"Forb\", i.e, ground and non-tree sets by expanding Trunk\r\n  % as much as possible\r\n  Trunk = union(Trunk,vertcat(Nei{Trunk}));\r\n  Forb = aux.Fal;\r\n  Ground = setdiff(vertcat(Nei{Base}),Trunk);\r\n  Ground = setdiff(union(Ground,vertcat(Nei{Ground})),Trunk);\r\n  Forb(Ground) = true;\r\n  Forb(Base) = false;\r\n  Add = Forb;\r\n  while any(Add)\r\n    Add(vertcat(Nei{Add})) = true;\r\n    Add(Forb) = false;\r\n    Add(Trunk) = false;\r\n    Forb(Add) = true;\r\n  end\r\n\r\n  % Try to expand the \"Forb\" more by adding all the bottom sets\r\n  Bot = min(Ce(Trunk,3));\r\n  Ground = Ce(:,3) < Bot+0.03*aux.Height;\r\n  Forb(Ground) = true;\r\n  Forb(Trunk) = false;\r\n  cover.ball = Bal;\r\nend\r\n\r\nend % End of function\r\n\r\n\r\nfunction [Trunk,cover] = define_trunk(cover,aux,Base,Forb,inputs)\r\n\r\n% This function tries to make sure that likely \"route\" of the trunk from\r\n% the bottom to the top is connected. However, this does not mean that the\r\n% final trunk follows this \"route\".\r\n\r\nNei = cover.neighbor;\r\nCe = aux.Ce;\r\n% Determine the output \"Trunk\" which indicates which sets are part of\r\n% likely trunk\r\nTrunk = aux.Fal;\r\nTrunk(Base) = true;\r\n% Expand Trunk from the base above with neighbors as long as possible\r\nExp = Base; % the current \"top\" of Trunk\r\n% select the unique neighbors of Exp\r\nExp = unique_elements([Exp; vertcat(Nei{Exp})],aux.Fal);\r\nI = Trunk(Exp);\r\nJ = Forb(Exp);\r\nExp = Exp(~I|~J); % Only non forbidden sets that are not already in Trunk\r\nTrunk(Exp) = true; % Add the expansion Exp to Trunk\r\nL = 0.25; % maximum height difference in Exp from its top to bottom\r\nH = max(Ce(Trunk,3))-L; % the minimum bottom heigth for the current Exp\r\n% true as long as the expansion is possible with original neighbors:\r\nFirstMod = true;\r\nwhile ~isempty(Exp)\r\n  % Expand Trunk similarly as above as long as possible\r\n  H0 = H;\r\n  Exp0 = Exp;\r\n  Exp = union(Exp,vertcat(Nei{Exp}));\r\n  I = Trunk(Exp);\r\n  Exp = Exp(~I);\r\n  I = Ce(Exp,3) >= H;\r\n  Exp = Exp(I);\r\n  Trunk(Exp) = true;\r\n  if ~isempty(Exp)\r\n    H = max(Ce(Exp,3))-L;\r\n  end\r\n\r\n  % If the expansion Exp is empty and the top of the tree is still over 5\r\n  % meters higher, then search new neighbors from above\r\n  if (isempty(Exp) || H < H0+inputs.PatchDiam1/2) && H < aux.Height-5\r\n\r\n    % Generate rectangular partition of the sets\r\n    if FirstMod\r\n      FirstMod = false;\r\n      % The vertices of the rectangle containing C\r\n      Min = double(min(Ce(:,1:2)));\r\n      Max = double(max(Ce(:,1:2)));\r\n      nb = size(Ce,1);\r\n\r\n      % Number of rectangles with edge length \"E\" in the plane\r\n      EdgeLenth = 0.2;\r\n      NRect = double(ceil((Max-Min)/EdgeLenth)+1);\r\n\r\n      % Calculates the rectangular-coordinates of the points\r\n      px = floor((Ce(:,1)-Min(1))/EdgeLenth)+1;\r\n      py = floor((Ce(:,2)-Min(2))/EdgeLenth)+1;\r\n\r\n      % Sorts the points according a lexicographical order\r\n      LexOrd = [px py-1]*[1 NRect(1)]';\r\n      [LexOrd,SortOrd] = sort(LexOrd);\r\n\r\n      Partition = cell(NRect(1),NRect(2));\r\n      p = 1; % The index of the point under comparison\r\n      while p <= nb\r\n        t = 1;\r\n        while (p+t <= nb) && (LexOrd(p) == LexOrd(p+t))\r\n          t = t+1;\r\n        end\r\n        q = SortOrd(p);\r\n        J = SortOrd(p:p+t-1);\r\n        Partition{px(q),py(q)} = J;\r\n        p = p+t;\r\n      end\r\n    end\r\n\r\n    % Select the region that is connected to a set above it\r\n    if ~isempty(Exp)\r\n      Region = Exp;\r\n    else\r\n      Region = Exp0;\r\n    end\r\n\r\n    % Select the minimum and maximum rectangular coordinate of the\r\n    % region\r\n    X1 = min(px(Region));\r\n    if X1 <= 2\r\n      X1 = 3;\r\n    end\r\n    X2 = max(px(Region));\r\n    if X2 >= NRect(1)-1\r\n      X2 = NRect(1)-2;\r\n    end\r\n    Y1 = min(py(Region));\r\n    if Y1 <= 2\r\n      Y1 = 3;\r\n    end\r\n    Y2 = max(py(Region));\r\n    if Y2 >= NRect(2)-1\r\n      Y2 = NRect(2)-2;\r\n    end\r\n\r\n    % Select the sets in the 2 meter layer above the region\r\n    sets = Partition(X1-2:X2+2,Y1-2:Y2+2);\r\n    sets = vertcat(sets{:});\r\n    K = aux.Fal;\r\n    K(sets) = true; % the potential sets\r\n    I = Ce(:,3) > H;\r\n    J = Ce(:,3) < H+2;\r\n    I = I&J&K;\r\n    I(Trunk) = false; % Must be non-Trunk sets\r\n    SetsAbove = aux.Ind(I);\r\n\r\n    % Search the closest connection between Region and SetsAbove that\r\n    % is enough upward sloping (angle to the vertical has cosine larger\r\n    % than 0.7)\r\n    if ~isempty(SetsAbove)\r\n      % Compute the distances and cosines of the connections\r\n      n = length(Region);\r\n      m = length(SetsAbove);\r\n      Dist = zeros(n,m);\r\n      Cos = zeros(n,m);\r\n      for i = 1:n\r\n        V = mat_vec_subtraction(Ce(SetsAbove,:),Ce(Region(i),:));\r\n        Len = sum(V.*V,2);\r\n        v = normalize(V);\r\n        Dist(i,:) = Len';\r\n        Cos(i,:) = v(:,3)';\r\n      end\r\n      I = Cos > 0.7; % select those connection with large enough cosines\r\n      % if not any, search with smaller cosines\r\n      t = 0;\r\n      while ~any(I)\r\n        t = t+1;\r\n        I = Cos > 0.7-t*0.05;\r\n      end\r\n      % Search the minimum distance\r\n      Dist(~I) = 3;\r\n      if n > 1 && m > 1\r\n        [d,I] = min(Dist);\r\n        [~,J] = min(d);\r\n        I = I(J);\r\n      elseif n == 1 && m > 1\r\n        [~,J] = min(Dist);\r\n        I = 1;\r\n      elseif m == 1 && n < 1\r\n        [~,I] = min(Dist);\r\n        J = 1;\r\n      else\r\n        I = 1; % the set in component to be connected\r\n        J = 1; % the set in \"trunk\" to be connected\r\n      end\r\n\r\n      % Join to \"SetsAbove\"\r\n      I = Region(I);\r\n      J = SetsAbove(J);\r\n      % make the connection\r\n      Nei{I} = [Nei{I}; J];\r\n      Nei{J} = [Nei{J}; I];\r\n\r\n      % Expand \"Trunk\" again\r\n      Exp = union(Region,vertcat(Nei{Region}));\r\n      I = Trunk(Exp);\r\n      Exp = Exp(~I);\r\n      I = Ce(Exp,3) >= H;\r\n      Exp = Exp(I);\r\n      Trunk(Exp) = true;\r\n      H = max(Ce(Exp,3))-L;\r\n    end\r\n  end\r\nend\r\ncover.neighbor = Nei;\r\n\r\nend % End of function\r\n\r\n\r\nfunction [Trunk,cover] = define_main_branches(cover,segment,aux,inputs)\r\n\r\n% If previous segmentation exists, then use it to make the sets in its main\r\n% branches (stem and first (second or even up to third) order branches)\r\n% connected. This ensures that similar branching structure as in the\r\n% existing segmentation is possible.\r\n\r\nBal = cover.ball;\r\nNei = cover.neighbor;\r\nCe = aux.Ce;\r\n% Determine sets in the main branches of previous segmentation\r\nnb = size(Bal,1);\r\nMainBranches = zeros(nb,1);\r\nSegmentOfPoint = segment.SegmentOfPoint;\r\n% Determine which branch indexes define the main branches\r\nMainBranchIndexes = false(max(SegmentOfPoint),1);\r\nMainBranchIndexes(1) = true;\r\nMainBranchIndexes(segment.branch1indexes) = true;\r\nMainBranchIndexes(segment.branch2indexes) = true;\r\nMainBranchIndexes(segment.branch3indexes) = true;\r\nfor i = 1:nb\r\n  BranchInd = nonzeros(SegmentOfPoint(Bal{i}));\r\n  if ~isempty(BranchInd)\r\n    ind = min(BranchInd);\r\n    if MainBranchIndexes(ind)\r\n      MainBranches(i) = min(BranchInd);\r\n    end\r\n  end\r\nend\r\n\r\n% Define the trunk sets\r\nTrunk = aux.Fal;\r\nTrunk(MainBranches > 0) = true;\r\n\r\n% Update the neighbors to make the main branches connected\r\n[Par,CC] = cubical_partition(Ce,3*inputs.PatchDiam2Max,10);\r\nSets = zeros(aux.nb,1,'uint32');\r\nBI = max(MainBranches);\r\nN = size(Par);\r\nfor i = 1:BI\r\n  if MainBranchIndexes(i)\r\n    Branch = MainBranches == i; % The sets forming branch \"i\"\r\n    % the connected components of \"Branch\":\r\n    Comps = connected_components(Nei,Branch,1,aux.Fal);\r\n    n = size(Comps,1);\r\n    % Connect the components to each other as long as there are more than\r\n    % one component\r\n    while n > 1\r\n      for j = 1:n\r\n        comp = Comps{j};\r\n        NC = length(comp);\r\n\r\n        % Determine branch sets closest to the component\r\n        c = unique(CC(comp,:),'rows');\r\n        m = size(c,1);\r\n        t = 0;\r\n        NearSets = zeros(0,1);\r\n        while isempty(NearSets)\r\n          NearSets = aux.Fal;\r\n          t = t+1;\r\n          for k = 1:m\r\n            x1 = max(1,c(k,1)-t);\r\n            x2 = min(c(k,1)+t,N(1));\r\n            y1 = max(1,c(k,2)-t);\r\n            y2 = min(c(k,2)+t,N(2));\r\n            z1 = max(1,c(k,3)-t);\r\n            z2 = min(c(k,3)+t,N(3));\r\n            balls0 = Par(x1:x2,y1:y2,z1:z2);\r\n            if t == 1\r\n              balls = vertcat(balls0{:});\r\n            else\r\n              S = cellfun('length',balls0);\r\n              I = S > 0;\r\n              S = S(I);\r\n              balls0 = balls0(I);\r\n              stop = cumsum(S);\r\n              start = [0; stop]+1;\r\n              for l = 1:length(stop)\r\n                Sets(start(l):stop(l)) = balls0{l};\r\n              end\r\n              balls = Sets(1:stop(l));\r\n            end\r\n            I = Branch(balls);\r\n            balls = balls(I);\r\n            NearSets(balls) = true;\r\n          end\r\n          NearSets(comp) = false; % Only the non-component cover sets\r\n          NearSets = aux.Ind(NearSets);\r\n        end\r\n\r\n        % Determine the closest sets for \"comp\"\r\n        if ~isempty(NearSets)\r\n          d = pdist2(Ce(comp,:),Ce(NearSets,:));\r\n          if NC == 1 && length(NearSets) == 1\r\n            IU = 1; % the set in component to be connected\r\n            JU = 1; % the set in \"trunk\" to be connected\r\n          elseif NC == 1\r\n            [du,JU] = min(d);\r\n            IU = 1;\r\n          elseif length(NearSets) == 1\r\n            [du,IU] = min(d);\r\n            JU = 1;\r\n          else\r\n            [d,IU] = min(d);\r\n            [du,JU] = min(d);\r\n            IU = IU(JU);\r\n          end\r\n\r\n          % Join to the closest component\r\n          I = comp(IU);\r\n          J = NearSets(JU);\r\n          % make the connection\r\n          Nei{I} = [Nei{I}; J];\r\n          Nei{J} = [Nei{J}; I];\r\n        end\r\n      end\r\n\r\n      Comps = connected_components(Nei,Branch,1,aux.Fal);\r\n      n = size(Comps,1);\r\n    end\r\n  end\r\nend\r\n\r\n% Update the neigbors to connect 1st-order branches to the stem\r\nStem = MainBranches == 1;\r\nStem = aux.Ind(Stem);\r\nMainBranchIndexes = false(max(SegmentOfPoint),1);\r\nMainBranchIndexes(segment.branch1indexes) = true;\r\nBI = max(segment.branch1indexes);\r\nif isempty(BI)\r\n  BI = 0;\r\nend\r\nfor i = 2:BI\r\n  if MainBranchIndexes(i)\r\n    Branch = MainBranches == i;\r\n    Branch = aux.Ind(Branch);\r\n    if ~isempty(Branch)\r\n      Neigbors = MainBranches(vertcat(Nei{Branch})) == 1;\r\n      if ~any(Neigbors)\r\n        d = pdist2(Ce(Branch,:),Ce(Stem,:));\r\n        if length(Branch) > 1 && length(Stem) > 1\r\n          [d,I] = min(d);\r\n          [d,J] = min(d);\r\n          I = I(J);\r\n        elseif length(Branch) == 1 && length(Stem) > 1\r\n          [d,J] = min(d);\r\n          I = 1;\r\n        elseif length(Stem) == 1 && length(Branch) > 1\r\n          [d,I] = min(d);\r\n          J = 1;\r\n        elseif length(Branch) == 1 && length(Stem) == 1\r\n          I = 1; % the set in component to be connected\r\n          J = 1; % the set in \"trunk\" to be connected\r\n        end\r\n\r\n        % Join the Branch to Stem\r\n        I = Branch(I);\r\n        J = Stem(J);\r\n        Nei{I} = [Nei{I}; J];\r\n        Nei{J} = [Nei{J}; I];\r\n      end\r\n    end\r\n  end\r\nend\r\ncover.neighbor = Nei;\r\n\r\n% Check if the trunk is still in mutliple components and select the bottom\r\n% component to define \"Trunk\":\r\n[comps,cs] = connected_components(cover.neighbor,Trunk,aux.Fal);\r\nif length(cs) > 1\r\n  [cs,I] = sort(cs,'descend');\r\n  comps = comps(I);\r\n  Stem = MainBranches == 1;\r\n  Trunk = aux.Fal;\r\n  i = 1;\r\n  C = comps{i};\r\n  while i <= length(cs) && ~any(Stem(C))\r\n    i = i+1;\r\n    C = comps{i};\r\n  end\r\n  Trunk(C) = true;\r\nend\r\n\r\n\r\nend % End of function\r\n\r\n\r\nfunction [cover,Forb] = make_tree_connected(cover,aux,Forb,Base,Trunk,inputs)\r\n\r\n% Update neighbor-relation for whole tree such that the whole tree is one\r\n% connected component\r\n\r\nNei = cover.neighbor;\r\nCe = aux.Ce;\r\n% Expand trunk as much as possible\r\nTrunk(Forb) = false;\r\nExp = Trunk;\r\nwhile any(Exp)\r\n  Exp(vertcat(Nei{Exp})) = true;\r\n  Exp(Trunk) = false;\r\n  Exp(Forb) = false;\r\n  Exp(Base) = false;\r\n  Trunk(Exp) = true;\r\nend\r\n\r\n% Define \"Other\", sets not yet connected to trunk or Forb\r\nOther = ~aux.Fal;\r\nOther(Forb) = false;\r\nOther(Trunk) = false;\r\nOther(Base) = false;\r\n\r\n% Determine parameters on the extent of the \"Nearby Space\" and acceptable\r\n% component size\r\n% cell size for \"Nearby Space\" = k0 times PatchDiam:\r\nk0 = min(10,ceil(0.2/inputs.PatchDiam1));\r\n% current cell size, increases by k0 every time when new connections cannot\r\n% be made:\r\nk = k0;\r\nif inputs.OnlyTree\r\n  Cmin = 0;\r\nelse\r\n  Cmin = ceil(0.1/inputs.PatchDiam1);  % minimum accepted component size,\r\n  % smaller ones are added to Forb, the size triples every round\r\nend\r\n\r\n% Determine the components of \"Other\"\r\nif any(Other)\r\n  Comps = connected_components(Nei,Other,1,aux.Fal);\r\n  nc = size(Comps,1);\r\n  NonClassified = true(nc,1);\r\n  %plot_segs(P,Comps,6,1,cover.ball)\r\n  %pause\r\nelse\r\n  NonClassified = false;\r\nend\r\n\r\nbottom = min(Ce(Base,3));\r\n% repeat search and connecting as long as \"Other\" sets exists\r\nwhile any(NonClassified)\r\n  npre = nnz(NonClassified); % number of \"Other\" sets before new connections\r\n  again = true; % check connections again with same \"distance\" if true\r\n\r\n  % Partition the centers of the cover sets into cubes with size k*dmin\r\n  [Par,CC] = cubical_partition(Ce,k*inputs.PatchDiam1);\r\n  Neighbors = cell(nc,1);\r\n  Sizes = zeros(nc,2);\r\n  Pass = true(nc,1);\r\n  first_round = true;\r\n  while again\r\n    % Check each component: part of \"Tree\" or \"Forb\"\r\n    for i = 1:nc\r\n      if NonClassified(i) && Pass(i)\r\n        comp = Comps{i}; % candidate component for joining to the tree\r\n\r\n        % If the component is neighbor of forbidden sets, remove it\r\n        J = Forb(vertcat(Nei{comp}));\r\n        if any(J)\r\n          NonClassified(i) = false;\r\n          Forb(comp) = true;\r\n          Other(comp) = false;\r\n        else\r\n          % Other wise check nearest sets for a connection\r\n          NC = length(comp);\r\n          if first_round\r\n\r\n            % Select the cover sets the nearest to the component\r\n            c = unique(CC(comp,:),'rows');\r\n            m = size(c,1);\r\n            B = cell(m,1);\r\n            for j = 1:m\r\n              balls = Par(c(j,1)-1:c(j,1)+1,...\r\n                c(j,2)-1:c(j,2)+1,c(j,3)-1:c(j,3)+1);\r\n              B{j} = vertcat(balls{:});\r\n            end\r\n            NearSets = vertcat(B{:});\r\n            % Only the non-component cover sets\r\n            aux.Fal(comp) = true;\r\n            I = aux.Fal(NearSets);\r\n            NearSets = NearSets(~I);\r\n            aux.Fal(comp) = false;\r\n            NearSets = unique(NearSets);\r\n            Neighbors{i} = NearSets;\r\n            if isempty(NearSets)\r\n              Pass(i) = false;\r\n            end\r\n            % No \"Other\" sets\r\n            I = Other(NearSets);\r\n            NearSets = NearSets(~I);\r\n          else\r\n            NearSets = Neighbors{i};\r\n            % No \"Other\" sets\r\n            I = Other(NearSets);\r\n            NearSets = NearSets(~I);\r\n          end\r\n\r\n          % Select different class from NearSets\r\n          I = Trunk(NearSets);\r\n          J = Forb(NearSets);\r\n          trunk = NearSets(I); % \"Trunk\" sets\r\n          forb = NearSets(J); % \"Forb\" sets\r\n          if length(trunk) ~= Sizes(i,1) || length(forb) ~= Sizes(i,2)\r\n            Sizes(i,:) = [length(trunk) length(forb)];\r\n\r\n            % If large component is tall and close to ground, then\r\n            % search the connection near the component's bottom\r\n            if NC > 100\r\n              hmin = min(Ce(comp,3));\r\n              H = max(Ce(comp,3))-hmin;\r\n              if H > 5 && hmin < bottom+5\r\n                I = Ce(NearSets,3) < hmin+0.5;\r\n                NearSets = NearSets(I);\r\n                I = Trunk(NearSets);\r\n                J = Forb(NearSets);\r\n                trunk = NearSets(I); % \"Trunk\" sets\r\n                forb = NearSets(J); % \"Forb\" sets\r\n              end\r\n            end\r\n\r\n            % Determine the closest sets for \"trunk\"\r\n            if ~isempty(trunk)\r\n              d = pdist2(Ce(comp,:),Ce(trunk,:));\r\n              if NC == 1 && length(trunk) == 1\r\n                dt = d; % the minimum distance\r\n                IC = 1; % the set in component to be connected\r\n                IT = 1; % the set in \"trunk\" to be connected\r\n              elseif NC == 1\r\n                [dt,IT] = min(d);\r\n                IC = 1;\r\n              elseif length(trunk) == 1\r\n                [dt,IC] = min(d);\r\n                IT = 1;\r\n              else\r\n                [d,IC] = min(d);\r\n                [dt,IT] = min(d);\r\n                IC = IC(IT);\r\n              end\r\n            else\r\n              dt = 700;\r\n            end\r\n\r\n            % Determine the closest sets for \"forb\"\r\n            if ~isempty(forb)\r\n              d = pdist2(Ce(comp,:),Ce(forb,:));\r\n              df = min(d);\r\n              if length(df) > 1\r\n                df = min(df);\r\n              end\r\n            else\r\n              df = 1000;\r\n            end\r\n\r\n            % Determine what to do with the component\r\n            if (dt > 12 && dt < 100) || (NC < Cmin && dt > 0.5 && dt < 10)\r\n              % Remove small isolated component\r\n              Forb(comp) = true;\r\n              Other(comp) = false;\r\n              NonClassified(i) = false;\r\n            elseif 3*df < dt || (df < dt && df > 0.25)\r\n              % Join the component to \"Forb\"\r\n              Forb(comp) = true;\r\n              Other(comp) = false;\r\n              NonClassified(i) = false;\r\n            elseif (df == 1000 && dt == 700) || dt > k*inputs.PatchDiam1\r\n              % Isolated component, do nothing\r\n            else\r\n              % Join to \"Trunk\"\r\n              I = comp(IC);\r\n              J = trunk(IT);\r\n              Other(comp) = false;\r\n              Trunk(comp) = true;\r\n              NonClassified(i) = false;\r\n              % make the connection\r\n              Nei{I} = [Nei{I}; J];\r\n              Nei{J} = [Nei{J}; I];\r\n            end\r\n          end\r\n        end\r\n      end\r\n    end\r\n    first_round = false;\r\n    % If \"Other\" has decreased, do another check with same \"distance\"\r\n    if nnz(NonClassified) < npre\r\n      again = true;\r\n      npre = nnz(NonClassified);\r\n    else\r\n      again = false;\r\n    end\r\n  end\r\n  k = k+k0; % increase the cell size of the nearby search space\r\n  Cmin = 3*Cmin; % increase the acceptable component size\r\nend\r\nForb(Base) = false;\r\ncover.neighbor = Nei;\r\n\r\nend % End of function\r\n\r\n"
  },
  {
    "path": "src/make_models.m",
    "content": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction QSMs = make_models(dataname,savename,Nmodels,inputs)\n\n% ---------------------------------------------------------------------\n% MAKE_MODELS.M       Makes QSMs of given point clouds.\n%\n% Version 1.1.0\n% Latest update     9 May 2022\n%\n% Copyright (C) 2013-2022 Pasi Raumonen\n% ---------------------------------------------------------------------\n%\n% Makes QSMs of given point clouds specified by the \"dataname\" and by the\n% other inputs. The results are saved into file named \"savename\".\n% Notice, the code does not save indivual QSM runs into their own .mat or\n% .txt files but saves all models into one big .mat file.\n%\n% Inputs:\n% dataname      String specifying the .mat-file containing the point\n%                   clouds that are used for the QSM reconstruction.\n% savename      String, the name of the file where the QSMs are saved\n% Nmodels       (Optional) Number of models generated for each input\n%                   (cloud and input parameters). Default value is 5.\n% inputs        (Optional) The input parameters structure. Can be defined\n%                   below as part of this code. Can also be given as a\n%                   structure array where each tree gets its own, possibly\n%                   uniquely, defined parameters (e.g. optimal parameters)\n%                   but each tree has to have same number of parameter values.\n%\n% Output:\n% QSMs          Structure array containing all the QSMs generated\n% ---------------------------------------------------------------------\n\n% Changes from version 1.1.0 to 1.1.1, 18 Aug 2020:\n% 1) Removed the inputs \"lcyl\" and \"FilRad\" from the inputs and the\n%    calculations of number of input parameters\n\n% Changes from version 1.0.0 to 1.1.0, 03 Oct 2019:\n% 1) Added try-catch structure where \"treeqsm\" is called, so that if there\n%    is an error during the reconstruction process of one tree, then the\n%    larger process of making multiple QSMs from multiple tree is not\n%    stopped.\n% 2) Changed the way the data is loaded. Previously all the data was\n%    loaded into workspace, now only one point cloud is in the workspace.\n% 3) Corrected a bug where incomplete QSM was saved as complete QSM\n% 4) Changed where the input-structure for each tree is reconstructed\n\nif nargin < 2\n  disp('Not enough inputs, no models generated!')\n  QSMs =  struct([]);\n  return\nend\n\nif nargin == 2\n  Nmodels = 5; % Number of models per inputs, usually about 5 models is enough\nend\n\n%% Define the parameter values\nif nargin == 3 || nargin == 2\n  % The following parameters can be varied and should be optimised\n  % (each can have multiple values):\n  % Patch size of the first uniform-size cover:\n  inputs.PatchDiam1 = [0.08 0.1];\n  % Minimum patch size of the cover sets in the second cover:\n  inputs.PatchDiam2Min = [0.015 0.025];\n  % Maximum cover set size in the stem's base in the second cover:\n  inputs.PatchDiam2Max = [0.06 0.08];\n\n  % The following parameters can be varied and but usually can be kept as\n  % shown (i.e. as little bigger than PatchDiam parameters):\n  % Ball radius used for the first uniform-size cover generation:\n  inputs.BallRad1 = inputs.PatchDiam1+0.02;\n  % Maximum ball radius used for the second cover generation:\n  inputs.BallRad2 = inputs.PatchDiam2Max+0.01;\n\n  % The following parameters can be usually kept fixed as shown:\n  inputs.nmin1 = 3; % Minimum number of points in BallRad1-balls, good value is 3\n  inputs.nmin2 = 1; % Minimum number of points in BallRad2-balls, good value is 1\n  inputs.OnlyTree = 1; % If \"1\", then point cloud contains points only from the tree\n  inputs.Tria = 0; % If \"1\", then triangulation produces\n  inputs.Dist = 1; % If \"1\", then computes the point-model distances\n\n  % Different cylinder radius correction options for modifying too large and\n  % too small cylinders:\n  % Traditional TreeQSM choices:\n  % Minimum cylinder radius, used particularly in the taper corrections:\n  inputs.MinCylRad = 0.0025;\n  % Child branch cylinders radii are always smaller than the parent\n  % branche's cylinder radii:\n  inputs.ParentCor = 1;\n  % Use partially linear (stem) and parabola (branches) taper corrections:\n  inputs.TaperCor = 1;\n  % Growth volume correction approach introduced by Jan Hackenberg,\n  % allometry: GrowthVol = a*Radius^b+c\n  % Use growth volume correction:\n  inputs.GrowthVolCor = 0;\n  % fac-parameter of the growth vol. approach, defines upper and lower\n  % boundary:\n  inputs.GrowthVolFac = 2.5;\n\n  inputs.name = 'test';\n  inputs.tree = 0;\n  inputs.plot = 0;\n  inputs.savetxt = 0;\n  inputs.savemat = 0;\n  inputs.disp = 0;\nend\n\n% Compute the number of input parameter combinations\nin = inputs(1);\nninputs = prod([length(in.PatchDiam1) length(in.PatchDiam2Min)...\n  length(in.PatchDiam2Max)]);\n\n%% Load data\nmatobj = matfile([dataname,'.mat']);\nnames = fieldnames(matobj);\ni = 1;\nn = max(size(names));\nwhile i <= n && ~strcmp(names{i,:},'Properties')\n  i = i+1;\nend\nI = (1:1:n);\nI = setdiff(I,i);\nnames = names(I,1);\nnames = sort(names);\nnt = max(size(names)); % number of trees/point clouds\n\n%% make the models\nQSMs = struct('cylinder',{},'branch',{},'treedata',{},'rundata',{},...\n  'pmdistance',{},'triangulation',{});\n\n% Generate Inputs struct that contains the input parameters for each tree\nif max(size(inputs)) == 1\n  for i = 1:nt\n    Inputs(i) = inputs;\n    Inputs(i).name = names{i};\n    Inputs(i).tree = i;\n    Inputs(i).plot = 0;\n    Inputs(i).savetxt = 0;\n    Inputs(i).savemat = 0;\n    Inputs(i).disp = 0;\n  end\nelse\n  Inputs = inputs;\nend\n\nm = 1;\nfor t = 1:nt % trees\n  disp(['Modelling tree ',num2str(t),'/',num2str(nt),' (',Inputs(t).name,'):'])\n  P = matobj.(Inputs(t).name);\n  j = 1; % model number under generation, make \"Nmodels\" models per tree\n  inputs = Inputs(t);\n  while j <= Nmodels % generate N models per input\n    k = 1;\n    n0 = 0;\n    inputs.model = j;\n    while k <= 5 % try up to five times to generate non-empty models\n      try\n        QSM = treeqsm(P,inputs);\n      catch\n        QSM = struct('cylinder',{},'branch',{},'treedata',{},...\n          'rundata',{},'pmdistance',{},'triangulation',{});\n        QSM(ninputs).treedata = 0;\n      end\n\n      n = max(size(QSM));\n      Empty = false(n,1);\n      for b = 1:n\n        if isempty(QSM(b).branch)\n          Empty(b) = true;\n        end\n      end\n      if n < ninputs || any(Empty)\n        n = nnz(~Empty);\n        k = k+1;\n        if n >= n0\n          qsm = QSM(~Empty);\n          n0 = n;\n        end\n      else\n        % Succesfull models generated\n        QSMs(m:m+n-1) = QSM;\n        m = m+n;\n        k = 10;\n      end\n    end\n    if k == 6\n      disp('Incomplete run!!')\n      QSMs(m:m+n0-1) = qsm;\n      m = m+n0;\n    end\n    j = j+1;\n  end\n  stri = ['results/',savename];\n  save(stri,'QSMs')\nend\n"
  },
  {
    "path": "src/make_models_parallel.m",
    "content": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction QSMs = make_models_parallel(dataname,savename,Nmodels,inputs)\n\n% ---------------------------------------------------------------------\n% MAKE_MODELS.M       Makes QSMs of given point clouds.\n%\n% Version 1.1.2\n% Latest update     9 May 2022\n%\n% Copyright (C) 2013-2022 Pasi Raumonen\n% ---------------------------------------------------------------------\n%\n% Makes QSMs of given point clouds specified by the \"dataname\" and by the\n% other inputs. The results are saved into file named \"savename\".\n% Notice, the code does not save indivual QSM runs into their own .mat or\n% .txt files but saves all models into one big .mat file. Same as\n% MAKE_MODELS but uses parfor command (requires Parallel Computing Toolbox)\n% which allows the utilization of multiple processors/cores to compute in\n% parallel number of QSMs with the same inputs.\n%\n% Inputs:\n% dataname    String specifying the .mat-file containing the point\n%               clouds that are used for the QSM reconstruction.\n% savename    String, the name of the file where the QSMs are saved\n% Nmodels     (Optional) Number of models generated for each input\n%               (cloud and input parameters). Default value is 5.\n% inputs      (Optional) The input parameters structure. Can be defined\n%               below as part of this code. Can also be given as a\n%               structure array where each tree gets its own, possibly\n%               uniquely, defined parameters (e.g. optimal parameters)\n%               but each tree has to have same number of parameter values.\n%\n% Output:\n% QSMs        Structure array containing all the QSMs generated\n% ---------------------------------------------------------------------\n\n% Changes from version 1.1.1 to 1.1.2, 18 Aug 2020:\n% 1) Removed the inputs \"lcyl\" and \"FilRad\" from the inputs and the\n%    calculations of number of input parameters\n\n% Changes from version 1.1.0 to 1.1.1, 13 Jan 2020:\n% 1) Changed \"m = m+n;\" to \"m = m+n(j);\" at the end of the function.\n\n% Changes from version 1.0.0 to 1.1.0, 03 Oct 2019:\n% 1) Added try-catch structure where \"treeqsm\" is called, so that if there\n%    is an error during the reconstruction process of one tree, then the\n%    larger process of making multiple QSMs from multiple tree is not\n%    stopped.\n% 2) Changed the way the data is loaded. Previously all the data was\n%    loaded into workspace, now only one point cloud is in the workspace.\n% 3) Corrected a bug where incomplete QSM was saved as complete QSM\n% 4) Changed where the input-structure for each tree reconstructed\n% 5) Changed the coding to separate more the results of the different\n%    parallel processes (less warnings and errors)\n\nif nargin < 2\n  disp('Not enough inputs, no models generated!')\n  QSMs =  struct([]);\n  return\nend\n\nif nargin == 2\n  Nmodels = 5; % Number of models per inputs, usually about 5 models is enough\nend\n\n%% Define the parameter values\nif nargin == 3 || nargin == 2\n  % The following parameters can be varied and should be optimised\n  % (each can have multiple values):\n  % Patch size of the first uniform-size cover:\n  inputs.PatchDiam1 = [0.08 0.15];\n  % Minimum patch size of the cover sets in the second cover:\n  inputs.PatchDiam2Min = [0.015 0.025];\n  % Maximum cover set size in the stem's base in the second cover:\n  inputs.PatchDiam2Max = [0.06 0.08];\n\n  % The following parameters can be varied and but usually can be kept as\n  % shown (i.e. as little bigger than PatchDiam parameters):\n  % Ball radius used for the first uniform-size cover generation:\n  inputs.BallRad1 = inputs.PatchDiam1+0.02;\n  % Maximum ball radius used for the second cover generation:\n  inputs.BallRad2 = inputs.PatchDiam2Max+0.01;\n\n  % The following parameters can be usually kept fixed as shown:\n  inputs.nmin1 = 3; % Minimum number of points in BallRad1-balls, good value is 3\n  inputs.nmin2 = 1; % Minimum number of points in BallRad2-balls, good value is 1\n  inputs.OnlyTree = 1; % If \"1\", then point cloud contains points only from the tree\n  inputs.Tria = 0; % If \"1\", then triangulation produces\n  inputs.Dist = 1; % If \"1\", then computes the point-model distances\n\n  % Different cylinder radius correction options for modifying too large and\n  % too small cylinders:\n  % Traditional TreeQSM choices:\n  % Minimum cylinder radius, used particularly in the taper corrections:\n  inputs.MinCylRad = 0.0025;\n  % Child branch cylinders radii are always smaller than the parent\n  % branche's cylinder radii:\n  inputs.ParentCor = 1;\n  % Use partially linear (stem) and parabola (branches) taper corrections:\n  inputs.TaperCor = 1;\n  % Growth volume correction approach introduced by Jan Hackenberg,\n  % allometry: GrowthVol = a*Radius^b+c\n  % Use growth volume correction:\n  inputs.GrowthVolCor = 0;\n  % fac-parameter of the growth vol. approach, defines upper and lower\n  % boundary:\n  inputs.GrowthVolFac = 2.5;\n\n  inputs.name = 'test';\n  inputs.tree = 0;\n  inputs.plot = 0;\n  inputs.savetxt = 0;\n  inputs.savemat = 0;\n  inputs.disp = 0;\nend\n\n% Compute the number of input parameter combinations\nin = inputs(1);\nninputs = prod([length(in.PatchDiam1) length(in.PatchDiam2Min)...\n  length(in.PatchDiam2Max)]);\n\n\n%% Load data\nmatobj = matfile([dataname,'.mat']);\nnames = fieldnames(matobj);\ni = 1;\nn = max(size(names));\nwhile i <= n && ~strcmp(names{i,:},'Properties')\n  i = i+1;\nend\nI = (1:1:n);\nI = setdiff(I,i);\nnames = names(I,1);\nnames = sort(names);\nnt = max(size(names)); % number of trees/point clouds\n\n%% make the models\nQSMs = struct('cylinder',{},'branch',{},'treedata',{},'rundata',{},...\n  'pmdistance',{},'triangulation',{});\n\n% Generate Inputs struct that contains the input parameters for each tree\nif max(size(inputs)) == 1\n  for i = 1:nt\n    Inputs(i) = inputs;\n    Inputs(i).name = names{i};\n    Inputs(i).tree = i;\n    Inputs(i).plot = 0;\n    Inputs(i).savetxt = 0;\n    Inputs(i).savemat = 0;\n    Inputs(i).disp = 0;\n  end\nelse\n  Inputs = inputs;\nend\n\nm = 1;\nfor t = 1:nt % trees\n  disp(['Modelling tree ',num2str(t),'/',num2str(nt),' (',Inputs(t).name,'):'])\n  P = matobj.(Inputs(t).name);\n  qsms = cell(Nmodels,1); % save here the accepted models\n  qsm = cell(Nmodels,1); % cell-structure to keep different models separate\n  n = ones(Nmodels,1);\n  n0 = zeros(Nmodels,1);\n  k = ones(Nmodels,1);\n  parfor j = 1:Nmodels % generate N models per input\n    inputs = Inputs(t);\n    inputs.model = j;\n    while k(j) <= 5 % try up to five times to generate non-empty models\n      try\n        qsm{j} = treeqsm(P,inputs);\n      catch\n        qsm{j} = struct('cylinder',{},'branch',{},'treedata',{},...\n          'rundata',{},'pmdistance',{},'triangulation',{});\n        qsm{j}(ninputs).treedata = 0;\n      end\n      n(j) = max(size(qsm{j}));\n      Empty = false(n(j),1);\n      for b = 1:n(j)\n        if isempty(qsm{j}(b).branch)\n          Empty(b) = true;\n        end\n      end\n      if n(j) < ninputs || any(Empty)\n        n(j) = nnz(~Empty);\n        k(j) = k(j)+1;\n        if n(j) > n0(j)\n          qsms{j} = qsm{j}(~Empty);\n          n0(j) = n(j);\n        end\n      else\n        % Successful models generated\n        qsms{j} = qsm{j};\n        k(j) = 10;\n      end\n    end\n    if k(j) == 6\n      disp('Incomplete run!!')\n    end\n  end\n  % Save the models\n  for j = 1:Nmodels\n    QSM = qsms{j};\n    a = max(size(QSM));\n    QSMs(m:m+a-1) = QSM;\n    m = m+n(j);\n  end\n  str = ['results/',savename];\n  save(str,'QSMs')\nend\n"
  },
  {
    "path": "src/plotting/plot2d.m",
    "content": "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, ylabel, \n% legends and error bars can be specied with the inputs.\n\nlw = 1.5; % linewidth\nn = size(Y,1);\nif n < 9\n    col = ['-b '; '-r '; '-g '; '-c '; '-m '; '-k '; '-y '; '-.b'];\nelse\n    col = [\n\t0.00  0.00  1.00\n\t0.00  0.50  0.00\n\t1.00  0.00  0.00\n\t0.00  0.75  0.75\n\t0.75  0.00  0.75\n\t0.75  0.75  0.00\n\t0.25  0.25  0.25\n\t0.75  0.25  0.25\n\t0.95  0.95  0.00\n\t0.25  0.25  0.75\n\t0.75  0.75  0.75\n\t0.00  1.00  0.00\n\t0.76  0.57  0.17\n\t0.54  0.63  0.22\n\t0.34  0.57  0.92\n\t1.00  0.10  0.60\n\t0.88  0.75  0.73\n\t0.10  0.49  0.47\n    0.66  0.34  0.65\n    0.99  0.41  0.23];\n    if n > 20\n        k = ceil(n/20);\n        col = repmat(col,[k 1]);\n    end\nend\nfigure(fig)\nif nargin <= 7\n    % plots without errorbars\n    if ~iscell(Y)\n        if ~isempty(X)\n            if n < 9\n                h = plot(X(1,:),Y(1,:),'-b','Linewidth',lw);\n            else\n                h = plot(X(1,:),Y(1,:),'Color',col(1,:),'Linewidth',lw);\n            end\n        else\n            if n < 9\n                h = plot(Y(1,:),'-b','Linewidth',lw);\n            else\n                h = plot(Y(1,:),'Color',col(1,:),'Linewidth',lw);\n            end\n        end\n        if n > 1\n            hold on\n            if ~isempty(X)\n                if n < 9\n                    for i = 2:n\n                        plot(X(i,:),Y(i,:),col(i,:),'Linewidth',lw)\n                    end\n                else\n                    for i = 2:n\n                        plot(X(i,:),Y(i,:),'Color',col(i,:),'Linewidth',lw)\n                    end\n                end\n            else\n                if n < 9\n                    for i = 2:n\n                        plot(Y(i,:),col(i,:),'Linewidth',lw)\n                    end\n                else\n                    for i = 2:n\n                        plot(Y(i,:),'Color',col(i,:),'Linewidth',lw)\n                    end\n                end\n            end\n            hold off\n        end\n    else\n        if ~isempty(X)\n            x = X{1};\n        end\n        y = Y{1};\n        if ~isempty(X)\n            if n < 9\n                h = plot(x,y,'-b','Linewidth',lw);\n            else\n                h = plot(x,y,'Color',col(1,:),'Linewidth',lw);\n            end\n        else\n            if n < 9\n                h = plot(y,'-b','Linewidth',lw);\n            else\n                h = plot(y,'Color',col(1,:),'Linewidth',lw);\n            end\n        end\n        if n > 1\n            hold on\n            if ~isempty(X)\n                for i = 2:n\n                    x = X{i};\n                    y = Y{i};\n                    if n < 9\n                        plot(x,y,col(i,:),'Linewidth',lw)\n                    else\n                        plot(x,y,'Color',col(i,:),'Linewidth',lw)\n                    end\n                end\n            else\n                for i = 2:n\n                    y = Y{i};\n                    if n < 9\n                        plot(y,col(i,:),'Linewidth',lw)\n                    else\n                        plot(y,'Color',col(i,:),'Linewidth',lw)\n                    end\n                end\n            end\n            hold off\n        end\n    end\n    \nelse\n    % plots with errorbars\n    if ~iscell(Y)\n        if ~isempty(X)\n            if n < 9\n                h = errorbar(X(1,:),Y(1,:),E(1,:),'-b','Linewidth',lw);\n            else\n                h = errorbar(X(1,:),Y(1,:),E(1,:),'Color',col(1,:),'Linewidth',lw);\n            end\n        else\n            if n < 9\n                h = errorbar(Y(1,:),E(1,:),'-b','Linewidth',lw);\n            else\n                h = errorbar(Y(1,:),E(1,:),'Color',col(1,:),'Linewidth',lw);\n            end\n        end\n        if n > 1\n            hold on\n            if ~isempty(X)\n                if n < 9\n                    for i = 2:n\n                        errorbar(X(i,:),Y(i,:),E(1,:),col(i,:),'Linewidth',lw)\n                    end\n                else\n                    for i = 2:n\n                        errorbar(X(i,:),Y(i,:),E(1,:),'Color',col(i,:),'Linewidth',lw)\n                    end\n                end\n            else\n                if n < 9\n                    for i = 2:n\n                        errorbar(Y(i,:),E(1,:),col(i,:),'Linewidth',lw)\n                    end\n                else\n                    for i = 2:n\n                        errorbar(Y(i,:),E(1,:),'Color',col(i,:),'Linewidth',lw)\n                    end\n                end\n            end\n            hold off\n        end\n    else\n        if ~isempty(X)\n            x = X{1};\n        end\n        y = Y{1};\n        e = E{1};\n        if ~isempty(X)\n            if n < 9\n                h = errorbar(x,y,e(1,:),'-b','Linewidth',lw);\n            else\n                h = errorbar(x,y,'Color',e(1,:),col(1,:),'Linewidth',lw);\n            end\n        else\n            if n < 9\n                h = errorbar(y,e(1,:),'-b','Linewidth',lw);\n            else\n                h = errorbar(y,e(1,:),'Color',col(1,:),'Linewidth',lw);\n            end\n        end\n        if n > 1\n            hold on\n            if ~isempty(X)\n                for i = 2:n\n                    x = X{i};\n                    y = Y{i};\n                    e = E{i};\n                    if n < 9\n                        h = errorbar(x,y,e(1,:),col(i,:),'Linewidth',lw);\n                    else\n                        h = errorbar(x,y,e(1,:),'Color',col(i,:),'Linewidth',lw);\n                    end\n                end\n            else\n                for i = 2:n\n                    y = Y{i};\n                    e = E{i};\n                    if n < 9\n                        errorbar(y,e(1,:),col(i,:),'Linewidth',lw);\n                    else\n                        errorbar(y,e(1,:),'Color',col(i,:),'Linewidth',lw);\n                    end\n                end\n            end\n            hold off\n        end\n    end\nend\n\ngrid on\nt = title(strtit);\nx = xlabel(strx);\ny = ylabel(stry);\nif nargin > 6\n    legend(leg)\nend\nset(gca,'fontsize',12)\nset(gca,'FontWeight','bold')\nset(t,'fontsize',12)\nset(t,'FontWeight','bold')\nset(x,'fontsize',12)\nset(x,'FontWeight','bold')\nset(y,'fontsize',12)\nset(y,'FontWeight','bold')"
  },
  {
    "path": "src/plotting/plot_branch_segmentation.m",
    "content": "function plot_branch_segmentation(P,cover,segment,Color,fig,ms,segind,BO)\n\n% ---------------------------------------------------------------------\n% PLOT_BRANCH_SEGMENTATION.M   Plots branch-segmented point cloud, coloring\n%                               based on branching order or branches\n%\n% Version 1.0.0\n% Latest update     13 July 2020\n%\n% Copyright (C) 2013-2020 Pasi Raumonen\n% ---------------------------------------------------------------------\n% \n% If the coloring is based on branches (Color = 'branch'), then each segment \n% is colored with unique color. If the coloring is based on branching order \n% (Color = 'order'), then Blue = trunk, Green = 1st-order branches, \n% Red = 2nd-order branches, etc.\n% \n% If segind = 1 and BO = 0, then plots the stem. If segind = 1 and BO = 1, \n% then plots the stem and the 1st-order branches. If segind = 1 and \n% BO >= maximum branching order or BO input is not given, then plots the \n% whole tree. If segind = 2 and BO is not given or it is high enough, then\n% plots the branch whose index is 2 and all its sub-branches. \n%\n% Inputs\n% P         Point cloud\n% cover     Cover sets structure\n% segment   Segments structure\n% Color     Color option, 'order' or 'branch'\n% fig       Figure number\n% ms        Marker size\n% segind    Index of the segment where the plotting of tree structure starts. \n% BO        How many branching orders are plotted. 0 = stem, 1 = 1st order, etc\n\nn = nargin;\nif n < 8\n    BO = 1000;\n    if n < 7\n        segind = 1;\n        if n < 6\n            ms = 1;\n            if n < 5\n                fig = 1;\n                if n == 3\n                    Color = 'order';\n                end\n            end\n        end\n    end\nend\n\nBal = cover.ball;\nSegs = segment.segments;\nSChi = segment.ChildSegment;\nSPar = segment.ParentSegment;\nns = max(size(Segs));\n\nif iscell(Segs{1})\n    Seg = cell(ns,1);\n    for i = 1:ns\n        m = size(Segs{i},1);\n        S = zeros(0);\n        for j = 1:m\n            s = Segs{i}(j);\n            s = s{:};\n            S = [S; s];\n        end\n        Seg{i} = S;\n    end\nelse\n    Seg = Segs;\nend\n\nif strcmp(Color,'branch')\n    Color = 1;\n    % Color the segments with unique colors\n    col = rand(ns,3);\n    for i = 2:ns\n        C = col(SPar(i),:);\n        c = col(i,:);\n        while sum(abs(C-c)) < 0.2\n            c = rand(1,3);\n        end\n        col(i,:) = c;\n    end\nelseif strcmp(Color,'order')\n    Color = 0;\n    % Color the cylinders in branches based on the branch order\n    col = [\n        0.00  0.00  1.00\n        0.00  0.50  0.00\n        1.00  0.00  0.00\n        0.00  0.75  0.75\n        0.75  0.00  0.75\n        0.75  0.75  0.00\n        0.25  0.25  0.25\n        0.75  0.25  0.25\n        0.95  0.95  0.00\n        0.25  0.25  0.75\n        0.75  0.75  0.75\n        0.00  1.00  0.00\n        0.76  0.57  0.17\n        0.54  0.63  0.22\n        0.34  0.57  0.92\n        1.00  0.10  0.60\n        0.88  0.75  0.73\n        0.10  0.49  0.47\n        0.66  0.34  0.65\n        0.99  0.41  0.23];\n    col = repmat(col,[10,1]);\nend\n\nsegments = segind;\nC = SChi{segind};\nb = 1;\norder = 1;\nwhile ~isempty(C) && b <= BO\n    b = b+1;\n    segments = [segments; C];\n    order = [order; b*ones(length(C),1)];\n    C = vertcat(SChi{C});\nend\n\nns = length(segments);\nfigure(fig)\nfor i = 1:ns\n    if i == 2\n        hold on\n    end\n    S = vertcat(Bal{Seg{segments(i)}});\n    if Color\n    % Coloring based on branch \n    plot3(P(S,1),P(S,2),P(S,3),'.','Color',col(segments(i),:),'Markersize',ms)\n    else\n    % Coloring based on branch order\n    plot3(P(S,1),P(S,2),P(S,3),'.','Color',col(order(i),:),'Markersize',ms)    \n    end\nend\nhold off\naxis equal\n"
  },
  {
    "path": "src/plotting/plot_branches.m",
    "content": "function plot_branches(P,cover,segment,fig,ms,segind,BO)\n\nn = nargin;\nif n < 7\n    BO = 1000;\n    if n < 6\n        segind = 1;\n        if n < 5\n            ms = 1;\n            if n == 3\n                fig = 1;\n            end\n        end\n    end\nend\n\nBal = cover.ball;\nSegs = segment.segments;\nSChi = segment.ChildSegment;\nSPar = segment.ParentSegment;\n\nif iscell(Segs{1})\n    ns = max(size(Segs));\n    Seg = cell(ns,1);\n    for i = 1:ns\n        m = size(Segs{i},1);\n        S = zeros(0);\n        for j = 1:m\n            s = Segs{i}(j);\n            s = s{:};\n            S = [S; s];\n        end\n        Seg{i} = S;\n    end\nelse\n    Seg = Segs;\nend\n\n% Color the segments with unique colors\ncol = rand(ns,3);\nfor i = 2:ns\n    C = col(SPar(i),:);\n    c = col(i,:);\n    while sum(abs(C-c)) < 0.2\n        c = rand(1,3);\n    end\n    col(i,:) = c;\nend\n\nsegments = segind;\nC = SChi{segind};\nb = 0;\nwhile ~isempty(C) && b <= BO\n    b = b+1;\n    segments = [segments; C];\n    C = SChi{segind};\nend\n\nns = length(segment);\nfigure(fig)\nfor i = 1:ns\n    if i == 2\n        hold on\n    end\n    S = vertcat(Bal{Seg{segments(i)}});\n    plot3(P(S,1),P(S,2),P(S,3),'.','Color',col(segments(i),:),'Markersize',ms)\nend\nhold off\n"
  },
  {
    "path": "src/plotting/plot_comparison.m",
    "content": "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 are\r\n% not in \"P1\" are plotted in red whereas the common points are plotted in\r\n% blue. \"fig\" and \"ms1\" and \"ms2\" are the figure number and marker sizes.\r\n\r\nif nargin == 3\r\n    ms1 = 3;\r\n    ms2 = 3;\r\nelseif nargin == 4\r\n    ms2 = 3;\r\nend\r\n\r\nif ms1 == 0\r\n    ms1 = 3;\r\nend\r\nif ms2 == 0\r\n    ms2 = 3;\r\nend\r\n\r\nP2 = setdiff(P2,P1,'rows');\r\n\r\nfigure(fig)\r\nif size(P1,2) == 3\r\n    plot3(P1(:,1),P1(:,2),P1(:,3),'.b','Markersize',ms1)\r\n    hold on\r\n    plot3(P2(:,1),P2(:,2),P2(:,3),'.r','Markersize',ms2)\r\nelseif size(P1,2) == 2\r\n    plot(P1(:,1),P1(:,2),'.b','Markersize',ms1)\r\n    hold on\r\n    plot(P2(:,1),P2(:,2),'.r','Markersize',ms2)\r\nend\r\nhold off\r\naxis equal"
  },
  {
    "path": "src/plotting/plot_cone_model.m",
    "content": "function plot_cone_model(cylinder,fig,nf,alp,Ind)\n\n% Plots the given cylinder model as truncated cones defined by the cylinders.\n% cylinder  Structure array containin the cylinder info \n%               (radius, length, start, axis, BranchOrder)\n% fig       Figure number\n% nf        Number of facets in the cyliders (in the thickest cylinder, \n%               scales down with radius to 4 which is the minimum)\n% alp       Alpha value (1 = no trasparency, 0 = complete transparency)\n% Ind       Indexes of cylinders to be plotted from a subset of cylinders\n%               (Optional, if not given then all cylinders are plotted)\n\n\nif isstruct(cylinder)\n    Rad = cylinder.radius;\n    Len = cylinder.length;\n    Sta = cylinder.start;\n    %Sta = mat_vec_subtraction(Sta,Sta(1,:));\n    Axe = cylinder.axis;\n    Bran = cylinder.branch;\n    PiB = cylinder.PositionInBranch;\n    nb = max(Bran);\nelse\n    Rad = cylinder(:,1);\n    Len = cylinder(:,2);\n    Sta = cylinder(:,3:5);\n    %Sta = mat_vec_subtraction(Sta,Sta(1,:));\n    Axe = cylinder(:,6:8);\n    Bran = cylinder(:,12);\n    PiB = cylinder(:,14);\n    nb = max(Bran);\nend\nif nargin == 5\n    Rad = Rad(Ind);\n    Len = Len(Ind);\n    Sta = Sta(Ind,:);\n    Axe = Axe(Ind,:);\nend\n\nnc = size(Rad,1);\n\nCir = cell(nf,2);\nfor i = 4:nf\n    Cir{i,1} = [cos((1/i:1/i:1)*2*pi)' sin((1/i:1/i:1)*2*pi)' zeros(i,1)];\n    Cir{i,2} = [(1:1:i)' (i+1:1:2*i)' [(i+2:1:2*i)'; i+1] [(2:1:i)'; 1]];\nend\n\nVert = zeros(2*nc*(nf+1),3);\nFacets = zeros(nc*(nf+1),4);\nt = 1;\nf = 1;\n\n% Scale, rotate and translate the standard cylinders\nInd = (1:1:nc)';\nfor j = 1:nb\n    I = Bran == j;\n    I = Ind(I);\n    if ~isempty(I)\n        P = PiB(I);\n        [P,J] = sort(P);\n        I = I(J);\n        n = ceil(sqrt(mean(Rad(I))/Rad(1))*nf);\n        n = min(n,nf);\n        n = max(n,4);\n        C0 = Cir{n,1};\n        m = length(I);\n        for i = 1:m\n            C = C0;\n            \n            % Scale radius\n            C(1:n,1:2) = Rad(I(i))*C(1:n,1:2);\n            if i == m\n                % Define the last circle of the branch\n                C1 = C;\n                C1(:,1:2) = min(0.005/Rad(I(i)),1)*C(:,1:2);\n            end\n            \n            % Rotate\n            if i == 1\n                ang = real(acos(Axe(I(i),3)));\n                Axis = cross([0 0 1]',Axe(I(i),:)');\n                Rot = rotation_matrix(Axis,ang);\n                C = C*Rot';\n            elseif i > 1\n                ang = real(acos(Axe(I(i),3)));\n                Axis = cross([0 0 1]',Axe(I(i),:)');\n                Rot = rotation_matrix(Axis,ang);\n                C = C*Rot';\n                %%% Should be somehow corrected so that high angles between\n                %%% cylinders do not cause narrowing the surface!!!\n                \n                \n                if i == m\n                    ang = real(acos(Axe(I(i),3)));\n                    Axis = cross([0 0 1]',Axe(I(i),:)');\n                    Rot = rotation_matrix(Axis,ang);\n                    C1 = C1*Rot';\n                end\n            end\n            \n            % Translate\n            C = mat_vec_subtraction(C,-Sta(I(i),:));\n            if i == m\n                C1 = mat_vec_subtraction(C1,-(Sta(I(i),:)+Len(I(i))*Axe(I(i),:)));\n            end\n            \n            % Save the new vertices\n            Vert(t:t+n-1,:) = C;\n            if i == m\n                t = t+n;\n                Vert(t:t+n-1,:) = C1;\n            end\n            t = t+n;\n            \n            % Define the new facets\n            if i == 1 && i == m\n                Facets(f:f+n-1,:) = Cir{n,2}+t-2*n-1;\n                f = f+n;\n            elseif i > 1 && i < m \n                Facets(f:f+n-1,:) = Cir{n,2}+t-2*n-1;\n                f = f+n;\n            elseif i > 1 && i == m\n                Facets(f:f+n-1,:) = Cir{n,2}+t-3*n-1;\n                f = f+n;\n                Facets(f:f+n-1,:) = Cir{n,2}+t-2*n-1;\n                f = f+n;\n            end\n        end\n    end\nend\n\nt = t-1;\nf = f-1;\nVert = Vert(1:t,:);\nFacets = Facets(1:f,:);\nfvd = [139/255*ones(f,1) 69/255*ones(f,1) 19/255*ones(f,1)];\n\nfigure(fig)\nplot3(Vert(1,1),Vert(1,2),Vert(1,3))\npatch('Vertices',Vert,'Faces',Facets,'FaceVertexCData',fvd,'FaceColor','flat')\nalpha(alp)\naxis equal\ngrid on\nview(-37.5,30)\n"
  },
  {
    "path": "src/plotting/plot_cylinder_model.m",
    "content": "function plot_cylinder_model(cylinder,Color,fig,nf,alp,Ind)\n\n% ---------------------------------------------------------------------\n% PLOT_CYLINDER_MODEL.M       Plots the given cylinder model\n%\n% Version 1.2.0\n% Latest update     3 Aug 2021\n%\n% Copyright (C) 2013-2021 Pasi Raumonen\n% ---------------------------------------------------------------------\n\n% Plots the cylinder model.\n% cylinder  Structure array containin the cylinder info\n%               (radius, length, start, axis, BranchOrder)\n% fig       Figure number\n% nf        Number of facets in the cyliders (in the thickest cylinder,\n%               scales down with radius to 4 which is the minimum)\n% alp       Alpha value (1 = no trasparency, 0 = complete transparency)\n% Color     If equals to \"order\", colors the cylinders based on branching\n%               order, otherwise colors each branch with unique color\n% Ind       Indexes of cylinders to be plotted from a subset of cylinders\n%               (Optional, if not given then all cylinders are plotted)\n\n% Changes from version 1.1.0 to 1.2.0, 3 Aug 2021:\n% 1) Changed the surface plot (\"patch\") so that the edges are not plotted\n%    with separate color, so the surface looks more smooth. Similarly added\n%    shading. (These are added at the end of the file)\n% 2) Added cylinder branch \"Bran\" and branch order \"BOrd\" vectors where the\n%    coloring options are defined to prevent some errors\n\n% Changes from version 1.0.0 to 1.1.0, 13 July 2020:\n% 1) Added option for choosing the coloring based either on branch order or\n%    unique color for each branch\n% 2) Removed the possibility of the input \"cylinder\" being a matrix\n% 3) Added default values for inputs\n\nn = nargin;\nif n < 5\n  alp = 1;\n  if n < 4\n    nf = 20;\n    if n < 3\n      fig = 1;\n      if n == 1\n        Color = 'order';\n      end\n    end\n  end\nend\n\nRad = cylinder.radius;\nLen = cylinder.length;\nSta = cylinder.start;\n%Sta = Sta-Sta(1,:);\nAxe = cylinder.axis;\nif strcmp(Color,'order')\n  BOrd = cylinder.BranchOrder;\n  Bran = cylinder.branch;\nend\nif strcmp(Color,'branch')\n  Bran = cylinder.branch;\n  BOrd = cylinder.BranchOrder;\nend\n\nif nargin == 6\n  Rad = Rad(Ind);\n  Len = Len(Ind);\n  Sta = Sta(Ind,:);\n  Axe = Axe(Ind,:);\n  BOrd = BOrd(Ind);\n  if strcmp(Color,'branch')\n    Bran = Bran(Ind);\n  end\nend\n\nnc = size(Rad,1); % Number of cylinder\n\nif strcmp(Color,'order')\n  Color = 1;\n  % Color the cylinders in branches based on the branch order\n  col = [\n    0.00  0.00  1.00\n    0.00  0.50  0.00\n    1.00  0.00  0.00\n    0.00  0.75  0.75\n    0.75  0.00  0.75\n    0.75  0.75  0.00\n    0.25  0.25  0.25\n    0.75  0.25  0.25\n    0.95  0.95  0.00\n    0.25  0.25  0.75\n    0.75  0.75  0.75\n    0.00  1.00  0.00\n    0.76  0.57  0.17\n    0.54  0.63  0.22\n    0.34  0.57  0.92\n    1.00  0.10  0.60\n    0.88  0.75  0.73\n    0.10  0.49  0.47\n    0.66  0.34  0.65\n    0.99  0.41  0.23];\n  col = repmat(col,[10,1]);\nelseif strcmp(Color,'branch')\n  Color = 0;\n  % Color the cylinders in branches with an unique color of each branch\n  N = double(max(Bran));\n  col = rand(N,3);\n  Par = cylinder.parent;\n  for i = 2:nc\n    if Par(i) > 0 && Bran(Par(i)) ~= Bran(i)\n      C = col(Bran(Par(i)),:);\n      c = col(Bran(i),:);\n      while sum(abs(C-c)) < 0.2\n        c = rand(1,3);\n      end\n      col(Bran(i),:) = c;\n    end\n  end\nend\n\nCir = cell(nf,2);\nfor i = 4:nf\n  B = [cos((1/i:1/i:1)*2*pi)' sin((1/i:1/i:1)*2*pi)' zeros(i,1)];\n  T = [cos((1/i:1/i:1)*2*pi)' sin((1/i:1/i:1)*2*pi)' ones(i,1)];\n  Cir{i,1} = [B; T];\n  Cir{i,2} = [(1:1:i)' (i+1:1:2*i)' [(i+2:1:2*i)'; i+1] [(2:1:i)'; 1]];\nend\n\nVert = zeros(2*nc*(nf+1),3);\nFacets = zeros(nc*(nf+1),4);\nfvd = zeros(nc*(nf+1),3);\nt = 1;\nf = 1;\n\n% Scale, rotate and translate the standard cylinders\nfor i = 1:nc\n  n = ceil(sqrt(Rad(i)/Rad(1))*nf);\n  n = min(n,nf);\n  n = max(n,4);\n  C = Cir{n,1};\n  % Scale\n  C(:,1:2) = Rad(i)*C(:,1:2);\n  C(n+1:end,3) = Len(i)*C(n+1:end,3);\n  % Rotate\n  ang = real(acos(Axe(i,3)));\n  Axis = cross([0 0 1]',Axe(i,:)');\n  Rot = rotation_matrix(Axis,ang);\n  C = (Rot*C')';\n  % Translate\n  C = mat_vec_subtraction(C,-Sta(i,:));\n  Vert(t:t+2*n-1,:) = C;\n  Facets(f:f+n-1,:) = Cir{n,2}+t-1;\n  if Color == 1\n    fvd(f:f+n-1,:) = repmat(col(BOrd(i)+1,:),[n 1]);\n  else\n    fvd(f:f+n-1,:) = repmat(col(Bran(i),:),[n 1]);\n  end\n  t = t+2*n;\n  f = f+n;\nend\nt = t-1;\nf = f-1;\nVert = Vert(1:t,:);\nFacets = Facets(1:f,:);\nfvd = fvd(1:f,:);\n\nfigure(fig)\nplot3(Vert(1,1),Vert(1,2),Vert(1,3))\npatch('Vertices',Vert,'Faces',Facets,'FaceVertexCData',fvd,'FaceColor','flat')\nalpha(alp)\naxis equal\ngrid on\nview(-37.5,30)\n\nshading flat\nlightangle(gca,-45,30)\nlighting gouraud"
  },
  {
    "path": "src/plotting/plot_cylinder_model2.m",
    "content": "function plot_cylinder_model2(cylinder,fig,nf,alp,Ind)\n\n% Plots the cylinder model.\n% cylinder  Structure array containin the cylinder info \n%               (radius, length, start, axis, BranchOrder)\n% fig       Figure number\n% nf        Number of facets in the cyliders (in the thickest cylinder, \n%               scales down with radius to 4 which is the minimum)\n% alp       Alpha value (1 = no trasparency, 0 = complete transparency)\n% Ind       Indexes of cylinders to be plotted from a subset of cylinders\n%               (Optional, if not given then all cylinders are plotted)\n\n\nRad = cylinder.radius;\nRad2 = cylinder.TopRadius;\nLen = cylinder.length;\nSta = cylinder.start;\nSta = mat_vec_subtraction(Sta,Sta(1,:));\nAxe = cylinder.axis;\nBOrd = cylinder.BranchOrder;\nif nargin == 5\n    Rad = Rad(Ind);\n    Len = Len(Ind);\n    Sta = Sta(Ind,:);\n    Axe = Axe(Ind,:);\n    BOrd = BOrd(Ind);\nend\n\nnc = size(Rad,1);\n\ncol = [\n    0.00  0.00  1.00\n    0.00  0.50  0.00\n    1.00  0.00  0.00\n    0.00  0.75  0.75\n    0.75  0.00  0.75\n    0.75  0.75  0.00\n    0.25  0.25  0.25\n    0.75  0.25  0.25\n    0.95  0.95  0.00\n    0.25  0.25  0.75\n    0.75  0.75  0.75\n    0.00  1.00  0.00\n    0.76  0.57  0.17\n    0.54  0.63  0.22\n    0.34  0.57  0.92\n    1.00  0.10  0.60\n    0.88  0.75  0.73\n    0.10  0.49  0.47\n    0.66  0.34  0.65\n    0.99  0.41  0.23];\n\nN = max(BOrd)+1;\nif N <= 20\n    col = col(1:N,:);\nelse\n    m = ceil(N/20);\n    col = repmat(col,[m,1]);\n    col = col(1:N,:);\nend\n\nCir = cell(nf,2);\nfor i = 4:nf\n    B = [cos((1/i:1/i:1)*2*pi)' sin((1/i:1/i:1)*2*pi)' zeros(i,1)];\n    T = [cos((1/i:1/i:1)*2*pi)' sin((1/i:1/i:1)*2*pi)' ones(i,1)];\n    Cir{i,1} = [B; T];\n    Cir{i,2} = [(1:1:i)' (i+1:1:2*i)' [(i+2:1:2*i)'; i+1] [(2:1:i)'; 1]];\nend\n\nVert = zeros(2*nc*(nf+1),3);\nFacets = zeros(nc*(nf+1),4);\nfvd = zeros(nc*(nf+1),3);\nt = 1;\nf = 1;\n\n% Scale, rotate and translate the standard cylinders\nfor i = 1:nc\n    n = ceil(sqrt(Rad(i)/Rad(1))*nf);\n    n = min(n,nf);\n    n = max(n,4);\n    C = Cir{n,1};\n    % Scale\n    m = size(C,1);\n    C(1:m/2,1:2) = Rad(i)*C(1:m/2,1:2);\n    C(m/2+1:m,1:2) = Rad2(i)*C(m/2+1:m,1:2);\n    C(n+1:end,3) = Len(i)*C(n+1:end,3);\n    % Rotate\n    ang = real(acos(Axe(i,3)));\n    Axis = cross([0 0 1]',Axe(i,:)');\n    Rot = rotation_matrix(Axis,ang);\n    C = (Rot*C')';\n    % Translate\n    C = mat_vec_subtraction(C,-Sta(i,:));\n    Vert(t:t+2*n-1,:) = C;\n    Facets(f:f+n-1,:) = Cir{n,2}+t-1;\n    fvd(f:f+n-1,:) = repmat(col(BOrd(i)+1,:),[n 1]);\n    t = t+2*n;\n    f = f+n;\nend\nt = t-1;\nf = f-1;\nVert = Vert(1:t,:);\nFacets = Facets(1:f,:);\nfvd = fvd(1:f,:);\n\nfigure(fig)\nplot3(Vert(1),Vert(2),Vert(3))\npatch('Vertices',Vert,'Faces',Facets,'FaceVertexCData',fvd,'FaceColor','flat')\nalpha(alp)\naxis equal\ngrid on\nview(-37.5,30)\n"
  },
  {
    "path": "src/plotting/plot_distribution.m",
    "content": "function plot_distribution(QSM,fig,rela,cumu,dis,dis2,dis3,dis4)\n\n% ---------------------------------------------------------------------\n% PLOT_DISTRIBUTION     Plots the specified distribution(s) in the \n%                           \"treedata\" field of the QSM structure array.\n%\n% Version 1.1.0\n% Latest update     3 May 2022\n%\n% Copyright (C) 2020-2022 Pasi Raumonen\n% ---------------------------------------------------------------------\n%\n% Inputs:\n% QSM       The output of treeqsm function, may contain multiple models if\n%               only one distribution. If multiple distributions are plotted, \n%               then only one model.\n% fig       Figure number\n% rela      If rela = 1, then plots relative values (%), otherwise plots \n%               absolute values\n% cumu      If cumu = 1, then plot cumulative distribution\n% dis       Distribution to be plotted, string name, e.g. 'VolCylDia'.\n%               The name string is the one used in the \"treedata\"\n% dis2      Optional, Second distribution to be plotted. Notice with more\n%               than one distribution, only one model.\n% dis3      Optional, Third distribution to be plotted\n% dis4      Optional, Fourth distribution to be plotted\n% ---------------------------------------------------------------------\n\n% Changes from version 1.0.0 to 1.1.0, 3 May 2022:\n% 1) Added new input \"cum\" for plottig the distributions as cumulative.\n% 2) Added return if distributions are empty or all zero\n\n% Generate strings for title, xlabel and ylabel:\nif strcmp(dis(1:3),'Vol')\n  str = 'volume';\n  ylab = 'Volume (L)';\nelseif strcmp(dis(1:3),'Are')\n  str = 'area';\n  ylab = 'Area (m^2)';\nelseif strcmp(dis(1:3),'Len')\n  str = 'length';\n  ylab = 'Length (m)';\nelseif strcmp(dis(1:3),'Num')\n  str = 'number';\n  ylab = 'Number';\nend\n\nif strcmp(dis(end-2:end),'Dia')\n  str2 = 'diameter';\n  xlab = 'diameter (cm)';\nelseif strcmp(dis(end-2:end),'Hei')\n  str2 = 'height';\n  xlab = 'height (m)';\nelseif strcmp(dis(end-2:end),'Ord')\n  str2 = 'order';\n  xlab = 'order';\nelseif strcmp(dis(end-2:end),'Ang')\n  str2 = 'angle';\n  xlab = 'angle (deg)';\nelseif strcmp(dis(end-2:end),'Azi')\n  str2 = 'azimuth direction';\n  xlab = 'azimuth direction (deg)';\nelseif strcmp(dis(end-2:end),'Zen')\n  str2 = 'zenith direction';\n  xlab = 'zenith direction (deg)';\nend\n\n% Collect the distributions\nif nargin == 5\n  % Multiple QSMs, one and the same distribution\n  m = max(size(QSM));\n  D = QSM(1).treedata.(dis);\n  n = size(D,2);\n  for i = 2:m\n    d = QSM(i).treedata.(dis);\n    k = size(d,2);\n    if k > n\n      n = k;\n      D(m,n) = 0;\n      D(i,1:n) = d;\n    elseif k < n\n      D(i,1:k) = d;\n    else\n      D(i,:) = d;\n    end\n  end\n  D = D(:,1:n);\nelse\n  % One QSM, multiple distributions of the same type\n  % (e.g. diameter distributions: 'NumCylDia', 'VolCylDia' and 'LenCylDia')\n  m = nargin-4;\n  D = QSM.treedata.(dis);\n  n = size(D,2);\n  if n == 0 || all(D == 0)\n    return\n  end\n  for i = 2:m\n    if i == 2\n      D(m,n) = 0;\n      D(i,:) = QSM.treedata.(dis2);\n    elseif i == 3\n      D(i,:) = QSM.treedata.(dis3);\n    else\n      D(i,:) = QSM.treedata.(dis4);\n    end\n  end\nend\n\nif rela\n  % use relative value\n  for i = 1:m\n    D(i,:) = D(i,:)/sum(D(i,:))*100;\n  end\n  ylab = 'Relative value (%)';\nend\n\nif cumu\n  % use cumulative distribution\n  D = cumsum(D,2);\nend\n\n% Generate the bar plot\nfigure(fig)\nif strcmp(dis(end-3:end),'hAzi') || strcmp(dis(end-3:end),'1Azi') || strcmp(dis(end-2:end),'Azi')\n  bar(-170:10:180,D')\nelseif strcmp(dis(end-2:end),'Zen') || strcmp(dis(end-2:end),'Ang')\n  bar(10:10:10*n,D')\nelse\n  bar(1:1:n,D')\nend\n\n% Generate the title of the plot\nif strcmp(dis(end-2:end),'Ord') && ~strcmp(dis(1:3),'Num')\n  tit = ['Branch ',str,' per branching order'];\nelseif strcmp(dis(end-2:end),'Ord')\n  tit = 'Number of branches per branching order';\nelseif strcmp(dis(1:3),'Num')\n  tit = ['Number of branches per ',str2,' class'];\nelseif strcmp(dis(end-3),'h') || strcmp(dis(end-3),'1')\n  tit = ['Branch ',str,' per ',str2,' class'];\nelse\n  tit = ['Tree segment ',str,' per ',str2,' class'];\nend\nn = nargin;\nif n > 5\n  if ~strcmp(dis(1:3),dis2(1:3))\n    if strcmp(dis(4),'C')\n      tit = 'Tree segment distribution';\n    else\n      tit = 'Branch distribution';\n    end\n  elseif n > 6\n    if ~strcmp(dis(1:3),dis3(1:3))\n      if strcmp(dis(4),'C')\n        tit = 'Tree segment distribution';\n      else\n        tit = 'Branch distribution';\n      end\n    elseif n > 7\n      if ~strcmp(dis(1:3),dis4(1:3))\n        if strcmp(dis(4),'C')\n          tit = 'Tree segment distribution';\n        else\n          tit = 'Branch distribution';\n        end\n      end\n    end\n  end\nend\ntitle(tit)\n\n% Generate the x-axis label\nif strcmp(dis(end-5:end-3),'Cyl')\n  xlab = ['Cylinder ',xlab];\nelse\n  xlab = ['Branch ',xlab];\nend\nxlabel(xlab)\n\n% Generate the y-axis label\nylabel(ylab);\n\n% Tight axes and grid lines\naxis tight\ngrid on\n\nm = max(size(QSM));\n% Add legends, if needed\nif m > 1\n  L = cell(m,1);\n  for i = 1:m\n    L{i} = ['model',num2str(i)];\n  end\n  legend(L,'location','best')\nelseif nargin > 5\n  m = nargin-4;\n  L = cell(m,1);\n  for i = 1:m\n    if i == 1\n      L{i} = dis(1:end-3);\n    elseif i == 2\n      L{i} = dis2(1:end-3);\n    elseif i == 3\n      L{i} = dis3(1:end-3);\n    else\n      L{i} = dis4(1:end-3);\n    end\n  end\n  legend(L,'location','best')\nend"
  },
  {
    "path": "src/plotting/plot_large_point_cloud.m",
    "content": "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% relative size of the subset (input \"rel\" given as in percentage points).\n%\n% Inputs:\n% P     Point cloud\n% fig   Figure number\n% ms    Marker size\n% rel   Subset size in percentage points (%). \n%           E.g. if rel = 12, then about 12 % poinst are plotted\n\nrel = 0.5/(1-rel/100); % Compute a coeffiecient\n\nI = logical(round(rel*rand(size(P,1),1)));\nplot_point_cloud(P(I,:),fig,ms)"
  },
  {
    "path": "src/plotting/plot_models_segmentations.m",
    "content": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction plot_models_segmentations(P,cover,segment,cylinder,trunk,triangulation)\n\n% ---------------------------------------------------------------------\n% PLOT_MODELS_SEGMENTATION.M   Plots the segmented point clouds and\n%                               cylinder/triangulation models\n%\n% Version 1.1.0\n% Latest update     13 July 2020\n%\n% Copyright (C) 2013-2020 Pasi Raumonen\n% ---------------------------------------------------------------------\n\n% Inputs:\n% P             Point cloud\n% cover         cover-structure array\n% segment       segment-structure array\n% cylinder      cylinder-structure array\n% trunk         point cloud of the trunk\n% triangulation triangulation-structure array\n\n% Changes from version 1.0.0 to 1.1.0, 13 July 2020:\n% 1) plots now figure 1 and 2 with two subplots; in the first the colors \n%    are based on branching order and in the second they are based on\n%    branch\n\n%% figure 1: branch-segmented point cloud \n% colors denote the branching order and branches\nfigure(1)\nsubplot(1,2,1)\nplot_branch_segmentation(P,cover,segment,'order')\nsubplot(1,2,2)\nplot_branch_segmentation(P,cover,segment,'branch')\n\n%% figure 2: cylinder model \n% colors denote the branching order and branches\nSta = cylinder.start;\nP = P-Sta(1,:);\nif nargin > 5\n    trunk = trunk-Sta(1,:);\n    Vert = double(triangulation.vert);\n    Vert = Vert-Sta(1,:);\nend\nSta = Sta-Sta(1,:);\ncylinder.start = Sta;\nfigure(2)\nsubplot(1,2,1)\nplot_cylinder_model(cylinder,'order',2,10)\nsubplot(1,2,2)\nplot_cylinder_model(cylinder,'branch',2,10)\n\n%% figure 3, segmented point cloud and cylinder model\nplot_branch_segmentation(P,cover,segment,'order',3,1)\nhold on\nplot_cylinder_model(cylinder,'order',3,10,0.7)\nhold off\n\nif nargin > 4 \n    %% figure 4, triangulation model (bottom) and cylinder model (top) \n    % of the stem\n    Facets = double(triangulation.facet);\n    CylInd = triangulation.cylind;\n    fvd = triangulation.fvd;\n    if max(size(Vert)) > 5\n        Bran = cylinder.branch;\n        nc = size(Bran,1);\n        ind = (1:1:nc)';\n        C = ind(Bran == 1);\n        n = size(trunk,1);\n        I = logical(round(0.55*rand(n,1)));\n        figure(4)\n        point_cloud_plotting(trunk(I,:),4,3)\n        patch('Vertices',Vert,'Faces',Facets,'FaceVertexCData',fvd,...\n            'FaceColor','flat')\n        alpha(1)\n        hold on\n        plot_cylinder_model(cylinder,'order',4,20,1,(CylInd:C(end)))\n        axis equal\n        hold off\n    else\n        disp('No triangulation model generated!')\n    end\nend"
  },
  {
    "path": "src/plotting/plot_point_cloud.m",
    "content": "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 point cloud P in figure FIG using \r\n%   marker size MS and point color COL (string). P is a 2- or 3-column matrix \r\n%   where the first, second and third column gives the X-, Y-, and \r\n%   Z-coordinates of the points. \r\n%\r\n%   PLOT_POINT_CLOUD(P,FIG) plots point cloud P in figure FIG using \r\n%   marker size 3 and color blue ('b').\r\n%\r\n%   PLOT_POINT_CLOUD(P) plots point cloud P in figure 1 using marker size 3\r\n%   and color blue ('b').\r\n\r\nif nargin == 1\r\n    fig = 1;\r\n    ms = 3;\r\n    col = 'b';\r\nelseif nargin == 2\r\n    ms = 3;\r\n    col = 'b';\r\nelseif nargin == 3\r\n    col = 'b';\r\nend\r\nif ms == 0\r\n   ms = 3; \r\nend\r\n\r\ncol = ['.',col];\r\n\r\nfigure(fig)\r\nif size(P,2) == 3\r\n    plot3(P(:,1),P(:,2),P(:,3),col,'Markersize',ms)\r\nelseif size(P,2) == 2\r\n    plot(P(:,1),P(:,2),col,'Markersize',ms)\r\nend\r\naxis equal\r\n    "
  },
  {
    "path": "src/plotting/plot_scatter.m",
    "content": "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%\n% Inputs:\n% P     point cloud\n% C     color data (vector, value for each point in P)\n% fig   figure number\n% ms    marker size\n\nS = normalize(C);\nfigure(fig)\nif size(P,2) == 3\n    scatter3(P(:,1),P(:,2),P(:,3),ms*ones(size(P,1),1),C,'filled')\n    %scatter3(P(:,1),P(:,2),P(:,3),ms*S.*ones(size(P,1),1),C,'filled')\nelseif size(P,2) == 2\n    scatter(P(:,1),P(:,2),ms*S.*ones(size(P,1),1),C,'filled')\nend\naxis equal\nif size(C,2) == 1\n    colormap(jet(25))\n    %caxis([0 max(C)])\n    if min(C) < max(C)\n    caxis([min(C) max(C)])\n    end\n    colorbar\nend\n"
  },
  {
    "path": "src/plotting/plot_segments.m",
    "content": "function plot_segments(P,Bal,fig,ms,seg1,seg2,seg3,seg4,seg5)\r\n\r\n% Plots point cloud segments/subsets defined as subsets of cover sets.\r\n% If the subsets intersect, then assiggnes the common points to the\r\n% segments given first.\r\n%\r\n% Inputs\r\n% P     Point cloud\r\n% Bal   Cover sets. Bal = cover.ball\r\n% fig   figure number\r\n% seg1  Segment/subset 1, color blue\r\n% seg2  (Optional) Segment/subset 2, color red\r\n% seg3  (Optional) Segment/subset 3, color green\r\n% seg4  (Optional) Segment/subset 4, color cyan\r\n% seg5  (Optional) Segment/subset 5, color magenta\r\n\r\n\r\nif nargin == 5\r\n    S1 = unique(vertcat(Bal{seg1}));\r\n    figure(fig)\r\n    plot3(P(S1,1),P(S1,2),P(S1,3),'b.','Markersize',ms)\r\n    axis equal\r\nelseif nargin == 6\r\n    S1 = unique(vertcat(Bal{seg1}));\r\n    S2 = unique(vertcat(Bal{seg2}));\r\n    S2 = setdiff(S2,S1);\r\n    figure(fig)\r\n    plot3(P(S1,1),P(S1,2),P(S1,3),'b.','Markersize',1.5*ms)\r\n    hold on\r\n    plot3(P(S2,1),P(S2,2),P(S2,3),'r.','Markersize',ms)\r\n    axis equal\r\n    hold off\r\nelseif nargin == 7\r\n    S1 = unique(vertcat(Bal{seg1}));\r\n    S2 = unique(vertcat(Bal{seg2}));\r\n    S3 = unique(vertcat(Bal{seg3}));\r\n    S2 = setdiff(S2,S1);\r\n    S3 = setdiff(S3,S1);\r\n    S3 = setdiff(S3,S2);\r\n    figure(fig)\r\n    plot3(P(S1,1),P(S1,2),P(S1,3),'b.','Markersize',ms)\r\n    hold on\r\n    plot3(P(S2,1),P(S2,2),P(S2,3),'r.','Markersize',ms)\r\n    plot3(P(S3,1),P(S3,2),P(S3,3),'g.','Markersize',ms)\r\n    axis equal\r\n    hold off\r\nelseif nargin == 8\r\n    S1 = unique(vertcat(Bal{seg1}));\r\n    S2 = unique(vertcat(Bal{seg2}));\r\n    S3 = unique(vertcat(Bal{seg3}));\r\n    S4 = unique(vertcat(Bal{seg4}));\r\n    S2 = setdiff(S2,S1);\r\n    S3 = setdiff(S3,S1);\r\n    S3 = setdiff(S3,S2);\r\n    S4 = setdiff(S4,S1);\r\n    S4 = setdiff(S4,S2);\r\n    S4 = setdiff(S4,S3);\r\n    figure(fig)\r\n    plot3(P(S1,1),P(S1,2),P(S1,3),'b.','Markersize',ms)\r\n    hold on\r\n    plot3(P(S2,1),P(S2,2),P(S2,3),'r.','Markersize',ms)\r\n    plot3(P(S3,1),P(S3,2),P(S3,3),'g.','Markersize',ms)\r\n    plot3(P(S4,1),P(S4,2),P(S4,3),'c.','Markersize',ms)\r\n    axis equal\r\n    hold off\r\nelseif nargin == 9\r\n    S1 = unique(vertcat(Bal{seg1}));\r\n    S2 = unique(vertcat(Bal{seg2}));\r\n    S3 = unique(vertcat(Bal{seg3}));\r\n    S4 = unique(vertcat(Bal{seg4}));\r\n    S5 = unique(vertcat(Bal{seg5}));\r\n    S2 = setdiff(S2,S1);\r\n    S3 = setdiff(S3,S1);\r\n    S3 = setdiff(S3,S2);\r\n    S4 = setdiff(S4,S1);\r\n    S4 = setdiff(S4,S2);\r\n    S4 = setdiff(S4,S3);\r\n    S5 = setdiff(S5,S1);\r\n    S5 = setdiff(S5,S2);\r\n    S5 = setdiff(S5,S3);\r\n    S5 = setdiff(S5,S4);\r\n    figure(fig)\r\n    plot3(P(S1,1),P(S1,2),P(S1,3),'b.','Markersize',ms)\r\n    hold on\r\n    plot3(P(S2,1),P(S2,2),P(S2,3),'r.','Markersize',ms)\r\n    plot3(P(S3,1),P(S3,2),P(S3,3),'g.','Markersize',ms)\r\n    plot3(P(S4,1),P(S4,2),P(S4,3),'c.','Markersize',ms)\r\n    plot3(P(S5,1),P(S5,2),P(S5,3),'m.','Markersize',ms)\r\n    axis equal\r\n    hold off\r\nend"
  },
  {
    "path": "src/plotting/plot_segs.m",
    "content": "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 inputs, cells contain the point indexes. If 5 input, cells contain \r\n% the indexes of the cover sets given by \"Bal\".\r\n% \"fig\" is the figure number and \"ms\" is the marker size.\r\n\r\n\r\ncol = [\r\n\t0.00  0.00  1.00\r\n\t0.00  0.50  0.00\r\n\t1.00  0.00  0.00\r\n\t0.00  0.75  0.75\r\n\t0.75  0.00  0.75\r\n\t0.75  0.75  0.00\r\n\t0.25  0.25  0.25\r\n\t0.75  0.25  0.25\r\n\t0.95  0.95  0.00\r\n\t0.25  0.25  0.75\r\n\t0.75  0.75  0.75\r\n\t0.00  1.00  0.00\r\n\t0.76  0.57  0.17\r\n\t0.54  0.63  0.22\r\n\t0.34  0.57  0.92\r\n\t1.00  0.10  0.60\r\n\t0.88  0.75  0.73\r\n\t0.10  0.49  0.47\r\n\t0.66  0.34  0.65\r\n\t0.99  0.41  0.23];\r\n\r\nn = max(size(comps));\r\nif n < 100\r\n    col = repmat(col,[ceil(n/20),1]);\r\nelse\r\n    col = rand(n,3);\r\nend\r\n\r\nS = comps{1};\r\nif iscell(S)\r\n    n = size(comps,1);\r\n    for i = 1:n\r\n        S = comps{i};\r\n        if ~isempty(S)\r\n            S = vertcat(S{:});\r\n            comps{i} = S;\r\n        else\r\n            comps{i} = zeros(0,1);\r\n        end\r\n    end\r\nend\r\n\r\n\r\nif nargin == 4\r\n    \r\n    % Plot the segments\r\n    figure(fig)\r\n    C = comps{1};\r\n    plot3(P(C,1),P(C,2),P(C,3),'.','Color',col(1,:),'Markersize',ms)\r\n    hold on\r\n    for i = 2:n\r\n        C = comps{i};\r\n        plot3(P(C,1),P(C,2),P(C,3),'.','Color',col(i,:),'Markersize',ms)\r\n    end\r\n    axis equal\r\n    hold off\r\n    pause(0.1)\r\n    \r\nelse\r\n    \r\n    np = size(P,1);\r\n    D = false(np,1);\r\n    C = unique(vertcat(Bal{comps{1}}));\r\n    figure(fig)\r\n    plot3(P(C,1),P(C,2),P(C,3),'.','Color',col(1,:),'Markersize',ms)\r\n    hold on\r\n    for i = 2:n\r\n        if ~isempty(comps{i})\r\n            C = unique(vertcat(Bal{comps{i}}));\r\n            I = D(C);\r\n            C = C(~I);\r\n            D(C) = true;\r\n            plot3(P(C,1),P(C,2),P(C,3),'.','Color',col(i,:),'Markersize',ms)\r\n        end\r\n    end\r\n    hold off\r\n    axis equal\r\n    pause(0.1)\r\nend"
  },
  {
    "path": "src/plotting/plot_spreads.m",
    "content": "function plot_spreads(treedata,fig,lw,rel)\n\n% Plots the spreads as a polar plot with different height layers presented\n% with different colors. Inputs \"fig\" and \"lw\" define the figure number and\n% the line width. Input Rel = 1 specifies relative spreads, i.e. the\n% maximum spread is one, otherwise use the actual values.\n\nif nargin == 2\n    lw = 1;\n    rel = 1;\nelseif nargin == 3\n    rel = 1;\nend\n\nspreads = treedata.spreads;\nfigure(fig)\nn = size(spreads,1);\ncol = zeros(n,3);\ncol(:,1) = (0:1/n:(n-1)/n)';\ncol(:,3) = (1:-1/n:1/n)';\nd = max(max(spreads));\nD = [spreads(1,end) spreads(1,:)];\nif rel\n    polarplot(D/d,'-','Color',col(1,:),'Linewidth',lw)\nelse\n    polarplot(D,'-','Color',col(1,:),'Linewidth',lw)\nend\nhold on\nfor i = 1:n\n    D = [spreads(i,end) spreads(i,:)];\n    if rel\n        polarplot(D/d,'-','Color',col(i,:),'Linewidth',lw)\n    else\n        polarplot(D,'-','Color',col(i,:),'Linewidth',lw)\n    end\nend\nhold off\nif rel\n    rlim([0 1])\nelse\n    rlim([0 d])\nend\n"
  },
  {
    "path": "src/plotting/plot_tree_structure.m",
    "content": "function plot_tree_structure(P,cover,segment,fig,ms,segind,BO)\r\n\r\n% ---------------------------------------------------------------------\r\n% PLOT_TREE_STRUCTURE.M       Plots branch-segmented point cloud with unique\r\n%                               color for each branching order\r\n%\r\n% Version 1.1.0\r\n% Latest update     13 July 2020\r\n%\r\n% Copyright (C) 2013-2020 Pasi Raumonen\r\n% ---------------------------------------------------------------------\r\n% \r\n% Blue = trunk, Green = 1st-order branches, Red = 2nd-order branches, etc.\r\n% If segind = 1 and BO = 0, then plots the stem. If segind = 1 and BO = 1, \r\n% then plots the stem and the 1st-order branches. If segind = 1 and \r\n% BO >= maximum branching order or BO input is not given, then plots the \r\n% whole tree. If segind = 2 and BO is not given or it is high enough, then\r\n% plots the branch whose index is 2 and all its sub-branches. \r\n%\r\n% Inputs\r\n% P         Point cloud\r\n% cover     Cover sets structure\r\n% Segs      Segments structure\r\n% fig       Figure number\r\n% ms        Marker size\r\n% segind    Index of the segment where the plotting of tree structure\r\n%                   starts. \r\n% BO        How many branching orders are plotted. 0 = stem, 1 = 1st order, etc\r\n% \r\n\r\n% Changes from version 1.0.0 to 1.1.0, 13 July 2020:\r\n% 1) Added option for choosing the coloring based either on branch order or\r\n%    unique color for each branch\r\n\r\nn = nargin;\r\nif n < 7\r\n    BO = 1000;\r\n    if n < 6\r\n        segind = 1;\r\n        if n < 5\r\n            ms = 1;\r\n            if n == 3\r\n                fig = 1;\r\n            end\r\n        end\r\n    end\r\nend\r\n\r\nBal = cover.ball;\r\nSegs = segment.segments;\r\nSChi = segment.ChildSegment;\r\n\r\ncol = [\r\n\t0.00  0.00  1.00\r\n\t0.00  0.50  0.00\r\n\t1.00  0.00  0.00\r\n\t0.00  0.75  0.75\r\n\t0.75  0.00  0.75\r\n\t0.75  0.75  0.00\r\n\t0.25  0.25  0.25\r\n\t0.75  0.25  0.25\r\n\t0.95  0.95  0.00\r\n\t0.25  0.25  0.75\r\n\t0.75  0.75  0.75\r\n\t0.00  1.00  0.00\r\n\t0.76  0.57  0.17\r\n\t0.54  0.63  0.22\r\n\t0.34  0.57  0.92\r\n\t1.00  0.10  0.60\r\n\t0.88  0.75  0.73\r\n\t0.10  0.49  0.47\r\n\t0.66  0.34  0.65\r\n\t0.99  0.41  0.23];\r\ncol = repmat(col,[1000,1]);\r\n\r\nif iscell(Segs{1})\r\n    n = max(size(Segs));\r\n    Seg = cell(n,1);\r\n    for i = 1:n\r\n        m = size(Segs{i},1);\r\n        S = zeros(0);\r\n        for j = 1:m\r\n            s = Segs{i}(j);\r\n            s = s{:};\r\n            S = [S; s];\r\n        end\r\n        Seg{i} = S;\r\n    end\r\nelse\r\n    Seg = Segs;\r\nend\r\n\r\nS = vertcat(Bal{Seg{segind}});\r\nfigure(fig)\r\nplot3(P(S,1),P(S,2),P(S,3),'.','Color',col(1,:),'Markersize',ms)\r\naxis equal\r\n%forb = S;\r\nif BO > 0\r\n    hold on\r\n    c = SChi{segind};\r\n    order = 1;\r\n    while (order <= BO) && (~isempty(c))\r\n        C = vertcat(Bal{vertcat(Seg{c})});\r\n        %C = setdiff(C,forb);\r\n        figure(fig)\r\n        plot3(P(C,1),P(C,2),P(C,3),'.','Color',col(order+1,:),'Markersize',ms)\r\n        axis equal\r\n        c = unique(vertcat(SChi{c}));\r\n        order = order+1;\r\n        %forb = union(forb,C);\r\n    end\r\n    hold off\r\nend\r\n"
  },
  {
    "path": "src/plotting/plot_tree_structure2.m",
    "content": "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 each branching order\r\n% has its own color Blue = trunk, green = 1st-order branches, \r\n% red = 2nd-order branches, etc.\r\n%\r\n% Inputs\r\n% P         Point cloud\r\n% Bal       Cover sets, Bal = cover.bal\r\n% Segs      Segments, Segs = segment.segments\r\n% SChi      Child segments, SChi = segment.ChildSegment\r\n% fig       Figure number\r\n% ms        Marker size\r\n% BO        How many branching orders are plotted. 0 = all orders\r\n% segind    Index of the segment where the plotting of tree structure\r\n%                   starts. If segnum = 1 and BO = 0, then plots the whole\r\n%                   tree. If segnum = 1 and B0 = 2, then plots the stem and\r\n%                   the 1st-order branches. If segnum = 2 and BO = 0, then \r\n%                   plots the branch whose index is 2 and all its sub-branches. \r\n\r\n\r\ncol = [\r\n\t0.00  0.00  1.00\r\n\t0.00  0.50  0.00\r\n\t1.00  0.00  0.00\r\n\t0.00  0.75  0.75\r\n\t0.75  0.00  0.75\r\n\t0.75  0.75  0.00\r\n\t0.25  0.25  0.25\r\n\t0.75  0.25  0.25\r\n\t0.95  0.95  0.00\r\n\t0.25  0.25  0.75\r\n\t0.75  0.75  0.75\r\n\t0.00  1.00  0.00\r\n\t0.76  0.57  0.17\r\n\t0.54  0.63  0.22\r\n\t0.34  0.57  0.92\r\n\t1.00  0.10  0.60\r\n\t0.88  0.75  0.73\r\n\t0.10  0.49  0.47\r\n\t0.66  0.34  0.65\r\n\t0.99  0.41  0.23];\r\ncol = repmat(col,[1000,1]);\r\n\r\nif iscell(Segs{1})\r\n    n = max(size(Segs));\r\n    Seg = cell(n,1);\r\n    for i = 1:n\r\n        m = size(Segs{i},1);\r\n        S = zeros(0);\r\n        for j = 1:m\r\n            s = Segs{i}(j);\r\n            s = s{:};\r\n            S = [S; s];\r\n        end\r\n        Seg{i} = S;\r\n    end\r\nelse\r\n    Seg = Segs;\r\nend\r\n\r\nif BO == 0\r\n    BO = 1000;\r\nend\r\n\r\nS = vertcat(Bal{Seg{segind}});\r\nfigure(fig)\r\nplot3(P(S,1),P(S,2),P(S,3),'.','Color',col(1,:),'Markersize',ms)\r\naxis equal\r\nforb = S;\r\nif BO > 1\r\n    %pause\r\n    hold on\r\n    c = SChi{segind};\r\n    i = 2;\r\n    while (i <= BO) && (~isempty(c))\r\n        C = vertcat(Bal{unique(vertcat(Seg{c}))});\r\n        C = setdiff(C,forb);\r\n        figure(fig)\r\n        plot3(P(C,1),P(C,2),P(C,3),'.','Color',col(i,:),'Markersize',ms)\r\n        axis equal\r\n        c = unique(vertcat(SChi{c}));\r\n        i = i+1;\r\n        forb = union(forb,C);\r\n        if i <= BO\r\n            %pause\r\n        end\r\n    end\r\n    hold off\r\nend\r\n"
  },
  {
    "path": "src/plotting/plot_triangulation.m",
    "content": "function plot_triangulation(QSM,fig,nf,AllTree)\n\n% Plots the triangulation model of the stem's bottom part and the cylinder\n% model (rest of the stem or the rest of the tree). The optional inputs\n% \"fig\", \"nf\", \"All\" are the figure number, number of facets for the \n% cylinders, and if All = 1, then all the tree is plotted. \n\nn = nargin;\nif n < 4\n    AllTree = 0;\n    if n < 3\n        nf = 20;\n        if n == 1\n            fig = 1;\n        end\n    end\nend\n\nVert = double(QSM.triangulation.vert);\nFacets = double(QSM.triangulation.facet);\nCylInd = QSM.triangulation.cylind;\nfvd = QSM.triangulation.fvd;\nBran = QSM.cylinder.branch;\nnc = size(Bran,1);\nind = (1:1:nc)';\nC = ind(Bran == 1);\nfigure(fig)\npatch('Vertices',Vert,'Faces',Facets,'FaceVertexCData',fvd,'FaceColor','flat')\nhold on\nif AllTree\n    Ind = (CylInd:1:nc)';\nelse\n    Ind = (CylInd:1:C(end))';\nend\nplot_cylinder_model(QSM.cylinder,fig,nf,1,'branch',Ind)\naxis equal\nhold off\nalpha(1)\n"
  },
  {
    "path": "src/plotting/point_cloud_plotting.m",
    "content": "function point_cloud_plotting(P,fig,ms,Bal,Sub)\r\n\r\n% Plots the given point cloud \"P\". With additional inputs one can plot only\r\n% those points that are included in the cover sets \"Bal\" or in the\r\n% subcollection \"Sub\" of the cover sets. \r\n% \"fig\" and \"ms\" are the figure number and marker size.\r\n\r\nif nargin == 2\r\n    ms = 3;\r\nelseif ms == 0\r\n    ms = 3;\r\nend\r\n\r\nif nargin < 4\r\n    figure(fig)\r\n    if size(P,2) == 3\r\n        plot3(P(:,1),P(:,2),P(:,3),'.b','Markersize',ms)\r\n    elseif size(P,2) == 2\r\n        plot(P(:,1),P(:,2),'.b','Markersize',ms)\r\n    end\r\n    axis equal\r\n    \r\nelseif nargin == 4\r\n    I = vertcat(Bal{:});\r\n    figure(fig)\r\n    plot3(P(I,1),P(I,2),P(I,3),'.b','Markersize',ms)\r\n    axis equal\r\n    \r\nelse\r\n    if iscell(Sub)\r\n        S = vertcat(Sub{:});\r\n        Sub = vertcat(S{:});\r\n        I = vertcat(Bal{Sub});\r\n        figure(fig)\r\n        plot3(P(I,1),P(I,2),P(I,3),'.b','Markersize',ms)\r\n        axis equal\r\n    else\r\n        I = vertcat(Bal{Sub});\r\n        figure(fig)\r\n        plot3(P(I,1),P(I,2),P(I,3),'.b','Markersize',ms)\r\n        axis equal\r\n    end\r\nend"
  },
  {
    "path": "src/select_optimum.m",
    "content": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction [TreeData,OptModels,OptInputs,OptQSM] = ...\n  select_optimum(QSMs,Metric,savename)\n\n% ---------------------------------------------------------------------\n% SELECT_OPTIMUM.M       Selects optimum models based on point-cylinder model\n%                           distances or standard deviations of attributes\n%\n% Version 1.4.0 \n% Latest update     2 May 2022\n%\n% Copyright (C) 2013-2022 Pasi Raumonen\n% ---------------------------------------------------------------------\n%\n% Works for single or multiple tree cases where the input QSMs contains\n% multiple models for the same tree with different inputs and multiple runs\n% with the same inputs. Allows the user to select from 34 different metrics\n% for the optimization. These include average point-model distances from\n% all, trunk, branch, 1st-order branch and 2nd-order branch cylinders plus\n% some combinations where e.g. \"mean trunk and mean branch\" or \"mean trunk\n% and mean 1st-order branch\" point-model distances are added together.\n% Similarly for the maximum point-model distances and the sums of mean and\n% the maximum distances.\n%   The difference between \"all\" and \"trunk and branch\" is that \"all\"\n% is the average of all cylinder distances which usually emphasizes\n% branch cylinder as there usually much more those, whereas \"trunk and branch\"\n% gives equal weight for trunk and branch cylinders.\n%   The other options for metric are based on minimizing the standard deviations\n% of volumes (total, trunk, branch, trunk+branch which have equal emphasis\n% between trunk and branches), lengths (trunk, branches) or total number of\n% branches. Here the idea is that if the variance (standard deviation) of\n% some attribute between models with the same inputs is small, then it\n% indicates some kind of robustness which might indicate that the inputs\n% are close to optimal.\n%   The optimal single model out of the models with the optimal inputs is\n% selected based on the minimum mean point-model-distance.\n%\n% Inputs:\n% QSMs      Contain all the QSMs, possibly from multiple trees\n% Metric    Optional input, Metric to be minimized:\n%           CYLINDER-DISTANCE METRICS:\n%           'all_mean_dis' = mean distances from (mdf) all cylinders, DEFAULT option\n%           'trunk_mean_dis' = mdf trunk cylinders,\n%           'branch_mean_dis' = mdf all branch cylinders,\n%           '1branch_mean_dis' = mdf 1st-order branch cylinders,\n%           '2branch_mean_dis' = mdf 2nd-order branch cylinders,\n%           'trunk+branch_mean_dis' = mdf trunk + mdf branch cylinders,\n%           'trunk+1branch_mean_dis' = mdf trunk + mdf 1st-ord branch cyls,\n%           'trunk+1branch+2branch_mean_dis' = above + mdf 2nd-ord branch cyls\n%           '1branch+2branch_mean_dis' = mdf 1branch cyls + mdf 2branch cyls\n%           'all_max_dis' = maximum distances from (mdf) all cylinders\n%           'trunk_max_dis' = mdf trunk cylinders,\n%           'branch_max_dis' = mdf all branch cylinders,\n%           '1branch_max_dis' = mdf 1st-order branch cylinders,\n%           '2branch_max_dis' = mdf 2nd-order branch cylinders,\n%           'trunk+branch_max_dis' = mdf trunk + mdf branch cylinders,\n%           'trunk+1branch_max_dis' = mdf trunk + mdf 1st-ord branch cyls,\n%           'trunk+1branch+2branch_max_dis' = above + mdf 2nd-ord branch cyls.\n%           '1branch+2branch_max_dis' = mdf 1branch cyls + mdf 2branch cyls\n%           'all_mean+max_dis' = mean + maximum distances from (m+mdf) all cylinders\n%           'trunk_mean+max_dis' = (m+mdf) trunk cylinders,\n%           'branch_mean+max_dis' = (m+mdf) all branch cylinders,\n%           '1branch_mean+max_dis' = (m+mdf) 1st-order branch cylinders,\n%           '2branch_mean+max_dis' = (m+mdf) 2nd-order branch cylinders,\n%           'trunk+branch_mean+max_dis' = (m+mdf) trunk + (m+mdf) branch cylinders,\n%           'trunk+1branch_mean+max_dis' = (m+mdf) trunk + (m+mdf) 1branch cyls,\n%           'trunk+1branch+2branch_mean+max_dis' = above + (m+mdf) 2branch cyls.\n%           '1branch+2branch_mean+max_dis' = (m+mdf) 1branch cyls + (m+mdf) 2branch cyls\n%           STANDARD DEVIATION METRICS:\n%           'tot_vol_std' = standard deviation of total volume\n%           'trunk_vol_std' = standard deviation of trunk volume\n%           'branch_vol_std' = standard deviation of branch volume\n%           'trunk+branch_vol_std' = standard deviation of trunk plus branch volume\n%           'tot_are_std' = standard deviation of total area\n%           'trunk_are_std' = standard deviation of trunk area\n%           'branch_are_std' = standard deviation of branch area\n%           'trunk+branch_are_std' = standard deviation of trunk plus branch area\n%           'trunk_len_std' = standard deviation of trunk length\n%           'branch_len_std' = standard deviation of branch length\n%           'branch_num_std' = standard deviation of number of branches\n%           BRANCH-ORDER DISTRIBUTION METRICS:\n%           'branch_vol_ord3_mean' = mean difference in volume of 1-3 branch orders\n%           'branch_are_ord3_mean' = mean difference in area of 1-3 branch orders\n%           'branch_len_ord3_mean' = mean difference in length of 1-3 branch orders\n%           'branch_num_ord3_mean' = mean difference in number of 1-3 branch orders\n%           'branch_vol_ord3_max' = max difference in volume of 1-3 branch orders\n%           'branch_are_ord3_max' = max difference in area of 1-3 branch orders\n%           'branch_len_ord3_max' = max difference in length of 1-3 branch orders\n%           'branch_num_ord3_max' = max difference in number of 1-3 branch orders\n%           'branch_vol_ord6_mean' = mean difference in volume of 1-6 branch orders\n%           'branch_are_ord6_mean' = mean difference in area of 1-6 branch orders\n%           'branch_len_ord6_mean' = mean difference in length of 1-6 branch orders\n%           'branch_num_ord6_mean' = mean difference in number of 1-6 branch orders\n%           'branch_vol_ord6_max' = max difference in volume of 1-6 branch orders\n%           'branch_are_ord6_max' = max difference in area of 1-6 branch orders\n%           'branch_len_ord6_max' = max difference in length of 1-6 branch orders\n%           'branch_num_ord6_max' = max difference in number of 1-6 branch orders\n%           CYLINDER DISTRIBUTION METRICS:\n%           'cyl_vol_dia10_mean') = mean diff. in volume of 1-10cm diam cyl classes\n%           'cyl_are_dia10_mean') = mean diff. in area of 1-10cm diam cyl classes\n%           'cyl_len_dia10_mean') = mean diff. in length of 1-10cm diam cyl classes\n%           'cyl_vol_dia10_max') = max diff. in volume of 1-10cm diam cyl classes\n%           'cyl_are_dia10_max') = max diff. in area of 1-10cm diam cyl classes\n%           'cyl_len_dia10_max') = max diff. in length of 1-10cm diam cyl classes\n%           'cyl_vol_dia20_mean') = mean diff. in volume of 1-20cm diam cyl classes\n%           'cyl_are_dia20_mean') = mean diff. in area of 1-20cm diam cyl classes\n%           'cyl_len_dia20_mean') = mean diff. in length of 1-20cm diam cyl classes\n%           'cyl_vol_dia20_max') = max diff. in volume of 1-20cm diam cyl classes\n%           'cyl_are_dia20_max') = max diff. in area of 1-20cm diam cyl classes\n%           'cyl_len_dia20_max') = max diff. in length of 1-20cm diam cyl classes\n%           'cyl_vol_zen_mean') = mean diff. in volume of cyl zenith distribution\n%           'cyl_are_zen_mean') = mean diff. in area of cyl zenith distribution\n%           'cyl_len_zen_mean') = mean diff. in length of cyl zenith distribution\n%           'cyl_vol_zen_max') = max diff. in volume of cyl zenith distribution\n%           'cyl_are_zen_max') = max diff. in area of cyl zenith distribution\n%           'cyl_len_zen_max') = max diff. in length of cyl zenith distribution\n%           SURFACE COVERAGE METRICS:\n%               metric to be minimized is 1-mean(surface_coverage) or 1-min(SC)\n%           'all_mean_surf' = mean surface coverage from (msc) all cylinders\n%           'trunk_mean_surf' = msc trunk cylinders,\n%           'branch_mean_surf' = msc all branch cylinders,\n%           '1branch_mean_surf' = msc 1st-order branch cylinders,\n%           '2branch_mean_surf' = msc 2nd-order branch cylinders,\n%           'trunk+branch_mean_surf' = msc trunk + msc branch cylinders,\n%           'trunk+1branch_mean_surf' = msc trunk + msc 1st-ord branch cyls,\n%           'trunk+1branch+2branch_mean_surf' = above + msc 2nd-ord branch cyls\n%           '1branch+2branch_mean_surf' = msc 1branch cyls + msc 2branch cyls\n%           'all_min_surf' = minimum surface coverage from (msc) all cylinders\n%           'trunk_min_surf' = msc trunk cylinders,\n%           'branch_min_surf' = msc all branch cylinders,\n%           '1branch_min_surf' = msc 1st-order branch cylinders,\n%           '2branch_min_surf' = msc 2nd-order branch cylinders,\n%           'trunk+branch_min_surf' = msc trunk + msc branch cylinders,\n%           'trunk+1branch_min_surf' = msc trunk + msc 1st-ord branch cyls,\n%           'trunk+1branch+2branch_min_surf' = above + msc 2nd-ord branch cyls.\n%           '1branch+2branch_min_surf' = msc 1branch cyls + msc 2branch cyls\n% savename      Optional input, name string specifying the name of the saved file\n%               containing the outputs\n%\n% Outputs:\n% TreeData      Similar structure array as the \"treedata\" in QSMs but now each\n%               attribute contains the mean and std computed from the models\n%               with the optimal inputs. Also contains the sensitivities\n%               for the inputs PatchDiam1, PatchDiam2Min, PatchDiam2Max.\n%               Thus for single number attributes (e.g. TotalVolume) there\n%               are five numbers [mean std sensi_PD1 sensi_PD2Min sensi_PD2Max]\n% OptModels     Indexes of the models with the optimal inputs (column 1) and\n%               the index of the optimal single model (column 2) in \"QSMs\" \n%               for each tree\n% OptInputs     The optimal input parameters for each tree\n% OptQSMs       The single best QSM for each tree, OptQSMs = QSMs(OptModel);\n% ---------------------------------------------------------------------\n\n\n% Changes from version 1.3.1 to 1.4.0, 2 May 2022:\n% 1) Added estimation of (relative) sensitivity of the single number\n%    attributes in TreeData for the inputs PatchDiam1, PatchDiam2Min,\n%    PatchDiam2Max. Now TreeData contains also these values as the columns\n%    3 to 5.\n% 2) Corrected a small bug in the subfunction \"collect_data\" (assignment\n%    of values for \"CylSurfCov(i,:)\"). The bug caused error for QSMs whose\n%    maximum branch order is less than 2.\n% 3) Bug fix for 3 lines (caused error for some cases and for other cases\n%    the optimal single model was wrongly selected):\n%    [~,T] = min(dist(ind,best));  -->  [~,T] = min(Data.CylDist(ind,best));\n\n% Changes from version 1.2.0 to 1.3.0, 4 Aug 2020:\n% 1) Removed two inputs (\"lcyl\" and \"FilRad\") from the inputs to be\n%    optimised. This corresponds to changes in the cylinder fitting.\n% 2) Added more choices for the optimisation criteria or cost\n%    functions (\"metric\") that are minimised. There is now 91 metrics and\n%    the new ones include surface coverage based metrics.\n\n% Changes from version 1.1.1 to 1.2.0, 4 Feb 2020:\n% 1) Major change in the structure: subfunctions\n% 2) Added more choices for the optimisation criteria or cost\n%    functions (\"metric\") that are minimised. There is now 73 metrics and in\n%    particular the new ones include some area related metrics and branch\n%    and cylinder distribution based metrics.\n\n% Changes from version 1.1.0 to 1.1.1, 26 Nov 2019:\n% 1) Added the \"name\" of the point cloud from the inputs.name to the output\n%    TreeData as a field. Also now displays the name together with the tree\n%    number.\n% 2) TreeData contains now correctly fields (\"location\", \"StemTaper\",\n%    \"VolumeBranchOrder\", etc) from the Optimal QSMs.\n\n% Changes from version 1.0.0 to 1.1.0, 08 Oct 2019:\n% 1) Added the posibility to select the optimisation criteria or cost\n%    function (\"metric\") that is minimised from 34 different options.\n%    Previously only one option was used. The used metric is also included\n%    in \"OptInputs\" output as one of the fields.\n% 2) Added OptQSM as one of the outputs\n\n%% Select the metric based on the input\nif nargin > 1\n  [met,Metric] = select_metric(Metric);\nelse\n  met = 1;\n  Metric = 'all_mean_dis';\nend\n\n\n% The metric for selecting the optimal single model from the models with\n% the optimal inputs is the mean point-model-distance.\nbest = 1;\n\n%% Collect data\n% Find the first non-empty model\ni = 1;\nwhile isempty(QSMs(i).cylinder)\n  i = i+1;\nend\n% Determine how many single-number attributes there are in treedata\nnames = fieldnames(QSMs(i).treedata);\nn = 1;\nwhile numel(QSMs(i).treedata.(names{n})) == 1\n  n = n+1;\nend\nn = n-1;\nNames = names(1:n);\nL = max(cellfun('length',Names))+1;\nfor i = 1:n\n  name = Names{i};\n  name(L) = ' ';\n  Names{i} = name;\nend\n\n% Collect data:\n[treedata,inputs,TreeId,Data] = collect_data(QSMs,names,n);\n\n% Trees and their unique IDs\nTreeIds = unique(TreeId(:,1));\nnt = length(TreeIds); % number of trees\n\nDataM = zeros(n,nt);\nDataS = zeros(n,nt); % Standard deviation of tree data for each tree\nDataM2 = DataM;     DataM3 = DataM;\nDataS2 = DataS;     DataS3 = DataS;\n\nOptIn = zeros(nt,9); % Optimal input values\nOptDist = zeros(nt,9); % Smallest metric values\n\n\n% average treedata and inputs for each tree-input-combination:\nTreeDataAll = zeros(nt,5*5*5,n);\nInputs = zeros(nt,5*5*5,3);\n\nIndAll = (1:1:size(TreeId,1))';\n\n% Indexes of the optimal single models in QSMs:\nOptModel = zeros(nt,3);\n% The indexes of models in QSMs with the optimal inputs (col 1)\n% and the indexes of the optimal single models (col 2):\nOptModels = cell(nt,2);\n\nNInputs = zeros(nt,1);\n\n%% Process each tree separately\nfor tree = 1:nt\n  % Select the models for the tree\n  Models = TreeId(:,1) == TreeIds(tree);\n\n  %% Determine the input parameter values\n  InputParComb = unique(inputs(Models,:),'rows'); % Input parameter combinations\n  IV = cell(3,1);\n  N = zeros(3,1);\n  for i = 1:3\n    I = unique(InputParComb(:,i));\n    IV{i} = I;\n    N(i) = length(I);\n  end\n\n  %% Determine metric-value for each input\n  % (average over number of models with the same inputs)\n  input = cell(1,N(1)*N(2)*N(3));\n  distM = zeros(1,N(1)*N(2)*N(3)); % average distances or volume stds\n  b = 0;\n  for d = 1:N(1) % PatchDiam1\n    J = abs(inputs(:,1)-IV{1}(d)) < 0.0001;\n    for a = 1:N(2) % PatchDiam2Min\n      K = abs(inputs(:,2)-IV{2}(a)) < 0.0001;\n      for i = 1:N(3) % PatchDiam2Max\n        L = abs(inputs(:,3)-IV{3}(i)) < 0.0001;\n\n        % Select models for the tree with the same inputs:\n        T = Models & J & K & L;\n        b = b+1;\n        input{b} = [d a i];\n\n        % Compute the metric value;\n        D = compute_metric_value(met,T,treedata,Data);\n        distM(b) = D;\n\n        % Collect the data and inputs\n        TreeDataAll(tree,b,:) = mean(treedata(:,T),2);\n        Inputs(tree,b,:) = [IV{1}(d) IV{2}(a) IV{3}(i)];\n      end\n    end\n  end\n\n  %% Determine the optimal inputs and models\n  ninputs = prod(N);\n  NInputs(tree) = ninputs;\n  [d,J] = sort(distM);\n  O = input{J(1)};\n  OptIn(tree,1:3) = [IV{1}(O(1)) IV{2}(O(2)) IV{3}(O(3))];\n  OptDist(tree,1) = d(1);\n  if ninputs > 1\n    O = input{J(2)};\n    OptIn(tree,4:6) = [IV{1}(O(1)) IV{2}(O(2)) IV{3}(O(3))];\n    OptDist(tree,2) = d(2);\n    if ninputs > 2\n      O = input{J(3)};\n      OptIn(tree,7:9) = [IV{1}(O(1)) IV{2}(O(2)) IV{3}(O(3))];\n      OptDist(tree,3) = d(3);\n    end\n  end\n\n  %% Mean of tree data for each tree computed from the optimal models:\n  % Select the optimal models for each tree: In the case of multiple models\n  % with same inputs, select the one model with the optimal inputs that\n  % has the minimum metric value.\n  J = abs(inputs(:,1)-OptIn(tree,1)) < 0.0001;\n  K = abs(inputs(:,2)-OptIn(tree,2)) < 0.0001;\n  L = abs(inputs(:,3)-OptIn(tree,3)) < 0.0001;\n  T = Models & J & K & L;\n  ind = IndAll(T);\n  [~,T] = min(Data.CylDist(ind,best));\n  OptModel(tree,1) = ind(T);\n  OptModels{tree,1} = ind;\n  OptModels{tree,2} = ind(T);\n  DataM(:,tree) = mean(treedata(:,ind),2);\n  DataS(:,tree) = std(treedata(:,ind),[],2);\n  if ninputs > 1\n    J = abs(inputs(:,1)-OptIn(tree,4)) < 0.0001;\n    K = abs(inputs(:,2)-OptIn(tree,5)) < 0.0001;\n    L = abs(inputs(:,3)-OptIn(tree,6)) < 0.0001;\n    T = Models & J & K & L;\n    ind = IndAll(T);\n    [~,T] = min(Data.CylDist(ind,best));\n    OptModel(tree,2) = ind(T);\n    DataM2(:,tree) = mean(treedata(:,ind),2);\n    DataS2(:,tree) = std(treedata(:,ind),[],2);\n    if ninputs > 2\n      J = abs(inputs(:,1)-OptIn(tree,7)) < 0.0001;\n      K = abs(inputs(:,2)-OptIn(tree,8)) < 0.0001;\n      L = abs(inputs(:,3)-OptIn(tree,9)) < 0.0001;\n      T = Models & J & K & L;\n      ind = IndAll(T);\n      [~,T] = min(Data.CylDist(ind,best));\n      OptModel(tree,3) = ind(T);\n      DataM3(:,tree) = mean(treedata(:,ind),2);\n      DataS3(:,tree) = std(treedata(:,ind),[],2);\n    end\n  end\n\n  % Decrease the number on non-zero decimals\n  DataM(:,tree) = change_precision(DataM(:,tree));\n  DataS(:,tree) = change_precision(DataS(:,tree));\n  if ninputs > 1\n    DataM2(:,tree) = change_precision(DataM2(:,tree));\n    DataS2(:,tree) = change_precision(DataS2(:,tree));\n    if ninputs > 2\n      DataM3(:,tree) = change_precision(DataM3(:,tree));\n      DataS3(:,tree) = change_precision(DataS3(:,tree));\n    end\n  end\n\n  % Define the output \"OptInputs\"\n  OptM = IndAll(OptModel(tree,1));\n  OptInputs(tree) = QSMs(OptM).rundata.inputs;\n  if ninputs > 1\n    OptM2 = IndAll(OptModel(tree,2));\n    OI2(tree) = QSMs(OptM2).rundata.inputs;\n    if ninputs > 2\n      OptM3 = IndAll(OptModel(tree,3));\n      OI3(tree) = QSMs(OptM3).rundata.inputs;\n    end\n  end\n\nend\nN = max(NInputs);\nTreeDataAll = TreeDataAll(:,1:N,:);\nInputs = Inputs(:,1:N,:);\n\n% Compute Coefficient of variation for the data\nOptModel = IndAll(OptModel(:,1));\nOptQSM = QSMs(OptModel);\nDataCV = DataS./DataM*100; % Coefficient of variation\nif ninputs > 1\n  DataCV2 = DataS2./DataM2*100; % Coefficient of variation\n  if ninputs > 2\n    DataCV3 = DataS3./DataM3*100; % Coefficient of variation\n  end\nend\n% Decrease the number on non-zero decimals\nfor j = 1:nt\n  DataCV(:,j) = change_precision(DataCV(:,j));\n  if ninputs > 1\n    DataCV2(:,j) = change_precision(DataCV2(:,j));\n    if ninputs > 2\n      DataCV3(:,j) = change_precision(DataCV3(:,j));\n    end\n  end\nend\n\n%% Display some data about optimal models\n% Display optimal inputs, model and attributes for each tree\nfor t = 1:nt\n  disp('-------------------------------')\n  disp(['  Tree: ',num2str(OptInputs(t).tree),', ',OptInputs(t).name])\n  if NInputs(t) == 1\n    disp(['    Metric: ',Metric])\n    disp(['    Metric value:  ',num2str(1000*OptDist(t,1))])\n    disp(['    Optimal inputs:  PatchDiam1 = ',...\n      num2str(OptInputs(t).PatchDiam1)])\n    disp(['                  PatchDiam2Min = ',...\n      num2str(OptInputs(t).PatchDiam2Min)])\n    disp(['                  PatchDiam2Max = ',...\n      num2str(OptInputs(t).PatchDiam2Max)])\n    disp(['    Optimal model: ',num2str(OptModel(t))])\n    sec = num2str(round(QSMs(OptModel(t)).rundata.time(end)));\n    disp(['    Reconstruction time for the optimal model: ',sec,' seconds'])\n    disp('    Attributes (mean, std, CV(%)):')\n    for i = 1:n\n      str = (['      ',Names{i},': ',num2str([...\n        DataM(i,t) DataS(i,t) DataCV(i,t)])]);\n      disp(str)\n    end\n  elseif NInputs(t) == 2\n    disp('    The best two cases:')\n    disp(['    Metric: ',Metric])\n    disp(['    Metric values:  ',num2str(OptDist(t,1:2))])\n    disp(['            inputs:  PatchDiam1 = ',...\n      num2str([OptInputs(t).PatchDiam1 OI2(t).PatchDiam1])])\n    disp(['                  PatchDiam2Min = ',...\n      num2str([OptInputs(t).PatchDiam2Min OI2(t).PatchDiam2Min])])\n    disp(['                  PatchDiam2Max = ',...\n      num2str([OptInputs(t).PatchDiam2Max OI2(t).PatchDiam2Max])])\n    disp(['    Optimal model: ',num2str(OptModel(t))])\n    sec = num2str(round(QSMs(OptModel(t)).rundata.time(end)));\n    disp(['    Reconstruction time for the optimal model: ',sec,' seconds'])\n    disp('    Attributes (mean, std, CV(%), second best mean):')\n    for i = 1:n\n      str = (['      ',Names{i},':  ',num2str([DataM(i,t) ...\n        DataS(i,t) DataCV(i,t) DataM2(i,t)])]);\n      disp(str)\n    end\n  elseif NInputs(t) > 2\n    disp('    The best three cases:')\n    disp(['    Metric: ',Metric])\n    disp(['    Metric values:  ',num2str(OptDist(t,1:3))])\n    disp(['            inputs:  PatchDiam1 = ',num2str([...\n      OptInputs(t).PatchDiam1 OI2(t).PatchDiam1 OI3(t).PatchDiam1])])\n    disp(['                  PatchDiam2Min = ',num2str([...\n      OptInputs(t).PatchDiam2Min OI2(t).PatchDiam2Min OI3(t).PatchDiam2Min])])\n    disp(['                  PatchDiam2Max = ',num2str([...\n      OptInputs(t).PatchDiam2Max OI2(t).PatchDiam2Max OI3(t).PatchDiam2Max])])\n    disp(['    Optimal model: ',num2str(OptModel(t))])\n    sec = num2str(round(QSMs(OptModel(t)).rundata.time(end)));\n    disp(['    Reconstruction time for the optimal model: ',sec,' seconds'])\n    str = ['    Attributes (mean, std, CV(%),',...\n      ' second best mean, third best mean, sensitivity):'];\n    disp(str)\n    for i = 1:n\n      sensi = max(abs([DataM(i,t)-DataM2(i,t)...\n        DataM(i,t)-DataM3(i,t)])/DataM(i,t));\n      sensi2 = 100*sensi;\n      sensi = 100*sensi/DataCV(i,t);\n      sensi2 = change_precision(sensi2);\n      sensi = change_precision(sensi);\n      str = (['      ',Names{i},':  ',num2str([DataM(i,t) DataS(i,t) ...\n        DataCV(i,t) DataM2(i,t) DataM3(i,t) sensi sensi2])]);\n      disp(str)\n    end\n  end\n  disp('------')\nend\n\n%% Compute the sensitivity of the tree attributes relative to PatchDiam-parameters\nSensi = sensitivity_analysis(TreeDataAll,TreeId,Inputs,OptIn,NInputs);\n\n%% Generate TreeData sructure for optimal models\nclear TreeData\nTreeData = vertcat(OptQSM(:).treedata);\nfor t = 1:nt\n  for i = 1:n\n    TreeData(t).(names{i}) = [DataM(i,t) DataS(i,t) squeeze(Sensi(t,i,:))'];\n  end\n  TreeData(t).name = OptInputs(t).name;\nend\n\n%% Add the metric for the \"OptInputs\"\nfor i = 1:nt\n  OptInputs(i).metric = Metric;\nend\n\n%% Save results\nif nargin == 3\n  str = ['results/OptimalQSMs_',savename];\n  save(str,'TreeData','OptModels','OptInputs','OptQSM')\n\n  str = ['results/tree_data_',savename,'.txt'];\n  fid = fopen(str, 'wt');\n  fprintf(fid, [repmat('%g\\t', 1, size(DataM,2)-1) '%g\\n'], DataM.');\n  fclose(fid);\nend\n\n% End of main function\nend\n\n\nfunction [treedata,inputs,TreeId,Data] = collect_data(...\n  QSMs,names,Nattri)\n\nNmod = max(size(QSMs)); % number of models\ntreedata = zeros(Nattri,Nmod); % Collect all tree attributes from all models\ninputs = zeros(Nmod,3); % collect the inputs from all models\n% ([PatchDiam1 PatchDiam2Min PatchDiam2Max])\nCylDist = zeros(Nmod,10); % collect the distances from all models\nCylSurfCov = zeros(Nmod,10); % collect the surface coverages from all models\ns = 6; % maximum branch order\nOrdDis = zeros(Nmod,4*s); % collect the distributions from all the models\nr = 20; % maximum cylinder diameter\nCylDiaDis = zeros(Nmod,3*r);\nCylZenDis = zeros(Nmod,54);\nTreeId = zeros(Nmod,2); % collectd the tree and model indexes from all models\nKeep = true(Nmod,1); % Non-empty models\n\nfor i = 1:Nmod\n  if ~isempty(QSMs(i).cylinder)\n    % Collect input-parameter values and tree IDs:\n    p = QSMs(i).rundata.inputs;\n    inputs(i,:) = [p.PatchDiam1 p.PatchDiam2Min p.PatchDiam2Max];\n    TreeId(i,:) = [p.tree p.model];\n\n    % Collect cylinder-point distances: mean of all cylinders,\n    % mean of trunk, branch, 1st- and 2nd-order branch cylinders.\n    % And the maximum of the previous:\n    D = QSMs(i).pmdistance;\n    CylDist(i,:) =  [D.mean  D.TrunkMean  D.BranchMean  D.Branch1Mean ...\n      D.Branch2Mean D.max  D.TrunkMax  D.BranchMax  D.Branch1Max ...\n      D.Branch2Max];\n\n    % Collect surface coverages: mean of all cylinders,\n    % mean of trunk, branch, 1st- and 2nd-order branch cylinders.\n    % And the minimum of the previous:\n    D = QSMs(i).cylinder.SurfCov;\n    T = QSMs(i).cylinder.branch == 1;\n    B1 = QSMs(i).cylinder.BranchOrder == 1;\n    B2 = QSMs(i).cylinder.BranchOrder == 2;\n    if ~any(B1)\n      CylSurfCov(i,:) =  [mean(D)  mean(D(T))  0 0 0 ...\n         min(D) min(D(T)) 0 0 0];\n    elseif ~any(B2)\n      CylSurfCov(i,:) =  [mean(D)  mean(D(T))  mean(D(~T))  mean(D(B1)) ...\n        0 min(D) min(D(T)) min(D(~T)) min(D(B1)) 0];\n    else\n      CylSurfCov(i,:) =  [mean(D)  mean(D(T))  mean(D(~T))  mean(D(B1)) ...\n        mean(D(B2)) min(D) min(D(T)) min(D(~T)) min(D(B1)) min(D(B2))];\n    end\n\n    % Collect branch-order distributions:\n    d = QSMs(i).treedata.VolBranchOrd;\n    nd = length(d);\n    if nd > 0\n      a = min(nd,s);\n      OrdDis(i,1:a) = d(1:a);\n      OrdDis(i,s+1:s+a) = QSMs(i).treedata.AreBranchOrd(1:a);\n      OrdDis(i,2*s+1:2*s+a) = QSMs(i).treedata.LenBranchOrd(1:a);\n      OrdDis(i,3*s+1:3*s+a) = QSMs(i).treedata.NumBranchOrd(1:a);\n    end\n\n    % Collect cylinder diameter distributions:\n    d = QSMs(i).treedata.VolCylDia;\n    nd = length(d);\n    if nd > 0\n      a = min(nd,r);\n      CylDiaDis(i,1:a) = d(1:a);\n      CylDiaDis(i,r+1:r+a) = QSMs(i).treedata.AreCylDia(1:a);\n      CylDiaDis(i,2*r+1:2*r+a) = QSMs(i).treedata.LenCylDia(1:a);\n    end\n\n    % Collect cylinder zenith direction distributions:\n    d = QSMs(i).treedata.VolCylZen;\n    if ~isempty(d)\n      CylZenDis(i,1:18) = d;\n      CylZenDis(i,19:36) = QSMs(i).treedata.AreCylZen;\n      CylZenDis(i,37:54) = QSMs(i).treedata.LenCylZen;\n    end\n\n    % Collect the treedata values from each model\n    for j = 1:Nattri\n      treedata(j,i) = QSMs(i).treedata.(names{j});\n    end\n\n  else\n    Keep(i) = false;\n  end\nend\ntreedata = treedata(:,Keep);\ninputs = inputs(Keep,:);\nTreeId = TreeId(Keep,:);\nclear Data\nData.CylDist = CylDist(Keep,:);\nData.CylSurfCov = CylSurfCov(Keep,:);\nData.BranchOrdDis = OrdDis(Keep,:);\nData.CylDiaDis = CylDiaDis(Keep,:);\nData.CylZenDis = CylZenDis(Keep,:);\n\n% End of function\nend\n\n\nfunction [met,Metric] = select_metric(Metric)\n\n% Mean distance metrics:\nif strcmp(Metric,'all_mean_dis')\n  met = 1;\nelseif strcmp(Metric,'trunk_mean_dis')\n  met = 2;\nelseif strcmp(Metric,'branch_mean_dis')\n  met = 3;\nelseif strcmp(Metric,'1branch_mean_dis')\n  met = 4;\nelseif strcmp(Metric,'2branch_mean_dis')\n  met = 5;\nelseif strcmp(Metric,'trunk+branch_mean_dis')\n  met = 6;\nelseif strcmp(Metric,'trunk+1branch_mean_dis')\n  met = 7;\nelseif strcmp(Metric,'trunk+1branch+2branch_mean_dis')\n  met = 8;\nelseif strcmp(Metric,'1branch+2branch_mean_dis')\n  met = 9;\n\n  % Maximum distance metrics:\nelseif strcmp(Metric,'all_max_dis')\n  met = 10;\nelseif strcmp(Metric,'trunk_max_dis')\n  met = 11;\nelseif strcmp(Metric,'branch_max_dis')\n  met = 12;\nelseif strcmp(Metric,'1branch_max_dis')\n  met = 13;\nelseif strcmp(Metric,'2branch_max_dis')\n  met = 14;\nelseif strcmp(Metric,'trunk+branch_max_dis')\n  met = 15;\nelseif strcmp(Metric,'trunk+1branch_max_dis')\n  met = 16;\nelseif strcmp(Metric,'trunk+1branch+2branch_max_dis')\n  met = 17;\nelseif strcmp(Metric,'1branch+2branch_max_dis')\n  met = 18;\n\n  % Mean plus Maximum distance metrics:\nelseif strcmp(Metric,'all_mean+max_dis')\n  met = 19;\nelseif strcmp(Metric,'trunk_mean+max_dis')\n  met = 20;\nelseif strcmp(Metric,'branch_mean+max_dis')\n  met = 21;\nelseif strcmp(Metric,'1branch_mean+max_dis')\n  met = 22;\nelseif strcmp(Metric,'2branch_mean+max_dis')\n  met = 23;\nelseif strcmp(Metric,'trunk+branch_mean+max_dis')\n  met = 24;\nelseif strcmp(Metric,'trunk+1branch_mean+max_dis')\n  met = 25;\nelseif strcmp(Metric,'trunk+1branch+2branch_mean+max_dis')\n  met = 26;\nelseif strcmp(Metric,'1branch+2branch_mean+max_dis')\n  met = 27;\n\n  % Standard deviation metrics:\nelseif strcmp(Metric,'tot_vol_std')\n  met = 28;\nelseif strcmp(Metric,'trunk_vol_std')\n  met = 29;\nelseif strcmp(Metric,'branch_vol_std')\n  met = 30;\nelseif strcmp(Metric,'trunk+branch_vol_std')\n  met = 31;\nelseif strcmp(Metric,'tot_are_std')\n  met = 32;\nelseif strcmp(Metric,'trunk_are_std')\n  met = 33;\nelseif strcmp(Metric,'branch_are_std')\n  met = 34;\nelseif strcmp(Metric,'trunk+branch_are_std')\n  met = 35;\nelseif strcmp(Metric,'trunk_len_std')\n  met = 36;\nelseif strcmp(Metric,'trunk+branch_len_std')\n  met = 37;\nelseif strcmp(Metric,'branch_len_std')\n  met = 38;\nelseif strcmp(Metric,'branch_num_std')\n  met = 39;\n\n  % Branch order distribution metrics:\nelseif strcmp(Metric,'branch_vol_ord3_mean')\n  met = 40;\nelseif strcmp(Metric,'branch_are_ord3_mean')\n  met = 41;\nelseif strcmp(Metric,'branch_len_ord3_mean')\n  met = 42;\nelseif strcmp(Metric,'branch_num_ord3_mean')\n  met = 43;\nelseif strcmp(Metric,'branch_vol_ord3_max')\n  met = 44;\nelseif strcmp(Metric,'branch_are_ord3_max')\n  met = 45;\nelseif strcmp(Metric,'branch_len_ord3_max')\n  met = 46;\nelseif strcmp(Metric,'branch_num_ord3_max')\n  met = 47;\nelseif strcmp(Metric,'branch_vol_ord6_mean')\n  met = 48;\nelseif strcmp(Metric,'branch_are_ord6_mean')\n  met = 49;\nelseif strcmp(Metric,'branch_len_ord6_mean')\n  met = 50;\nelseif strcmp(Metric,'branch_num_ord6_mean')\n  met = 51;\nelseif strcmp(Metric,'branch_vol_ord6_max')\n  met = 52;\nelseif strcmp(Metric,'branch_are_ord6_max')\n  met = 53;\nelseif strcmp(Metric,'branch_len_ord6_max')\n  met = 54;\nelseif strcmp(Metric,'branch_num_ord6_max')\n  met = 55;\n\n  % Cylinder distribution metrics:\nelseif strcmp(Metric,'cyl_vol_dia10_mean')\n  met = 56;\nelseif strcmp(Metric,'cyl_are_dia10_mean')\n  met = 57;\nelseif strcmp(Metric,'cyl_len_dia10_mean')\n  met = 58;\nelseif strcmp(Metric,'cyl_vol_dia10_max')\n  met = 59;\nelseif strcmp(Metric,'cyl_are_dia10_max')\n  met = 60;\nelseif strcmp(Metric,'cyl_len_dia10_max')\n  met = 61;\nelseif strcmp(Metric,'cyl_vol_dia20_mean')\n  met = 62;\nelseif strcmp(Metric,'cyl_are_dia20_mean')\n  met = 63;\nelseif strcmp(Metric,'cyl_len_dia20_mean')\n  met = 64;\nelseif strcmp(Metric,'cyl_vol_dia20_max')\n  met = 65;\nelseif strcmp(Metric,'cyl_are_dia20_max')\n  met = 66;\nelseif strcmp(Metric,'cyl_len_dia20_max')\n  met = 67;\nelseif strcmp(Metric,'cyl_vol_zen_mean')\n  met = 68;\nelseif strcmp(Metric,'cyl_are_zen_mean')\n  met = 69;\nelseif strcmp(Metric,'cyl_len_zen_mean')\n  met = 70;\nelseif strcmp(Metric,'cyl_vol_zen_max')\n  met = 71;\nelseif strcmp(Metric,'cyl_are_zen_max')\n  met = 72;\nelseif strcmp(Metric,'cyl_len_zen_max')\n  met = 73;\n\n  % Mean surface coverage metrics:\nelseif strcmp(Metric,'all_mean_surf')\n  met = 74;\nelseif strcmp(Metric,'trunk_mean_surf')\n  met = 75;\nelseif strcmp(Metric,'branch_mean_surf')\n  met = 76;\nelseif strcmp(Metric,'1branch_mean_surf')\n  met = 77;\nelseif strcmp(Metric,'2branch_mean_surf')\n  met = 78;\nelseif strcmp(Metric,'trunk+branch_mean_surf')\n  met = 79;\nelseif strcmp(Metric,'trunk+1branch_mean_surf')\n  met = 80;\nelseif strcmp(Metric,'trunk+1branch+2branch_mean_surf')\n  met = 81;\nelseif strcmp(Metric,'1branch+2branch_mean_surf')\n  met = 82;\n\n  % Minimum surface coverage metrics:\nelseif strcmp(Metric,'all_min_surf')\n  met = 83;\nelseif strcmp(Metric,'trunk_min_surf')\n  met = 84;\nelseif strcmp(Metric,'branch_min_surf')\n  met = 85;\nelseif strcmp(Metric,'1branch_min_surf')\n  met = 86;\nelseif strcmp(Metric,'2branch_min_surf')\n  met = 87;\nelseif strcmp(Metric,'trunk+branch_min_surf')\n  met = 88;\nelseif strcmp(Metric,'trunk+1branch_min_surf')\n  met = 89;\nelseif strcmp(Metric,'trunk+1branch+2branch_min_surf')\n  met = 90;\nelseif strcmp(Metric,'1branch+2branch_min_surf')\n  met = 91;\n\n  % Not given in right form, take the default option\nelse\n  met = 1;\n  Metric = 'all_mean_dis';\nend\n% End of function\nend\n\n\nfunction D = compute_metric_value(met,T,treedata,Data)\n\n\nif met <= 27 % cylinder distance metrics:\n  D = mean(Data.CylDist(T,:),1);\n  D(6:10) = 0.5*D(6:10); % Half the maximum values\nend\n\nif met < 10 % mean cylinder distance metrics:\n  if met == 1 % all_mean_dis\n    D = D(1);\n  elseif met == 2 % trunk_mean_dis\n    D = D(2);\n  elseif met == 3 % branch_mean_dis\n    D = D(3);\n  elseif met == 4 % 1branch_mean_dis\n    D = D(4);\n  elseif met == 5 % 2branch_mean_dis\n    D = D(5);\n  elseif met == 6 % trunk+branch_mean_dis\n    D = D(2)+D(3);\n  elseif met == 7 % trunk+1branch_mean_dis\n    D = D(2)+D(4);\n  elseif met == 8 % trunk+1branch+2branch_mean_dis\n    D = D(2)+D(4)+D(5);\n  elseif met == 9 % 1branch+2branch_mean_dis\n    D = D(4)+D(5);\n  end\n\nelseif met < 19 % maximum cylinder distance metrics:\n  if met == 10 % all_max_dis\n    D = D(6);\n  elseif met == 11 % trunk_max_dis\n    D = D(7);\n  elseif met == 12 % branch_max_dis\n    D = D(8);\n  elseif met == 13 % 1branch_max_dis\n    D = D(9);\n  elseif met == 14 % 2branch_max_dis\n    D = D(10);\n  elseif met == 15 % trunk+branch_max_dis\n    D = D(7)+D(8);\n  elseif met == 16 % trunk+1branch_max_dis\n    D = D(7)+D(9);\n  elseif met == 17 % trunk+1branch+2branch_max_dis\n    D = D(7)+D(9)+D(10);\n  elseif met == 18 % 1branch+2branch_max_dis\n    D = D(9)+D(10);\n  end\n\nelseif met < 28 % Mean plus maximum cylinder distance metrics:\n  if met == 19 % all_mean+max_dis\n    D = D(1)+D(6);\n  elseif met == 20 % trunk_mean+max_dis\n    D = D(2)+D(7);\n  elseif met == 21 % branch_mean+max_dis\n    D = D(3)+D(8);\n  elseif met == 22 % 1branch_mean+max_dis\n    D = D(4)+D(9);\n  elseif met == 23 % 2branch_mean+max_dis\n    D = D(5)+D(10);\n  elseif met == 24 % trunk+branch_mean+max_dis\n    D = D(2)+D(3)+D(7)+D(8);\n  elseif met == 25 % trunk+1branch_mean+max_dis\n    D = D(2)+D(4)+D(7)+D(9);\n  elseif met == 26 % trunk+1branch+2branch_mean+max_dis\n    D = D(2)+D(4)+D(5)+D(7)+D(9)+D(10);\n  elseif met == 27 % 1branch+2branch_mean+max_dis\n    D = D(4)+D(5)+D(9)+D(10);\n  end\n\nelseif met < 39 % Standard deviation metrics:\n  if met == 28 % tot_vol_std\n    D = std(treedata(1,T));\n  elseif met == 29 % trunk_vol_std\n    D = std(treedata(2,T));\n  elseif met == 30 % branch_vol_std\n    D = std(treedata(3,T));\n  elseif met == 31 % trunk+branch_vol_std\n    D = std(treedata(2,T))+std(treedata(3,T));\n  elseif met == 32 % tot_are_std\n    D = std(treedata(12,T));\n  elseif met == 33 % trunk_are_std\n    D = std(treedata(10,T));\n  elseif met == 34 % branch_are_std\n    D = std(treedata(11,T));\n  elseif met == 35 % trunk+branch_are_std\n    D = std(treedata(10,T))+std(treedata(11,T));\n  elseif met == 36 % trunk_len_std\n    D = std(treedata(5,T));\n  elseif met == 37 % branch_len_std\n    D = std(treedata(6,T));\n  elseif met == 38 % trunk+branch_len_std\n    D = std(treedata(5,T))+std(treedata(6,T));\n  elseif met == 39 % branch_num_std\n    D = std(treedata(8,T));\n  end\n\nelseif met < 56 % Branch order metrics:\n  dis = max(Data.BranchOrdDis(T,:),[],1)-min(Data.BranchOrdDis(T,:),[],1);\n  M = mean(Data.BranchOrdDis(T,:),1);\n  I = M > 0;\n  dis(I) = dis(I)./M(I);\n  if met == 40 % branch_vol_ord3_mean\n    D = mean(dis(1:3));\n  elseif met == 41 % branch_are_ord3_mean\n    D = mean(dis(7:9));\n  elseif met == 42 % branch_len_ord3_mean\n    D = mean(dis(13:15));\n  elseif met == 43 % branch_num_ord3_mean\n    D = mean(dis(19:21));\n  elseif met == 44 % branch_vol_ord3_max\n    D = max(dis(1:3));\n  elseif met == 45 % branch_are_ord3_max\n    D = max(dis(7:9));\n  elseif met == 46 % branch_len_ord3_max\n    D = max(dis(13:15));\n  elseif met == 47 % branch_vol_ord3_max\n    D = max(dis(19:21));\n  elseif met == 48 % branch_vol_ord6_mean\n    D = mean(dis(1:6));\n  elseif met == 49 % branch_are_ord6_mean\n    D = mean(dis(7:12));\n  elseif met == 50 % branch_len_ord6_mean\n    D = mean(dis(13:18));\n  elseif met == 51 % branch_num_ord6_mean\n    D = mean(dis(19:24));\n  elseif met == 52 % branch_vol_ord6_max\n    D = max(dis(1:6));\n  elseif met == 53 % branch_are_ord6_max\n    D = max(dis(7:12));\n  elseif met == 54 % branch_len_ord6_max\n    D = max(dis(13:18));\n  elseif met == 55 % branch_vol_ord6_max\n    D = max(dis(19:24));\n  end\n\nelseif met < 68 % Cylinder diameter distribution metrics:\n  dis = max(Data.CylDiaDis(T,:),[],1)-min(Data.CylDiaDis(T,:),[],1);\n  M = mean(Data.CylDiaDis(T,:),1);\n  I = M > 0;\n  dis(I) = dis(I)./M(I);\n  if met == 56 % cyl_vol_dia10_mean\n    D = mean(dis(1:10));\n  elseif met == 57 % cyl_are_dia10_mean\n    D = mean(dis(21:30));\n  elseif met == 58 % cyl_len_dia10_mean\n    D = mean(dis(41:50));\n  elseif met == 59 % cyl_vol_dia10_max\n    D = max(dis(1:10));\n  elseif met == 60 % cyl_are_dia10_max\n    D = max(dis(21:30));\n  elseif met == 61 % cyl_len_dia10_max\n    D = max(dis(41:50));\n  elseif met == 62 % cyl_vol_dia20_mean\n    D = mean(dis(1:20));\n  elseif met == 63 % cyl_are_dia20_mean\n    D = mean(dis(21:40));\n  elseif met == 64 % cyl_len_dia20_mean\n    D = mean(dis(41:60));\n  elseif met == 65 % cyl_vol_dia20_max\n    D = max(dis(1:20));\n  elseif met == 66 % cyl_are_dia20_max\n    D = max(dis(21:40));\n  elseif met == 67 % cyl_len_dia20_max\n    D = max(dis(41:60));\n  end\n\nelseif met < 74 % Cylinder zenith distribution metrics:\n  dis = max(Data.CylZenDis(T,:),[],1)-min(Data.CylZenDis(T,:),[],1);\n  M = mean(Data.CylZenDis(T,:),1);\n  I = M > 0;\n  dis(I) = dis(I)./M(I);\n  if met == 68 % cyl_vol_zen_mean\n    D = mean(dis(1:18));\n  elseif met == 69 % cyl_are_zen_mean\n    D = mean(dis(19:36));\n  elseif met == 70 % cyl_len_zen_mean\n    D = mean(dis(37:54));\n  elseif met == 71 % cyl_vol_zen_max\n    D = max(dis(1:18));\n  elseif met == 72 % cyl_are_zen_max\n    D = max(dis(19:36));\n  elseif met == 73 % cyl_len_zen_max\n    D = max(dis(37:54));\n  end\n\nelseif met < 92 % Surface coverage metrics:\n  D = 1-mean(Data.CylSurfCov(T,:),1);\n  if met == 74 % all_mean_surf\n    D = D(1);\n  elseif met == 75 % trunk_mean_surf\n    D = D(2);\n  elseif met == 76 % branch_mean_surf\n    D = D(3);\n  elseif met == 77 % 1branch_mean_surf\n    D = D(4);\n  elseif met == 78 % 2branch_mean_surf\n    D = D(5);\n  elseif met == 79 % trunk+branch_mean_surf\n    D = D(2)+D(3);\n  elseif met == 80 % trunk+1branch_mean_surf\n    D = D(2)+D(4);\n  elseif met == 81 % trunk+1branch+2branch_mean_surf\n    D = D(2)+D(4)+D(5);\n  elseif met == 82 % 1branch+2branch_mean_surf\n    D = D(4)+D(5);\n  elseif met == 83 % all_min_surf\n    D = D(6);\n  elseif met == 84 % trunk_min_surf\n    D = D(7);\n  elseif met == 85 % branch_min_surf\n    D = D(8);\n  elseif met == 86 % 1branch_min_surf\n    D = D(9);\n  elseif met == 87 % 2branch_min_surf\n    D = D(10);\n  elseif met == 88 % trunk+branch_min_surf\n    D = D(6)+D(7);\n  elseif met == 89 % trunk+1branch_min_surf\n    D = D(6)+D(8);\n  elseif met == 90 % trunk+1branch+2branch_min_surf\n    D = D(6)+D(9)+D(10);\n  elseif met == 91 % 1branch+2branch_min_surf\n    D = D(9)+D(10);\n  end\nend\n% End of function\nend\n\n\nfunction Sensi = sensitivity_analysis(TreeDataAll,TreeId,Inputs,OptIn,NInputs)\n\n% Computes the sensitivity of tree attributes (e.g. total volume) to the\n% changes of input parameter, the PatchDiam parameters, values. The\n% sensitivity is normalized, i.e. the relative change of attribute value\n% (= max change in attribute value divided by the value with the optimal\n% inputs) is divided by the relative change of input parameter value. The\n% sensitivity is also expressed as percentage, i.e. multiplied by 100. The\n% sensitivity is computed relative PatchDiam1, PatchDiam2Min, and\n% PatchDiam2Max. The sensitivity is computed only from the attributes with\n% the input parameter values the closest to the optimal value. This way we\n% get the local sensitivity in the neighborhood of the optimal input.\n%\n% Output:\n% Sensi       3D-array (#trees,#attributes,#inputs)\n\nTreeIds = unique(TreeId(:,1)); % Unique tree IDs\nnt = length(TreeIds); % number of trees\nA = [2 3; 1 3; 1 2]; % Keep other two inputs constant and let one varie\nSensi = zeros(nt,size(TreeDataAll,3),3); % initialization of the output\nfor t = 1:nt % trees\n  if NInputs(t) > 1\n    D = squeeze(TreeDataAll(t,1:NInputs(t),:))'; % Select the attributes for the tree\n    In = squeeze(Inputs(t,1:NInputs(t),:)); % Select the inputs for the tree\n    n = size(In,1); % number of different input-combinations\n    I = all(In == OptIn(t,1:3),2); % Which data are with the optimal inputs\n    ind = (1:1:n)';\n    I = ind(I);\n    for i = 1:3 % inputs\n      if length(unique(In(:,i))) > 1\n        dI = abs(max(In(:,i),[],2)-OptIn(t,i));\n        dImin = min(dI(dI > 0)); % the minimum nonzero absolute change in inputs\n        dI = dImin/OptIn(t,i); % relative change in the attributes\n        K1 = abs(max(In(:,i),[],2)-min(OptIn(t,i),[],2)) < dImin+0.0001;\n        K = K1 & abs(max(In(:,i),[],2)-min(OptIn(t,i),[],2)) > 0.0001;\n        K = ind(K); % the inputs the closest to the optimal input\n        J = all(In(K,A(i,:)) == OptIn(t,A(i,:)),2);\n        J = K(J); % input i the closest to the optimal and the other two equal the optimal\n        dD = max(abs(D(:,J)-D(:,I)),[],2);\n        dD = dD./D(:,I); % relative change in the input\n        d = dD/dI*100; % relative sensitivity as a percentage\n        Sensi(t,:,i) = round(100*d)/100;\n      end\n    end\n  end\nend\n% End of function\nend\n"
  },
  {
    "path": "src/tools/average.m",
    "content": "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;\nelse\n    A = X;\nend"
  },
  {
    "path": "src/tools/change_precision.m",
    "content": "function v = change_precision(v)\n\n% Decrease the number of nonzero decimals in the vector v according to the\n% exponent of the number for displaying and writing.\n\nn = length(v);\nfor i = 1:n\n    if abs(v(i)) >= 1e3\n        v(i) = round(v(i));\n    elseif abs(v(i)) >= 1e2\n        v(i) = round(10*v(i))/10;\n    elseif abs(v(i)) >= 1e1\n        v(i) = round(100*v(i))/100;\n    elseif abs(v(i)) >= 1e0\n        v(i) = round(1000*v(i))/1000;\n    elseif abs(v(i)) >= 1e-1\n        v(i) = round(10000*v(i))/10000;\n    else\n        v(i) = round(100000*v(i))/100000;\n    end\nend"
  },
  {
    "path": "src/tools/connected_components.m",
    "content": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction [Components,CompSize] = connected_components(Nei,Sub,MinSize,Fal)\n\n% ---------------------------------------------------------------------\n% CONNECTED_COMPONENTS.M      Determines the connected components of cover\n%                                   sets using their neighbour-relation\n%\n% Version 1.1\n% Latest update     16 Aug 2017\n%\n% Copyright (C) 2013-2017 Pasi Raumonen\n% ---------------------------------------------------------------------\n\n% Determines connected components of the subset of cover sets defined\n% by \"Sub\" such that each component has at least \"MinSize\"\n% number of cover sets.\n%\n% Inputs:\n% Nei       Neighboring cover sets of each cover set, (n_sets x 1)-cell\n% Sub       Subset whose components are determined,\n%               length(Sub) < 2 means no subset and thus the whole point cloud\n%               \"Sub\" may be also a vector of cover set indexes in the subset\n%               or a logical (n_sets)-vector, where n_sets is the number of\n%               all cover sets\n% MinSize   Minimum number of cover sets in an acceptable component\n% Fal       Logical false vector for the cover sets\n%\n% Outputs:\n% Components    Connected components, (n_comp x 1)-cell\n% CompSize      Number of sets in the components, (n_comp x 1)-vector\n\nif length(Sub) <= 3 && ~islogical(Sub) && Sub(1) > 0\n    % Very small subset, i.e. at most 3 cover sets\n    n = length(Sub);\n    if n == 1\n        Components = cell(1,1);\n        Components{1} = uint32(Sub);\n        CompSize = 1;\n    elseif n == 2\n        I = Nei{Sub(1)} == Sub(2);\n        if any(I)\n            Components = cell(1,1);\n            Components{1} = uint32((Sub));\n            CompSize = 1;\n        else\n            Components = cell(2,1);\n            Components{1} = uint32(Sub(1));\n            Components{2} = uint32(Sub(2));\n            CompSize = [1 1];\n        end\n    elseif n == 3\n        I = Nei{Sub(1)} == Sub(2);\n        J = Nei{Sub(1)} == Sub(3);\n        K = Nei{Sub(2)} == Sub(3);\n        if any(I)+any(J)+any(K) >= 2\n            Components = cell(1,1);\n            Components{1} = uint32(Sub);\n            CompSize = 1;\n        elseif any(I)\n            Components = cell(2,1);\n            Components{1} = uint32(Sub(1:2));\n            Components{2} = uint32(Sub(3));\n            CompSize = [2 1];\n        elseif any(J)\n            Components = cell(2,1);\n            Components{1} = uint32(Sub([1 3]));\n            Components{2} = uint32(Sub(2));\n            CompSize = [2 1];\n        elseif any(K)\n            Components = cell(2,1);\n            Components{1} = uint32(Sub(2:3));\n            Components{2} = uint32(Sub(1));\n            CompSize = [2 1];\n        else\n            Components = cell(3,1);\n            Components{1} = uint32(Sub(1));\n            Components{2} = uint32(Sub(2));\n            Components{3} = uint32(Sub(3));\n            CompSize = [1 1 1];\n        end\n    end\n    \nelseif any(Sub) || (length(Sub) == 1 && Sub(1) == 0)\n    nb = size(Nei,1);\n    if nargin == 3\n        Fal = false(nb,1);\n    end\n    if length(Sub) == 1 && Sub == 0\n        % All the cover sets\n        ns = nb;\n        if nargin == 3\n            Sub = true(nb,1);\n        else\n            Sub = ~Fal;\n        end\n    elseif ~islogical(Sub)\n        % Subset of cover sets\n        ns = length(Sub);\n        if nargin == 3\n            sub = false(nb,1);\n        else\n            sub = Fal;\n        end\n        sub(Sub) = true;\n        Sub = sub;\n    else\n        % Subset of cover sets\n        ns = nnz(Sub);\n    end\n    \n    Components = cell(ns,1);\n    CompSize = zeros(ns,1,'uint32');\n    nc = 0;      % number of components found\n    m = 1;\n    while ~Sub(m)\n        m = m+1;\n    end\n    i = 0;\n    Comp = zeros(ns,1,'uint32');\n    while i < ns\n        Add = Nei{m};\n        I = Sub(Add);\n        Add = Add(I);\n        a = length(Add);\n        Comp(1) = m;\n        Sub(m) = false;\n        t = 1;\n        while a > 0\n            Comp(t+1:t+a) = Add;\n            Sub(Add) = false;\n            t = t+a;\n            Add = vertcat(Nei{Add});\n            I = Sub(Add);\n            Add = Add(I);\n            % select the unique elements of Add:\n            n = length(Add);\n            if n > 2\n                I = true(n,1);\n                for j = 1:n\n                    if ~Fal(Add(j))\n                        Fal(Add(j)) = true;\n                    else\n                        I(j) = false;\n                    end\n                end\n                Fal(Add) = false;\n                Add = Add(I);\n            elseif n == 2\n                if Add(1) == Add(2)\n                    Add = Add(1);\n                end\n            end\n            a = length(Add);\n        end\n        i = i+t;\n        if t >= MinSize\n            nc = nc+1;\n            Components{nc} = uint32(Comp(1:t));\n            CompSize(nc) = t;\n        end\n        if i < ns\n            while m <= nb && Sub(m) == false\n                m = m+1;\n            end\n        end\n    end\n    Components = Components(1:nc);\n    CompSize = CompSize(1:nc);\nelse\n    Components = cell(0,1);\n    CompSize = 0;\nend"
  },
  {
    "path": "src/tools/cross_product.m",
    "content": "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(3)*B(1)-A(1)*B(3);  A(1)*B(2)-A(2)*B(1)]; "
  },
  {
    "path": "src/tools/cubical_averaging.m",
    "content": "function DSP = cubical_averaging(P,CubeSize)\n\ntic\n% Downsamples the given point cloud by averaging points from each \n% cube of side length CubeSize. \n\n% The vertices of the big cube containing P\nMin = double(min(P));\nMax = double(max(P));\n\n% Number of cubes with edge length \"EdgeLength\" in the sides \n% of the big cube\nN = double(ceil((Max-Min)/CubeSize)+1);\n\nCubeCoord = floor([P(:,1)-Min(1) P(:,2)-Min(2) P(:,3)-Min(3)]/CubeSize)+1;\n\n% Sorts the points according a lexicographical order\nLexOrd = [CubeCoord(:,1) CubeCoord(:,2)-1 CubeCoord(:,3)-1]*[1 N(1) N(1)*N(2)]';\n[LexOrd,SortOrd] = sort(LexOrd);\nnc = size(unique(LexOrd),1); % number of points in the downsampled point cloud\nnp = size(P,1);     % number of points\nDSP = zeros(nc,3);  % Downsampled point cloud\np = 1;              % The index of the point under comparison\nq = 0;\nwhile p <= np\n    t = 1;\n    while (p+t <= np) && (LexOrd(p) == LexOrd(p+t))\n        t = t+1;\n    end\n    q = q+1;\n    DSP(q,:) = average(P(SortOrd(p:p+t-1),:));\n    p = p+t;\nend\ntoc\n\ndisp(['    Points before:  ',num2str(np)])\ndisp(['  Filtered points:  ',num2str(np-nc)])\ndisp(['      Points left:  ',num2str(nc)]);\n"
  },
  {
    "path": "src/tools/cubical_downsampling.m",
    "content": "function Pass = cubical_downsampling(P,CubeSize)\n\n% Downsamples the given point cloud by selecting one point from each \n% cube of side length \"CubeSize\". \n\n% The vertices of the big cube containing P\nMin = double(min(P));\nMax = double(max(P));\n\n% Number of cubes with edge length \"EdgeLength\" in the sides \n% of the big cube\nN = double(ceil((Max-Min)/CubeSize)+1);\n\n% Process the data in 1e7-point blocks to consume much less memory \nnp = size(P,1);\nm = 1e7;\nif np < m\n    m = np;\nend\nnblocks = ceil(np/m); % number of blocks\n\n% Downsample\nR = cell(nblocks,1);\np = 1;\nfor i = 1:nblocks\n    if i < nblocks\n        % Compute the cube coordinates of the points\n        C = floor([double(P(p:p+m-1,1))-Min(1) double(P(p:p+m-1,2))-Min(2)...\n            double(P(p:p+m-1,3))-Min(3)]/CubeSize)+1;\n        % Compute the lexicographical order of the cubes\n        S = [C(:,1) C(:,2)-1 C(:,3)-1]*[1 N(1) N(1)*N(2)]';\n        [S,I] = unique(S); % Select the unique cubes\n        J = (p:1:p+m-1)';\n        J = J(I);\n        R{i} = [S J];\n    else\n        C = floor([double(P(p:end,1))-Min(1) double(P(p:end,2))-Min(2)...\n            double(P(p:end,3))-Min(3)]/CubeSize)+1;\n        S = [C(:,1) C(:,2)-1 C(:,3)-1]*[1 N(1) N(1)*N(2)]';\n        [S,I] = unique(S);\n        J = (p:1:np)';\n        J = J(I);\n        R{i} = [S J];\n    end\n    p = p+m;\nend\n% Select the unique cubes and their points\nR = vertcat(R{:});\n[~,I] = unique(R(:,1));\nPass = false(np,1);\nPass(R(I,2)) = true;\n"
  },
  {
    "path": "src/tools/cubical_partition.m",
    "content": "% 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 terms of the GNU General Public License as published by\r\n% the Free Software Foundation, either version 3 of the License, or\r\n% (at your option) any later version.\r\n%\r\n% TREEQSM is distributed in the hope that it will be useful,\r\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n% GNU General Public License for more details.\r\n%\r\n% You should have received a copy of the GNU General Public License\r\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\r\n\r\nfunction [Partition,CubeCoord,Info,Cubes] = cubical_partition(P,EL,NE)\r\n\r\n% ---------------------------------------------------------------------\r\n% CUBICAL_PARTITION.M    Partitions the point cloud into cubes.\r\n%\r\n% Version 1.1.0\r\n% Latest update     6 Oct 2021\r\n%\r\n% Copyright (C) 2015-2021 Pasi Raumonen\r\n% ---------------------------------------------------------------------\r\n\r\n% Inputs:\r\n% P           Point cloud, (n_points x 3)-matrix\r\n% EL          Length of the cube edges\r\n% NE          Number of empty edge layers\r\n%\r\n% Outputs:\r\n% Partition   Point cloud partitioned into cubical cells,\r\n%                 (nx x ny x nz)-cell, where nx,ny,nz are the number\r\n%                 of cubes in x,y,z-directions, respectively. If \"Cubes\"\r\n%                 is outputed, then \"Partition\" is (n x 1)-cell, where each\r\n%                 cell corresponds to a nonempty cube.\r\n%\r\n% CC          (n_points x 3)-matrix whose rows are the cube coordinates\r\n%                 of each point: x,y,z-coordinates\r\n% Info        The minimum coordinate values and number of cubes in each\r\n%                 coordinate direction\r\n% Cubes       (Optional) (nx x ny x nz)-matrix (array), each nonzero\r\n%                 element indicates that its cube is nonempty and the\r\n%                 number indicates which cell in \"Partition\" contains the\r\n%                 points of the cube.\r\n% ---------------------------------------------------------------------\r\n\r\n% Changes from version 1.0.0 to 1.1.0, 6 Oct 2021:\r\n% 1) Changed the determinationa EL and NE so that the while loop don't\r\n%     continue endlessly in some cases\r\n\r\nif nargin == 2\r\n  NE = 3;\r\nend\r\n\r\n% The vertices of the big cube containing P\r\nMin = double(min(P));\r\nMax = double(max(P));\r\n\r\n% Number of cubes with edge length \"EdgeLength\" in the sides\r\n% of the big cube\r\nN = double(ceil((Max-Min)/EL)+2*NE+1);\r\nt = 0;\r\nwhile t < 10 && 8*N(1)*N(2)*N(3) > 4e9\r\n  t = t+1;\r\n  EL = 1.1*EL;\r\n  N = double(ceil((Max-Min)/EL)+2*NE+1);\r\nend\r\nif 8*N(1)*N(2)*N(3) > 4e9\r\n  NE = 3;\r\n  N = double(ceil((Max-Min)/EL)+2*NE+1);\r\nend\r\nInfo = [Min N EL NE];\r\n\r\n% Calculates the cube-coordinates of the points\r\nCubeCoord = floor([P(:,1)-Min(1) P(:,2)-Min(2) P(:,3)-Min(3)]/EL)+NE+1;\r\n\r\n% Sorts the points according a lexicographical order\r\nLexOrd = [CubeCoord(:,1) CubeCoord(:,2)-1 CubeCoord(:,3)-1]*[1 N(1) N(1)*N(2)]';\r\nCubeCoord = uint16(CubeCoord);\r\n[LexOrd,SortOrd] = sort(LexOrd);\r\nSortOrd = uint32(SortOrd);\r\nLexOrd = uint32(LexOrd);\r\n\r\nif nargout <= 3\r\n  % Define \"Partition\"\r\n  Partition = cell(N(1),N(2),N(3));\r\n  np = size(P,1);     % number of points\r\n  p = 1;              % The index of the point under comparison\r\n  while p <= np\r\n    t = 1;\r\n    while (p+t <= np) && (LexOrd(p) == LexOrd(p+t))\r\n      t = t+1;\r\n    end\r\n    q = SortOrd(p);\r\n    Partition{CubeCoord(q,1),CubeCoord(q,2),CubeCoord(q,3)} = SortOrd(p:p+t-1);\r\n    p = p+t;\r\n  end\r\n\r\nelse\r\n  nc = size(unique(LexOrd),1);\r\n\r\n  % Define \"Partition\"\r\n  Cubes = zeros(N(1),N(2),N(3),'uint32');\r\n  Partition = cell(nc,1);\r\n  np = size(P,1);     % number of points\r\n  p = 1;              % The index of the point under comparison\r\n  c = 0;\r\n  while p <= np\r\n    t = 1;\r\n    while (p+t <= np) && (LexOrd(p) == LexOrd(p+t))\r\n      t = t+1;\r\n    end\r\n    q = SortOrd(p);\r\n    c = c+1;\r\n    Partition{c,1} = SortOrd(p:p+t-1);\r\n    Cubes(CubeCoord(q,1),CubeCoord(q,2),CubeCoord(q,3)) = c;\r\n    p = p+t;\r\n  end\r\nend\r\n"
  },
  {
    "path": "src/tools/define_input.m",
    "content": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction inputs = define_input(Clouds,nPD1,nPD2Min,nPD2Max)\n\n% ---------------------------------------------------------------------\n% DEFINE_INPUT.M       Defines the required inputs (PatchDiam and BallRad \n%                        parameters) for TreeQSM based in estimated tree\n%                        radius.\n%\n% Version 1.0.0\n% Latest update     4 May 2022\n%\n% Copyright (C) 2013-2022 Pasi Raumonen\n% ---------------------------------------------------------------------\n\n% Takes in a single tree point clouds, that preferably contains only points \n% from the tree and not e.g. from groung. User defines the number of\n% PatchDiam1, PatchDiam2Min, PatchDiam2Max parameter values needed. Then\n% the code estimates automatically these parameter values based on the \n% tree stem radius and tree height. Thus this code can be used to generate\n% the inputs needed for QSM reconstruction with TreeQSM.\n%\n% Inputs:\n% P         Point cloud of a tree OR string specifying the name of the .mat\n%             file where multiple point clouds are saved              \n% nPD1      Number of parameter values estimated for PatchDiam1\n% nPD2Min   Number of parameter values estimated for PatchDiam2Min\n% nPD2Max   Number of parameter values estimated for PatchDiam2Max\n%\n% Output:\n% inputs    Input structure with the estimated parameter values\n% ---------------------------------------------------------------------\n\n\n% Create inputs-structure\ncreate_input\nInputs = inputs;\n\n% If given multiple clouds, extract the names\nif ischar(Clouds) || isstring(Clouds)\n  matobj = matfile([Clouds,'.mat']);\n  names = fieldnames(matobj);\n  i = 1;\n  n = max(size(names));\n  while i <= n && ~strcmp(names{i,:},'Properties')\n    i = i+1;\n  end\n  I = (1:1:n);\n  I = setdiff(I,i);\n  names = names(I,1);\n  names = sort(names);\n  nt = max(size(names)); % number of trees/point clouds\nelse\n  P = Clouds;\n  nt = 1;\nend\ninputs(nt).PatchDiam1 = 0;\n\n\n%% Estimate the PatchDiam and BallRad parameters\nfor i = 1:nt\n  if nt > 1\n    % Select point cloud\n    P = matobj.(names{i});\n    inputs(i) = Inputs;\n    inputs(i).name = names{i};\n    inputs(i).tree = i;\n    inputs(i).plot = 0;\n    inputs(i).savetxt = 0;\n    inputs(i).savemat = 0;\n    inputs(i).disp = 0;\n  end\n\n  %% Estimate the stem diameter close to bottom\n  % Define height\n  Hb = min(P(:,3));\n  Ht = max(P(:,3));\n  TreeHeight = double(Ht-Hb);\n  Hei = P(:,3)-Hb;\n\n  % Select a section (0.02-0.1*tree_height) from the bottom of the tree\n  hSecTop = min(4,0.1*TreeHeight);\n  hSecBot = 0.02*TreeHeight;\n  hSec = hSecTop-hSecBot;\n  Sec = Hei > hSecBot & Hei < hSecTop;\n  StemBot = P(Sec,1:3);\n\n  % Estimate stem axis (point and direction)\n  AxisPoint = mean(StemBot);\n  V = StemBot-AxisPoint;\n  V = normalize(V);\n  AxisDir = optimal_parallel_vector(V);\n\n  % Estimate stem diameter\n  d = distances_to_line(StemBot,AxisDir,AxisPoint);\n  Rstem = double(median(d));\n\n  % Point resolution (distance between points)\n  Res = sqrt((2*pi*Rstem*hSec)/size(StemBot,1));\n\n  %% Define the PatchDiam parameters\n  % PatchDiam1 is around stem radius divided by 3.\n  pd1 = Rstem/3;%*max(1,TreeHeight/20);\n  if nPD1 == 1\n    inputs(i).PatchDiam1 = pd1;\n  else\n    n = nPD1;\n    inputs(i).PatchDiam1 = linspace((0.90-(n-2)*0.1)*pd1,(1.10+(n-2)*0.1)*pd1,n);\n  end\n\n  % PatchDiam2Min is around stem radius divided by 6 and increased for\n  % over 20 m heigh trees.\n  pd2 = Rstem/6*min(1,20/TreeHeight);\n  if nPD2Min == 1\n    inputs(i).PatchDiam2Min = pd2;\n  else\n    n = nPD2Min;\n    inputs(i).PatchDiam2Min = linspace((0.90-(n-2)*0.1)*pd2,(1.10+(n-2)*0.1)*pd2,n);\n  end\n\n  % PatchDiam2Max is around stem radius divided by 2.5.\n  pd3 = Rstem/2.5;%*max(1,TreeHeight/20);\n  if nPD2Max == 1\n    inputs(i).PatchDiam2Max = pd3;\n  else\n    n = nPD2Max;\n    inputs(i).PatchDiam2Max = linspace((0.90-(n-2)*0.1)*pd3,(1.10+(n-2)*0.1)*pd3,n);\n  end\n\n  % Define the BallRad parameters:\n  inputs(i).BallRad1 = max([inputs(i).PatchDiam1+1.5*Res;\n    min(1.25*inputs(i).PatchDiam1,inputs(i).PatchDiam1+0.025)]);\n  inputs(i).BallRad2 = max([inputs(i).PatchDiam2Max+1.25*Res;\n    min(1.2*inputs(i).PatchDiam2Max,inputs(i).PatchDiam2Max+0.025)]);\n\n  %plot_point_cloud(P,1,1)\nend\n"
  },
  {
    "path": "src/tools/dimensions.m",
    "content": "function [D,dir] = dimensions(points,varargin)\r\n\r\n% Calculates the box-dimensions and dimension estimates of the point set \r\n% \"points\". Returns also the corresponding direction vectors.\r\n\r\n\r\nif nargin == 2\r\n    P = varargin{1};\r\n    points = P(points,:);\r\nelseif nargin == 3\r\n    P = varargin{1};\r\n    Bal = varargin{2};\r\n    I = vertcat(Bal{points});\r\n    points = P(I,:);\r\nend\r\n\r\nif size(points,2) == 3\r\n    X = cov(points);\r\n    [U,S,~] = svd(X);\r\n    \r\n    dp1 = points*U(:,1);\r\n    dp2 = points*U(:,2);\r\n    dp3 = points*U(:,3);\r\n    \r\n    D = [max(dp1)-min(dp1) max(dp2)-min(dp2) max(dp3)-min(dp3) ...\r\n        (S(1,1)-S(2,2))/S(1,1) (S(2,2)-S(3,3))/S(1,1) S(3,3)/S(1,1)];\r\n    \r\n    dir = [U(:,1)' U(:,2)' U(:,3)'];\r\nelse\r\n    X = cov(points);\r\n    [U,S,~] = svd(X);\r\n    \r\n    dp1 = points*U(:,1);\r\n    dp2 = points*U(:,2);\r\n    \r\n    D = [max(dp1)-min(dp1) max(dp2)-min(dp2) ...\r\n        (S(1,1)-S(2,2))/S(1,1) S(2,2)/S(1,1)];\r\n    \r\n    dir = [U(:,1)' U(:,2)'];\r\nend\r\n"
  },
  {
    "path": "src/tools/display_time.m",
    "content": "function display_time(T1,T2,string,display)\n\n% Display the two times given. \"T1\" is the time named with the \"string\" and\n% \"T2\" is named \"Total\".\n\n% Changes 12 Mar 2018: moved the if statement with display from the end to \n%                      the beginning \n\nif display\n    [tmin,tsec] = sec2min(T1);\n    [Tmin,Tsec] = sec2min(T2);\n    if tmin < 60 && Tmin < 60\n        if tmin < 1 && Tmin < 1\n            str = [string,' ',num2str(tsec),' sec.   Total: ',num2str(Tsec),' sec'];\n        elseif tmin < 1\n            str = [string,' ',num2str(tsec),' sec.   Total: ',num2str(Tmin),...\n                ' min ',num2str(Tsec),' sec'];\n        else\n            str = [string,' ',num2str(tmin),' min ',num2str(tsec),...\n                ' sec.   Total: ',num2str(Tmin),' min ',num2str(Tsec),' sec'];\n        end\n    elseif tmin < 60\n        Thour = floor(Tmin/60);\n        Tmin = Tmin-Thour*60;\n        str = [string,' ',num2str(tmin),' min ',num2str(tsec),...\n            ' sec.   Total: ',num2str(Thour),' hours ',num2str(Tmin),' min'];\n    else\n        thour = floor(tmin/60);\n        tmin = tmin-thour*60;\n        Thour = floor(Tmin/60);\n        Tmin = Tmin-Thour*60;\n        str = [string,' ',num2str(thour),' hours ',num2str(tmin),...\n            ' min.   Total: ',num2str(Thour),' hours ',num2str(Tmin),' min'];\n    end\n    disp(str)\nend"
  },
  {
    "path": "src/tools/distances_between_lines.m",
    "content": "function [DistLines,DistOnRay,DistOnLines] = distances_between_lines(PointRay,DirRay,PointLines,DirLines)\r\n\r\n% Calculates the distances between a ray and lines\r\n\r\n% PointRay      A point of the ray\r\n% DirRay        Unit direction vector of the line\r\n% PointLines    One point of every line\r\n% DirLines      Unit direction vectors of the lines \r\n\r\nPointLines = double(PointLines);\r\nPointRay = double(PointRay);\r\nDirLines = double(DirLines);\r\nDirRay = double(DirRay);\r\n\r\n% Calculate unit vectors N orthogonal to the ray and the lines\r\nN = [DirRay(2)*DirLines(:,3)-DirRay(3)*DirLines(:,2) ...\r\n    DirRay(3)*DirLines(:,1)-DirRay(1)*DirLines(:,3) ...\r\n    DirRay(1)*DirLines(:,2)-DirRay(2)*DirLines(:,1)];\r\nl = sqrt(sum(N.*N,2));\r\nN = [1./l.*N(:,1) 1./l.*N(:,2) 1./l.*N(:,3)];\r\n\r\n% Calculate the distances between the lines\r\nA = -mat_vec_subtraction(PointLines,PointRay);\r\nDistLines = sqrt(abs(sum(A.*N,2))); % distance between lines and the ray\r\n\r\n% Calculate the distances on ray and on lines\r\nb = DirLines*DirRay';\r\nd = A*DirRay';\r\ne = sum(A.*DirLines,2);\r\nDistOnRay = (b.*e-d)./(1-b.^2); % Distances to PointRay from the closest points on the ray\r\nDistOnLines = (e-b.*d)./(1-b.^2); % Distances to PointLines from the closest points on the lines\r\n"
  },
  {
    "path": "src/tools/distances_to_line.m",
    "content": "function [d,V,h,B] = distances_to_line(Q,LineDirec,LinePoint)\r\n\r\n% Calculates the distances of the points, given in the rows of the\r\n% matrix Q, to the line defined by one of its point and its direction.\r\n% \"LineDirec\" must be a unit (1x3)-vector and LinePoint must be a (1x3)-vector.\r\n% \r\n% Last update 8 Oct 2021\r\n\r\nA = Q-LinePoint;\r\nh = A*LineDirec';\r\nB = h*LineDirec;\r\nV = A-B;\r\nd = sqrt(sum(V.*V,2));"
  },
  {
    "path": "src/tools/dot_product.m",
    "content": "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.*B,2);"
  },
  {
    "path": "src/tools/expand.m",
    "content": "function C = expand(Nei,C,n,Forb)\n\n% Expands the given subset \"C\" of cover sets \"n\" times with their neighbors, \n% and optionally, prevents the expansion into \"Forb\" sets. \"C\" is a vector \n% and \"Forb\" can be a number vector or a logical vector.\n\nif nargin == 3\n  for i = 1:n\n    C = union(C,vertcat(Nei{C}));\n  end\n  if size(C,2) > 1\n    C = C';\n  end\nelse\n  if islogical(Forb)\n    for i = 1:n\n      C = union(C,vertcat(Nei{C}));\n      I = Forb(C);\n      C = C(~I);\n    end\n  else\n    for i = 1:n\n      C = union(C,vertcat(Nei{C}));\n      C = setdiff(C,Forb);\n    end\n  end\n  if size(C,2) > 1\n    C = C';\n  end\nend"
  },
  {
    "path": "src/tools/growth_volume_correction.m",
    "content": "function cylinder = growth_volume_correction(cylinder,inputs)\n\n% ---------------------------------------------------------------------\n% GROWTH_VOLUME_CORRECTION.M       Use growth volume allometry approach to \n%                                   modify the radius of cylinders.\n%\n% Version 2.0.0\n% Latest update     16 Sep 2021\n%\n% Copyright (C) 2013-2021 Pasi Raumonen\n% ---------------------------------------------------------------------\n%\n% Use growth volume (= the total volume \"supported by the cylinder\") \n% allometry approach to modify the radius of too large and too small \n% cylinders. Uses the allometry: \n%\n%       Radius = a * GrowthVolume^b + c\n%\n% If cylinder's radius is over fac-times or under 1/fac-times the radius\n% predicted from the growth volume allometry, then correct the radius to \n% match the allometry. However, the radius of the cylinders in the branch\n% tips are never incresed, only decreased by the correction. More details \n% can be from Jan Hackenberg's \"SimpleTree\" papers and documents.\n% ---------------------------------------------------------------------\n% Inputs:\n% cylinder    Structure array that needs to contains the following fields: \n%   radius (Rad)        Radii of the cylinders, vector\n%   length (Len)        Lengths of the cylinders, vector\n%   parent (CPar)       Parents of the cylinders, vector\n% inputs.GrowthVolFac   The factor \"fac\", defines the upper and lower\n%                         allowed radius from the predicted one:\n%                         1/fac*predicted_rad <= rad <= fac*predicted_rad\n% ---------------------------------------------------------------------\n\n% Changes from version 1.0.0 to 2.0.0, 16 Sep 2021:\n% 1) Changed the roles of RADIUS and GROWTH_VOLUME in the allometry, i.e.\n%    the radius is now predicted from the growth volume\n% 2) Do not increase the radius of the branch tip cylinders \n\ndisp('----------')\ndisp('Growth volume based correction of cylinder radii:')\n\nRad = double(cylinder.radius);\nRad0 = Rad;\nLen = double(cylinder.length);\nCPar = cylinder.parent;\nCExt = cylinder.extension;\n\ninitial_volume = round(1000*pi*sum(Rad.^2.*Len));\ndisp([' Initial_volume (L): ',num2str(initial_volume)])\n\n%% Define the child cylinders for each cylinder\nn = length(Rad);\nCChi = cell(n,1);\nind = (1:1:n)';\nfor i = 1:n\n  CChi{i} = ind(CPar == i);\nend\n\n%% Compute the growth volume\nGrowthVol = zeros(n,1); % growth volume\nS = cellfun('length',CChi);\nmodify = S == 0;\nGrowthVol(modify) = pi*Rad(modify).^2.*Len(modify);\nparents = unique(CPar(modify));\nif parents(1) == 0\n  parents = parents(2:end);\nend\nwhile ~isempty(parents)\n  V = pi*Rad(parents).^2.*Len(parents);\n  m = length(parents);\n  for i = 1:m\n    GrowthVol(parents(i)) = V(i)+sum(GrowthVol(CChi{parents(i)}));\n  end\n  parents = unique(CPar(parents));\n  if parents(1) == 0\n    parents = parents(2:end);\n  end\nend\n\n%% Fit the allometry: Rad = a*GV^b;\noptions = optimset('Display','off');\nX = lsqcurvefit(@allometry,[0.5 0.5 0],GrowthVol,Rad,[],[],options);\ndisp(' Allometry model parameters R = a*GV^b+c:')\ndisp(['   Multiplier a: ', num2str(X(1))])\ndisp(['   Exponent b: ', num2str(X(2))])\nif length(X) > 2\ndisp(['   Intersect c: ', num2str(X(3))])\nend\n\n%% Compute the predicted radius from the allometry\nPredRad = allometry(X,GrowthVol);\n\n%% Correct the radii based on the predictions\n% If cylinder's radius is over fac-times or under 1/fac-times the\n% predicted radius, then correct the radius to match the allometry\nfac = inputs.GrowthVolFac;\nmodify = Rad < PredRad/fac | Rad > fac*PredRad;\nmodify(Rad < PredRad/fac & CExt == 0) = 0; % Do not increase the radius at tips\nCorRad = PredRad(modify);\n\n% Plot allometry and radii modification\ngvm = max(GrowthVol);\ngv = (0:0.001:gvm);\nPRad = allometry(X,gv);\nfigure(1)\nplot(GrowthVol,Rad,'.b','Markersize',2)\nhold on\nplot(gv,PRad,'-r','Linewidth',2)\nplot(gv,PRad/fac,'-g','Linewidth',2)\nplot(gv,fac*PRad,'-g','Linewidth',2)\nhold off\ngrid on\nxlabel('Growth volume (m^3)')\nylabel('Radius (m)')\nlegend('radius','predicted radius','minimum radius','maximum radius','Location','NorthWest')\n\nfigure(2)\nhistogram(CorRad-Rad(modify))\nxlabel('Change in radius')\ntitle('Number of cylinders per change in radius class')\n\n% Determine the maximum radius change\nR = Rad(modify);\nD = max(abs(R-CorRad)); % Maximum radius change\nJ = abs(R-CorRad) == D;\nD = CorRad(J)-R(J);\n\n% modify the radius according to allometry\nRad(modify) = CorRad; \ncylinder.radius = Rad;\n\ndisp([' Modified ',num2str(nnz(modify)),' of the ',num2str(n),' cylinders'])\ndisp([' Largest radius change (cm): ',num2str(round(1000*D)/10)])\ncorrected_volume = round(1000*pi*sum(Rad.^2.*Len));\ndisp([' Corrected volume (L): ', num2str(corrected_volume)])\ndisp([' Change in volume (L): ', num2str(corrected_volume-initial_volume)])\ndisp('----------')\n\n% % Plot cylinder models where the color indicates change (green = no change, \n% % red = decreased radius, cyan = increased radius)\n% cylinder.branch = ones(n,1);\n% cylinder.BranchOrder = ones(n,1);\n% I = Rad < Rad0;\n% cylinder.BranchOrder(I) = 2;\n% I = Rad > Rad0;\n% cylinder.BranchOrder(I) = 3;\n% plot_cylinder_model(cylinder,'order',3,20,1)\n% \n% cyl = cylinder;\n% cyl.radius = Rad0;\n% plot_cylinder_model(cyl,'order',4,20,1)\n\nend % End of main function\n\n\nfunction F = allometry(x,xdata)\nF = x(1)*xdata.^x(2)+x(3);\nend\n"
  },
  {
    "path": "src/tools/intersect_elements.m",
    "content": "function Set = intersect_elements(Set1,Set2,False1,False2)\n\n% Determines the intersection of Set1 and Set2.\n\nSet = unique_elements([Set1; Set2],False1);\nFalse1(Set1) = true;\nFalse2(Set2) = true;\nI = False1(Set)&False2(Set);\nSet = Set(I);\n"
  },
  {
    "path": "src/tools/mat_vec_subtraction.m",
    "content": "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)-matrix, then v needs to be m-vector.\r\n\r\nfor i = 1:size(A,2)\r\n    A(:,i) = A(:,i)-v(i);\r\nend"
  },
  {
    "path": "src/tools/median2.m",
    "content": "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 = floor(n/2);\n    if 2*m == n\n        y = (X(m)+X(m+1))/2;\n    elseif m == 0\n        y = (X(1)+X(2))/2;\n    else\n        y = X(m+1);\n    end\nelse\n    y = X;\nend"
  },
  {
    "path": "src/tools/normalize.m",
    "content": "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(:,i) = A(:,i)./L;\nend\n"
  },
  {
    "path": "src/tools/optimal_parallel_vector.m",
    "content": "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 matrix \"V\"),\r\n% returns a unit vector (\"v\") that is the most parallel to them all\r\n% in the sense that the sum of squared dot products of v with the\r\n% vectors of V is maximized.\r\n \r\nA = V'*V;\r\n[U,~,~] = svd(A);\r\nv = U(:,1)';\r\n\r\nif nargout > 1\r\n    residual = abs(V*v');\r\n    mean_res = mean(residual);\r\n    sigmah = std(residual);\r\nend"
  },
  {
    "path": "src/tools/orthonormal_vectors.m",
    "content": "function [V,W] = orthonormal_vectors(U)\n\n% Generate vectors V and W that are unit vectors orthogonal to themselves \n% and to the input vector U\n\nV = rand(3,1);\nV = cross_product(V,U);\nwhile norm(V) == 0\n    V = rand(3,1);\n    V = cross_product(V,U);\nend\nW = cross_product(V,U);\nW = W/norm(W);\nV = V/norm(V);\nif size(V,2) > 1\n    V = V';\nend\nif size(W,2) > 1\n    W = W';\nend"
  },
  {
    "path": "src/tools/rotation_matrix.m",
    "content": "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 = A/norm(A);\r\nR = zeros(3,3);\r\nc = cos(angle); \r\ns = sin(angle);\r\nR(1,:) = [A(1)^2+(1-A(1)^2)*c  A(1)*A(2)*(1-c)-A(3)*s  A(1)*A(3)*(1-c)+A(2)*s];\r\nR(2,:) = [A(1)*A(2)*(1-c)+A(3)*s  A(2)^2+(1-A(2)^2)*c  A(2)*A(3)*(1-c)-A(1)*s];\r\nR(3,:) = [A(1)*A(3)*(1-c)-A(2)*s  A(2)*A(3)*(1-c)+A(1)*s  A(3)^2+(1-A(3)^2)*c];\r\n"
  },
  {
    "path": "src/tools/save_model_text.m",
    "content": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction save_model_text(QSM,savename)\n\n% ---------------------------------------------------------------------\n% SAVE_MODEL_TEXT.M       Saves QSM (cylinder, branch, treedata) into text\n%                           files\n%\n% Version 1.1.0\n% Latest update     17 Aug 2020\n%\n% Copyright (C) 2013-2020 Pasi Raumonen\n% ---------------------------------------------------------------------\n\n% Save the cylinder, branch, and treedata structures in text-formats (.txt) \n% into /result-folder with the input \"savename\" defining the file names:\n% 'cylinder_',savename,'.txt'\n% 'branch_',savename,'.txt'\n% 'treedata_',savename,'.txt'\n% !!! Notice that only part of the treedata, the single number tree \n% attributes are saved in the text-file.\n% Every user can change this code easily to define what is saved into \n% their text-files.\n\n% Changes from version 1.0.0 to 1.1.0, 17 Aug 2020:\n% 1) Added the new fields of cylinder, branch and treedata structures\n% 2) Added header names to the files\n% 3) Changed the names of the files to be saved\n% 4) Changed the name of second input from \"string\" to \"savename\"\n% 5) Changed the rounding of some parameters and attributes\n\ncylinder = QSM.cylinder;\nbranch = QSM.branch;\ntreedata = QSM.treedata;\n\n%% Form cylinder data, branch data and tree data\n% Use less decimals\nRad = round(10000*cylinder.radius)/10000; % radius (m)\nLen = round(10000*cylinder.length)/10000; % length (m)\nSta = round(10000*cylinder.start)/10000; % starting point (m)\nAxe = round(10000*cylinder.axis)/10000; % axis (m)\nCPar = single(cylinder.parent); % parent cylinder\nCExt = single(cylinder.extension); % extension cylinder\nAdded = single(cylinder.added); % is cylinder added to fil a gap\nRad0 = round(10000*cylinder.UnmodRadius)/10000; % unmodified radius (m)\nB = single(cylinder.branch); % branch index of the cylinder\nBO = single(cylinder.BranchOrder); % branch order of the branch\nPIB = single(cylinder.PositionInBranch); % position of the cyl. in the branch\nMad = single(round(10000*cylinder.mad)/10000); % mean abso. distance (m)\nSC = single(round(10000*cylinder.SurfCov)/10000); % surface coverage\nCylData = [Rad Len Sta Axe CPar CExt B BO PIB Mad SC Added Rad0];\nNamesC = ['radius (m)',\"length (m)\",\"start_point\",\"axis_direction\",...\n  \"parent\",\"extension\",\"branch\",\"branch_order\",\"position_in_branch\",...\n  \"mad\",\"SurfCov\",\"added\",\"UnmodRadius (m)\"];\n\nBOrd = single(branch.order); % branch order\nBPar = single(branch.parent); % parent branch\nBDia = round(10000*branch.diameter)/10000; % diameter (m)\nBVol = round(10000*branch.volume)/10000; % volume (L)\nBAre = round(10000*branch.area)/10000; % area (m^2)\nBLen = round(1000*branch.length)/1000; % length (m)\nBAng = round(10*branch.angle)/10; % angle (deg)\nBHei = round(1000*branch.height)/1000; % height (m)\nBAzi = round(10*branch.azimuth)/10; % azimuth (deg)\nBZen = round(10*branch.zenith)/10; % zenith (deg)\nBranchData = [BOrd BPar BDia BVol BAre BLen BHei BAng BAzi BZen];\nNamesB = [\"order\",\"parent\",\"diameter (m)\",\"volume (L)\",\"area (m^2)\",...\n  \"length (m)\",\"height (m)\",\"angle (deg)\",\"azimuth (deg)\",\"zenith (deg)\"];\n\n% Extract the field names of treedata\nNames = fieldnames(treedata);\nn = 1;\nwhile ~strcmp(Names{n},'location')\n    n = n+1;\nend\nn = n-1;\nNames = Names(1:n);\n\nTreeData = zeros(n,1); \n% TreeData contains TotalVolume, TrunkVolume, BranchVolume, etc\nfor i = 1:n\n    TreeData(i) = treedata.(Names{i,:});\nend\nTreeData = change_precision(TreeData); % use less decimals\nNamesD = string(Names);\n\n%% Save the data as text-files\nstr = ['results/cylinder_',savename,'.txt'];\nfid = fopen(str, 'wt');\nfprintf(fid, [repmat('%s\\t', 1, size(NamesC,2)-1) '%s\\n'], NamesC.');\nfprintf(fid, [repmat('%g\\t', 1, size(CylData,2)-1) '%g\\n'], CylData.');\nfclose(fid);\n\nstr = ['results/branch_',savename,'.txt'];\nfid = fopen(str, 'wt');\nfprintf(fid, [repmat('%s\\t', 1, size(NamesB,2)-1) '%s\\n'], NamesB.');\nfprintf(fid, [repmat('%g\\t', 1, size(BranchData,2)-1) '%g\\n'], BranchData.');\nfclose(fid);\n\nstr = ['results/treedata_',savename,'.txt'];\nfid = fopen(str, 'wt');\nNamesD(:,2) = TreeData;\nfprintf(fid,'%s\\t %g\\n',NamesD.');\nfclose(fid);\n"
  },
  {
    "path": "src/tools/sec2min.m",
    "content": "function [Tmin,Tsec] = sec2min(T)\n\n% Transforms the given number of seconds into minutes and residual seconds\n\nTmin = floor(T/60);\nTsec = round((T-Tmin*60)*10)/10;"
  },
  {
    "path": "src/tools/select_cylinders.m",
    "content": "function cylinder = select_cylinders(cylinder,Ind)\n\nNames = fieldnames(cylinder);\nn = size(Names,1);\nfor i = 1:n\n    cylinder.(Names{i}) = cylinder.(Names{i})(Ind,:);\nend"
  },
  {
    "path": "src/tools/set_difference.m",
    "content": "function Set1 = set_difference(Set1,Set2,False)\n\n% Performs the set difference so that the common elements of Set1 and Set2\n% are removed from Set1, which is the output. Uses logical vector whose\n% length must be up to the maximum element of the sets.\n\nFalse(Set2) = true;\nI = False(Set1);\nSet1 = Set1(~I);"
  },
  {
    "path": "src/tools/simplify_qsm.m",
    "content": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction QSM = simplify_qsm(QSM,MaxOrder,SmallRadii,ReplaceIterations,Plot,Disp)\n\n% ---------------------------------------------------------------------\n% SIMPLIFY_QSM.M   Simplifies cylinder QSMs by restricting the maximum\n%                       branching order, by removing thin branches, and by \n%                       replacing two concecutive cylinders with a longer cylinder\n%\n% Version 2.0.0\n% Latest update     4 May 2022\n%\n% Copyright (C) 2015-2022 Pasi Raumonen\n% ---------------------------------------------------------------------\n%\n% Inputs:\n% QSM           QSM-structure, output of treeqsm.m, must contain only one model\n% MaxOrder      Maximum branching order, higher order branches removed\n% SmallRadii    Minimum acceptable radius for a branch at its base\n% ReplaceIterations Number of iterations for replacing two concecutive\n%                     cylinders inside one branch with one longer cylinder \n% Plot          If true/1, then plots the cylinder models before and\n%                 after the simplification\n% Disp          If Disp == 1, then display the simplication results \n%                 (the number of cylinders after each step). If \n%                 Disp == 2, then display also the treedata results for\n%                 the original and simplified QSMs. If Disp == 0, then\n%                 nothing is displayed.\n%\n% Output:\n% Modified QSM      NOTICE: cylinder, branch and treedata are modified.\n\n% Changes from version 1.1.0 to 2.0.0, 4 May 2022:\n% 1) Added modification of branch and treedata structures based on the\n%     modified cylinders\n% 2) Added input for plotting and displaying the results\n% 3) Corrected some bugs that could cause errors in some special cases \n\nif nargin <= 4\n  Plot = 0;\n  Disp = 1;\nelseif nargin <= 5\n  Disp = 1;\nend\n\nif Disp == 2\n  inputs = QSM.rundata.inputs;\n  display_treedata(QSM.treedata,inputs)\nend\n% Plot the cylinder model before the simplification\nif Plot\n  plot_cylinder_model(QSM.cylinder,'branch',1,20,1)\nend\n\n%% Maximum branching order\nc = QSM.cylinder;\nnc = size(c.radius,1);\nif Disp >= 1\n  disp([' ',num2str(nc),' cylinders originally'])\nend\n\n% Cylinders with branching order up to MaxBranchOrder\nSmallOrder = c.BranchOrder <= MaxOrder; \nN = fieldnames(c);\nn = max(size(N));\nfor i = 1:n\n  c.(N{i}) = c.(N{i})(SmallOrder,:);\nend\n\n% Modify topology information\nInd = (1:1:nc)';\nm = nnz(SmallOrder);\nInd(SmallOrder) = (1:1:m)';\nI = c.parent > 0;\nc.parent(I) = Ind(c.parent(I));\nI = c.extension > 0;\nc.extension(I) = Ind(c.extension(I));\n\nif Disp == 1\n  nc = nnz(SmallOrder);\n  disp([' ',num2str(nc),' cylinders after branching order simplification'])\nend\n\n\n%% Small branches\nif nargin >= 3 && SmallRadii > 0\n  \n  nc = size(c.radius,1);\n  % Determine child branches\n  BPar = QSM.branch.parent;\n  nb = size(BPar,1);\n  BChi = cell(nb,1);\n  for i = 1:nb\n    P = BPar(i);\n    if P > 0\n      BChi{P} = [BChi{P}; i];\n    end\n  end\n  \n  % Remove branches whose radii is too small compared to its parent\n  Large = true(nc,1);\n  Pass = true(nb,1);\n  for i = 1:nb\n    if Pass(i)\n      if QSM.branch.diameter(i) < SmallRadii\n        B = i;\n        BC = BChi{B};\n        while ~isempty(BC)\n          B = [B; BC];\n          BC = vertcat(BChi{BC});\n        end\n        Pass(B) = false;\n        m = length(B);\n        for k = 1:m\n          Large(c.branch == B(k)) = false;\n        end\n      end\n    end\n  end\n  \n  % Modify topology information\n  Ind = (1:1:nc)';\n  m = nnz(Large);\n  Ind(Large) = (1:1:m)';\n  I = c.parent > 0;\n  c.parent(I) = Ind(c.parent(I));\n  I = c.extension > 0;\n  c.extension(I) = Ind(c.extension(I));\n  \n  % Update/reduce cylinders\n  for i = 1:n\n    c.(N{i}) = c.(N{i})(Large,:);\n  end\n  \n  if Disp >= 1\n    nc = nnz(Large);\n    disp([' ',num2str(nc),' cylinders after small branch simplification'])\n  end\nend\n\n\n%% Cylinder replacing\nif nargin >= 4 && ReplaceIterations > 0\n  \n  % Determine child cylinders\n  nc = size(c.radius,1);\n  CChi = cell(nc,1);\n  for i = 1:nc\n    P = c.parent(i);\n    if P > 0\n      PE = c.extension(P);\n      if PE ~= i\n        CChi{P} = [CChi{P}; i];\n      end\n    end\n  end\n  \n  % Replace cylinders\n  for j = 1:ReplaceIterations\n    \n    nc = size(c.radius,1);\n    Ind = (1:1:nc)';\n    Keep = false(nc,1);\n    i = 1;\n    while i <= nc\n      t = 1;\n      while i+t <= nc && c.branch(i+t) == c.branch(i)\n        t = t+1;\n      end\n      Cyls = (i:1:i+t-1)';\n      S = c.start(Cyls,:);\n      A = c.axis(Cyls,:);\n      L = c.length(Cyls);\n      if t == 1 % one cylinder in the branch\n        Keep(i) = true;\n      elseif ceil(t/2) == floor(t/2) % even number of cylinders in the branch\n        I = (1:2:t)'; % select 1., 3., 5., ...\n        % Correct radii, axes and lengths\n        E = S(end,:)+L(end)*A(end,:);\n        S = S(I,:);\n        m = length(I);\n        if m > 1\n          A = [S(2:end,:); E]-S(1:end,:);\n        else\n          A = E-S(1,:);\n        end\n        L = sqrt(sum(A.*A,2));\n        A = [A(:,1)./L A(:,2)./L A(:,3)./L];\n        cyls = Cyls(I);\n        Keep(cyls) = true;\n        V = pi*c.radius(Cyls).^2.*c.length(Cyls);\n        J = (2:2:t)';\n        V = V(I)+V(J);\n        R = sqrt(V./L/pi);\n        c.radius(cyls) = R;\n        \n      else % odd number of cylinders\n        I = [1 2:2:t]'; % select 1., 2., 4., 6., ...\n        % Correct radii, axes and lengths\n        E = S(end,:)+L(end)*A(end,:);\n        S = S(I,:);\n        l = L(1);\n        a = A(I,:);\n        m = length(I);\n        if m > 2\n          a(2:end,:) = [S(3:end,:); E]-S(2:end,:);\n        else\n          a(2,:) = E-S(2,:);\n        end\n        A = a;\n        L = sqrt(sum(A.*A,2));\n        L(1) = l;\n        A(2:end,:) = [A(2:end,1)./L(2:end) A(2:end,2)./L(2:end) A(2:end,3)./L(2:end)];\n        cyls = Cyls(I);\n        Keep(cyls) = true;\n        V = pi*c.radius(Cyls).^2.*c.length(Cyls);\n        J = (3:2:t)';\n        V = V(I(2:end))+V(J);\n        R = sqrt(V./L(2:end)/pi);\n        c.radius(cyls(2:end)) = R;\n      end\n      \n      if t > 1\n        % Modify cylinders\n        c.length(cyls) = L;\n        c.axis(cyls,:) = A;\n        % Correct branching/topology information\n        c.PositionInBranch(cyls) = (1:1:m)';\n        c.extension(cyls) = [cyls(2:end); 0];\n        c.parent(cyls(2:end)) = cyls(1:end-1);\n        par = c.parent(cyls(1));\n        if par > 0 && ~Keep(par)\n          par0 = c.parent(par);\n          if Keep(par0) && c.extension(par0) == par\n            c.parent(cyls(1)) = par0;\n          end\n        end\n        \n        % Correct child branches\n        chi = vertcat(CChi{Cyls});\n        if ~isempty(chi)\n          par = c.parent(chi);\n          J = Keep(par);\n          par = par(~J)-1;\n          c.parent(chi(~J)) = par;\n          \n          par = c.parent(chi);\n          rp = c.radius(par);\n          sp = c.start(par,:);\n          ap = c.axis(par,:);\n          lc = c.length(chi);\n          sc = c.start(chi,:);\n          ac = c.axis(chi,:);\n          ec = sc+[lc.*ac(:,1) lc.*ac(:,2) lc.*ac(:,3)];\n          m = length(chi);\n          for k = 1:m\n            [d,V,h,B] = distances_to_line(sc(k,:),ap(k,:),sp(k,:));\n            V = V/d;\n            sc(k,:) = sp(k,:)+rp(k)*V+B;\n          end\n          ac = ec-sc;\n          [ac,lc] = normalize(ac);\n          c.length(chi) = lc;\n          c.start(chi,:) = sc;\n          c.axis(chi,:) = ac;\n        end\n      end\n      \n      i = i+t;\n    end\n    % Change topology (parent, extension) indexes\n    m = nnz(Keep);\n    Ind(Keep) = (1:1:m)';\n    I = c.parent > 0;\n    c.parent(I) = Ind(c.parent(I));\n    I = c.extension > 0;\n    c.extension(I) = Ind(c.extension(I));\n    \n    % Update/reduce cylinders\n    for i = 1:n\n      c.(N{i}) = c.(N{i})(Keep,:);\n    end\n    \n    if j < ReplaceIterations\n      % Determine child cylinders\n      nc = size(c.radius,1);\n      CChi = cell(nc,1);\n      for i = 1:nc\n        P = c.parent(i);\n        if P > 0\n          PE = c.extension(P);\n          if PE ~= i\n            CChi{P} = [CChi{P}; i];\n          end\n        end\n      end\n    end\n  end\n  \n  if Disp >= 1\n    nc = size(c.radius,1);\n    disp([' ',num2str(nc),' cylinders after cylinder replacements'])\n  end\nend\nif Disp >= 1\n  nc = size(c.radius,1);\n  disp([' ',num2str(nc),' cylinders after all simplifications'])\nend\n\n\n%% Updata the QSM\n% Update the branch\nbranch = branches(c);\n\n% Update the treedata\ninputs = QSM.rundata.inputs;\ninputs.plot = 0;\n% Display\nif Disp == 2\n  inputs.disp = 2;\nelse\n  inputs.disp = 0;  \nend\ntreedata = update_tree_data(QSM,c,branch,inputs);\n\n% Update the cylinder, branch, and treedata of the QSM\nQSM.cylinder = c;\nQSM.branch = branch;\nQSM.treedata = treedata;\n\n% Plot the cylinder model after the simplification\nif Plot\n  plot_cylinder_model(QSM.cylinder,'branch',2,20,1)\nend\n\nend % End of main function\n\n\nfunction display_treedata(treedata,inputs)\n%% Generate units for displaying the treedata\nNames = fieldnames(treedata);\nn = size(Names,1);\nUnits = zeros(n,3);\nm = 23;\nfor i = 1:n\n  if ~inputs.Tria && strcmp(Names{i},'CrownVolumeAlpha')\n    m = i;\n  elseif inputs.Tria && strcmp(Names{i},'TriaTrunkLength')\n    m = i;\n  end\n  if strcmp(Names{i}(1:3),'DBH')\n    Units(i,:) = 'm  ';\n  elseif strcmp(Names{i}(end-2:end),'ume')\n    Units(i,:) = 'L  ';\n  elseif strcmp(Names{i}(end-2:end),'ght')\n    Units(i,:) = 'm  ';\n  elseif strcmp(Names{i}(end-2:end),'gth')\n    Units(i,:) = 'm  ';\n  elseif strcmp(Names{i}(1:3),'vol')\n    Units(i,:) = 'L  ';\n  elseif strcmp(Names{i}(1:3),'len')\n    Units(i,:) = 'm  ';\n  elseif strcmp(Names{i}(end-2:end),'rea')\n    Units(i,:) = 'm^2';\n  elseif strcmp(Names{i}(1:3),'loc')\n    Units(i,:) = 'm  ';\n  elseif strcmp(Names{i}(end-4:end),'aConv')\n    Units(i,:) = 'm^2';\n  elseif strcmp(Names{i}(end-5:end),'aAlpha')\n    Units(i,:) = 'm^2';\n  elseif strcmp(Names{i}(end-4:end),'eConv')\n    Units(i,:) = 'm^3';\n  elseif strcmp(Names{i}(end-5:end),'eAlpha')\n    Units(i,:) = 'm^3';\n  elseif strcmp(Names{i}(end-2:end),'Ave')\n    Units(i,:) = 'm  ';\n  elseif strcmp(Names{i}(end-2:end),'Max')\n    Units(i,:) = 'm  ';\n  end\nend\n%% Display treedata\ndisp('------------')\ndisp('  Tree attributes before simplification:')\nfor i = 1:m\n  v = change_precision(treedata.(Names{i}));\n  if strcmp(Names{i},'DBHtri')\n    disp('  -----')\n    disp('  Tree attributes from triangulation:')\n  end\n  disp(['  ',Names{i},' = ',num2str(v),' ',Units(i,:)])\nend\ndisp('  -----')\nend"
  },
  {
    "path": "src/tools/surface_coverage.m",
    "content": "function [SurfCov,Dis,CylVol,dis] = surface_coverage(P,Axis,Point,nl,ns,Dmin,Dmax)\n \n% ---------------------------------------------------------------------\n% SURFACE_COVERAGE.M   Computes point surface coverage measure\n%\n% Version       1.1.0\n% Last update   7 Oct 2021\n%\n% Copyright (C) 2017-2021 Pasi Raumonen\n% ---------------------------------------------------------------------\n% Inputs:    \n% Axis      Axis direction (1 x 3) \n% Point     Starting point of the cylinder (1 x 3)\n% nl        Number of layers in the axis direction used for to partition\n%               the cylinder surface into layer/sectors\n% ns        Number of sectors used to partition the cylinder surface into \n%               layer/sectors\n% Dmin      (Optional) Minimum point distance from the axis to be included\n%               into SurfCov calculations\n% Dmax      (Optional) Maximum point distance from the axis to be included\n%               into SurfCov calculations\n% \n% Output:  \n% SurfCov   Number between 0 and 1 descring how big portion of the cylinder\n%               surface is covered with points\n% Dis       (Optional) Mean distances of the distances of the layer/sectors\n% CylVol    (Optional) Volume of the cylinder estimated by the mean\n%               distances of the layer/sectors as cylindrical sections\n% dis       (Optional) Same as \"Dis\" but empty cells are interpolated\n% ---------------------------------------------------------------------\n% Computes surface coverage (number between 0 and 1) of points on cylinder \n% surface defined by \"Axis\" and \"Point\".\n\n% Changes from version 1.0.0 to 1.1.0, 7 Oct 2021:\n% 1) Added two possible inputs, minimum and maximum distance, \n%    Dmin and Dmax, which can be used to filter out points for the surface\n%    coverage calculations\n% 2) Computes the SurfCov estimate with four baseline directions used in\n%    the sector determination and selects the largest value\n% 3) Smalle changes to speed up computations\n\n%% Compute the distances and heights of the points\n[d,V,h] = distances_to_line(P,Axis,Point);\nh = h-min(h);\nLen = max(h);\n\n%% (Optional) Filter out points based on the distance to the axis\nif nargin >= 6\n  Keep = d > Dmin;\n  if nargin == 7\n    Keep = Keep & d < Dmax;\n  end\n  V = V(Keep,:);\n  h = h(Keep);\nend\n\n%% Compute SurfCov\n% from 4 different baseline directions to determine the angles and select\n% the maximum value\nV0 = V;\n[U,W] = orthonormal_vectors(Axis); % First planar axes\nR = rotation_matrix(Axis,2*pi/ns/4); % Rotation matrix to rotate the axes\nSurfCov = zeros(1,4);\nfor i = 1:4\n  %% Rotate the axes\n  if i > 1\n    U = R*U;\n    W = R*W;\n  end\n  \n  %% Compute the angles (sectors) of the points\n  V = V0*[U W];\n  ang = atan2(V(:,2),V(:,1))+pi;\n  \n  %% Compute lexicographic order (sector,layer) of every point\n  Layer = ceil(h/Len*nl);\n  Layer(Layer <= 0) = 1;\n  Layer(Layer > nl) = nl;\n  Sector = ceil(ang/2/pi*ns);\n  Sector(Sector <= 0) = 1;\n  LexOrd = [Layer Sector-1]*[1 nl]';\n  \n  %% Compute SurfCov\n  Cov = zeros(nl,ns);\n  Cov(LexOrd) = 1;\n  SurfCov(i) = nnz(Cov)/nl/ns;\nend\nSurfCov = max(SurfCov);\n\n\n%% Compute volume estimate\nif nargout > 1\n  % Sort according to increasing lexicographic order\n  [LexOrd,SortOrd] = sort(LexOrd);\n  d = d(SortOrd);\n  \n  % Compute mean distance of the sector-layer intersections\n  Dis = zeros(nl,ns); % mean distances\n  np = length(LexOrd);     % number of points\n  p = 1;\n  while p <= np\n    t = 1;\n    while (p+t <= np) && (LexOrd(p) == LexOrd(p+t))\n      t = t+1;\n    end\n    Dis(LexOrd(p)) = average(d(p:p+t-1));\n    p = p+t;\n  end\n  \n  if nargout > 2\n    % Interpolate missing distances\n    D = Dis;\n    dis = Dis;\n    Dinv = D((nl:-1:1)',:);\n    D = [Dinv Dinv Dinv; D D D; Dinv Dinv Dinv];\n    Zero = Dis == 0;\n    RadMean = average(Dis(Dis > 0));\n    for i = 1:nl\n      for j = 1:ns\n        if Zero(i,j)\n          if nnz(D(i+nl-1:i+nl+1,j+ns-1:j+ns+1)) > 1\n            d = D(i+nl-1:i+nl+1,j+ns-1:j+ns+1);\n            dis(i,j) = average(d(d > 0));\n          elseif nnz(D(i+nl-2:i+nl+2,j+ns-2:j+ns+2)) > 1\n            d = D(i+nl-2:i+nl+2,j+ns-2:j+ns+2);\n            dis(i,j) = average(d(d > 0));\n          elseif nnz(D(i+nl-3:i+nl+3,j+ns-3:j+ns+3)) > 1\n            d = D(i+nl-3:i+nl+3,j+ns-3:j+ns+3);\n            dis(i,j) = average(d(d > 0));\n          else\n            dis(i,j) = RadMean;\n          end\n        end\n      end\n    end\n    % Compute the volume estimate\n    r = dis(:);\n    CylVol = 1000*pi*sum(r.^2)/ns*Len/nl;\n  end\nend\n"
  },
  {
    "path": "src/tools/surface_coverage2.m",
    "content": "function SurfCov = surface_coverage2(Axis,Len,Vec,height,nl,ns)\n\n% Computes surface coverage (number between 0 and 1) of points on cylinder \n% surface defined by \"Axis\" and \"Len\". \"Vec\" are the vectors connecting \n% points to the Axis and \"height\" are the heights of the points from \n% the base of the cylinder\n\n[U,W] = orthonormal_vectors(Axis);\nVec = Vec*[U W];\nang = atan2(Vec(:,2),Vec(:,1))+pi;\nI = ceil(height/Len*nl);\nI(I == 0) = 1;\nI(I > nl) = nl;\nJ = ceil(ang/2/pi*ns);\nJ(J == 0) = 1;\nK = [I J-1]*[1 nl]';\nSurfCov = length(unique(K))/nl/ns;"
  },
  {
    "path": "src/tools/surface_coverage_filtering.m",
    "content": "function [Pass,c] = surface_coverage_filtering(P,c,lh,ns)\n\n% ---------------------------------------------------------------------\n% SURFACE_COVERAGE_FILTERING.M    Filters a point cloud based on the \n%                                   assumption that it samples a cylinder\n%\n% Version 1.1.0\n% Latest update     6 Oct 2021\n%\n% Copyright (C) 2017-2021 Pasi Raumonen\n% ---------------------------------------------------------------------\n\n% Filter a 3d-point cloud based on given cylinder (axis and radius) by \n% dividing the point cloud into \"ns\" equal-angle sectors and \"lh\"-height\n% layers along the axis. For each sector-layer intersection (a region in \n% the cylinder surface) keep only the points closest to the axis. \n\n% Inputs:\n% P             Point cloud, (n_points x 3)-matrix\n% c             Cylinder, stucture array with fields \"axis\", \"start\",\n%                 \"length\"\n% lh            Height of the layers\n% ns            Number of sectors\n%\n% Outputs:              \n% Pass          Logical vector indicating which points pass the filtering\n% c             Cylinder, stucture array with additional fields \"radius\",\n%                 \"SurfCov\", \"mad\", \"conv\", \"rel\", estimated from the\n%                 filtering\n% ---------------------------------------------------------------------\n\n% Changes from version 1.0.0 to 1.1.0, 6 Oct 2021:  \n% 1) Small changes to make the code little faster\n% 2) Change the radius estimation to make it much faster\n \n\n% Compute the distances, heights and angles of the points\n[d,V,h] = distances_to_line(P,c.axis,c.start);\nh = h-min(h);\n[U,W] = orthonormal_vectors(c.axis);\nV = V*[U W];\nang = atan2(V(:,2),V(:,1))+pi;\n\n% Sort based on lexicographic order of (sector,layer)\nnl = ceil(c.length/lh);\nLayer = ceil(h/c.length*nl);\nLayer(Layer == 0) = 1;\nLayer(Layer > nl) = nl;\nSector = ceil(ang/2/pi*ns);\nSector(Sector == 0) = 1;\nLexOrd = [Layer Sector-1]*[1 nl]';\n[LexOrd,SortOrd] = sort(LexOrd);\nds = d(SortOrd);\n\n% Estimate the distances for each sector-layer intersection\nDis = zeros(nl,ns);\nnp = size(P,1);     % number of points\np = 1;\nwhile p <= np\n  t = 1;\n  while (p+t <= np) && (LexOrd(p) == LexOrd(p+t))\n    t = t+1;\n  end\n  D = min(ds(p:p+t-1));\n  Dis(LexOrd(p)) = min(1.05*D,D+0.02);\n  p = p+t;\nend\n\n% Compute the number of sectors based on the estimated radius\nR = median(Dis(Dis > 0));\na = max(0.02,0.2*R);\nns = ceil(2*pi*R/a);\nns = min(36,max(ns,8));\nnl = ceil(c.length/a);\nnl = max(nl,3);\n\n% Sort based on lexicographic order of (sector,layer)\nLayer = ceil(h/c.length*nl);\nLayer(Layer == 0) = 1;\nLayer(Layer > nl) = nl;\nSector = ceil(ang/2/pi*ns);\nSector(Sector == 0) = 1;\nLexOrd = [Layer Sector-1]*[1 nl]';\n[LexOrd,SortOrd] = sort(LexOrd);\nd = d(SortOrd);\n\n% Filtering for each sector-layer intersection\nDis = zeros(nl,ns);\nPass = false(np,1);\np = 1; % index of point under processing\nk = 0; % number of nonempty cells \nr = max(0.01,0.05*R); % cell diameter from the closest point\nwhile p <= np\n  t = 1;\n  while (p+t <= np) && (LexOrd(p) == LexOrd(p+t))\n    t = t+1;\n  end\n  ind = p:p+t-1;\n  D = d(ind);\n  Dmin = min(D);\n  I = D <= Dmin+r;\n  Pass(ind(I)) = true;\n  Dis(LexOrd(p)) = min(1.05*Dmin,Dmin+0.02);\n  p = p+t;\n  k = k+1;\nend\nd = d(Pass);\n\n% Sort the \"Pass\"-vector back to original point cloud order\nn = length(SortOrd);\nInvSortOrd = zeros(n,1);\nInvSortOrd(SortOrd) = (1:1:n)';\nPass = Pass(InvSortOrd);\n\n% Compute radius, SurfCov and mad\nR = median(Dis(Dis > 0));\nmad = sum(abs(d-R))/length(d);\n\nc.radius = R;\nc.SurfCov = k/nl/ns;\nc.mad = mad;\nc.conv = 1;\nc.rel = 1;\n"
  },
  {
    "path": "src/tools/unique2.m",
    "content": "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(2:n);\n    I = d > 0;\n    SetUni = [Set(1); A(I)];\nelse\n    SetUni = Set;\nend"
  },
  {
    "path": "src/tools/unique_elements.m",
    "content": "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 ~False(Set(j))\n            False(Set(j)) = true;\n        else\n            I(j) = false;\n        end\n    end\n    Set = Set(I);\nelseif n == 2\n    if Set(1) == Set(2)\n        Set = Set(1);\n    end\nend"
  },
  {
    "path": "src/tools/update_tree_data.m",
    "content": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction treedata = update_tree_data(QSM,cylinder,branch,inputs)\n\n% ---------------------------------------------------------------------\n% UPDATE_TREE_DATA.M       Updates the treedata structure, e.g. after\n%                            simplification of QSM\n%\n% Version 1.0.0\n% Latest update     4 May 2022\n%\n% Copyright (C) 2013-2022 Pasi Raumonen\n% ---------------------------------------------------------------------\n\n% Inputs:\n% treedata    Treedata structure from \"tree_data\"\n% cylinder    Cylinder structure from \"cylinders\"\n% branch      Branch structure from \"branches\"\n%\n% Output:\n% treedata     Tree data/attributes in a struct\n% ---------------------------------------------------------------------\n\n\n% Define some variables from cylinder:\ntreedata = QSM.treedata;\nRad = cylinder.radius;\nLen = cylinder.length;\nSta = cylinder.start;\nAxe = cylinder.axis;\nnc = length(Rad);\nind = (1:1:nc)';\nTrunk = cylinder.branch == 1; % Trunk cylinders\n\n%% Tree attributes from cylinders\n% Volumes, areas, lengths, branches\ntreedata.TotalVolume = 1000*pi*Rad.^2'*Len;\ntreedata.TrunkVolume = 1000*pi*Rad(Trunk).^2'*Len(Trunk);\ntreedata.BranchVolume = 1000*pi*Rad(~Trunk).^2'*Len(~Trunk);\nbottom = min(Sta(:,3));\n[top,i] = max(Sta(:,3));\nif Axe(i,3) > 0\n  top = top+Len(i)*Axe(i,3);\nend\ntreedata.TreeHeight = top-bottom;\ntreedata.TrunkLength = sum(Len(Trunk));\ntreedata.BranchLength = sum(Len(~Trunk));\ntreedata.TotalLength = treedata.TrunkLength+treedata.BranchLength;\nNB = length(branch.order)-1; % number of branches\ntreedata.NumberBranches = NB;\nBO = max(branch.order); % maximum branch order\ntreedata.MaxBranchOrder = BO;\ntreedata.TrunkArea = 2*pi*sum(Rad(Trunk).*Len(Trunk));\ntreedata.BranchArea = 2*pi*sum(Rad(~Trunk).*Len(~Trunk));\ntreedata.TotalArea = 2*pi*sum(Rad.*Len);\n\n%% Crown measures,Vertical profile and spreads\n[treedata,spreads] = crown_measures(treedata,cylinder,branch);\n\n%% Update triangulation information\nif inputs.Tria\n  treedata = update_triangulation(QSM,treedata,cylinder);\nend\n\n%% Tree Location\ntreedata.location = Sta(1,:);\n\n%% Stem taper\nR = Rad(Trunk);\nn = length(R);\nTaper = zeros(n+1,2);\nTaper(1,2) = 2*R(1);\nTaper(2:end,1) = cumsum(Len(Trunk));\nTaper(2:end,2) = [2*R(2:end); 2*R(n)];\ntreedata.StemTaper = Taper';\n\n%% Vertical profile and spreads\ntreedata.VerticalProfile = mean(spreads,2);\ntreedata.spreads = spreads;\n\n%% CYLINDER DISTRIBUTIONS:\n%% Wood part diameter distributions\n% Volume, area and length of wood parts as functions of cylinder diameter\n% (in 1cm diameter classes)\ntreedata = cylinder_distribution(treedata,Rad,Len,Axe,'Dia');\n\n%% Wood part height distributions\n% Volume, area and length of cylinders as a function of height\n% (in 1 m height classes)\ntreedata = cylinder_height_distribution(treedata,Rad,Len,Sta,Axe,ind);\n\n%% Wood part zenith direction distributions\n% Volume, area and length of wood parts as functions of cylinder zenith\n% direction (in 10 degree angle classes)\ntreedata = cylinder_distribution(treedata,Rad,Len,Axe,'Zen');\n\n%% Wood part azimuth direction distributions\n% Volume, area and length of wood parts as functions of cylinder zenith\n% direction (in 10 degree angle classes)\ntreedata = cylinder_distribution(treedata,Rad,Len,Axe,'Azi');\n\n%% BRANCH DISTRIBUTIONS:\n%% Branch order distributions\n% Volume, area, length and number of branches as a function of branch order\ntreedata = branch_order_distribution(treedata,branch);\n\n%% Branch diameter distributions\n% Volume, area, length and number of branches as a function of branch diameter\n% (in 1cm diameter classes)\ntreedata = branch_distribution(treedata,branch,'Dia');\n\n%% Branch height distribution\n% Volume, area, length and number of branches as a function of branch height\n% (in 1 meter classes) for all and 1st-order branches\ntreedata = branch_distribution(treedata,branch,'Hei');\n\n%% Branch angle distribution\n% Volume, area, length and number of branches as a function of branch angle\n% (in 10 deg angle classes) for all and 1st-order branches\ntreedata = branch_distribution(treedata,branch,'Ang');\n\n%% Branch azimuth distribution\n% Volume, area, length and number of branches as a function of branch azimuth\n% (in 22.5 deg angle classes) for all and 1st-order branches\ntreedata = branch_distribution(treedata,branch,'Azi');\n\n%% Branch zenith distribution\n% Volume, area, length and number of branches as a function of branch zenith\n% (in 10 deg angle classes) for all and 1st-order branches\ntreedata = branch_distribution(treedata,branch,'Zen');\n\n%% change into single-format\nNames = fieldnames(treedata);\nn = size(Names,1);\nfor i = 1:n\n  treedata.(Names{i}) = single(treedata.(Names{i}));\nend\n\nif inputs.disp == 2\n  %% Generate units for displaying the treedata\n  Units = zeros(n,3);\n  m = 23;\n  for i = 1:n\n    if ~inputs.Tria && strcmp(Names{i},'CrownVolumeAlpha')\n      m = i;\n    elseif inputs.Tria && strcmp(Names{i},'TriaTrunkLength')\n      m = i;\n    end\n    if strcmp(Names{i}(1:3),'DBH')\n      Units(i,:) = 'm  ';\n    elseif strcmp(Names{i}(end-2:end),'ume')\n      Units(i,:) = 'L  ';\n    elseif strcmp(Names{i}(end-2:end),'ght')\n      Units(i,:) = 'm  ';\n    elseif strcmp(Names{i}(end-2:end),'gth')\n      Units(i,:) = 'm  ';\n    elseif strcmp(Names{i}(1:3),'vol')\n      Units(i,:) = 'L  ';\n    elseif strcmp(Names{i}(1:3),'len')\n      Units(i,:) = 'm  ';\n    elseif strcmp(Names{i}(end-2:end),'rea')\n      Units(i,:) = 'm^2';\n    elseif strcmp(Names{i}(1:3),'loc')\n      Units(i,:) = 'm  ';\n    elseif strcmp(Names{i}(end-4:end),'aConv')\n      Units(i,:) = 'm^2';\n    elseif strcmp(Names{i}(end-5:end),'aAlpha')\n      Units(i,:) = 'm^2';\n    elseif strcmp(Names{i}(end-4:end),'eConv')\n      Units(i,:) = 'm^3';\n    elseif strcmp(Names{i}(end-5:end),'eAlpha')\n      Units(i,:) = 'm^3';\n    elseif strcmp(Names{i}(end-2:end),'Ave')\n      Units(i,:) = 'm  ';\n    elseif strcmp(Names{i}(end-2:end),'Max')\n      Units(i,:) = 'm  ';\n    end\n  end\n  %% Display treedata\n  disp('------------')\n  disp('  Tree attributes:')\n  for i = 1:m\n    v = change_precision(treedata.(Names{i}));\n    if strcmp(Names{i},'DBHtri')\n      disp('  -----')\n      disp('  Tree attributes from triangulation:')\n    end\n    disp(['  ',Names{i},' = ',num2str(v),' ',Units(i,:)])\n  end\n  disp('  -----')\nend\n\nif inputs.plot > 1\n  %% Plot distributions\n  figure(6)\n  subplot(2,4,1)\n  plot(Taper(:,1),Taper(:,2),'-b')\n  title('Stem taper')\n  xlabel('Distance from base (m)')\n  ylabel('Diameter (m)')\n  axis tight\n  grid on\n  \n  Q.treedata = treedata;\n  subplot(2,4,2)\n  plot_distribution(Q,6,0,0,'VolCylDia')\n  \n  subplot(2,4,3)\n  plot_distribution(Q,6,0,0,'AreCylDia')\n  \n  subplot(2,4,4)\n  plot_distribution(Q,6,0,0,'LenCylDia')\n  \n  subplot(2,4,5)\n  plot_distribution(Q,6,0,0,'VolBranchOrd')\n  \n  subplot(2,4,6)\n  plot_distribution(Q,6,0,0,'LenBranchOrd')\n  \n  subplot(2,4,7)\n  plot_distribution(Q,6,0,0,'AreBranchOrd')\n  \n  subplot(2,4,8)\n  plot_distribution(Q,6,0,0,'NumBranchOrd')\n  \n  figure(7)\n  subplot(3,3,1)\n  plot_distribution(Q,7,0,0,'VolCylHei')\n  \n  subplot(3,3,2)\n  plot_distribution(Q,7,0,0,'AreCylHei')\n  \n  subplot(3,3,3)\n  plot_distribution(Q,7,0,0,'LenCylHei')\n  \n  subplot(3,3,4)\n  plot_distribution(Q,7,0,0,'VolCylZen')\n  \n  subplot(3,3,5)\n  plot_distribution(Q,7,0,0,'AreCylZen')\n  \n  subplot(3,3,6)\n  plot_distribution(Q,7,0,0,'LenCylZen')\n  \n  subplot(3,3,7)\n  plot_distribution(Q,7,0,0,'VolCylAzi')\n  \n  subplot(3,3,8)\n  plot_distribution(Q,7,0,0,'AreCylAzi')\n  \n  subplot(3,3,9)\n  plot_distribution(Q,7,0,0,'LenCylAzi')\n  \n  figure(8)\n  subplot(3,4,1)\n  plot_distribution(Q,8,1,0,'VolBranchDia','VolBranch1Dia')\n  \n  subplot(3,4,2)\n  plot_distribution(Q,8,1,0,'AreBranchDia','AreBranch1Dia')\n  \n  subplot(3,4,3)\n  plot_distribution(Q,8,1,0,'LenBranchDia','LenBranch1Dia')\n  \n  subplot(3,4,4)\n  plot_distribution(Q,8,1,0,'NumBranchDia','NumBranch1Dia')\n  \n  subplot(3,4,5)\n  plot_distribution(Q,8,1,0,'VolBranchHei','VolBranch1Hei')\n  \n  subplot(3,4,6)\n  plot_distribution(Q,8,1,0,'AreBranchHei','AreBranch1Hei')\n  \n  subplot(3,4,7)\n  plot_distribution(Q,8,1,0,'LenBranchHei','LenBranch1Hei')\n  \n  subplot(3,4,8)\n  plot_distribution(Q,8,1,0,'NumBranchHei','NumBranch1Hei')\n  \n  subplot(3,4,9)\n  plot_distribution(Q,8,1,0,'VolBranchAng','VolBranch1Ang')\n  \n  subplot(3,4,10)\n  plot_distribution(Q,8,1,0,'AreBranchAng','AreBranch1Ang')\n  \n  subplot(3,4,11)\n  plot_distribution(Q,8,1,0,'LenBranchAng','LenBranch1Ang')\n  \n  subplot(3,4,12)\n  plot_distribution(Q,8,1,0,'NumBranchAng','NumBranch1Ang')\n  \n  figure(9)\n  subplot(2,4,1)\n  plot_distribution(Q,9,1,0,'VolBranchZen','VolBranch1Zen')\n  \n  subplot(2,4,2)\n  plot_distribution(Q,9,1,0,'AreBranchZen','AreBranch1Zen')\n  \n  subplot(2,4,3)\n  plot_distribution(Q,9,1,0,'LenBranchZen','LenBranch1Zen')\n  \n  subplot(2,4,4)\n  plot_distribution(Q,9,1,0,'NumBranchZen','NumBranch1Zen')\n  \n  subplot(2,4,5)\n  plot_distribution(Q,9,1,0,'VolBranchAzi','VolBranch1Azi')\n  \n  subplot(2,4,6)\n  plot_distribution(Q,9,1,0,'AreBranchAzi','AreBranch1Azi')\n  \n  subplot(2,4,7)\n  plot_distribution(Q,9,1,0,'LenBranchAzi','LenBranch1Azi')\n  \n  subplot(2,4,8)\n  plot_distribution(Q,9,1,0,'NumBranchAzi','NumBranch1Azi')\nend\n\nend % End of main function\n\n\nfunction [treedata,spreads] = crown_measures(treedata,cylinder,branch)\n\n%% Generate point clouds from the cylinder model\nAxe = cylinder.axis;\nLen = cylinder.length;\nSta = cylinder.start;\nTip = Sta+[Len.*Axe(:,1) Len.*Axe(:,2) Len.*Axe(:,3)]; % tips of the cylinders\nnc = length(Len);\nP = zeros(5*nc,3); % four mid points on the cylinder surface\nt = 0;\nfor i = 1:nc\n  [U,V] = orthonormal_vectors(Axe(i,:));\n  U = cylinder.radius(i)*U;\n  if cylinder.branch(i) == 1\n    % For stem cylinders generate more points\n    for k = 1:4\n      M = Sta(i,:)+k*Len(i)/4*Axe(i,:);\n      R = rotation_matrix(Axe(i,:),pi/12);\n      for j = 1:12\n        if j > 1\n          U = R*U;\n        end\n        t = t+1;\n        P(t,:) = M+U';\n      end\n    end\n  else\n    M = Sta(i,:)+Len(i)/2*Axe(i,:);\n    R = rotation_matrix(Axe(i,:),pi/4);\n    for j = 1:4\n      if j > 1\n        U = R*U;\n      end\n      t = t+1;\n      P(t,:) = M+U';\n    end\n  end\nend\nP = P(1:t,:);\nP = double([P; Sta; Tip]);\nP = unique(P,'rows');\n\n%% Vertical profiles (layer diameters/spreads), mean:\nbot = min(P(:,3));\ntop = max(P(:,3));\nHei = top-bot;\nif Hei > 10\n  m = 20;\nelseif Hei > 2\n  m = 10;\nelse\n  m = 5;\nend\nspreads = zeros(m,18);\nfor j = 1:m\n  I = P(:,3) >= bot+(j-1)*Hei/m & P(:,3) < bot+j*Hei/m;\n  X = unique(P(I,:),'rows');\n  if size(X,1) > 5\n    [K,A] = convhull(X(:,1),X(:,2));\n    % compute center of gravity for the convex hull and use it as\n    % center for computing average diameters\n    n = length(K);\n    x = X(K,1);\n    y = X(K,2);\n    CX = sum((x(1:n-1)+x(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A;\n    CY = sum((y(1:n-1)+y(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A;\n    \n    V = mat_vec_subtraction(X(:,1:2),[CX CY]);\n    ang = atan2(V(:,2),V(:,1))+pi;\n    [ang,I] = sort(ang);\n    L = sqrt(sum(V.*V,2));\n    L = L(I);\n    for i = 1:18\n      I = ang >= (i-1)*pi/18 & ang < i*pi/18;\n      if any(I)\n        L1 = max(L(I));\n      else\n        L1 = 0;\n      end\n      J = ang >= (i-1)*pi/18+pi & ang < i*pi/18+pi;\n      if any(J)\n        L2 = max(L(J));\n      else\n        L2 = 0;\n      end\n      spreads(j,i) = L1+L2;\n    end\n  end\nend\n\n%% Crown diameters (spreads), mean and maximum:\nX = unique(P(:,1:2),'rows');\n[K,A] = convhull(X(:,1),X(:,2));\n% compute center of gravity for the convex hull and use it as center for\n% computing average diameters\nn = length(K);\nx = X(K,1);\ny = X(K,2);\nCX = sum((x(1:n-1)+x(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A;\nCY = sum((y(1:n-1)+y(2:n)).*(x(1:n-1).*y(2:n)-x(2:n).*y(1:n-1)))/6/A;\nV = mat_vec_subtraction(Tip(:,1:2),[CX CY]);\nang = atan2(V(:,2),V(:,1))+pi;\n[ang,I] = sort(ang);\nL = sqrt(sum(V.*V,2));\nL = L(I);\nS = zeros(18,1);\nfor i = 1:18\n  I = ang >= (i-1)*pi/18 & ang < i*pi/18;\n  if any(I)\n    L1 = max(L(I));\n  else\n    L1 = 0;\n  end\n  J = ang >= (i-1)*pi/18+pi & ang < i*pi/18+pi;\n  if any(J)\n    L2 = max(L(J));\n  else\n    L2 = 0;\n  end\n  S(i) = L1+L2;\nend\ntreedata.CrownDiamAve = mean(S);\nMaxDiam = 0;\nfor i = 1:n\n  V = mat_vec_subtraction([x y],[x(i) y(i)]);\n  L = max(sqrt(sum(V.*V,2)));\n  if L > MaxDiam\n    MaxDiam = L;\n  end\nend\ntreedata.CrownDiamMax = L;\n\n%% Crown areas from convex hull and alpha shape:\ntreedata.CrownAreaConv = A;\nalp = max(0.5,treedata.CrownDiamAve/10);\nshp = alphaShape(X(:,1),X(:,2),alp);\ntreedata.CrownAreaAlpha = shp.area;\n\n%% Crown base\n% Define first major branch as the branch whose diameter > min(0.05*dbh,5cm)\n% and whose horizontal relative reach is more than the median reach of 1st-ord.\n% branches (or at maximum 10). The reach is defined as the horizontal\n% distance from the base to the tip divided by the dbh.\ndbh = treedata.DBHcyl;\nnb = length(branch.order);\nHL = zeros(nb,1); % horizontal reach\nbranches1 = (1:1:nb)';\nbranches1 = branches1(branch.order == 1); % 1st-order branches\nnb = length(branches1);\nnc = size(Sta,1);\nind = (1:1:nc)';\nfor i = 1:nb\n  C = ind(cylinder.branch == branches1(i));\n  if ~isempty(C)\n    base = Sta(C(1),:);\n    C = C(end);\n    tip = Sta(C,:)+Len(C)*Axe(C);\n    V = tip(1:2)-base(1:2);\n    HL(branches1(i)) = sqrt(V*V')/dbh*2;\n  end\nend\nM = min(10,median(HL));\n\n% Sort the branches according to the their heights\nHei = branch.height(branches1);\n[Hei,SortOrd] = sort(Hei);\nbranches1 = branches1(SortOrd);\n\n% Search the first/lowest branch:  \nd = min(0.05,0.05*dbh);\nb = 0;\nif nb > 1\n  i = 1;\n  while i < nb\n    i = i+1;\n    if branch.diameter(branches1(i)) > d && HL(branches1(i)) > M\n      b = branches1(i);\n      i = nb+2;\n    end\n  end\n  if i == nb+1 && nb > 1\n    b = branches1(1);\n  end\nend\n\nif b > 0\n  % search all the children of the first major branch:\n  nb = size(branch.parent,1);\n  Ind = (1:1:nb)';\n  chi = Ind(branch.parent == b);\n  B = b;\n  while ~isempty(chi)\n    B = [B; chi];\n    n = length(chi);\n    C = cell(n,1);\n    for i = 1:n\n      C{i} = Ind(branch.parent == chi(i));\n    end\n    chi = vertcat(C{:});\n  end\n  \n  % define crown base height from the ground:\n  BaseHeight = max(Sta(:,3)); % Height of the crown base\n  for i = 1:length(B)\n    C = ind(cylinder.branch == B(i));\n    ht = min(Tip(C,3));\n    hb = min(Sta(C,3));\n    h = min(hb,ht);\n    if h < BaseHeight\n      BaseHeight = h;\n    end\n  end\n  treedata.CrownBaseHeight = BaseHeight-Sta(1,3);\n  \n  %% Crown length and ratio\n  treedata.CrownLength = treedata.TreeHeight-treedata.CrownBaseHeight;\n  treedata.CrownRatio = treedata.CrownLength/treedata.TreeHeight;\n  \n  %% Crown volume from convex hull and alpha shape:\n  I = P(:,3) >= BaseHeight;\n  X = P(I,:);\n  [K,V] = convhull(X(:,1),X(:,2),X(:,3));\n  treedata.CrownVolumeConv = V;\n  alp = max(0.5,treedata.CrownDiamAve/5);\n  shp = alphaShape(X(:,1),X(:,2),X(:,3),alp,'HoleThreshold',10000);\n  treedata.CrownVolumeAlpha = shp.volume;\n\nelse \n  % No branches\n  treedata.CrownBaseHeight = treedata.TreeHeight;\n  treedata.CrownLength = 0;\n  treedata.CrownRatio = 0;\n  treedata.CrownVolumeConv = 0;\n  treedata.CrownVolumeAlpha = 0;\nend\n\nend % End of function\n\n\nfunction treedata = update_triangulation(QSM,treedata,cylinder)\n\n% Update the mixed results:\nif ~isempty(QSM.triangulation)\n  CylInd = QSM.triangulation.cylind;\n  Rad = cylinder.radius;\n  Len = cylinder.length;\n  % Determine the new stem cylinder that is about the location where the\n  % triangulation stops:\n  nc = length(Rad);\n  ind = (1:1:nc)';\n  ind = ind(cylinder.branch == 1); % cylinders in the stem\n  S = QSM.cylinder.start(CylInd,:); % The place where the triangulation stops\n  V = cylinder.start(ind,:)-S;\n  d = sqrt(sum(V.*V,2));\n  [d,I] = min(d);\n  V = V(I,:);\n  CylInd = ind(I); % The new cylinder closest to the correct place\n  if d < 0.01\n    TrunkVolMix = treedata.TrunkVolume-...\n      1000*pi*sum(Rad(1:CylInd-1).^2.*Len(1:CylInd-1))+QSM.triangulation.volume;\n    TrunkAreaMix = treedata.TrunkArea-...\n      2*pi*sum(Rad(1:CylInd-1).*Len(1:CylInd-1))+QSM.triangulation.SideArea;\n  else\n    % Select the following cylinder\n    h = V*cylinder.axis(CylInd,:)';\n    if h < 0\n      CylInd = CylInd+1;\n      V = cylinder.start(CylInd,:)-S;\n      h = V*cylinder.axis(CylInd,:)';\n    end\n    Len(CylInd-1) = Len(CylInd-1)-h;\n    \n    TrunkVolMix = treedata.TrunkVolume-...\n      1000*pi*sum(Rad(1:CylInd-1).^2.*Len(1:CylInd-1))+QSM.triangulation.volume;\n    TrunkAreaMix = treedata.TrunkArea-...\n      2*pi*sum(Rad(1:CylInd-1).*Len(1:CylInd-1))+QSM.triangulation.SideArea;\n  end\n  treedata.MixTrunkVolume = TrunkVolMix;\n  treedata.MixTotalVolume = TrunkVolMix+treedata.BranchVolume;\n  treedata.MixTrunkArea = TrunkAreaMix;\n  treedata.MixTotalArea = TrunkAreaMix+treedata.BranchArea;\nend\nend\n\n\nfunction treedata = cylinder_distribution(treedata,Rad,Len,Axe,dist)\n%% Wood part diameter, zenith and azimuth direction distributions\n% Volume, area and length of wood parts as functions of cylinder\n% diameter, zenith, and azimuth\nif strcmp(dist,'Dia')\n  Par = Rad;\n  n = ceil(max(200*Rad));\n  a = 0.005; % diameter in 1 cm classes\nelseif strcmp(dist,'Zen')\n  Par = 180/pi*acos(Axe(:,3));\n  n = 18;\n  a = 10; % zenith direction in 10 degree angle classes\nelseif strcmp(dist,'Azi')\n  Par = 180/pi*atan2(Axe(:,2),Axe(:,1))+180;\n  n = 36;\n  a = 10; % azimuth direction in 10 degree angle classes\nend\n\nCylDist = zeros(3,n);\nfor i = 1:n\n  K = Par >= (i-1)*a & Par < i*a;\n  CylDist(1,i) = 1000*pi*sum(Rad(K).^2.*Len(K)); % volumes in litres\n  CylDist(2,i) = 2*pi*sum(Rad(K).*Len(K)); % areas in litres\n  CylDist(3,i) = sum(Len(K)); % lengths in meters\nend\ntreedata.(['VolCyl',dist]) = CylDist(1,:);\ntreedata.(['AreCyl',dist]) = CylDist(2,:);\ntreedata.(['LenCyl',dist]) = CylDist(3,:);\nend\n\n\nfunction treedata = cylinder_height_distribution(treedata,Rad,Len,Sta,Axe,ind)\n\n%% Wood part height distributions\n% Volume, area and length of cylinders as a function of height\n% (in 1 m height classes)\nMaxHei= ceil(treedata.TreeHeight);\ntreedata.VolCylHei = zeros(1,MaxHei);\ntreedata.AreCylHei = zeros(1,MaxHei);\ntreedata.LenCylHei = zeros(1,MaxHei);\nEnd = Sta+[Len.*Axe(:,1) Len.*Axe(:,2) Len.*Axe(:,3)];\nbot = min(Sta(:,3));\nB = Sta(:,3)-bot;\nT = End(:,3)-bot;\nfor j = 1:MaxHei\n  I1 = B >= (j-2) & B < (j-1); % base below this bin\n  J1 = B >= (j-1) & B < j; % base in this bin\n  K1 = B >= j & B < (j+1); % base above this bin\n  I2 = T >= (j-2) & T < (j-1); % top below this bin\n  J2 = T >= (j-1) & T < j; % top in this bin\n  K2 = T >= j & T < (j+1); % top above this bin\n  C1 = ind(J1&J2); % base and top in this bin\n  C2 = ind(J1&K2); % base in this bin, top above\n  C3 = ind(J1&I2); % base in this bin, top below\n  C4 = ind(I1&J2); % base in bin below, top in this\n  C5 = ind(K1&J2); % base in bin above, top in this\n  v1 = 1000*pi*sum(Rad(C1).^2.*Len(C1));\n  a1 = 2*pi*sum(Rad(C1).*Len(C1));\n  l1 = sum(Len(C1));\n  r2 = (j-B(C2))./(T(C2)-B(C2)); % relative portion in this bin\n  v2 = 1000*pi*sum(Rad(C2).^2.*Len(C2).*r2);\n  a2 = 2*pi*sum(Rad(C2).*Len(C2).*r2);\n  l2 = sum(Len(C2).*r2);\n  r3 = (B(C3)-j+1)./(B(C3)-T(C3)); % relative portion in this bin\n  v3 = 1000*pi*sum(Rad(C3).^2.*Len(C3).*r3);\n  a3 = 2*pi*sum(Rad(C3).*Len(C3).*r3);\n  l3 = sum(Len(C3).*r3);\n  r4 = (T(C4)-j+1)./(T(C4)-B(C4)); % relative portion in this bin\n  v4 = 1000*pi*sum(Rad(C4).^2.*Len(C4).*r4);\n  a4 = 2*pi*sum(Rad(C4).*Len(C4).*r4);\n  l4 = sum(Len(C4).*r4);\n  r5 = (j-T(C5))./(B(C5)-T(C5)); % relative portion in this bin\n  v5 = 1000*pi*sum(Rad(C5).^2.*Len(C5).*r5);\n  a5 = 2*pi*sum(Rad(C5).*Len(C5).*r5);\n  l5 = sum(Len(C5).*r5);\n  treedata.VolCylHei(j) = v1+v2+v3+v4+v5;\n  treedata.AreCylHei(j) = a1+a2+a3+a4+a5;\n  treedata.LenCylHei(j) = l1+l2+l3+l4+l5;\nend\nend\n\n\nfunction treedata = branch_distribution(treedata,branch,dist)\n%% Branch diameter, height, angle, zenith and azimuth distributions\n% Volume, area, length and number of branches as a function of branch\n% diamater, height, angle, zenith and aximuth\nBOrd = branch.order(2:end);\nBVol = branch.volume(2:end);\nBAre = branch.area(2:end);\nBLen = branch.length(2:end);\nif strcmp(dist,'Dia')\n  Par = branch.diameter(2:end);\n  n = ceil(max(100*Par));\n  a = 0.005; % diameter in 1 cm classes\nelseif strcmp(dist,'Hei')\n  Par = branch.height(2:end);\n  n = ceil(treedata.TreeHeight);\n  a = 1; % height in 1 m classes\nelseif strcmp(dist,'Ang')\n  Par = branch.angle(2:end);\n  n = 18;\n  a = 10; % angle in 10 degree classes\nelseif strcmp(dist,'Zen')\n  Par = branch.zenith(2:end);\n  n = 18;\n  a = 10; % zenith direction in 10 degree angle classes\nelseif strcmp(dist,'Azi')\n  Par = branch.azimuth(2:end)+180;\n  n = 36;\n  a = 10; % azimuth direction in 10 degree angle classes\nend\n\nBranchDist = zeros(8,n);\nfor i = 1:n\n  I = Par >= (i-1)*a & Par < i*a;\n  BranchDist(1,i) = sum(BVol(I)); % volume (all branches)\n  BranchDist(2,i) = sum(BVol(I & BOrd == 1)); % volume (1st-branches)\n  BranchDist(3,i) = sum(BAre(I)); % area (all branches)\n  BranchDist(4,i) = sum(BAre(I & BOrd == 1)); % area (1st-branches)\n  BranchDist(5,i) = sum(BLen(I)); % length (all branches)\n  BranchDist(6,i) = sum(BLen(I & BOrd == 1)); % length (1st-branches)\n  BranchDist(7,i) = nnz(I); % number (all branches)\n  BranchDist(8,i) = nnz(I & BOrd == 1); % number (1st-branches)\nend\ntreedata.(['VolBranch',dist]) = BranchDist(1,:);\ntreedata.(['VolBranch1',dist]) = BranchDist(2,:);\ntreedata.(['AreBranch',dist]) = BranchDist(3,:);\ntreedata.(['AreBranch1',dist]) = BranchDist(4,:);\ntreedata.(['LenBranch',dist]) = BranchDist(5,:);\ntreedata.(['LenBranch1',dist]) = BranchDist(6,:);\ntreedata.(['NumBranch',dist]) = BranchDist(7,:);\ntreedata.(['NumBranch1',dist]) = BranchDist(8,:);\nend\n\n\nfunction treedata = branch_order_distribution(treedata,branch)\n%% Branch order distributions\n% Volume, area, length and number of branches as a function of branch order\nBO = max(branch.order);\nBranchOrdDist = zeros(BO,4);\nfor i = 1:max(1,BO)\n  I = branch.order == i;\n  BranchOrdDist(i,1) = sum(branch.volume(I)); % volumes\n  BranchOrdDist(i,2) = sum(branch.area(I)); % areas\n  BranchOrdDist(i,3) = sum(branch.length(I)); % lengths\n  BranchOrdDist(i,4) = nnz(I); % number of ith-order branches\nend\ntreedata.VolBranchOrd = BranchOrdDist(:,1)';\ntreedata.AreBranchOrd = BranchOrdDist(:,2)';\ntreedata.LenBranchOrd = BranchOrdDist(:,3)';\ntreedata.NumBranchOrd = BranchOrdDist(:,4)';\nend\n"
  },
  {
    "path": "src/tools/verticalcat.m",
    "content": "function [Vector,IndElements] = verticalcat(CellArray)\n\n% Vertical concatenation of the given cell-array into a vector.\n\nCellSize = cellfun('length',CellArray); % determine the size of each cell\nnc = max(size(CellArray)); % number of cells\nIndElements = ones(nc,2); % indexes for elements in each cell\nIndElements(:,2) = cumsum(CellSize);\nIndElements(2:end,1) = IndElements(2:end,1)+IndElements(1:end-1,2);\nVector = zeros(sum(CellSize),1); % concatenation of the cell-array into a vector\nfor j = 1:nc\n    Vector(IndElements(j,1):IndElements(j,2)) = CellArray{j};\nend"
  },
  {
    "path": "src/treeqsm.m",
    "content": "% This file is part of TREEQSM.\n% \n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n% \n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n% \n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\n\nfunction QSM = treeqsm(P,inputs)\n\n% ---------------------------------------------------------------------\n% TREEQSM.M     Reconstructs quantitative structure tree models from point \n%                   clouds containing a tree.\n%\n% Version 2.4.1\n% Latest update     2 May 2022\n%\n% Copyright (C) 2013-2022 Pasi Raumonen\n% ---------------------------------------------------------------------\n%\n% INPUTS:\n%\n% P                 (Filtered) point cloud, (m_points x 3)-matrix, the rows\n%                       give the coordinates of the points.\n%\n% inputs            Structure field defining reconstruction parameters.\n%                       Created with the \"create_input.m\" script. Contains \n%                       the following main fields:\n%   PatchDiam1        Patch size of the first uniform-size cover\n%\n%   PatchDiam2Min     Minimum patch size of the cover sets in the second cover\n%\n%   PatchDiam2Max     Maximum cover set size in the stem's base in the \n%                       second cover\n%\n%   BallRad1          Ball size used for the first cover generation\n%\n%   BallRad2          Maximum ball radius used for the second cover generation\n%\n%   nmin1             Minimum number of points in BallRad1-balls, \n%                       default value is 3.\n%\n%   nmin2             Minimum number of points in BallRad2-balls, \n%                       default value is 1.\n%\n%   OnlyTree          If \"1\", the point cloud contains only points from the \n%                       tree and the trunk's base is defined as the lowest \n%                       part of the point cloud. Default value is \"1\". \n%\n%   Tria              If \"1\", tries to make triangulation for the stem up \n%                       to first main branch. Default value is \"0\". \n%\n%   Dist              If \"1\", compute the point-model distances. \n%                       Default value is \"1\".\n%\n%   MinCylRad         Minimum cylinder radius, used particularly in the \n%                       taper corrections\n%\n%   ParentCor         If \"1\", child branch cylinders radii are always \n%                       smaller than the parent branche's cylinder radii\n%\n%   TaperCor          If \"1\", use partially linear (stem) and parabola \n%                       (branches) taper corrections\n%\n%   GrowthVolCor      If \"1\", use growth volume correction introduced \n%                       by Jan Hackenberg\n%\n%   GrowthVolFac      fac-parameter of the growth volume approach, \n%                       defines upper and lower bound\n%\n%   name              Name string for saving output files and name for the\n%                       model in the output object\n% \n%   tree              Numerical id/index given to the tree\n% \n%   model             Model number of the tree, e.g. with the same inputs\n%\n%   savemat           If \"1\", saves the output struct QSM as a matlab-file\n%                       into \\result folder \n%\n%   savetxt           If \"1\", saves the models in .txt-files into \n%                       \\result folder \n%\n%   plot              Defines what is plotted during the reconstruction:\n%                       2 = same as below plus distributions\n%                       1 = plots the segmented point cloud and QSMs\n%                       0 = plots nothing\n%\n%   disp              Defines what is displayed during the reconstruction:\n%                       2 = same as below plus times and tree attributes; \n%                       1 = display name, parameters and fit metrics;\n%                       0 = display only the name\n% ---------------------------------------------------------------------\n% OUTPUT:\n%\n% QSM           Structure array with the following fields:\n%               cylinder        Cylinder data  \n%               branch          Branch data\n%               treedata        Tree attributes  \n%               rundata         Information about the modelling run\n%               pmdistances     Point-to-model distance statistics\n%               triangulation   Triangulation of the stem (if inputs.Tria = 1)\n% ---------------------------------------------------------------------\n\n% cylinder (structure-array) contains the following fields:\n% radius\n% length\n% start         xyz-coordinates of the starting point\n% axis          xyz-component of the cylinder axis\n% parent        index (in this file) of the parent cylinder\n% extension     index (in this file) of the extension cylinder\n% added         is cylinder added after normal cylinder fitting (= 1 if added)\n% UnmodRadius   unmodified radius of the cylinder\n% branch        branch (index in the branch structure array) of the cylinder\n% BranchOrder   branch order of the branch the cylinder belongs\n% PositionInBranch\trunning number of the cylinder in the branch it belongs\n%\n% branch (structure-array) contains the following fields:\n% order     branch order (0 for trunk, 1 for branches originating from \n%               the trunk, etc.)\n% parent\tindex (in this file) of the parent branch\n% volume\tvolume (L) of the branch (sum of the volumes of the cylinders \n%               forming the branch)\n% length\tlength (m) of the branch (sum of the lengths of the cylinders)\n% angle     branching angle (deg) (angle between the branch and its parent \n%               at the branching point)\n% height    height (m) of the base of the branch\n% azimuth   azimuth (deg) of the branch at the base \n% diameter  diameter (m) of the branch at the base\n%\n% treedata (structure-array) contains the following fields:\n% TotalVolume\n% TrunkVolume\n% BranchVolume\n% TreeHeight\n% TrunkLength\n% BranchLength\n% NumberBranches    Total number of branches\n% MaxBranchOrder \n% TotalArea \n% DBHqsm        From the cylinder of the QSM at the right heigth\n% DBHcyl        From the cylinder fitted to the section 1.1-1.5m\n% location      (x,y,z)-coordinates of the base of the tree\n% StemTaper     Stem taper function/curve from the QSM\n% VolumeCylDiam     Distribution of the total volume in diameter classes\n% LengthCylDiam     Distribution of the total length in diameter classes\n% VolumeBranchOrder     Branch volume per branching order\n% LengthBranchOrder     Branch length per branching order\n% NumberBranchOrder     Number of branches per branching order\n\n% treedata from mixed model (cylinders and triangulation) contains also \n% the following fields:\n% DBHtri            Computed from triangulation model\n% TriaTrunkVolume   Triangulated trunk volume (up to first branch)\n% MixTrunkVolume    Mixed trunk volume, bottom (triang.) + top (cylinders)\n% MixTotalVolume    Mixed total volume, mixed trunk volume + branch volume\n% TriaTrunkLength   Triangulated trunk length\n%\n% pmdistances (structure-array) contains the following fields (and others):\n% CylDists  Average point-model distance for each cylinder\n% median    median of CylDist for all, stem, 1branch, 2branch cylinder\n% mean      mean of CylDist for all, stem, 1branch, 2branch cylinder\n% max       max of CylDist for all, stem, 1branch, 2branch cylinder\n% std       standard dev. of CylDist for all, stem, 1branch, 2branch cylinder\n% \n% rundata (structure-array) contains the following fields:\n% inputs    The input parameters in a structure-array\n% time      Computation times for each step\n% date      Starting and stopping dates (year,month,day,hour,minute,second) \n%             of the computation\n% \n% triangulation (structure-array) contains the following fields:\n% vert      Vertices (xyz-coordinates) of the triangulation\n% facet     Facet information\n% fvd       Color information for plotting the model\n% volume    Volume enclosed by the triangulation\n% bottom    Z-coordinate of the bottom plane of the triangulation\n% top       Z-coordinate of the top plane of the triangulation\n% triah     Height of the triangles\n% triah     Width of the triangles\n% cylind    Cylinder index in the stem where the triangulation stops\n% ---------------------------------------------------------------------\n\n% Changes from version 2.4.0 to 2.4.1, 2 May 2022:  \n% Minor update. New filtering options, new code (\"define_input\") for \n% selecting automatically PatchDiam and BallRad parameter values for \n% the optimization process, added sensitivity estimates of the results, \n% new smoother plotting of QSMs, corrected some bugs, rewrote some \n% functions (e.g. \"branches\").\n% Particular changes in treeqsm.m file:\n% 1) Deleted the remove of the field \"ChildCyls\" and \"CylsInSegment\".\n\n% Changes from version 2.3.2 to 2.4.0, 17 Aug 2020:  \n% First major update. Cylinder fitting process and the taper correction \n% has changed. The fitting is adaptive and no more “lcyl” and “FilRad” \n% parameters. Treedata has many new outputs: Branch and cylinder \n% distributions; surface areas; crown dimensions. More robust triangulation \n% of stem. Branch, cylinder and triangulation structures have new fields. \n% More optimisation metrics, more plots of the results and more plotting \n% functions.\n% Particular changes in treeqsm.m file:\n% 1) Removed the for-loops for lcyl and FilRad.\n% 2) Changes what is displayed about the quality of QSMs \n%    (point-model-distances and surface coverage) during reconstruction\n% 3) Added version number to rundata\n% 4) Added remove of the field \"ChildCyls\" and \"CylsInSegment\" of \"cylinder\"\n%    from \"branches\" to \"treeqsm\".\n\n% Changes from version 2.3.1 to 2.3.2, 2 Dec 2019:  \n% Small changes in the subfunction to allow trees without branches\n\n% Changes from version 2.3.0 to 2.3.1, 8 Oct 2019:  \n% 1) Some changes in the subfunctions, particularly in \"cylinders\" and \n%    \"tree_sets\"\n% 2) Changed how \"treeqsm\" displays things during the running of the\n%    function\n\n\n%% Code starts -->\nTime = zeros(11,1); % Save computation times for modelling steps\nDate = zeros(2,6); % Starting and stopping dates of the computation\nDate(1,:) = clock;\n% Names of the steps to display\nname = ['Cover sets      ';\n        'Tree sets       ';\n        'Initial segments';\n        'Final segments  ';\n        'Cylinders       ';\n        'Branch & data   ';\n        'Distances       '];\n \nif inputs.disp > 0\n  disp('---------------')\n  disp(['  ',inputs.name,', Tree = ',num2str(inputs.tree),...\n    ', Model = ',num2str(inputs.model)])\nend\n\n% Input parameters\nPatchDiam1 = inputs.PatchDiam1;\nPatchDiam2Min = inputs.PatchDiam2Min;\nPatchDiam2Max = inputs.PatchDiam2Max;\nBallRad1 = inputs.BallRad1; \nBallRad2 = inputs.BallRad2; \nnd = length(PatchDiam1);\nni = length(PatchDiam2Min);\nna = length(PatchDiam2Max);\n\nif inputs.disp == 2\n  % Display parameter values\n  disp(['  PatchDiam1 = ',num2str(PatchDiam1)])\n  disp(['  BallRad1 = ',num2str(BallRad1)])\n  disp(['  PatchDiam2Min = ',num2str(PatchDiam2Min)])\n  disp(['  PatchDiam2Max = ',num2str(PatchDiam2Max)])\n  disp(['  BallRad2 = ',num2str(BallRad2)])\n  disp(['  Tria = ',num2str(inputs.Tria),...\n      ', OnlyTree = ',num2str(inputs.OnlyTree)])\n  disp('Progress:')\nend\n\n%% Make the point cloud into proper form\n% only 3-dimensional data\nif size(P,2) > 3\n    P = P(:,1:3);\nend\n% Only double precision data\nif ~isa(P,'double')\n    P = double(P);\nend\n\n%% Initialize the output file\nQSM = struct('cylinder',{},'branch',{},'treedata',{},'rundata',{},...\n    'pmdistance',{},'triangulation',{});\n\n%% Reconstruct QSMs\nnmodel = 0;\nfor h = 1:nd\n  tic\n  Inputs = inputs;\n  Inputs.PatchDiam1 = PatchDiam1(h);\n  Inputs.BallRad1 = BallRad1(h);\n  if nd > 1 && inputs.disp >= 1\n    disp('  -----------------')\n    disp(['  PatchDiam1 = ',num2str(PatchDiam1(h))]);\n    disp('  -----------------')\n  end\n  \n  %% Generate cover sets\n  cover1 = cover_sets(P,Inputs);\n  Time(1) = toc;\n  if inputs.disp == 2\n    display_time(Time(1),Time(1),name(1,:),1)\n  end\n  \n  %% Determine tree sets and update neighbors\n  [cover1,Base,Forb] = tree_sets(P,cover1,Inputs);\n  Time(2) = toc-Time(1);\n  if inputs.disp == 2\n    display_time(Time(2),sum(Time(1:2)),name(2,:),1)\n  end\n  \n  %% Determine initial segments\n  segment1 = segments(cover1,Base,Forb);\n  Time(3) = toc-sum(Time(1:2));\n  if inputs.disp == 2\n    display_time(Time(3),sum(Time(1:3)),name(3,:),1)\n  end\n  \n  %% Correct segments\n  % Don't remove small segments and add the modified base to the segment\n  segment1 = correct_segments(P,cover1,segment1,Inputs,0,1,1);\n  Time(4) = toc-sum(Time(1:3));\n  if inputs.disp == 2\n    display_time(Time(4),sum(Time(1:4)),name(4,:),1)\n  end\n  \n  for i = 1:na\n    % Modify inputs\n    Inputs.PatchDiam2Max = PatchDiam2Max(i);\n    Inputs.BallRad2 = BallRad2(i);\n    if na > 1 && inputs.disp >= 1\n      disp('    -----------------')\n      disp(['    PatchDiam2Max = ',num2str(PatchDiam2Max(i))]);\n      disp('    -----------------')\n    end\n    for j = 1:ni\n      tic\n      % Modify inputs\n      Inputs.PatchDiam2Min = PatchDiam2Min(j);\n      if ni > 1 && inputs.disp >= 1\n        disp('      -----------------')\n        disp(['      PatchDiam2Min = ',num2str(PatchDiam2Min(j))]);\n        disp('      -----------------')\n      end\n      \n      %% Generate new cover sets\n      % Determine relative size of new cover sets and use only tree points\n      RS = relative_size(P,cover1,segment1);\n      \n      % Generate new cover\n      cover2 = cover_sets(P,Inputs,RS);\n      Time(5) = toc;\n      if inputs.disp == 2\n          display_time(Time(5),sum(Time(1:5)),name(1,:),1)\n      end\n      \n      %% Determine tree sets and update neighbors\n      [cover2,Base,Forb] = tree_sets(P,cover2,Inputs,segment1);\n      Time(6) = toc-Time(5);\n      if inputs.disp == 2\n        display_time(Time(6),sum(Time(1:6)),name(2,:),1)\n      end\n      \n      %% Determine segments\n      segment2 = segments(cover2,Base,Forb);\n      Time(7) = toc-sum(Time(5:6));\n      if inputs.disp == 2\n        display_time(Time(7),sum(Time(1:7)),name(3,:),1)\n      end\n      \n      %% Correct segments\n      % Remove small segments and the extended bases.\n      segment2 = correct_segments(P,cover2,segment2,Inputs,1,1,0);\n      Time(8) = toc-sum(Time(5:7));\n      if inputs.disp == 2\n        display_time(Time(8),sum(Time(1:8)),name(4,:),1)\n      end\n      \n      %% Define cylinders\n      cylinder = cylinders(P,cover2,segment2,Inputs);\n      Time(9) = toc;\n      if inputs.disp == 2\n        display_time(Time(9),sum(Time(1:9)),name(5,:),1)\n      end\n      \n      if ~isempty(cylinder.radius)\n        %% Determine the branches\n        branch = branches(cylinder);\n        \n        %% Compute (and display) model attributes\n        T = segment2.segments{1};\n        T = vertcat(T{:});\n        T = vertcat(cover2.ball{T});\n        trunk = P(T,:); % point cloud of the trunk\n        % Compute attributes and distibutions from the cylinder model\n        % and possibly some from a triangulation\n        [treedata,triangulation] = tree_data(cylinder,branch,trunk,inputs);\n        Time(10) = toc-Time(9);\n        if inputs.disp == 2\n          display_time(Time(10),sum(Time(1:10)),name(6,:),1)\n        end\n        \n        %% Compute point model distances\n        if inputs.Dist\n          pmdis = point_model_distance(P,cylinder);\n          \n          % Display the mean point-model distances and surface coverages\n          % for stem, branch, 1branc and 2branch cylinders\n          if inputs.disp >= 1\n            D = [pmdis.TrunkMean pmdis.BranchMean ...\n                pmdis.Branch1Mean pmdis.Branch2Mean];\n            D = round(10000*D)/10;\n            \n            T = cylinder.branch == 1;\n            B1 = cylinder.BranchOrder == 1;\n            B2 = cylinder.BranchOrder == 2;\n            SC = 100*cylinder.SurfCov;\n            S = [mean(SC(T)) mean(SC(~T)) mean(SC(B1)) mean(SC(B2))];\n            S = round(10*S)/10;\n            \n            disp('  ----------')\n            str = ['  PatchDiam1 = ',num2str(PatchDiam1(h)), ...\n                ', PatchDiam2Max = ',num2str(PatchDiam2Max(i)), ...\n                ', PatchDiam2Min = ',num2str(PatchDiam2Min(j))];\n            disp(str)\n            str = ['  Distances and surface coverages for ',...\n                'trunk, branch, 1branch, 2branch:'];\n            disp(str)\n            str = ['  Average cylinder-point distance:  '...\n                num2str(D(1)),'  ',num2str(D(2)),'  ',...\n                num2str(D(3)),'  ',num2str(D(4)),' mm'];\n            disp(str)\n            str = ['  Average surface coverage:  '...\n                num2str(S(1)),'  ',num2str(S(2)),'  ',...\n                num2str(S(3)),'  ',num2str(S(4)),' %'];\n            disp(str)\n            disp('  ----------')\n          end\n          Time(11) = toc-sum(Time(9:10));\n          if inputs.disp == 2\n            display_time(Time(11),sum(Time(1:11)),name(7,:),1)\n          end\n        end\n        \n        %% Reconstruct the output \"QSM\"\n        Date(2,:) = clock;\n        Time(12) = sum(Time(1:11));\n        clear qsm\n        qsm = struct('cylinder',{},'branch',{},'treedata',{},'rundata',{},...\n          'pmdistance',{},'triangulation',{});\n        qsm(1).cylinder = cylinder;\n        qsm(1).branch = branch;\n        qsm(1).treedata = treedata;\n        qsm(1).rundata.inputs = Inputs;\n        qsm(1).rundata.time = single(Time);\n        qsm(1).rundata.date = single(Date);\n        qsm(1).rundata.version = '2.4.1';\n        if inputs.Dist\n          qsm(1).pmdistance = pmdis;\n        end\n        if inputs.Tria\n          qsm(1).triangulation = triangulation;\n        end\n        nmodel = nmodel+1;\n        QSM(nmodel) = qsm;\n        \n        %% Save the output into results-folder\n        % matlab-format (.mat)\n        if inputs.savemat\n          str = [inputs.name,'_t',num2str(inputs.tree),'_m',...\n            num2str(inputs.model)];\n          save(['results/QSM_',str],'QSM')\n        end\n        % text-format (.txt)\n        if inputs.savetxt\n          if nd > 1 || na > 1 || ni > 1\n            str = [inputs.name,'_t',num2str(inputs.tree),'_m',...\n              num2str(inputs.model)];\n            if nd > 1\n              str = [str,'_D',num2str(PatchDiam1(h))];\n            end\n            if na > 1\n              str = [str,'_DA',num2str(PatchDiam2Max(i))];\n            end\n            if ni > 1\n              str = [str,'_DI',num2str(PatchDiam2Min(j))];\n            end\n          else\n            str = [inputs.name,'_t',num2str(inputs.tree),'_m',...\n              num2str(inputs.model)];\n          end\n          save_model_text(qsm,str)\n        end\n\n        %% Plot models and segmentations\n        if inputs.plot >= 1\n          if inputs.Tria\n            plot_models_segmentations(P,cover2,segment2,cylinder,trunk,...\n                triangulation)\n          else\n            plot_models_segmentations(P,cover2,segment2,cylinder)\n          end\n          if nd > 1 || na > 1 || ni > 1\n            pause\n          end\n        end\n      end\n    end\n  end\nend\n"
  },
  {
    "path": "src/triangulation/boundary_curve.m",
    "content": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction [Curve,Ind] = boundary_curve(P,Curve0,rball,dmax)\n\n% ---------------------------------------------------------------------\n% BOUNDARY_CURVE.M      Determines the boundary curve based on the\n%                           previously defined boundary curve.\n%\n% Version 1.1.0\n% Latest update     3 May 2022\n%\n% Copyright (C) 2015-2022 Pasi Raumonen\n% ---------------------------------------------------------------------\n%\n% Inputs:\n% P         Point cloud of the cross section\n% Curve0     Seed points from previous cross section curve\n% rball     Radius of the balls centered at seed points\n% dmax      Maximum distance between concecutive curve points, if larger,\n%               then create a new one between the points\n% ---------------------------------------------------------------------\n\n% Changes from version 1.0.0 to 1.1.0, 3 May 2022:\n% 1) Increased the cubical neighborhood in the generation of the segments\n\n%% Partition the point cloud into cubes\nMin = double(min([P(:,1:2); Curve0(:,1:2)]));\nMax = double(max([P(:,1:2); Curve0(:,1:2)]));\nN = double(ceil((Max-Min)/rball)+5);\n% cube coordinates of the section points\nCC = floor([P(:,1)-Min(1) P(:,2)-Min(2)]/rball)+3;\n% Sorts the points according a lexicographical order\nS = [CC(:,1) CC(:,2)-1]*[1 N(1)]';\n[S,I] = sort(S);\n% Define \"partition\"\nnp = size(P,1);\npartition = cell(N(1),N(2));\np = 1;              % The index of the point under comparison\nwhile p <= np\n  t = 1;\n  while (p+t <= np) && (S(p) == S(p+t))\n    t = t+1;\n  end\n  q = I(p);\n  partition{CC(q,1),CC(q,2)} = I(p:p+t-1);\n  p = p+t;\nend\n\n\n%% Define segments using the previous points\n% cube coordinates of the seed points:\nCC = floor([Curve0(:,1)-Min(1) Curve0(:,2)-Min(2)]/rball)+3;\nI = CC < 3;\nCC(I) = 3;\nnc = size(Curve0,1);  % number of sets\nDist = 1e8*ones(np,1);  % distance of point to the closest center\nSoP = zeros(np,1);  % the segment the points belong to\nRadius = rball^2;\nfor i = 1:nc\n  points = partition(CC(i,1)-2:CC(i,1)+2,CC(i,2)-2:CC(i,2)+2);\n  points = vertcat(points{:});\n  V = [P(points,1)-Curve0(i,1) P(points,2)-Curve0(i,2)];\n  dist = sum(V.*V,2);\n  PointsInBall = dist < Radius;\n  points = points(PointsInBall);\n  dist = dist(PointsInBall);\n  D = Dist(points);\n  L = dist < D;\n  I = points(L);\n  Dist(I) = dist(L);\n  SoP(I) = i;\nend\n\n%% Finalise the segments\n% Number of points in each segment and index of each point in its segment\nNum = zeros(nc,1);\nIndPoints = zeros(np,1);\nfor i = 1:np\n  if SoP(i) > 0\n    Num(SoP(i)) = Num(SoP(i))+1;\n    IndPoints(i) = Num(SoP(i));\n  end\nend\n% Continue if enough non-emtpy segments\nif nnz(Num) > 0.05*nc\n  % Initialization of the \"Seg\"\n  Seg = cell(nc,1);\n  for i = 1:nc\n    Seg{i} = zeros(Num(i),1);\n  end\n  % Define the \"Seg\"\n  for i = 1:np\n    if SoP(i) > 0\n      Seg{SoP(i),1}(IndPoints(i),1) = i;\n    end\n  end\n\n  %% Define the new curve points as the average of the segments\n  Curve = zeros(nc,3);  % the new boundary curve\n  Empty = false(nc,1);\n  for i = 1:nc\n    S = Seg{i};\n    if ~isempty(S)\n      Curve(i,:) = mean(P(S,:),1);\n      if norm(Curve(i,:)-Curve0(i,:)) > 1.25*dmax\n        Curve(i,:) = Curve0(i,:);\n      end\n    else\n      Empty(i) = true;\n    end\n  end\n\n  %% Interpolate for empty segments\n  % For empty segments create points by interpolation from neighboring \n  % non-empty segments\n  if any(Empty)\n    for i = 1:nc\n      if Empty(i)\n        if i > 1 && i < nc\n          k = 0;\n          while i+k <= nc && Empty(i+k)\n            k = k+1;\n          end\n          if i+k <= nc\n            LineEle = Curve(i+k,:)-Curve(i-1,:);\n          else\n            LineEle = Curve(1,:)-Curve(i-1,:);\n          end\n          if k < 5\n            for j = 1:k\n              Curve(i+j-1,:) = Curve(i-1,:)+j/(k+1)*LineEle;\n            end\n          else\n            Curve(i:i+k-1,:) = Curve0(i:i+k-1,:);\n          end\n        elseif i == 1\n          a = 0;\n          while Empty(end-a)\n            a = a+1;\n          end\n          b = 1;\n          while Empty(b)\n            b = b+1;\n          end\n          LineEle = Curve(b,:)-Curve(nc-a,:);\n          n = a+b-1;\n          if n < 5\n            for j = 1:a-1\n              Curve(nc-a+1+j,:) = Curve(nc-a,:)+j/n*LineEle;\n            end\n            for j = 1:b-1\n              Curve(j,:) = Curve(nc-a,:)+(j+a-1)/n*LineEle;\n            end\n          else\n            Curve(nc-a+2:nc,1:2) = Curve0(nc-a+2:nc,1:2);\n            Curve(nc-a+2:nc,3) = Curve0(nc-a+2:nc,3);\n            Curve(1:b-1,1:2) = Curve0(1:b-1,1:2);\n            Curve(1:b-1,3) = Curve0(1:b-1,3);\n          end\n        elseif i == nc\n          LineEle = Curve(1,:)-Curve(nc-1,:);\n          Curve(i,:) = Curve(nc-1,:)+0.5*LineEle;\n        end\n      end\n    end\n  end\n\n  % Correct the height\n  Curve(:,3) = min(Curve(:,3));\n\n  % Check self-intersection\n  [Intersect,IntersectLines] = check_self_intersection(Curve(:,1:2));\n\n  % If self-intersection, try to modify the curve\n  j = 1;\n  while Intersect && j <= 5\n    n = size(Curve,1);\n    InterLines = (1:1:n)';\n    NumberOfIntersections = cellfun('length',IntersectLines(:,1));\n    I = NumberOfIntersections > 0;\n    InterLines = InterLines(I);\n    CrossLen = vertcat(IntersectLines{I,2});\n    if length(CrossLen) == length(InterLines)\n      LineEle = Curve([2:end 1],:)-Curve(1:end,:);\n      d = sqrt(sum(LineEle.*LineEle,2));\n      m = length(InterLines);\n      for i = 1:2:m\n        if InterLines(i) ~= n\n          Curve(InterLines(i)+1,:) = Curve(InterLines(i),:)+...\n            0.9*CrossLen(i)/d(InterLines(i))*LineEle(InterLines(i),:);\n        else\n          Curve(1,:) = Curve(InterLines(i),:)+...\n            0.9*CrossLen(i)/d(InterLines(i))*LineEle(InterLines(i),:);\n        end\n      end\n      [Intersect,IntersectLines] = check_self_intersection(Curve(:,1:2));\n      j = j+1;\n    else\n      j = 6;\n    end\n  end\n\n  %% Add new points if too large distances\n  LineEle = Curve([2:end 1],:)-Curve(1:end,:);\n  d = sum(LineEle.*LineEle,2);\n  Large = d > dmax^2;\n  m = nnz(Large);\n  if m > 0\n    Curve0 = zeros(nc+m,3);\n    Ind = zeros(nc+m,2);\n    t = 0;\n    for i = 1:nc\n      if Large(i)\n        t = t+1;\n        Curve0(t,:) = Curve(i,:);\n        if i < nc\n          Ind(t,:) = [i i+1];\n        else\n          Ind(t,:) = [i 1];\n        end\n        t = t+1;\n        Curve0(t,:) = Curve(i,:)+0.5*LineEle(i,:);\n        if i < nc\n          Ind(t,:) = [i+1 0];\n        else\n          Ind(t,:) = [1 0];\n        end\n      else\n        t = t+1;\n        Curve0(t,:) = Curve(i,:);\n        if i < nc\n          Ind(t,:) = [i i+1];\n        else\n          Ind(t,:) = [i 1];\n        end\n      end\n    end\n    Curve = Curve0;\n\n  else\n    Ind = [(1:1:nc)' [(2:1:nc)'; 1]];\n  end\n\n\n  %% Remove new points if too small distances\n  nc = size(Curve,1);\n  LineEle = Curve([2:end 1],:)-Curve(1:end,:);\n  d = sum(LineEle.*LineEle,2);\n  Small = d < (0.333*dmax)^2;\n  m = nnz(Small);\n  if m > 0\n    for i = 1:nc-1\n      if ~Small(i) && Small(i+1)\n        Ind(i,2) = -1;\n      elseif Small(i) && Small(i+1)\n        Small(i+1) = false;\n      end\n    end\n    if ~Small(nc) && Small(1)\n      Ind(nc,2) = -1;\n      Ind(1,2) = -1;\n      Small(1) = false;\n      Small(nc) = true;\n      I = Ind(:,2) > 0;\n      Ind(2:end,1) = Ind(2:end,1)+1;\n      Ind(I,2) = Ind(I,2)+1;\n\n    end\n    Ind = Ind(~Small,:);\n    Curve = Curve(~Small,:);\n  end\n\nelse\n  % If not enough new points, return the old curve\n  Ind = [(1:1:nc)' [(2:1:nc)'; 1]];\n  Curve = Curve0;\nend\n"
  },
  {
    "path": "src/triangulation/boundary_curve2.m",
    "content": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction Curve = boundary_curve2(P,Curve0,rball,dmax)\n\n% ---------------------------------------------------------------------\n% BOUNDARY_CURVE2.M      Determines the boundary curve based on the\n%                           previously defined boundary curve.\n%\n% Version 1.0\n% Latest update     16 Aug 2017\n%\n% Copyright (C) 2015-2017 Pasi Raumonen\n% ---------------------------------------------------------------------\n%\n% Inputs:\n% P         Point cloud of the cross section\n% Curve0    Seed points from previous cross section curve\n% rball     Radius of the balls centered at seed points\n% dmax      Maximum distance between concecutive curve points, if larger,\n%               then create a new one between the points\n\n\n%% Partition the point cloud into cubes\nMin = double(min([P(:,1:2); Curve0(:,1:2)]));\nMax = double(max([P(:,1:2); Curve0(:,1:2)]));\nN = double(ceil((Max-Min)/rball)+5);\nCC = floor([P(:,1)-Min(1) P(:,2)-Min(2)]/rball)+3; % cube coordinates of the section points\n% Sorts the points according a lexicographical order\nS = [CC(:,1) CC(:,2)-1]*[1 N(1)]';\n[S,I] = sort(S);\n% Define \"partition\"\nnp = size(P,1);\npartition = cell(N(1),N(2));\np = 1;              % The index of the point under comparison\nwhile p <= np\n  t = 1;\n  while (p+t <= np) && (S(p) == S(p+t))\n    t = t+1;\n  end\n  q = I(p);\n  partition{CC(q,1),CC(q,2)} = I(p:p+t-1);\n  p = p+t;\nend\n\n\n%% Define segments using the previous points\nCC = floor([Curve0(:,1)-Min(1) Curve0(:,2)-Min(2)]/rball)+3; % cube coordinates of the seed points\nI = CC < 3;\nCC(I) = 3;\nnc = size(Curve0,1);  % number of sets\nDist = 1e8*ones(np,1);  % distance of point to the closest center\nSoP = zeros(np,1);  % the segment the points belong to\nRadius = rball^2;\nfor i = 1:nc\n  points = partition(CC(i,1)-1:CC(i,1)+1,CC(i,2)-1:CC(i,2)+1);\n  points = vertcat(points{:});\n  V = [P(points,1)-Curve0(i,1) P(points,2)-Curve0(i,2)];\n  dist = sum(V.*V,2);\n  PointsInBall = dist < Radius;\n  points = points(PointsInBall);\n  dist = dist(PointsInBall);\n  D = Dist(points);\n  L = dist < D;\n  I = points(L);\n  Dist(I) = dist(L);\n  SoP(I) = i;\nend\n\n%% Finalise the segments\n% Number of points in each segment and index of each point in its segment\nNum = zeros(nc,1);\nIndPoints = zeros(np,1);\nfor i = 1:np\n  if SoP(i) > 0\n    Num(SoP(i)) = Num(SoP(i))+1;\n    IndPoints(i) = Num(SoP(i));\n  end\nend\n% Continue if enough non-emtpy segments\nif nnz(Num) > 0.05*nc\n  % Initialization of the \"Seg\"\n  Seg = cell(nc,1);\n  for i = 1:nc\n    Seg{i} = zeros(Num(i),1);\n  end\n  % Define the \"Seg\"\n  for i = 1:np\n    if SoP(i) > 0\n      Seg{SoP(i),1}(IndPoints(i),1) = i;\n    end\n  end\n\n  %% Define the new curve points as the average of the segments\n  Curve = zeros(nc,3);  % the new boundary curve\n  for i = 1:nc\n    S = Seg{i};\n    if ~isempty(S)\n      Curve(i,:) = mean(P(S,:),1);\n      if norm(Curve(i,:)-Curve0(i,:)) > 1.25*dmax\n        Curve(i,:) = Curve0(i,:);\n      end\n    else\n      Curve(i,:) = Curve0(i,:);\n    end\n  end\n\n  %% Add new points if too large distances\n  V = Curve([2:end 1],:)-Curve(1:end,:);\n  d = sum(V.*V,2);\n  Large = d > dmax^2;\n  m = nnz(Large);\n  if m > 0\n    Curve0 = zeros(nc+m,3);\n    t = 0;\n    for i = 1:nc\n      if Large(i)\n        t = t+1;\n        Curve0(t,:) = Curve(i,:);\n        t = t+1;\n        Curve0(t,:) = Curve(i,:)+0.5*V(i,:);\n      else\n        t = t+1;\n        Curve0(t,:) = Curve(i,:);\n      end\n    end\n    Curve = Curve0;\n  end\n\n  %% Remove new points if too small distances\n  nc = size(Curve,1);\n  V = Curve([2:end 1],:)-Curve(1:end,:);\n  d = sum(V.*V,2);\n  Small = d < (0.333*dmax)^2;\n  m = nnz(Small);\n  if m > 0\n    for i = 1:nc-1\n      if Small(i) && Small(i+1)\n        Small(i+1) = false;\n      end\n    end\n    if ~Small(nc) && Small(1)\n      Small(1) = false;\n      Small(nc) = true;\n    end\n    Curve = Curve(~Small,:);\n  end\n\nelse\n  % If not enough new points, return the old curve\n  Curve = Curve0;\nend\n"
  },
  {
    "path": "src/triangulation/check_self_intersection.m",
    "content": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction [Intersect,IntersectLines] = check_self_intersection(Curve)\n\n% The function takes in a curve (the coordinates of the vertices, in the\n% right order) and checks if the curve intersects itself\n%\n% Outputs:\n% Intersect         Logical value indicating if the curve self-intersects\n% IntersectLines    Cell array containing for each line element which are\n%                       the intersecting elements and how far away along\n%                       the line the intersection point is\n\n\nif ~isempty(Curve)\n  dim = size(Curve,2); % two or three dimensional curve\n  n = size(Curve,1); % number of points in the curve\n  V = Curve([(2:n)'; 1],:)-Curve; % line elements forming the curve\n  L = sqrt(sum(V.*V,2)); % the lengths of the line elements\n  i = 1; % the line element under inspection\n  Ind = (1:1:n)'; % indexes of the line elements\n  if dim == 2 % 2d curves\n    % directions (unit vectors) of the line elements:\n    DirLines = [1./L.*V(:,1) 1./L.*V(:,2)]; \n    Intersect = false;\n    if nargout == 1 % check only if the curve intersects\n      while i <= n-1 && ~Intersect\n        % Select the line elements that can intersect element i\n        if i > 1\n          I = Ind > i+1 | Ind < i-1;\n        else\n          I = Ind > i+1 & Ind < n;\n        end\n        ind = Ind(I)';\n        for j = ind\n          % Solve for the crossing points of every line element\n          A = [DirLines(j,:)' -DirLines(i,:)'];\n          b = Curve(i,:)'-Curve(j,:)';\n          Ainv = 1/(A(1,1)*A(2,2)-A(1,2)*A(2,1))*[A(2,2) -A(1,2); -A(2,1) A(1,1)];\n          x = Ainv*b; % signed length along the line elements to the crossing\n          if x(1) >= 0 && x(1) <= L(j) && x(2) >= 0 && x(2) <= L(i)\n            Intersect = true;\n          end\n        end\n        i = i+1; % study the next line element\n      end\n    else % determine also all intersection points (line elements)\n      IntersectLines = cell(n,2);\n      for i = 1:n-1\n        % Select the line elements that can intersect element i\n        if i > 1\n          I = Ind > i+1 | Ind < i-1;\n        else\n          I = Ind > i+1 & Ind < n;\n        end\n        ind = Ind(I)';\n        for j = ind\n          % Solve for the crossing points of every line element\n          A = [DirLines(j,:)' -DirLines(i,:)'];\n          b = Curve(i,:)'-Curve(j,:)';\n          Ainv = 1/(A(1,1)*A(2,2)-A(1,2)*A(2,1))*[A(2,2) -A(1,2); -A(2,1) A(1,1)];\n          x = Ainv*b;\n          if x(1) >= 0 && x(1) <= L(j) && x(2) >= 0 && x(2) <= L(i)\n            Intersect = true;\n            % which line elements cross element i:\n            IntersectLines{i,1} = [IntersectLines{i,1}; j]; \n            % which line elements cross element j:\n            IntersectLines{j,1} = [IntersectLines{j,1}; i]; \n            % distances along element i to intersection points:\n            IntersectLines{i,2} = [IntersectLines{i,2}; x(1)]; \n            % distances along element j to intersection points:\n            IntersectLines{j,2} = [IntersectLines{j,2}; x(2)]; \n          end\n        end\n      end\n      % remove possible multiple values\n      for i = 1:n\n        IntersectLines{i,1} = unique(IntersectLines{i,1});\n        IntersectLines{i,2} = min(IntersectLines{i,2});\n      end\n    end\n\n  elseif dim == 3 % 3d curves\n    % directions (unit vectors) of the line elements\n    DirLines = [1./L.*V(:,1) 1./L.*V(:,2) 1./L.*V(:,3)];\n    Intersect = false;\n    if nargout == 1 % check only if the curve intersects\n      while i <= n-1\n        % Select the line elements that can intersect element i\n        if i > 1\n          I = Ind > i+1 | Ind < i-1;\n        else\n          I = Ind > i+1 & Ind < n;\n        end\n        % Solve for possible intersection points\n        [~,DistOnRay,DistOnLines] = distances_between_lines(...\n          Curve(i,:),DirLines(i,:),Curve(I,:),DirLines(I,:));\n        if any(DistOnRay >= 0 & DistOnRay <= L(i) &...\n            DistOnLines > 0 & DistOnLines <= L(I))\n          Intersect = true;\n          i = n;\n        else\n          i = i+1; % study the next line element\n        end\n      end\n    else % determine also all intersection points (line elements)\n      IntersectLines = cell(n,2);\n      for i = 1:n-1\n        % Select the line elements that can intersect element i\n        if i > 1\n          I = Ind > i+1 | Ind < i-1;\n        else\n          I = Ind > i+1 & Ind < n;\n        end\n        % Solve for possible intersection points\n        [D,DistOnRay,DistOnLines] = distances_between_lines(...\n          Curve(i,:),DirLines(i,:),Curve(I,:),DirLines(I,:));\n        if any(DistOnRay >= 0 & DistOnRay <= L(i) & ...\n            DistOnLines > 0 & DistOnLines <= L(I))\n          Intersect = true;\n          J = DistOnRay >= 0 & DistOnRay <= L(i) & ...\n            DistOnLines > 0 & DistOnLines <= L(I);\n          ind = Ind(I);\n          ind = ind(J);\n          DistOnLines = DistOnLines(J);\n          IntersectLines{i,1} = ind;\n          IntersectLines{i,2} = DistOnRay(J);\n          % Record the elements intersecting\n          for j = 1:length(ind)\n            IntersectLines{ind(j),1} = [IntersectLines{ind(j),1}; i];\n            IntersectLines{ind(j),2} = [IntersectLines{ind(j),2}; DistOnLines(j)];\n          end\n        end\n      end\n      % remove possible multiple values\n      for i = 1:n\n        IntersectLines{i} = unique(IntersectLines{i});\n        IntersectLines{i,2} = min(IntersectLines{i,2});\n      end\n    end\n  end\nelse % Empty curve\n  Intersect = false;\n  IntersectLines = cell(1,1);\nend\n"
  },
  {
    "path": "src/triangulation/curve_based_triangulation.m",
    "content": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction triangulation = curve_based_triangulation(P,TriaHeight,TriaWidth)\n\n% ---------------------------------------------------------------------\n% CURVE_BASED_TRIANGULATION.M   Reconstructs a triangulation for the\n%                               stem-buttress surface based on boundary curves\n%\n% Version 1.1.0\n% Latest update     3 May 2022\n%\n% Copyright (C) 2015-2022 Pasi Raumonen\n% ---------------------------------------------------------------------\n%\n% Inputs:\n% P             Point cloud of the stem to be triangulated\n% TriaHeight    Height of the triangles\n% TriaWidth     Width of the triangles\n%\n% Output:\n% triangulation  Structure field defining the triangulation. Contains\n%                   the following main fields:\n%   vert            Vertices of the triangulation model (nv x 3)-matrix\n%   facet           Facets (triangles) of the triangulation \n%                     (the vertices forming the facets)\n%   fvd             Color information of the facets for plotting with \"patch\"\n%   volume          Volume enclosed by the facets in liters\n%   bottom          The z-coordinate of the bottom of the model\n%   top             The z-coordinate of the top of the model\n%   triah           TriaHeight\n%   triaw           TriaWidth\n% ---------------------------------------------------------------------\n\n% Changes from version 1.0.2 to 1.1.0, 3 May 2022:\n% 1) Increased the radius of the balls at seed points from TriaWidth to \n%    2*TriaWidth in the input of \"boundary_curve\"\n% 2) Added triangle orientation check after the side is covered with\n%    triangles so that the surface normals are pointing outward \n% 3) Modified the check if the new boundary curve changes only a little and \n%    then stop reconstruction  \n% 4) Added halving the triangle height if the boundary curve length has\n%    increased three times.\n% 5) Changed the bottom level from the smallest z-coordinate to the  \n%    average of the lowest 100 z-coordinates. \n% 6) Minor streamlining the code and added more comments\n\n% Changes from version 1.0.2 to 1.0.3, 11 Aug 2020:\n% 1) Small changes in the code when computing the delaunay triangulation\n%    of the top layer\n\n% Changes from version 1.0.1 to 1.0.2, 15 Jan 2020:\n% 1) Added side surface areas (side, top, bottom) to output as fields\n\n% Changes from version 1.0.0 to 1.0.1, 26 Nov 2019:\n% 1) Removed the plotting of the triangulation model at the end of the code\n\n%% Determine the first boundary curve\nnp = size(P,1);\n[~,I] = sort(P(:,3),'descend');\nP = P(I,:);\nHbot = mean(P(end-100:end,3));\nHtop = P(1,3);\nN = ceil((Htop-Hbot)/TriaHeight);\nVert = zeros(1e5,3);\nTria = zeros(1e5,3);\nTriaLay = zeros(1e5,1);\nVertLay = zeros(1e5,1,'uint16');\nCurve = zeros(0,3);\ni = 0; % the layer whose cross section is under reconstruction\nps = 1;\nwhile P(ps,3) > Htop-i*TriaHeight\n  ps = ps+1;\nend\npe = ps;\nwhile i < N/4 && isempty(Curve)\n  % Define thin horizontal cross section of the stem\n  i = i+1;\n  ps = pe+1;\n  k = 1;\n  while P(ps+k,3) > Htop-i*TriaHeight\n    k = k+1;\n  end\n  pe = ps+k-1;\n  PSection = P(ps:pe,:);\n\n  % Create initial boundary curve:\n  iter = 0;\n  while iter <= 15 && isempty(Curve)\n    iter = iter+1;\n    Curve = initial_boundary_curve(PSection,TriaWidth);\n  end\nend\n\nif isempty(Curve)\n  triangulation = zeros(0,1);\n  disp('  No triangulation: Problem with the first curve')\n  return\nend\n\n% make the height of the curve even:\nCurve(:,3) = max(Curve(:,3));\n% Save vertices:\nnv = size(Curve,1); % number of vertices in the curve\nVert(1:nv,:) = Curve;\nVertLay(1:nv) = i;\nt = 0;\nm00 = size(Curve,1);\n\n%% Determine the other boundary curves and the triangulation downwards\ni0 = i;\ni = i0+1;\nnv0 = 0;\nLayerBottom = Htop-i*TriaHeight;\nwhile i <= N && pe < np\n  %% Define thin horizontal cross section of the stem\n  ps = pe+1;\n  k = 1;\n  while ps+k <= np && P(ps+k,3) > LayerBottom\n    k = k+1;\n  end\n  pe = ps+k-1;\n  PSection = P(ps:pe,:);\n\n  %% Create boundary curves using the previous curves as seeds\n  if i > i0+1\n    nv0 = nv1;\n  end\n  % Define seed points:\n  Curve(:,3) = Curve(:,3)-TriaHeight;\n  Curve0 = Curve;\n\n  % Create new boundary curve\n  [Curve,Ind] = boundary_curve(PSection,Curve,2*TriaWidth,1.5*TriaWidth);\n\n  if isempty(Curve)\n    disp('  No triangulation: Empty curve')\n    triangulation = zeros(0,1);\n    return\n  end\n  Curve(:,3) = max(Curve(:,3));\n\n  %% Check if the curve intersects itself\n  [Intersect,IntersectLines] = check_self_intersection(Curve(:,1:2));\n\n  %% If self-intersection, try to modify the curve\n  j = 1;\n  while Intersect && j <= 10\n    n = size(Curve,1);\n    CrossLines = (1:1:n)';\n    NumberOfIntersections = cellfun('length',IntersectLines(:,1));\n    I = NumberOfIntersections > 0;\n    CrossLines = CrossLines(I);\n    CrossLen = vertcat(IntersectLines{I,2});\n    if length(CrossLen) == length(CrossLines)\n      LineEle = Curve([2:end 1],:)-Curve(1:end,:);\n      d = sqrt(sum(LineEle.*LineEle,2));\n      m = length(CrossLines);\n      for k = 1:2:m\n        if CrossLines(k) ~= n\n          Curve(CrossLines(k)+1,:) = Curve(CrossLines(k),:)+...\n            0.9*CrossLen(k)/d(CrossLines(k))*LineEle(CrossLines(k),:);\n        else\n          Curve(1,:) = Curve(CrossLines(k),:)+...\n            0.9*CrossLen(k)/d(CrossLines(k))*LineEle(CrossLines(k),:);\n        end\n      end\n      [Intersect,IntersectLines] = check_self_intersection(Curve(:,1:2));\n      j = j+1;\n    else\n      j = 11;\n    end\n  end\n\n  m = size(Curve,1);\n  if Intersect\n    %% Curve self-intersects, use previous curve to extrapolate to the bottom\n    H = Curve0(1,3)-Hbot;\n    if H > 0.75 && Intersect\n      triangulation = zeros(0,1);\n      disp(['  No triangulation: Self-intersection at ',...\n        num2str(H),' m from the bottom'])\n      return\n    end\n    Curve = Curve0;\n    Curve(:,3) = Curve(:,3)-TriaHeight;\n    Nadd = floor(H/TriaHeight)+1;\n    m = size(Curve,1);\n    Ind = [(1:1:m)' [(2:1:m)'; 1]];\n    T = H/Nadd;\n    for k = 1:Nadd\n      if k > 1\n        Curve(:,3) = Curve(:,3)-T;\n      end\n      Vert(nv+1:nv+m,:) = Curve;\n      VertLay(nv+1:nv+m) = i;\n      %% Define the triangulation between two boundary curves\n      nv1 = nv;\n      nv = nv+m;\n      t0 = t+1;\n      pass = false;\n      for j = 1:m\n        if Ind(j,2) > 0 && j < m\n          t = t+1;\n          Tria(t,:) = [nv1+j nv0+Ind(j,:)];\n          t = t+1;\n          Tria(t,:) = [nv1+j nv0+Ind(j,2) nv1+j+1];\n        elseif Ind(j,2) > 0 && ~pass\n          t = t+1;\n          Tria(t,:) = [nv1+j nv0+Ind(j,:)];\n          t = t+1;\n          Tria(t,:) = [nv1+j nv0+Ind(j,2) nv1+1];\n        elseif Ind(j,2) == 0 && j < m\n          t = t+1;\n          Tria(t,:) = [nv1+j nv0+Ind(j,1) nv1+j+1];\n        elseif Ind(j,2) == 0 && ~pass\n          t = t+1;\n          Tria(t,:) = [nv1+j nv0+Ind(j,1) nv1+1];\n        elseif j == 1 && Ind(j,2) == -1\n          t = t+1;\n          Tria(t,:) = [nv nv1 nv0+1];\n          t = t+1;\n          Tria(t,:) = [nv nv0+1 nv1+1];\n          t = t+1;\n          Tria(t,:) = [nv0+1 nv0+2 nv1+1];\n          t = t+1;\n          Tria(t,:) = [nv1+1 nv0+2 nv0+3];\n          t = t+1;\n          Tria(t,:) = [nv1+1 nv0+3 nv1+2];\n          pass = true;\n        elseif Ind(j,2) == -1 && j < m\n          t = t+1;\n          Tria(t,:) = [nv1+j nv0+Ind(j,1) nv0+Ind(j,1)+1];\n          t = t+1;\n          Tria(t,:) = [nv1+j nv0+Ind(j,1)+1 nv1+j+1];\n          t = t+1;\n          Tria(t,:) = [nv0+Ind(j,1)+1 nv0+Ind(j,1)+2 nv1+j+1];\n        elseif Ind(j,2) == -1 && ~pass\n          t = t+1;\n          Tria(t,:) = [nv1+j nv0+Ind(j,1) nv0+Ind(j,1)+1];\n          t = t+1;\n          Tria(t,:) = [nv1+j nv0+Ind(j,1)+1 nv1+1];\n          t = t+1;\n          Tria(t,:) = [nv0+Ind(j,1)+1 nv0+1 nv1+1];\n        end\n      end\n\n      TriaLay(t0:t) = i;\n      i = i+1;\n      nv0 = nv1;\n    end\n    i = N+1;\n\n  else\n    %% No self-intersection, proceed with triangulation and new curves\n    Vert(nv+1:nv+m,:) = Curve;\n    VertLay(nv+1:nv+m) = i;\n\n    %% If little change between Curve and Curve0, stop the reconstruction\n    C = intersect(Curve0,Curve,\"rows\");\n    if size(C,1) > 0.7*size(Curve,1)\n      N = i;\n    end\n\n    %% If the boundary curve has grown much longer than originally, then\n    % decrease the triangle height\n    if m > 3*m00\n      TriaHeight = TriaHeight/2; % use half the height\n      N = N+ceil((N-i)/2); % update the number of layers \n      m00 = m;\n    end\n\n    %% Define the triangulation between two boundary curves\n    nv1 = nv;\n    nv = nv+m;\n    t0 = t+1;\n    pass = false;\n    for j = 1:m\n      if Ind(j,2) > 0 && j < m\n        t = t+1;\n        Tria(t,:) = [nv1+j nv0+Ind(j,:)];\n        t = t+1;\n        Tria(t,:) = [nv1+j nv0+Ind(j,2) nv1+j+1];\n      elseif Ind(j,2) > 0 && ~pass\n        t = t+1;\n        Tria(t,:) = [nv1+j nv0+Ind(j,:)];\n        t = t+1;\n        Tria(t,:) = [nv1+j nv0+Ind(j,2) nv1+1];\n      elseif Ind(j,2) == 0 && j < m\n        t = t+1;\n        Tria(t,:) = [nv1+j nv0+Ind(j,1) nv1+j+1];\n      elseif Ind(j,2) == 0 && ~pass\n        t = t+1;\n        Tria(t,:) = [nv1+j nv0+Ind(j,1) nv1+1];\n      elseif j == 1 && Ind(j,2) == -1\n        t = t+1;\n        Tria(t,:) = [nv nv1 nv0+1];\n        t = t+1;\n        Tria(t,:) = [nv nv0+1 nv1+1];\n        t = t+1;\n        Tria(t,:) = [nv0+1 nv0+2 nv1+1];\n        t = t+1;\n        Tria(t,:) = [nv1+1 nv0+2 nv0+3];\n        t = t+1;\n        Tria(t,:) = [nv1+1 nv0+3 nv1+2];\n        pass = true;\n      elseif Ind(j,2) == -1 && j < m\n        t = t+1;\n        Tria(t,:) = [nv1+j nv0+Ind(j,1) nv0+Ind(j,1)+1];\n        t = t+1;\n        Tria(t,:) = [nv1+j nv0+Ind(j,1)+1 nv1+j+1];\n        t = t+1;\n        Tria(t,:) = [nv0+Ind(j,1)+1 nv0+Ind(j,1)+2 nv1+j+1];\n      elseif Ind(j,2) == -1 && ~pass\n        t = t+1;\n        Tria(t,:) = [nv1+j nv0+Ind(j,1) nv0+Ind(j,1)+1];\n        t = t+1;\n        Tria(t,:) = [nv1+j nv0+Ind(j,1)+1 nv1+1];\n        t = t+1;\n        Tria(t,:) = [nv0+Ind(j,1)+1 nv0+1 nv1+1];\n      end\n    end\n\n    TriaLay(t0:t) = i;\n    i = i+1;\n    LayerBottom = LayerBottom-TriaHeight;\n  end\n\nend\nVert = Vert(1:nv,:);\nVertLay = VertLay(1:nv);\nTria = Tria(1:t,:);\nTriaLay = TriaLay(1:t);\n\n%% Check the orientation of the triangles \n% so that surface normals are outward pointing\na = round(t/10); % select the top triangles\nU = Vert(Tria(1:a,2),:)-Vert(Tria(1:a,1),:);\nV = Vert(Tria(1:a,3),:)-Vert(Tria(1:a,1),:);\nCenter = mean(Vert(1:nv-1,:)); % the center of the stem\nC = Vert(Tria(1:a,1),:)+0.25*V+0.25*U;\nW = C(:,1:2)-Center(1:2); % vectors from the triagles to the stem's center\nNormals = cross(U,V);\nif nnz(sum(Normals(:,1:2).*W,2) < 0) > 0.5*length(C)\n  Tria(1:t,1:2) = [Tria(1:t,2) Tria(1:t,1)];\nend\n\n% U = Vert(Tria(1:t,2),:)-Vert(Tria(1:t,1),:);\n% V = Vert(Tria(1:t,3),:)-Vert(Tria(1:t,1),:);\n% Normals = cross(U,V);\n% Normals = normalize(Normals);\n% C = Vert(Tria(1:t,1),:)+0.25*V+0.25*U;\n% fvd = ones(t,1);\n% figure(5)\n% point_cloud_plotting(P(1,:),5,6)\n% patch('Vertices',Vert,'Faces',Tria,'FaceVertexCData',fvd,'FaceColor','flat')\n% alpha(1)\n% hold on\n% arrow_plot(C,0.1*Normals,5)\n% hold off\n% axis equal\n% pause\n\n\n%% Remove possible double triangles\nnt = size(Tria,1);\nKeep = true(nt,1);\nScoord = Vert(Tria(:,1),:)+Vert(Tria(:,2),:)+Vert(Tria(:,3),:);\nS = sum(Scoord,2);\n[part,CC] = cubical_partition(Scoord,2*TriaWidth);\nfor j = 1:nt-1\n  if Keep(j)\n    points = part(CC(j,1)-1:CC(j,1)+1,CC(j,2)-1:CC(j,2)+1,CC(j,3)-1:CC(j,3)+1);\n    points = vertcat(points{:});\n    I = S(j) == S(points);\n    J = points ~= j;\n    I = I&J&Keep(points);\n    if any(I)\n      p = points(I);\n      I = intersect(Tria(j,:),Tria(p,:));\n      if length(I) == 3\n        Keep(p) = false;\n      end\n    end\n  end\nend\nTria = Tria(Keep,:);\nTriaLay = TriaLay(Keep);\n\n\n%% Generate triangles for the horizontal layers and compute the volumes\n% Triangles of the ground layer\n% Select the boundary curve:\nN = double(max(VertLay));\nI = VertLay == N;\nVert(I,3) = Hbot;\nind = (1:1:nv)';\nind = ind(I);\nCurve = Vert(I,:); % Boundary curve of the bottom\nn = size(Curve,1);\nif n < 10\n  triangulation = zeros(0,1);\n  disp('  No triangulation: Ground layer boundary curve too small')\n  return\nend\n\n% Define Delaunay triangulation for the bottom\nC = zeros(n,2);\nC(:,1) = (1:1:n)';\nC(1:n-1,2) = (2:1:n)';\nC(n,2) = 1;\nwarning off\ndt = delaunayTriangulation(Curve(:,1),Curve(:,2),C);\nIn = dt.isInterior();\nGroundTria = dt(In,:);\nPoints = dt.Points;\nwarning on\nif size(Points,1) > size(Curve,1)\n  disp('  No triangulation: Problem with delaunay in the bottom layer')\n  triangulation = zeros(0,1);\n  return\nend\nGroundTria0 = GroundTria;\nGroundTria(:,1) = ind(GroundTria(:,1));\nGroundTria(:,2) = ind(GroundTria(:,2));\nGroundTria(:,3) = ind(GroundTria(:,3));\n\n% Compute the normals and areas\nU = Curve(GroundTria0(:,2),:)-Curve(GroundTria0(:,1),:);\nV = Curve(GroundTria0(:,3),:)-Curve(GroundTria0(:,1),:);\nCg = Curve(GroundTria0(:,1),:)+0.25*V+0.25*U;\nNg = cross(U,V);\nI = Ng(:,3) > 0; % Check orientation\nNg(I,:) = -Ng(I,:);\nAg = 0.5*sqrt(sum(Ng.*Ng,2));\nNg = 0.5*[Ng(:,1)./Ag Ng(:,2)./Ag Ng(:,3)./Ag];\n\n% Remove possible negative area triangles:\nI = Ag > 0;   Ag = Ag(I);   Cg = Cg(I,:);   Ng = Ng(I,:);\nGroundTria = GroundTria(I,:);\n\n% Update the triangles:\nTria = [Tria; GroundTria];\nTriaLay = [TriaLay; (N+1)*ones(size(GroundTria,1),1)];\n\nif abs(sum(Ag)-polyarea(Curve(:,1),Curve(:,2))) > 0.001*sum(Ag)\n  disp('  No triangulation: Problem with delaunay in the bottom layer')\n  triangulation = zeros(0,1);\n  return\nend\n\n% Triangles of the top layer\n% Select the top curve:\nN = double(min(VertLay));\nI = VertLay == N;\nind = (1:1:nv)';\nind = ind(I);\nCurve = Vert(I,:);\nCenterTop = mean(Curve);\n%  Delaunay triangulation of the top:\nn = size(Curve,1);\nC = zeros(n,2);\nC(:,1) = (1:1:n)';\nC(1:n-1,2) = (2:1:n)';\nC(n,2) = 1;\nwarning off\ndt = delaunayTriangulation(Curve(:,1),Curve(:,2),C);\nPoints = dt.Points;\nwarning on\nif min(size(dt)) == 0 || size(Points,1) > size(Curve,1)\n  disp('  No triangulation: Problem with delaunay in the top layer')\n  triangulation = zeros(0,1);\n  return\nend\nIn = dt.isInterior();\nTopTria = dt(In,:);\nTopTria0 = TopTria;\nTopTria(:,1) = ind(TopTria(:,1));\nTopTria(:,2) = ind(TopTria(:,2));\nTopTria(:,3) = ind(TopTria(:,3));\n\n% Compute the normals and areas:\nU = Curve(TopTria0(:,2),:)-Curve(TopTria0(:,1),:);\nV = Curve(TopTria0(:,3),:)-Curve(TopTria0(:,1),:);\nCt = Curve(TopTria0(:,1),:)+0.25*V+0.25*U;\nNt = cross(U,V);\nI = Nt(:,3) < 0;\nNt(I,:) = -Nt(I,:);\nAt = 0.5*sqrt(sum(Nt.*Nt,2));\nNt = 0.5*[Nt(:,1)./At Nt(:,2)./At Nt(:,3)./At];\n\n% Remove possible negative area triangles:\nI = At > 0;   At = At(I);   Ct = Ct(I,:);   Nt = Nt(I,:);\nTopTria = TopTria(I,:);\n\n% Update the triangles:\nTria = [Tria; TopTria];\nTriaLay = [TriaLay; N*ones(size(TopTria,1),1)];\n\nif abs(sum(At)-polyarea(Curve(:,1),Curve(:,2))) > 0.001*sum(At)\n  disp('  No triangulation: Problem with delaunay in the top layer')\n  triangulation = zeros(0,1);\n  return\nend\n\n% Triangles of the side\nB = TriaLay <= max(VertLay) & TriaLay > 1;\nU = Vert(Tria(B,2),:)-Vert(Tria(B,1),:);\nV = Vert(Tria(B,3),:)-Vert(Tria(B,1),:);\nCs = Vert(Tria(B,1),:)+0.25*V+0.25*U;\nNs = cross(U,V);\nAs = 0.5*sqrt(sum(Ns.*Ns,2));\nNs = 0.5*[Ns(:,1)./As Ns(:,2)./As Ns(:,3)./As];\nI = As > 0;  Ns = Ns(I,:); As = As(I); Cs = Cs(I,:);\n\n% Volumes in liters\nVTotal = sum(At.*sum(Ct.*Nt,2))+sum(As.*sum(Cs.*Ns,2))+sum(Ag.*sum(Cg.*Ng,2));\nVTotal = round(10000*VTotal/3)/10;\n\nif VTotal < 0\n  disp('  No triangulation: Problem with volume')\n  triangulation = zeros(0,1);\n  return\nend\n\nV = Vert(Tria(:,1),1:2)-CenterTop(1:2);\nfvd = sqrt(sum(V.*V,2));\ntriangulation.vert = single(Vert);\ntriangulation.facet = uint16(Tria);\ntriangulation.fvd = single(fvd);\ntriangulation.volume = VTotal;\ntriangulation.SideArea = sum(As);\ntriangulation.BottomArea = sum(Ag);\ntriangulation.TopArea = sum(At);\ntriangulation.bottom = min(Vert(:,3));\ntriangulation.top = max(Vert(:,3));\ntriangulation.triah = TriaHeight;\ntriangulation.triaw = TriaWidth;\n\n% figure(5)\n% point_cloud_plotting(P,5,6)\n% patch('Vertices',Vert,'Faces',Tria,'FaceVertexCData',fvd,'FaceColor','flat')\n% % hold on\n% % arrow_plot(Cs,0.2*Ns,5)\n% % hold off\n% % axis equal\n% alpha(1)\n\n"
  },
  {
    "path": "src/triangulation/initial_boundary_curve.m",
    "content": "% This file is part of TREEQSM.\n%\n% TREEQSM is free software: you can redistribute it and/or modify\n% it under the terms of the GNU General Public License as published by\n% the Free Software Foundation, either version 3 of the License, or\n% (at your option) any later version.\n%\n% TREEQSM is distributed in the hope that it will be useful,\n% but WITHOUT ANY WARRANTY; without even the implied warranty of\n% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n% GNU General Public License for more details.\n%\n% You should have received a copy of the GNU General Public License\n% along with TREEQSM.  If not, see <http://www.gnu.org/licenses/>.\n\nfunction Curve = initial_boundary_curve(P,TriaWidth)\n\n% ---------------------------------------------------------------------\n% INITIAL_BOUNDARY_CURVE.M      Determines the boundary curve adaptively.\n%\n% Version 1.0.1\n% Latest update     26 Nov 2019\n%\n% Copyright (C) 2015-2017 Pasi Raumonen\n% ---------------------------------------------------------------------\n\n% Changes from version 1.0.0 to 1.0.1, 26 Nov 2019:\n% 1) Bug fix: Added \"return\" if the \"Curve\" is empty after it is first defined.\n\n%% Define suitable center\n% Use xy-data and even the z-coordinate to the top\nTop = max(P(:,3));\nP = [P(:,1:2) Top*ones(size(P,1),1)];\n\n% Define the \"center\" of points as the mean\nCenter = mean(P);\nCenter0 = Center;\n\n% If the center is outside or close to the boundary, define new center\ni = 0;\nA0 = 61;\nShortestDist = 0;\nwhile ShortestDist < 0.075 && i < 100\n  Center = Center0+[3*ShortestDist*randn(1,2) 0]; % Randomly move the center\n  % Compute angles of points as seen from the center\n  V = mat_vec_subtraction(P(:,1:2),Center(1:2));\n  angle = 180/pi*atan2(V(:,2),V(:,1))+180;\n  % % Check if the center is outside or near the boundary of the cross section\n  A = false(70,1);\n  a = ceil(angle/5);\n  I = a > 0;\n  A(a(I)) = true;\n  if i == 0\n    ShortestDist = 0.025;\n  elseif nnz(A) < A0\n    ShortestDist = 0.05;\n  else\n    PointDist = sqrt(sum(V.*V,2));\n    [ShortestDist,FirstPoint] = min(PointDist);\n  end\n  i = i+1;\n  if i == 100 && ShortestDist < 0.075\n    i = 0;\n    A0 = A0-2;\n  end\nend\n\n%% Define first boundary curve based on the center\nCurve = zeros(18,1); % the boundary curve, contains indexed of the point cloud rows\nCurve(1) = FirstPoint; % start the curve from the point the closest the center\n% Modify the angles so that first point has the angle 0\na0 = angle(FirstPoint);\nI = angle < a0;\nangle(I) = angle(I)+(360-a0);\nangle(~I) = angle(~I)-a0;\n% Select the rest of the points as the closest point in 15 deg sectors\n% centered at 20 deg intervals\nnp = size(P,1);\nInd = (1:1:np)';\nt = 0;\nfor i = 2:18\n  J = angle > 12.5+20*(i-2) & angle < 27.5+20*(i-2);\n  if ~any(J) % if no points, try 18 deg sector\n    J = angle > 11+20*(i-2) & angle < 29+20*(i-2);\n  end\n  if any(J)\n    % if sector has points, select the closest point as the curve point\n    D = PointDist(J);\n    ind = Ind(J);\n    [~,J] = min(D);\n    t = t+1;\n    Curve(t) = ind(J);\n  end\nend\nCurve = Curve(1:t);\nif isempty(Curve)\n  return\nend\nI = true(np,1);\nI(Curve) = false;\nInd = Ind(I);\n\n\n%% Adapt the initial curve to the data\nV = P(Curve([(2:t)'; 1]),:)-P(Curve,:);\nD = sqrt(sum(V(:,1:2).*V(:,1:2),2));\nn = t;\nn0 = 1;\n% Continue adding new points as long as too long edges exists\nwhile any(D > 1.25*TriaWidth) && n > n0\n  N = [V(:,2) -V(:,1) V(:,3)];\n  M = P(Curve,:)+0.5*V;\n\n  Curve1 = Curve;\n  t = 0;\n  for i = 1:n\n    if D(i) > 1.25*TriaWidth\n      [d,~,hc] = distances_to_line(P(Curve1,:),N(i,:),M(i,:));\n      I = hc > 0.01 & d < D(i)/2;\n      if any(I)\n        H = min(hc(I));\n      else\n        H = 1;\n      end\n      [d,~,h] = distances_to_line(P(Ind,:),N(i,:),M(i,:));\n      I = d < D(i)/3 & h > -TriaWidth/2 & h < H;\n\n      if any(I)\n        ind = Ind(I);\n        h = h(I);\n        [h,J] = min(h);\n        I = ind(J);\n\n        t = t+1;\n        if i < n\n          Curve1 = [Curve1(1:t); I; Curve1(t+1:end)];\n        else\n          Curve1 = [Curve1(1:t); I];\n        end\n        J = Ind ~= I;\n        Ind = Ind(J);\n        t = t+1;\n\n      else\n        t = t+1;\n      end\n    else\n      t = t+1;\n    end\n  end\n  Curve = Curve1(1:t);\n\n  n0 = n;\n  n = size(Curve,1);\n  V = P(Curve([(2:n)'; 1]),:)-P(Curve,:);\n  D = sqrt(sum(V.*V,2));\nend\n\n%% Refine the curve for longer edges if far away points\nn0 = n-1;\nwhile n > n0\n  N = [V(:,2) -V(:,1) V(:,3)];\n  M = P(Curve,:)+0.5*V;\n\n  Curve1 = Curve;\n  t = 0;\n  for i = 1:n\n    if D(i) > 0.5*TriaWidth\n      [d,~,hc] = distances_to_line(P(Curve1,:),N(i,:),M(i,:));\n      I = hc > 0.01 & d < D(i)/2;\n      if any(I)\n        H = min(hc(I));\n      else\n        H = 1;\n      end\n      [d,~,h] = distances_to_line(P(Ind,:),N(i,:),M(i,:));\n      I = d < D(i)/3 & h > -TriaWidth/3 & h < H;\n      ind = Ind(I);\n      h = h(I);\n      [h,J] = min(h);\n\n      if h > TriaWidth/10\n        I = ind(J);\n        t = t+1;\n        if i < n\n          Curve1 = [Curve1(1:t); I; Curve1(t+1:end)];\n        else\n          Curve1 = [Curve1(1:t); I];\n        end\n        J = Ind ~= I;\n        Ind = Ind(J);\n        t = t+1;\n\n      else\n        t = t+1;\n      end\n    else\n      t = t+1;\n    end\n\n  end\n  Curve = Curve1(1:t);\n\n  n0 = n;\n  n = size(Curve,1);\n  V = P(Curve([(2:n)'; 1]),:)-P(Curve,:);\n  D = sqrt(sum(V.*V,2));\nend\n\n%% Smooth the curve by defining the points by means of neighbors\nCurve = P(Curve,:); % Change the curve from point indexes to coordinates\nCurve = boundary_curve2(P,Curve,0.04,TriaWidth);\nif isempty(Curve)\n  return\nend\n\n%% Add points for too long edges\nn = size(Curve,1);\nV = Curve([(2:n)'; 1],:)-Curve;\nD = sqrt(sum(V.*V,2));\nCurve1 = Curve;\nt = 0;\nfor i = 1:n\n  if D(i) > TriaWidth\n    m = floor(D(i)/TriaWidth);\n    t = t+1;\n    W = zeros(m,3);\n    for j = 1:m\n      W(j,:) = Curve(i,:)+j/(m+1)*V(i,:);\n    end\n    Curve1 = [Curve1(1:t,:); W; Curve1(t+1:end,:)];\n    t = t+m ;\n  else\n    t = t+1;\n  end\nend\nCurve = Curve1;\nn = size(Curve,1);\n\n%% Define the curve again by equalising the point distances along the curve\nV = Curve([(2:n)'; 1],:)-Curve;\nD = sqrt(sum(V.*V,2));\nL = cumsum(D);\nm = ceil(L(end)/TriaWidth);\nTriaWidth = L(end)/m;\nCurve1 = zeros(m,3);\nCurve1(1,:) = Curve(1,:);\nb = 1;\nfor i = 2:m\n  while L(b) < (i-1)*TriaWidth\n    b = b+1;\n  end\n  if b > 1\n    a = ((i-1)*TriaWidth-L(b-1))/D(b);\n    Curve1(i,:) = Curve(b,:)+a*V(b,:);\n  else\n    a = (L(b)-(i-1)*TriaWidth)/D(b);\n    Curve1(i,:) = Curve(b,:)+a*V(b,:);\n  end\nend\nCurve = Curve1;\n\nIntersect = check_self_intersection(Curve(:,1:2));\nif Intersect\n  Curve = zeros(0,3);\nend\n\n"
  }
]