diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..b57ef3f
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,6 @@
+# Changelog
+
+
+## 0.1.0 - 2015-11-14
+### Added
+- Initial software version. Contains modules for UAVSAR data import, coherence optimization, data visualization, coherence region plotting, ground topography estimation using standard line fit procedure, RVoG forest model inversion, sinc function forest model inversion, and geocoding of output products. See user's manual and install guide in /docs folder.
\ No newline at end of file
diff --git a/LICENSE.md b/LICENSE.md
new file mode 100755
index 0000000..f718b3e
--- /dev/null
+++ b/LICENSE.md
@@ -0,0 +1,621 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100755
index 0000000..88c9614
--- /dev/null
+++ b/README.md
@@ -0,0 +1,28 @@
+# Kapok: An Open Source Python Library for PolInSAR Forest Height Estimation Using UAVSAR Data
+
+Kapok is a Python library created for the purposes of estimating forest height and structure using data collected by NASA's Uninhabited Aerial Vehicle Synthetic Aperture Radar (UAVSAR) instrument. The library contains implementations of basic algorithms for processing of polarimetric SAR interferometry (PolInSAR) data, and allows easy import of UAVSAR SLC (single-look complex) stacks (UAVSAR data from multiple repeat-pass flights).
+
+Software primarily designed and written by Michael Denbina, with contributions from Maxim Neumann. See individual source code files for more detailed author information.
+
+If you use this software in a published work, please cite it using the following DOI: https://doi.org/10.5281/zenodo.167040
+
+For reference, also see the following journal articles for PolInSAR forest height estimation results using this software:
+
+M. Simard and M. Denbina, "Forest Canopy Height Estimation with Airborne Repeat-Pass L-Band Polarimetric SAR Interferometry in North American Temperate and Boreal Forests," IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, Submitted, 2017.
+
+M. Denbina and M. Simard, "The effects of topography on forest height and structure estimation from PolInSAR," IEEE Transactions on Geoscience and Remote Sensing, Submitted, 2016.
+
+This library is dependent on the following open source software libraries:
+
+* Numerical Python (NumPy)
+* Scientific Python (SciPy)
+* HDF5 For Python (h5py)
+* matplotlib
+* Cython
+* Geospatial Data Abstraction Library (GDAL)
+
+See docs/manual.pdf for a user's manual and basic tutorial. The docs/ folder also contains installation guides for Mac OSX and Windows.
+
+Copyright 2016 California Institute of Technology. All rights reserved. United States Government Sponsorship acknowledged.
+
+This software is released under the GNU General Public License. For details, see the file license.txt included with this program, or visit http://www.gnu.org/licenses/. 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.
\ No newline at end of file
diff --git a/docs/install_guide_mac.docx b/docs/install_guide_mac.docx
new file mode 100755
index 0000000..755161a
Binary files /dev/null and b/docs/install_guide_mac.docx differ
diff --git a/docs/install_guide_windows.pdf b/docs/install_guide_windows.pdf
new file mode 100755
index 0000000..1410b3d
Binary files /dev/null and b/docs/install_guide_windows.pdf differ
diff --git a/docs/manual.pdf b/docs/manual.pdf
new file mode 100755
index 0000000..1806987
Binary files /dev/null and b/docs/manual.pdf differ
diff --git a/kapok/__init__.py b/kapok/__init__.py
new file mode 100755
index 0000000..a702eda
--- /dev/null
+++ b/kapok/__init__.py
@@ -0,0 +1,6 @@
+from .kapok import *
+
+print('Kapok: Python Toolbox for PolInSAR Forest Height Estimation')
+print(' ')
+print('Copyright 2016 California Institute of Technology. United States Government Sponsorship acknowledged.')
+print(' ')
\ No newline at end of file
diff --git a/kapok/cohopt.py b/kapok/cohopt.py
new file mode 100755
index 0000000..af423fb
--- /dev/null
+++ b/kapok/cohopt.py
@@ -0,0 +1,35 @@
+# -*- coding: utf-8 -*-
+"""Coherence Optimization Module.
+
+ Currently contains an implementation of the phase diversity coherence
+ optimization algorithm which finds the two coherences with the largest
+ separation in the complex plane. The actual code for this module is in
+ cohoptc.pyx. This file is just a wrapper that imports the Cython code.
+
+ Author: Michael Denbina
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import numpy as np
+
+try: # Import Cython Implementation
+ import pyximport; pyximport.install(setup_args={"include_dirs":np.get_include()})
+ from .cohoptc import pdopt, pdopt_pixel
+except ImportError: # Cython Import Failed
+ print('kapok.cohopt | WARNING: Cython import failed. Running in native Python (will be slow!).')
+ from .cohoptp import pdopt, pdopt_pixel
\ No newline at end of file
diff --git a/kapok/cohoptc.pyx b/kapok/cohoptc.pyx
new file mode 100755
index 0000000..815e3d4
--- /dev/null
+++ b/kapok/cohoptc.pyx
@@ -0,0 +1,245 @@
+# -*- coding: utf-8 -*-
+# cython: language_level=3
+"""Coherence Optimization Cython Functions.
+
+ Currently contains an implementation of the phase diversity coherence
+ optimization algorithm which finds the two coherences with the largest
+ separation in the complex plane. Written in Cython for improved speed.
+ Imported by main cohopt module.
+
+ Author: Michael Denbina
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import time
+
+import numpy as np
+import numpy.linalg as linalg
+
+cimport numpy as np
+cimport cython
+np.import_array()
+np.import_ufunc()
+
+
+
+def pdopt(np.ndarray[np.complex64_t, ndim=4] tm, np.ndarray[np.complex64_t, ndim=4] om, numph=30, step=50, returnweights=False):
+ """Phase diversity coherence optimization.
+
+ Solves an eigenvalue problem in order to find the complex coherences with
+ maximum separation (|a - b|) in the complex plane. Of these two
+ coherences, one should in theory represent the coherence with the
+ smallest ground contribution present in the data (the 'high' coherence).
+ The other then represents the coherence with the largest ground
+ contribution present in the data (the 'low' coherence).
+
+ Arguments:
+ tm (array): The polarimetric covariance (T) matrix of the data,
+ with dimensions: [num_pol, num_pol]. Note that in the
+ HDF5 file, covariance matrix elements below the diagonal are
+ zero-valued, in order to save disk space. The (j,i) elements
+ should therefore calculated from the complex conjugate of the
+ (i,j) elements using the kapok.lib.makehermitian() function before
+ the matrix is passed to this function. Note: This should be the
+ average matrix of the two tracks forming the baseline, assuming
+ polarimetric stationarity.
+ om (array): The polarimetric interferometric (Omega) matrix of the
+ data, with dimensions [az, rng, num_pol, num_pol].
+ numph (int): The number of phase shifts to calculate coherences for.
+ The higher the number, the smaller the spacing of the coherences
+ around the coherence region perimeter. The smaller the number,
+ the faster the computation time. Default: 30.
+ step (int): Block size (in pixels) used for linalg.eig. Higher values
+ will use more memory but can run a little faster.
+ Default: 50.
+ returnweights (bool): True/False flag. Set to true to return the
+ weight vectors for the optimized coherences. Default: False
+
+ Returns:
+ gammamax (array): the optimized coherence with the max eigenvalue.
+ gammamin (array): the optimized coherence with the min eigenvalue.
+ wmax (array): the weight vector for the max eigenvalue coherence, if
+ returnweights == True.
+ wmin (array): the weight vector for the min eigenvalue coherence, if
+ returnweights == True.
+
+ """
+ dim = np.shape(tm)
+
+ # Arrays to store coherence separation, and the two complex coherence values.
+ cohsize = (dim[0],dim[1]) # number of az, rng pixels
+ cdef np.ndarray[np.float32_t, ndim=2] cohdiff = np.zeros(cohsize,dtype='float32')
+ cdef np.ndarray[np.complex64_t, ndim=2] gammamax = np.zeros(cohsize,dtype='complex64')
+ cdef np.ndarray[np.complex64_t, ndim=2] gammamin = np.zeros(cohsize,dtype='complex64')
+
+ # Arrays to store polarimetric weighting vectors for each coherence.
+ weightsize = (dim[0],dim[1],dim[3])
+ cdef np.ndarray[np.complex64_t, ndim=3] wmax = np.zeros(weightsize,dtype='complex64')
+ cdef np.ndarray[np.complex64_t, ndim=3] wmin = np.zeros(weightsize,dtype='complex64')
+
+ cdef int az, rng, azend, rngend
+
+ # Main Loop
+ for Ph in np.arange(0,numph): # loop through rotation angles
+ Pr = Ph * np.pi / numph # phase shift to be applied
+
+ print('kapok.cohopt.pdopt | Current Progress: '+str(np.round(Pr/np.pi*100,decimals=2))+'%. ('+time.ctime()+') ', end='\r')
+
+ for az in range(0,dim[0],step):
+ azend = az + step
+ if azend > dim[0]:
+ azend = dim[0]
+
+ for rng in range(0,dim[1],step):
+ rngend = rng + step
+ if rngend > dim[1]:
+ rngend = dim[1]
+
+ omblock = om[az:azend,rng:rngend]
+ tmblock = tm[az:azend,rng:rngend]
+ z12 = omblock.copy()
+
+ # Apply phase shift to omega matrix:
+ z12 = z12*np.exp(1j*Pr)
+ z12 = 0.5 * (z12 + np.rollaxis(np.conj(z12),3,start=2))
+
+ # Check if any pixels have singular covariance matrices.
+ # If so, set those matrices to the identity, to keep an
+ # exception from being thrown by linalg.inv().
+ det = linalg.det(tmblock)
+ ind = (det == 0)
+ if np.any(ind):
+ tmblock[ind] = np.eye(dim[3])
+
+
+ # Solve the eigenvalue problem:
+ try:
+ nu, w = linalg.eig(np.einsum('...ij,...jk->...ik', linalg.inv(tmblock), z12))
+
+ wH = np.rollaxis(np.conj(w),3,start=2)
+
+ Tmp = np.einsum('...ij,...jk->...ik', omblock, w)
+ Tmp12 = np.einsum('...ij,...jk->...ik', wH, Tmp)
+
+ Tmp = np.einsum('...ij,...jk->...ik', tmblock, w)
+ Tmp11 = np.einsum('...ij,...jk->...ik', wH, Tmp)
+
+ azind = np.tile(np.arange(0,w.shape[0]),(w.shape[1],1)).T
+ rngind = np.tile(np.arange(0,w.shape[1]),(w.shape[0],1))
+
+ lmin = np.argmin(nu,axis=2)
+ gmin = Tmp12[azind,rngind,lmin,lmin] / np.abs(Tmp11[azind,rngind,lmin,lmin])
+
+ lmax = np.argmax(nu,axis=2)
+ gmax = Tmp12[azind,rngind,lmax,lmax] / np.abs(Tmp11[azind,rngind,lmax,lmax])
+
+ ind = (np.abs(gmax-gmin) > cohdiff[az:azend,rng:rngend])
+
+ # If we've found the coherences with the best separation
+ # so far, save them.
+ if np.any(ind):
+ (azupdate, rngupdate) = np.where(ind)
+
+ cohdiff[az+azupdate,rng+rngupdate] = np.abs(gmax-gmin)[azupdate,rngupdate]
+ gammamax[az+azupdate,rng+rngupdate] = gmax[azupdate,rngupdate]
+ gammamin[az+azupdate,rng+rngupdate] = gmin[azupdate,rngupdate]
+
+ if returnweights:
+ wmax[az+azupdate,rng+rngupdate,:] = np.squeeze(w[azupdate,rngupdate,:,lmax[azupdate,rngupdate]])
+ wmin[az+azupdate,rng+rngupdate,:] = np.squeeze(w[azupdate,rngupdate,:,lmin[azupdate,rngupdate]])
+ except:
+ pass # if this function receives a block containing any covariance matrices which are singular, an exception will be thrown, and rather than terminate, just move to the next block.
+
+ print('kapok.cohopt.pdopt | Optimization complete. ('+time.ctime()+') ')
+ if returnweights:
+ return gammamax, gammamin, wmax, wmin
+ else:
+ return gammamax, gammamin
+
+
+def pdopt_pixel(tm, om, numph=60):
+ """Phase diversity coherence optimization for a single pixel.
+
+ Same functionality as the pdopt function above, but for a single pixel
+ only. This is the function called when plotting a coherence region.
+
+ Arguments:
+ tm (array): The polarimetric covariance (T) matrix of the data,
+ with dimensions: [num_pol, num_pol]. Note that in the
+ HDF5 file, covariance matrix elements below the diagonal are
+ zero-valued, in order to save disk space. The (j,i) elements
+ should therefore calculated from the complex conjugate of the
+ (i,j) elements using the kapok.lib.makehermitian() function before
+ the matrix is passed to this function. Note: This should be the
+ average matrix of the two tracks forming the baseline, assuming
+ polarimetric stationarity.
+ om (array): The polarimetric interferometric (Omega) matrix of the
+ data, with dimensions [num_pol, num_pol].
+ numph (int): The number of phase shifts to calculate coherences for.
+ The higher the number, the smaller the spacing of the coherences
+ around the coherence region perimeter. The smaller the number,
+ the faster the computation time. Default: 30.
+
+ Returns:
+ gammamax (complex): the optimized coherence with the max eigenvalue.
+ gammamin (complex): the optimized coherence with the min eigenvalue.
+ gammaregion (array): Every coherence from the solved eigenvalue
+ problems. These coherences will lie around the edge of the
+ coherence region.
+
+ """
+ cohdiff = 0
+ gammaregion = np.empty((numph*2 + 1),dtype='complex')
+
+ for Ph in range(0,numph): # loop through rotation angles
+ Pr = Ph * np.pi / numph # phase shift to be applied
+
+
+ # Apply phase shift to omega matrix:
+ z12 = om.copy()*np.exp(1j*Pr)
+ z12 = 0.5 * (z12 + np.transpose(np.conj(z12)))
+
+
+ # Solve the eigenvalue problem:
+ nu, w = linalg.eig(np.dot(linalg.inv(tm),z12))
+
+ wH = np.transpose(np.conj(w))
+
+ Tmp = np.dot(om,w)
+ Tmp12 = np.dot(wH,Tmp)
+
+ Tmp = np.dot(tm,w)
+ Tmp11 = np.dot(wH,Tmp)
+
+ l = np.argmin(nu)
+ gmin = Tmp12[l,l] / np.abs(Tmp11[l,l]) # min eigenvalue coherence
+
+ l = np.argmax(nu)
+ gmax = Tmp12[l,l] / np.abs(Tmp11[l,l]) # max eigenvalue coherence
+
+ gammaregion[Ph] = gmin
+ gammaregion[Ph+numph] = gmax
+
+ if (np.abs(gmax-gmin) > cohdiff):
+ cohdiff = np.abs(gmax-gmin)
+ gammamax = gmax
+ gammamin = gmin
+
+ gammaregion[-1] = gammaregion[0] # copy the first coherence to the end of the array, for a continuous coherence region plot
+
+ return gammamax, gammamin, gammaregion
\ No newline at end of file
diff --git a/kapok/cohoptc.pyxbld b/kapok/cohoptc.pyxbld
new file mode 100755
index 0000000..6349da4
--- /dev/null
+++ b/kapok/cohoptc.pyxbld
@@ -0,0 +1,5 @@
+def make_ext(modname, pyxfilename):
+ from distutils.extension import Extension
+ return Extension(name=modname,
+ sources=[pyxfilename],
+ extra_compile_args=['-w'])
\ No newline at end of file
diff --git a/kapok/cohoptp.py b/kapok/cohoptp.py
new file mode 100755
index 0000000..c50d27e
--- /dev/null
+++ b/kapok/cohoptp.py
@@ -0,0 +1,239 @@
+# -*- coding: utf-8 -*-
+# cython: language_level=3
+"""Coherence Optimization Cython Functions.
+
+ Currently contains an implementation of the phase diversity coherence
+ optimization algorithm which finds the two coherences with the largest
+ separation in the complex plane. This is Python code which the cohopt.py
+ wrapper module defaults to when the Cython import fails.
+
+ Author: Michael Denbina
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import time
+
+import numpy as np
+import numpy.linalg as linalg
+
+
+
+def pdopt(tm, om, numph=30, step=50, returnweights=False):
+ """Phase diversity coherence optimization.
+
+ Solves an eigenvalue problem in order to find the complex coherences with
+ maximum separation (|a - b|) in the complex plane. Of these two
+ coherences, one should in theory represent the coherence with the
+ smallest ground contribution present in the data (the 'high' coherence).
+ The other then represents the coherence with the largest ground
+ contribution present in the data (the 'low' coherence).
+
+ Arguments:
+ tm (array): The polarimetric covariance (T) matrix of the data,
+ with dimensions: [num_pol, num_pol]. Note that in the
+ HDF5 file, covariance matrix elements below the diagonal are
+ zero-valued, in order to save disk space. The (j,i) elements
+ should therefore calculated from the complex conjugate of the
+ (i,j) elements using the kapok.lib.makehermitian() function before
+ the matrix is passed to this function. Note: This should be the
+ average matrix of the two tracks forming the baseline, assuming
+ polarimetric stationarity.
+ om (array): The polarimetric interferometric (Omega) matrix of the
+ data, with dimensions [az, rng, num_pol, num_pol].
+ numph (int): The number of phase shifts to calculate coherences for.
+ The higher the number, the smaller the spacing of the coherences
+ around the coherence region perimeter. The smaller the number,
+ the faster the computation time. Default: 30.
+ step (int): Block size (in pixels) used for linalg.eig. Higher values
+ will use more memory but can run a little faster.
+ Default: 50.
+ returnweights (bool): True/False flag. Set to true to return the
+ weight vectors for the optimized coherences. Default: False
+
+ Returns:
+ gammamax (array): the optimized coherence with the max eigenvalue.
+ gammamin (array): the optimized coherence with the min eigenvalue.
+ wmax (array): the weight vector for the max eigenvalue coherence, if
+ returnweights == True.
+ wmin (array): the weight vector for the min eigenvalue coherence, if
+ returnweights == True.
+
+ """
+ dim = np.shape(tm)
+
+ # Arrays to store coherence separation, and the two complex coherence values.
+ cohsize = (dim[0],dim[1]) # number of az, rng pixels
+ cohdiff = np.zeros(cohsize,dtype='float32')
+ gammamax = np.zeros(cohsize,dtype='complex64')
+ gammamin = np.zeros(cohsize,dtype='complex64')
+
+ # Arrays to store polarimetric weighting vectors for each coherence.
+ weightsize = (dim[0],dim[1],dim[3])
+ wmax = np.zeros(weightsize,dtype='complex64')
+ wmin = np.zeros(weightsize,dtype='complex64')
+
+
+ # Main Loop
+ for Ph in np.arange(0,numph): # loop through rotation angles
+ Pr = Ph * np.pi / numph # phase shift to be applied
+
+ print('kapok.cohopt.pdopt | Current Progress: '+str(np.round(Pr/np.pi*100,decimals=2))+'%. ('+time.ctime()+') ', end='\r')
+
+ for az in range(0,dim[0],step):
+ azend = az + step
+ if azend > dim[0]:
+ azend = dim[0]
+
+ for rng in range(0,dim[1],step):
+ rngend = rng + step
+ if rngend > dim[1]:
+ rngend = dim[1]
+
+ omblock = om[az:azend,rng:rngend]
+ tmblock = tm[az:azend,rng:rngend]
+ z12 = omblock.copy()
+
+ # Apply phase shift to omega matrix:
+ z12 = z12*np.exp(1j*Pr)
+ z12 = 0.5 * (z12 + np.rollaxis(np.conj(z12),3,start=2))
+
+ # Check if any pixels have singular covariance matrices.
+ # If so, set those matrices to the identity, to keep an
+ # exception from being thrown by linalg.inv().
+ det = linalg.det(tmblock)
+ ind = (det == 0)
+ if np.any(ind):
+ tmblock[ind] = np.eye(dim[3])
+
+
+ # Solve the eigenvalue problem:
+ try:
+ nu, w = linalg.eig(np.einsum('...ij,...jk->...ik', linalg.inv(tmblock), z12))
+
+ wH = np.rollaxis(np.conj(w),3,start=2)
+
+ Tmp = np.einsum('...ij,...jk->...ik', omblock, w)
+ Tmp12 = np.einsum('...ij,...jk->...ik', wH, Tmp)
+
+ Tmp = np.einsum('...ij,...jk->...ik', tmblock, w)
+ Tmp11 = np.einsum('...ij,...jk->...ik', wH, Tmp)
+
+ azind = np.tile(np.arange(0,w.shape[0]),(w.shape[1],1)).T
+ rngind = np.tile(np.arange(0,w.shape[1]),(w.shape[0],1))
+
+ lmin = np.argmin(nu,axis=2)
+ gmin = Tmp12[azind,rngind,lmin,lmin] / np.abs(Tmp11[azind,rngind,lmin,lmin])
+
+ lmax = np.argmax(nu,axis=2)
+ gmax = Tmp12[azind,rngind,lmax,lmax] / np.abs(Tmp11[azind,rngind,lmax,lmax])
+
+ ind = (np.abs(gmax-gmin) > cohdiff[az:azend,rng:rngend])
+
+ # If we've found the coherences with the best separation
+ # so far, save them.
+ if np.any(ind):
+ (azupdate, rngupdate) = np.where(ind)
+
+ cohdiff[az+azupdate,rng+rngupdate] = np.abs(gmax-gmin)[azupdate,rngupdate]
+ gammamax[az+azupdate,rng+rngupdate] = gmax[azupdate,rngupdate]
+ gammamin[az+azupdate,rng+rngupdate] = gmin[azupdate,rngupdate]
+
+ if returnweights:
+ wmax[az+azupdate,rng+rngupdate,:] = np.squeeze(w[azupdate,rngupdate,:,lmax[azupdate,rngupdate]])
+ wmin[az+azupdate,rng+rngupdate,:] = np.squeeze(w[azupdate,rngupdate,:,lmin[azupdate,rngupdate]])
+ except:
+ pass # if this function receives a block containing any covariance matrices which are singular, an exception will be thrown, and rather than terminate, just move to the next block.
+
+ print('kapok.cohopt.pdopt | Optimization complete. ('+time.ctime()+') ')
+ if returnweights:
+ return gammamax, gammamin, wmax, wmin
+ else:
+ return gammamax, gammamin
+
+
+def pdopt_pixel(tm, om, numph=60):
+ """Phase diversity coherence optimization for a single pixel.
+
+ Same functionality as the pdopt function above, but for a single pixel
+ only. This is the function called when plotting a coherence region.
+
+ Arguments:
+ tm (array): The polarimetric covariance (T) matrix of the data,
+ with dimensions: [num_pol, num_pol]. Note that in the
+ HDF5 file, covariance matrix elements below the diagonal are
+ zero-valued, in order to save disk space. The (j,i) elements
+ should therefore calculated from the complex conjugate of the
+ (i,j) elements using the kapok.lib.makehermitian() function before
+ the matrix is passed to this function. Note: This should be the
+ average matrix of the two tracks forming the baseline, assuming
+ polarimetric stationarity.
+ om (array): The polarimetric interferometric (Omega) matrix of the
+ data, with dimensions [num_pol, num_pol].
+ numph (int): The number of phase shifts to calculate coherences for.
+ The higher the number, the smaller the spacing of the coherences
+ around the coherence region perimeter. The smaller the number,
+ the faster the computation time. Default: 30.
+
+ Returns:
+ gammamax (complex): the optimized coherence with the max eigenvalue.
+ gammamin (complex): the optimized coherence with the min eigenvalue.
+ gammaregion (array): Every coherence from the solved eigenvalue
+ problems. These coherences will lie around the edge of the
+ coherence region.
+
+ """
+ cohdiff = 0
+ gammaregion = np.empty((numph*2 + 1),dtype='complex')
+
+ for Ph in range(0,numph): # loop through rotation angles
+ Pr = Ph * np.pi / numph # phase shift to be applied
+
+
+ # Apply phase shift to omega matrix:
+ z12 = om.copy()*np.exp(1j*Pr)
+ z12 = 0.5 * (z12 + np.transpose(np.conj(z12)))
+
+
+ # Solve the eigenvalue problem:
+ nu, w = linalg.eig(np.dot(linalg.inv(tm),z12))
+
+ wH = np.transpose(np.conj(w))
+
+ Tmp = np.dot(om,w)
+ Tmp12 = np.dot(wH,Tmp)
+
+ Tmp = np.dot(tm,w)
+ Tmp11 = np.dot(wH,Tmp)
+
+ l = np.argmin(nu)
+ gmin = Tmp12[l,l] / np.abs(Tmp11[l,l]) # min eigenvalue coherence
+
+ l = np.argmax(nu)
+ gmax = Tmp12[l,l] / np.abs(Tmp11[l,l]) # max eigenvalue coherence
+
+ gammaregion[Ph] = gmin
+ gammaregion[Ph+numph] = gmax
+
+ if (np.abs(gmax-gmin) > cohdiff):
+ cohdiff = np.abs(gmax-gmin)
+ gammamax = gmax
+ gammamin = gmin
+
+ gammaregion[-1] = gammaregion[0] # copy the first coherence to the end of the array, for a continuous coherence region plot
+
+ return gammamax, gammamin, gammaregion
\ No newline at end of file
diff --git a/kapok/geo.py b/kapok/geo.py
new file mode 100755
index 0000000..43f82d2
--- /dev/null
+++ b/kapok/geo.py
@@ -0,0 +1,200 @@
+# -*- coding: utf-8 -*-
+"""Geocoding Module
+
+ Use GDAL to make output products resampled to geographic projection with
+ constant lat/lon spacing.
+
+ Author: Michael Denbina
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import platform
+import subprocess
+import sys
+
+import numpy as np
+
+from kapok.lib import bilinear_interpolate
+
+
+def radar2ll(outpath, datafile, data, lat, lon, outformat='ENVI',
+ resampling='bilinear'):
+ """Create a geocoded file, in geographic projection, from input data
+ in azimuth, slant range radar coordinates.
+
+ Uses latitude and longitude arrays containing the geographic coordinates
+ of each pixel (geolocation arrays), in order to perform the resampling
+ using gdalwarp. For gdalwarp reference, see
+ http://www.gdal.org/gdalwarp.html.
+
+ Arguments:
+ outpath (str): The path in which to save the geocoded file, as well as
+ temporary latitude/longitude files used during the resampling
+ process.
+ datafile (str): The output file name for the geocoded file.
+ data (array): 2D array containing the data to geocode. Should be
+ in float32 format. (If it isn't, it will be converted to it.)
+ If resampling of complex-valued parameters is needed, geocode
+ the real and imaginary parts separately using this function.
+ lat (array): 2D array containing the latitudes for each pixel, in
+ degrees.
+ lon (array): 2D array containing the longitudes for each pixel, in
+ degrees.
+ outformat (str): The output format. Should be an identifying string
+ recognized by GDAL. Default is 'ENVI'. Other options include
+ 'GTiff' or 'KEA', etc. For reference, see
+ http://www.gdal.org/formats_list.html.
+ resampling (str): String identifying the resampling method. Options
+ include 'near', 'bilinear', 'cubic', 'lanczos', and others.
+ Default is 'bilinear'. For reference and more options, see
+ http://www.gdal.org/gdalwarp.html.
+
+ """
+ if sys.byteorder == 'little':
+ byte = 'LSB'
+ else:
+ byte = 'MSB'
+
+ if outpath != '':
+ outpath = outpath + '/'
+
+
+
+ # Save the lat/lon to temporary flat binary files.
+ lat.tofile(outpath+'templat.dat')
+ lon.tofile(outpath+'templon.dat')
+
+ # Save the data file.
+ data = data.astype('float32')
+ data.tofile(outpath+'tempdata.dat')
+
+ # Raster properties.
+ xsize = int(data.shape[1])
+ ysize = int(data.shape[0])
+ lineoffset = xsize*4
+
+ # Create the lat/lon .vrts.
+ outfile = outpath+'templat.vrt'
+ with open(outfile, "w") as hdr:
+ hdr.write('\n')
+ hdr.write(' \n')
+ hdr.write(' templat.dat\n')
+ hdr.write(' 0\n')
+ hdr.write(' 4\n')
+ hdr.write(' '+str(lineoffset)+'\n')
+ hdr.write(' '+byte+'\n')
+ hdr.write(' \n')
+ hdr.write('\n')
+
+ outfile = outpath+'templon.vrt'
+ with open(outfile, "w") as hdr:
+ hdr.write('\n')
+ hdr.write(' \n')
+ hdr.write(' templon.dat\n')
+ hdr.write(' 0\n')
+ hdr.write(' 4\n')
+ hdr.write(' '+str(lineoffset)+'\n')
+ hdr.write(' '+byte+'\n')
+ hdr.write(' \n')
+ hdr.write('\n')
+
+
+ # Create the data file vrt.
+ outfile = outpath+'tempdata.vrt'
+ with open(outfile, "w") as hdr:
+ hdr.write('\n')
+ hdr.write(' \n')
+ hdr.write(' 0\n')
+ hdr.write(' 1\n')
+ hdr.write(' 0\n')
+ hdr.write(' 1\n')
+ hdr.write(' 1\n')
+ hdr.write(' '+outpath+'templon.vrt\n')
+ hdr.write(' 1\n')
+ hdr.write(' '+outpath+'templat.vrt\n')
+ hdr.write(' \n')
+ hdr.write(' \n')
+ hdr.write(' tempdata.dat\n')
+ hdr.write(' 0\n')
+ hdr.write(' 4\n')
+ hdr.write(' '+str(lineoffset)+'\n')
+ hdr.write(' '+byte+'\n')
+ hdr.write(' \n')
+ hdr.write('\n')
+
+
+ # Call gdalwarp:
+ command = 'gdalwarp -overwrite -geoloc -t_srs EPSG:4326 -ot Float32 -r '+resampling+' -of '+outformat+' '+outpath+'tempdata.vrt '+outpath+datafile
+ print(subprocess.getoutput(command))
+
+
+ # Remove temporary files.
+ if 'Windows' in platform.system():
+ remcmd = 'del '
+ else:
+ remcmd = 'rm '
+
+ command = remcmd+outpath+'templat.dat'
+ print(subprocess.getoutput(command))
+ command = remcmd+outpath+'templat.vrt'
+ print(subprocess.getoutput(command))
+ command = remcmd+outpath+'templon.dat'
+ print(subprocess.getoutput(command))
+ command = remcmd+outpath+'templon.vrt'
+ print(subprocess.getoutput(command))
+ command = remcmd+outpath+'tempdata.dat'
+ print(subprocess.getoutput(command))
+ command = remcmd+outpath+'tempdata.vrt'
+ print(subprocess.getoutput(command))
+
+ return
+
+
+def ll2radar(data, origin, spacing, lat, lon):
+ """Convert an array in geographic (lat,lon) coordinates into a
+ corresponding array in the (azimuth, slant range) coordinates of the
+ radar image.
+
+ Arguments:
+ data (array): 2D array containing data in regularly spaced latitude/
+ longitude coordinates. First dimension of array should be
+ latitude, second dimension should be longitude.
+ origin (tuple): (Latitude, Longitude) of the first pixel in data,
+ in degrees.
+ spacing (tuple): (Latitude, Longitude) spacing of the data, in
+ degrees.
+ lat (array): 2D array containing the latitude values, in degrees,
+ for each pixel of the radar image.
+ lon (array): 2D array containing the longitude values, in degrees,
+ for each pixel of the radar image.
+
+ Returns:
+ resdata (array): Data resampled to radar coordinates, with the same
+ size as lat and lon.
+
+ """
+ x = (lon - origin[1])/spacing[1]
+ y = (lat - origin[0])/spacing[0]
+
+ if np.any(np.imag(data) != 0): # if data is complex, interpolate real and imaginary parts separately
+ resdata = 1j*bilinear_interpolate(np.imag(data),x,y)
+ resdata += bilinear_interpolate(np.real(data),x,y)
+ else: # data is real
+ resdata = bilinear_interpolate(data,x,y)
+
+ return resdata
\ No newline at end of file
diff --git a/kapok/kapok.py b/kapok/kapok.py
new file mode 100755
index 0000000..2a1c814
--- /dev/null
+++ b/kapok/kapok.py
@@ -0,0 +1,1145 @@
+# -*- coding: utf-8 -*-
+"""Kapok Main Module
+
+ Core Kapok module containing Scene class definition and methods. A Scene
+ object contains a PolInSAR dataset including covariance matrix, incidence
+ angle, kz, latitude, longitude, processor DEM, and metadata.
+
+ Methods available for data visualization, coherence optimization, and
+ forest model inversion.
+
+ Author: Michael Denbina
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import time
+import collections
+import os.path
+
+import numpy as np
+import h5py
+import matplotlib.pyplot as plt
+plt.ion()
+
+import kapok.geo
+import kapok.vis
+from kapok.lib import mb_cov_index, makehermitian
+
+
+screen_height = 1000 # Set to screen resolution height. Determines figure sizes.
+
+
+class Scene(object):
+ """Scene object containing a PolInSAR dataset, and methods for viewing
+ and processing the data.
+
+ """
+
+ def __init__(self, file):
+ """Scene initialization method.
+
+ Arguments:
+ file (str): Path and filename to a previously saved kapok HDF5
+ PolInSAR scene.
+
+ """
+ # Load the HDF5 file. If it can't be loaded, abort.
+ try:
+ self.f = h5py.File(file,'r+')
+ except:
+ print('kapok.Scene | Cannot load specified HDF5 file: "'+file+'". Ensure file exists. Aborting.')
+ self.f = None
+ return
+
+ # Easy access to datasets:
+ self.cov = self.f['cov']
+
+ self.lat = self.f['lat']
+ self.lon = self.f['lon']
+ self.dem = self.f['dem']
+
+ self.kz = self.f['kz']
+ self.inc = self.f['inc']
+
+ if 'pdopt/coh' in self.f:
+ self.pdcoh = self.f['pdopt/coh']
+ else:
+ self.pdcoh = None
+
+ if 'pdopt/weights' in self.f:
+ self.pdweights = self.f['pdopt/weights']
+ else:
+ self.pdweights = None
+
+ if 'products' in self.f:
+ self.products = self.f['products']
+
+
+ # Easy access to some commonly used metadata attributes:
+ self.site = self.f.attrs['site']
+ self.name = self.f.attrs['stack_name']
+ self.tracks = self.f.attrs['tracks']
+
+ self.dim = tuple(self.f.attrs['dim'])
+ self.spacing = (self.f.attrs['cov_azimuth_pixel_spacing'], self.f.attrs['cov_slant_range_pixel_spacing'])
+
+ self.num_tracks = self.f.attrs['num_tracks']
+ self.num_baselines = self.f.attrs['num_baselines']
+ self.num_pol = self.cov.attrs['num_pol']
+
+ self.ml_window = self.f.attrs['ml_window']
+ self.sm_window = self.f.attrs['sm_window']
+
+ self.wavelength = self.f.attrs['wavelength']
+
+ self.compression = self.f.attrs['compression']
+ self.compression_opts = self.f.attrs['compression_opts']
+
+
+ def __del__(self):
+ """Scene destructor. Closes the HDF5 file."""
+ if self.f is not None:
+ self.f.close()
+
+
+ def get(self, path):
+ """Returns a specified dataset from the HDF5 file.
+
+ Arguments:
+ path (str): Path and name to an HDF5 dataset within the Scene
+ file. Note that shorts can be used if you wish to access
+ a dataset within the 'products/' or 'ancillary/' groups.
+ These group names can be omitted and the function will check
+ within them for the given dataset name.
+
+ Returns:
+ data (array): The desired HDF5 dataset, in the form of a NumPy
+ array.
+
+ """
+ if path in self.f:
+ if isinstance(self.f[path], h5py.Dataset):
+ return self.f[path][:]
+ else:
+ print('kapok.Scene.get | Desired path exists in HDF5 file, but is not a dataset. Please specify the name of a HDF5 dataset.')
+ return None
+ elif ('products/'+path) in self.f:
+ if isinstance(self.f['products/'+path], h5py.Dataset):
+ return self.f['products/'+path][:]
+ else:
+ print('kapok.Scene.get | Desired path exists in HDF5 file, but is not a dataset. Please specify the name of a HDF5 dataset.')
+ return None
+ elif ('products'+path) in self.f:
+ if isinstance(self.f['products'+path], h5py.Dataset):
+ return self.f['products'+path][:]
+ else:
+ print('kapok.Scene.get | Desired path exists in HDF5 file, but is not a dataset. Please specify the name of a HDF5 dataset.')
+ return None
+ elif ('ancillary/'+path) in self.f:
+ if isinstance(self.f['ancillary/'+path], h5py.Dataset):
+ return self.f['ancillary/'+path][:]
+ else:
+ print('kapok.Scene.get | Desired path exists in HDF5 file, but is not a dataset. Please specify the name of a HDF5 dataset.')
+ return None
+ elif ('ancillary'+path) in self.f:
+ if isinstance(self.f['ancillary'+path], h5py.Dataset):
+ return self.f['ancillary'+path][:]
+ else:
+ print('kapok.Scene.get | Desired path exists in HDF5 file, but is not a dataset. Please specify the name of a HDF5 dataset.')
+ return None
+ else:
+ print('kapok.Scene.get | Desired path does not exist in HDF5 file.')
+ return None
+
+
+ def query(self, path=None):
+ """Prints useful lists of datasets and attributes inside the HDF5 file.
+
+ Arguments:
+ path (str): Path and name to an HDF5 dataset or group within the
+ Scene file. Its attributes will be printed. If path is not
+ specified, a list of all groups and datasets in the HDF5 file
+ will be printed instead. If path is an empty string, the
+ attributes of the main HDF5 file will be printed.
+
+ """
+ if path is None:
+ print('kapok.Scene.query | Printing groups and datasets in HDF5 file...')
+ def printindex(name):
+ print('kapok.Scene.query | '+name)
+ self.f.visit(printindex)
+ elif path in self.f:
+ print('kapok.Scene.index | Printing attributes of "'+path+'"...')
+ for item in self.f[path].attrs.keys():
+ try:
+ print('kapok.Scene.query | ' + item + ":", self.f[path].attrs[item].astype('str'))
+ except:
+ print('kapok.Scene.query | ' + item + ":", self.f[path].attrs[item])
+ elif path == '':
+ print('kapok.Scene.index | Printing attributes of main HDF5 file...')
+ for item in self.f.attrs.keys():
+ try:
+ print('kapok.Scene.query | ' + item + ":", self.f.attrs[item].astype('str'))
+ except:
+ print('kapok.Scene.query | ' + item + ":", self.f.attrs[item])
+ else:
+ print('kapok.Scene.query | Desired path does not exist in HDF5 file.')
+
+
+ def inv(self, method='rvog', name=None, desc=None, overwrite=False, bl=0,
+ tdf=None, epsilon=0.4, groundmag=None, ext=None, mu=0, mask=None,
+ **kwargs):
+ """Forest model inversion.
+
+ Estimate forest height using one of a number of models relating
+ the forest's physical parameters to the PolInSAR observables.
+
+ Currently implemented models:
+ 'sinc': Sinc model for the coherence magnitude. Calls
+ function kapok.sinc.sincinv().
+ 'sincphase': Sum of weighted sinc coherence model and phase
+ height of volume coherence above ground surface. Estimates
+ ground phase using kapok.topo.groundsolver(). Model
+ implemented in function kapok.sinc.sincphase().
+ 'rvog' (default): Random Volume over Ground model. Estimates
+ ground phase using kapok.topo.groundsolver(). Model inversion
+ is performed by function kapok.rvog.rvoginv().
+
+ After model inversion is performed, HDF5 datasets will be created in
+ 'products//' for each estimated model parameter, where the model
+ parameters are:
+ 'hv': Forest/volume height, in meters. Used by all models.
+ 'ext': Wave extinction, in Nepers/meter. Used by rvog model.
+ 'phi': Complex-valued ground coherence. The phase of this
+ coherence is the topographic phase. Used by sincphase and
+ rvog models.
+ 'mu': Ground-to-volume amplitude ratio for the highest observed
+ coherence. In the single baseline case, this is generally
+ set to a fixed value, often zero. Used by rvog model.
+ 'tdf': Temporal decorrelation factor, describing the effect of
+ temporal decorrelation on the highest observed coherence.
+ Can be used by sinc, sincphase, and rvog models, though the
+ default value is generally unity.
+
+ Note that datasets will not be created for all of the above parameters
+ for every inversion. Only parameters that vary from pixel to pixel
+ will be saved as datasets. In the event that parameters are fixed
+ during a model inversion, those fixed parameter values will be saved
+ as attributes to 'products//'.
+
+ Arguments:
+ method (str): Name of the desired model to invert. Currently
+ supported values: 'sinc', 'sincphase', and 'rvog'.
+ Default: 'rvog'.
+ name (str): Name for the saved group containing the inverted model
+ parameters (forest height, extinction, etc.). Default: Equal
+ to method.
+ desc (str): String describing the inversion model, parameters,
+ etc., which will be stored in the attributes
+ overwrite (bool): If a dataset with the requested name already
+ exists, overwrite it. Default: If the dataset already exists,
+ function will abort with an error message.
+ bl (int): Baseline index specifying which baseline to invert, if
+ scene contains multiple baselines. Default: 0.
+ tdf (array): Array of temporal decorrelation factors to use in
+ the model inversion, if desired. Default: None.
+ epsilon: Value of the epsilon parameter of the sinc and phase
+ difference inversion. Only used for method 'sincphase'.
+ groundmag (array): Value for the magnitude of the estimated ground
+ coherences. Used when finding the ground solution using the
+ line fit procedure. Default: No ground decorrelation.
+ ext: Fixed value(s) for the extinction parameter of the
+ RVoG model, if desired.
+ mu: Fixed value(s) for the ground-to-volume scattering ratio
+ of the RVoG model. Defaults to zero.
+ mask (array): Boolean array of mask values. Only pixels where
+ (mask == True) will be inverted. Defaults to array of ones
+ (all pixels inverted).
+ **kwargs: Additional keyword arguments passed to the model
+ inversion functions, if desired. See model inversion
+ function headers for more details. Default: None.
+
+ Returns:
+ result (hdf5 group): Link to the HDF5 group containing the
+ optimized model parameters.
+
+ """
+ if name is None:
+ name = method
+
+ # Check If Group Exists:
+ if ('products/'+name in self.f) and overwrite:
+ del self.f['products/'+name]
+ elif ('products/'+name in self.f) and (overwrite == False):
+ print('kapok.Scene.inv | Model inversion group with name "products/'+name+'" already exists. If you wish to replace it, set overwrite keyword. Aborting.')
+ return None
+
+ result = self.f.create_group('products/'+name)
+
+ if desc is not None:
+ result.attrs['desc'] = desc
+
+ # Perform Model Inversion...
+
+ # Sinc Model
+ if method == 'sinc':
+ import kapok.sinc
+ if 'pdopt/coh' in self.f:
+ print('kapok.Scene.inv | Performing sinc model inversion using phase diversity highest coherence. ('+time.ctime()+')')
+ if desc is None:
+ result.attrs['desc'] = 'Sinc coherence model. Used phase diversity high coherence as volume coherence.'
+
+ result.attrs['pol'] = 'high'
+ gammav = self.coh('high', bl=bl)
+ else:
+ print('kapok.Scene.inv | Phase diversity coherence optimization not yet run. Performing sinc model inversion using HV polarization coherence. ('+time.ctime()+')')
+ if desc is None:
+ result.attrs['desc'] = 'Sinc coherence model. Used HV coherence as volume coherence.'
+
+ result.attrs['pol'] = 'HV'
+ gammav = self.coh('HV', bl=bl)
+
+ if self.num_baselines > 1:
+ hv = kapok.sinc.sincinv(gammav, self.kz[bl], tdf=tdf, mask=mask, **kwargs)
+ else:
+ hv = kapok.sinc.sincinv(gammav, self.kz[:], tdf=tdf, mask=mask, **kwargs)
+
+ result.attrs['model'] = 'sinc'
+ result.attrs['baseline'] = bl
+ result.create_dataset('hv', data=hv, dtype='float32', compression=self.compression, compression_opts=self.compression_opts)
+ result['hv'].attrs['fixed'] = False
+ result['hv'].attrs['name'] = 'PolInSAR Forest Height'
+ result['hv'].attrs['units'] = 'm'
+
+ # Create TDF dataset, if TDF varies across image.
+ if isinstance(tdf, (collections.Sequence, np.ndarray)):
+ result.create_dataset('tdf', data=tdf, dtype='complex64', compression=self.compression, compression_opts=self.compression_opts)
+ result['tdf'].attrs['fixed'] = True
+ result['tdf'].attrs['name'] = 'Temporal Decorrelation Factor'
+ result['tdf'].attrs['units'] = ''
+ elif tdf is not None:
+ result.attrs['tdf'] = tdf
+
+
+ # Sinc and Phase Diff Model
+ elif method == 'sincphase':
+ import kapok.sinc
+ import kapok.topo
+
+ if 'pdopt/coh' not in self.f:
+ print('kapok.Scene.inv | Run phase diversity coherence optimization before performing sinc and phase difference inversion. Aborting.')
+ result = None
+ else:
+ if self.num_baselines > 1:
+ ground, groundalt, volindex = kapok.topo.groundsolver(self.pdcoh[bl], kz=self.kz[bl], groundmag=groundmag, returnall=True)
+ coh_high = np.where(volindex,self.pdcoh[bl,1],self.pdcoh[bl,0])
+ hv = kapok.sinc.sincphaseinv(coh_high, np.angle(ground), self.kz[bl], epsilon=epsilon, tdf=tdf, mask=mask, **kwargs)
+ else:
+ ground, groundalt, volindex = kapok.topo.groundsolver(self.pdcoh[:], kz=self.kz[:], groundmag=groundmag, returnall=True)
+ coh_high = np.where(volindex,self.pdcoh[1],self.pdcoh[0])
+ hv = kapok.sinc.sincphaseinv(coh_high, np.angle(ground), self.kz, epsilon=epsilon, tdf=tdf, mask=mask, **kwargs)
+
+ if desc is None:
+ result.attrs['desc'] = 'Sinc Coherence and Phase Difference model.'
+
+ result.attrs['model'] = 'sincphase'
+ result.attrs['baseline'] = bl
+ result.create_dataset('hv', data=hv, dtype='float32', compression=self.compression, compression_opts=self.compression_opts)
+ result['hv'].attrs['fixed'] = False
+ result['hv'].attrs['name'] = 'Forest Height'
+ result['hv'].attrs['units'] = 'm'
+ result.create_dataset('ground', data=ground, dtype='complex64', compression=self.compression, compression_opts=self.compression_opts)
+ result['ground'].attrs['fixed'] = False
+ result['ground'].attrs['name'] = 'Ground Complex Coherence'
+ result['ground'].attrs['units'] = ''
+
+ # Create epsilon dataset, if epsilon varies across the image.
+ # Otherwise, store it in an attribute.
+ if isinstance(epsilon, (collections.Sequence, np.ndarray)):
+ result.create_dataset('epsilon', data=epsilon, dtype='float32', compression=self.compression, compression_opts=self.compression_opts)
+ result['epsilon'].attrs['fixed'] = True
+ result['epsilon'].attrs['name'] = 'Epsilon'
+ result['epsilon'].attrs['units'] = ''
+ elif epsilon is not None:
+ result.attrs['epsilon'] = epsilon
+
+ # Create TDF dataset, if TDF varies across image.
+ if isinstance(tdf, (collections.Sequence, np.ndarray)):
+ if np.any(np.iscomplex(tdf)):
+ result.create_dataset('tdf', data=tdf, dtype='complex64', compression=self.compression, compression_opts=self.compression_opts)
+ else:
+ result.create_dataset('tdf', data=tdf, dtype='float32', compression=self.compression, compression_opts=self.compression_opts)
+ result['tdf'].attrs['fixed'] = True
+ result['tdf'].attrs['name'] = 'Temporal Decorrelation Factor'
+ result['tdf'].attrs['units'] = ''
+ elif tdf is not None:
+ result.attrs['tdf'] = tdf
+
+
+ # RVoG Model
+ elif method == 'rvog':
+ import kapok.rvog
+ import kapok.topo
+
+ if 'pdopt/coh' not in self.f:
+ print('kapok.Scene.inv | Run phase diversity coherence optimization before performing RVoG inversion. Aborting.')
+ result = None
+ else:
+ if self.num_baselines > 1:
+ ground, groundalt, volindex = kapok.topo.groundsolver(self.pdcoh[bl], kz=self.kz[bl], groundmag=groundmag, returnall=True)
+ coh_high = np.where(volindex,self.pdcoh[bl,1],self.pdcoh[bl,0])
+ hv, exttdf, converged = kapok.rvog.rvoginv(coh_high, ground, self.inc, self.kz[bl], ext=ext, tdf=tdf, mu=mu,
+ mask=mask, **kwargs)
+ else:
+ ground, groundalt, volindex = kapok.topo.groundsolver(self.pdcoh[:], kz=self.kz[:], groundmag=groundmag, returnall=True)
+ coh_high = np.where(volindex,self.pdcoh[1],self.pdcoh[0])
+ hv, exttdf, converged = kapok.rvog.rvoginv(coh_high, ground, self.inc, self.kz, ext=ext, tdf=tdf, mu=mu,
+ mask=mask, **kwargs)
+
+ if desc is None:
+ result.attrs['desc'] = 'Random Volume over Ground model.'
+
+ result.attrs['model'] = 'rvog'
+ result.attrs['baseline'] = bl
+ result.create_dataset('hv', data=hv, dtype='float32', compression=self.compression, compression_opts=self.compression_opts)
+ result['hv'].attrs['fixed'] = False
+ result['hv'].attrs['name'] = 'Forest Height'
+ result['hv'].attrs['units'] = 'm'
+ result.create_dataset('ground', data=ground, dtype='complex64', compression=self.compression, compression_opts=self.compression_opts)
+ result['ground'].attrs['fixed'] = False
+ result['ground'].attrs['name'] = 'Ground Complex Coherence'
+ result['ground'].attrs['units'] = ''
+
+ # Save Extinction
+ if (ext is not None) and isinstance(ext, (collections.Sequence, np.ndarray)):
+ result.create_dataset('ext', data=ext, dtype='float32', compression=self.compression, compression_opts=self.compression_opts)
+ result['ext'].attrs['fixed'] = True
+ result['ext'].attrs['name'] = 'Extinction'
+ result['ext'].attrs['units'] = 'Np/m'
+ elif ext is None:
+ result.create_dataset('ext', data=exttdf, dtype='float32', compression=self.compression, compression_opts=self.compression_opts)
+ result['ext'].attrs['fixed'] = False
+ result['ext'].attrs['name'] = 'Extinction'
+ result['ext'].attrs['units'] = 'Np/m'
+ else:
+ result.attrs['ext'] = ext
+
+ # Save TDF
+ if (tdf is not None) and isinstance(tdf, (collections.Sequence, np.ndarray)):
+ if np.any(np.iscomplex(tdf)):
+ result.create_dataset('tdf', data=tdf, dtype='complex64', compression=self.compression, compression_opts=self.compression_opts)
+ else:
+ result.create_dataset('tdf', data=tdf, dtype='float32', compression=self.compression, compression_opts=self.compression_opts)
+ result['tdf'].attrs['fixed'] = True
+ result['tdf'].attrs['name'] = 'Temporal Decorrelation Factor'
+ result['tdf'].attrs['units'] = ''
+ elif tdf is None:
+ result.create_dataset('tdf', data=exttdf, dtype='float32', compression=self.compression, compression_opts=self.compression_opts)
+ result['tdf'].attrs['fixed'] = False
+ result['tdf'].attrs['name'] = 'Temporal Decorrelation Factor'
+ result['tdf'].attrs['units'] = ''
+ else:
+ result.attrs['tdf'] = tdf
+
+
+ else:
+ print('kapok.Scene.inv | Inversion method "'+method+'" not recognized. Aborting.')
+ return None
+
+
+ # Create groundmag dataset, if groundmag varies across the image.
+ # Otherwise, store it in an attribute.
+ if (method == 'sincphase') or (method == 'rvog'):
+ if isinstance(groundmag, (collections.Sequence, np.ndarray)):
+ result.create_dataset('groundmag', data=groundmag, dtype='float32', compression=self.compression, compression_opts=self.compression_opts)
+ result['groundmag'].attrs['fixed'] = True
+ result['groundmag'].attrs['name'] = 'Ground Coherence Magnitude'
+ result['groundmag'].attrs['units'] = ''
+ elif groundmag is not None:
+ result.attrs['groundmag'] = groundmag
+
+
+ self.f.flush()
+ return result
+
+
+ def opt(self, method='pdopt', saveweights=False, overwrite=False):
+ """Coherence optimization.
+
+ Perform coherence optimization, and save the results to the HDF5 file.
+ Currently, phase diversity coherence optimization is the only method
+ supported. The coherences will be saved in 'pdopt/coh'. The
+ coherence weight vectors, if requested, will be saved in
+ 'pdopt/weights'.
+
+ Arguments:
+ method (str): Desired optimization algorithm. Currently 'pdopt'
+ (phase diversity) is the only method supported.
+ saveweights (bool): True/False flag, specifies whether to
+ save the polarization weight vectors for the optimized
+ coherences.
+ overwrite (bool): True/False flag that determines whether to
+ overwrite the current coherences. If False, will abort if
+ the coherences already exist.
+
+ """
+ if ('pd' in method) or ('pdopt' in method) or ('phase diversity' in method):
+ if ('pdopt/coh' in self.f) and (overwrite == False):
+ print('kapok.Scene.opt | Phase diversity coherence optimization already performed. If you want to overwrite, set the overwrite keyword to True. Aborting.')
+ else:
+ import kapok.cohopt
+
+ # If datasets already exist, remove them.
+ if ('pdopt/coh' in self.f):
+ del self.f['pdopt/coh']
+ self.pdcoh = None
+
+ if ('pdopt/weights' in self.f):
+ del self.f['pdopt/weights']
+ self.pdweights = None
+
+
+ if self.num_baselines > 1: # Multiple Baselines
+ self.pdcoh = self.f.create_dataset('pdopt/coh', (self.num_baselines, 2, self.dim[0], self.dim[1]), dtype='complex64', compression=self.compression, compression_opts=self.compression_opts)
+
+ if saveweights:
+ self.pdweights = self.f.create_dataset('pdopt/weights', (self.num_baselines, 2, self.dim[0], self.dim[1], 3), dtype='complex64', compression=self.compression, compression_opts=self.compression_opts)
+
+ for bl in range(self.num_baselines):
+ # Get Omega and T matrices:
+ row, col = mb_cov_index(bl, 0, n_pol=self.num_pol)
+ tm = 0.5*(self.cov[:,:,row:row+self.num_pol,row:row+self.num_pol] + self.cov[:,:,col:col+self.num_pol,col:col+self.num_pol])
+ tm = makehermitian(tm)
+ om = self.cov[:,:,row:row+self.num_pol,col:col+self.num_pol]
+
+ print('kapok.cohopt.pdopt | Beginning phase diversity coherence optimization for baseline index '+str(bl)+'. ('+time.ctime()+')')
+ if saveweights:
+ gammamax, gammamin, wmax, wmin = kapok.cohopt.pdopt(tm, om, returnweights=saveweights)
+ else:
+ gammamax, gammamin = kapok.cohopt.pdopt(tm, om, returnweights=saveweights)
+
+ temp = np.angle(gammamin*np.conj(gammamax))
+ ind = (np.sign(temp) == np.sign(self.kz[bl]))
+
+ swap = gammamax[ind].copy()
+ gammamax[ind] = gammamin[ind]
+ gammamin[ind] = swap
+
+ self.pdcoh[bl,0,:,:] = gammamax
+ self.pdcoh[bl,1,:,:] = gammamin
+
+ if saveweights:
+ ind = np.dstack((ind,ind,ind))
+ swap = wmax[ind].copy()
+ wmax[ind] = wmin[ind]
+ wmin[ind] = swap
+
+ self.pdweights[bl,0,:,:,:] = wmax
+ self.pdweights[bl,1,:,:,:] = wmin
+
+ else: # Single Baseline
+ self.pdcoh = self.f.create_dataset('pdopt/coh', (2, self.dim[0], self.dim[1]), dtype='complex64', compression=self.compression, compression_opts=self.compression_opts)
+
+ # Get Omega and T matrices:
+ row, col = mb_cov_index(0, 0, n_pol=self.num_pol)
+ tm = 0.5*(self.cov[:,:,row:row+self.num_pol,row:row+self.num_pol] + self.cov[:,:,col:col+self.num_pol,col:col+self.num_pol])
+ tm = makehermitian(tm)
+ om = self.cov[:,:,row:row+self.num_pol,col:col+self.num_pol]
+
+ print('kapok.cohopt.pdopt | Beginning phase diversity coherence optimization for single baseline. ('+time.ctime()+')')
+ if saveweights:
+ self.pdweights = self.f.create_dataset('pdopt/weights', (2, self.dim[0], self.dim[1], 3), dtype='complex64', compression=self.compression, compression_opts=self.compression_opts)
+ gammamax, gammamin, wmax, wmin = kapok.cohopt.pdopt(tm, om, returnweights=saveweights)
+ else:
+ gammamax, gammamin = kapok.cohopt.pdopt(tm, om, returnweights=saveweights)
+
+ temp = np.angle(gammamin*np.conj(gammamax))
+ ind = (np.sign(temp) == np.sign(self.kz))
+
+ swap = gammamax[ind].copy()
+ gammamax[ind] = gammamin[ind]
+ gammamin[ind] = swap
+
+ self.pdcoh[0,:,:] = gammamax
+ self.pdcoh[1,:,:] = gammamin
+
+ if saveweights:
+ ind = np.dstack((ind,ind,ind))
+ swap = wmax.copy()
+ wmax[ind] = wmin[ind]
+ wmin[ind] = swap[ind]
+
+ self.pdweights[0,:,:,:] = wmax
+ self.pdweights[1,:,:,:] = wmin
+
+ self.f.flush()
+
+ else:
+ print('kapok.Scene.opt | Requested coherence optimization method "'+method+'" not recognized. Aborting.')
+
+ return
+
+
+ def show(self, imagetype='pauli', pol=0, bl=0, tr=0, vmin=None, vmax=None,
+ bounds=None, cmap=None, figsize=None, dpi=125, savefile=None,
+ **kwargs):
+ """Display images of backscatter, coherence, estimated forest
+ heights, etc.
+
+ Arguments:
+ imagetype (str): String describing what to display, or an array
+ containing data to plot. Possible string options: 'pow' or
+ 'power' for backscatter image, 'coh' or 'coherence' for
+ complex coherence image, 'coh mag' for a coherence magnitude
+ image, 'coh ph' for coherence phase image, 'pauli' or 'rgb'
+ for Pauli basis RGB composite image, 'inc' or 'incidence'
+ for incidence angle image, 'kz' for vertical wavenumber image,
+ 'dem' for processor DEM heights. Derived products can be
+ displayed by entering their path within the HDF5 file, in the
+ form 'products//', where is the name
+ keyword argument originally given to Scene.inv(), and
+ is the parameter of interest. For example, 'products/rvog/hv'
+ would display the estimated forest height from a RVoG model
+ inversion with the default name. If '/hv', '/ext', or '/tdf'
+ are in the imagetype, the 'products/' group can be omitted.
+ The function will assume that is the location of parameters
+ with these names. See kapok.Scene.inv() for more details on
+ how the forest model inversion results are stored. Default:
+ 'pauli'.
+ pol: Polarization identifier, used only for backscatter and
+ coherence images. pol can be an integer from 0 to 2
+ (0: HH, 1: HV, 2: VV), a three element list containing the
+ polarimetric weights, or a string ('HH', 'HH+VV', 'HH-VV',
+ 'HV', or 'VV'). Can also be 'high' or 'low' to display the
+ phase diversity optimized coherences, if a coherence is
+ being displayed. Default: HH.
+ bl (int): Baseline number. Only used for coherence and kz images.
+ Default: 0.
+ tr (int): Track number. Only used for backscatter and Pauli RGB
+ images. Default: 0.
+ vmin (float): Min value for colormap. Only used for some
+ image types. Default value depends on image type and data.
+ vmax (float): Max value for colormap.
+ bounds (tuple): Bounds containing (azimuth start, azimuth end,
+ range start, range end), in that order. Will plot a subset of
+ the image rather than the entire image. For a full swath
+ subset, two element bounds can be given: (azimuth start,
+ azimuth end). Default: Full image.
+ cmap: Matplotlib colormap, if you wish to override the default
+ colormaps for each image type. cmap has no effect for some
+ image types (e.g., 'pauli' or 'coh').
+ figsize (tuple): Figure size argument passed to plotting functions.
+ Tuple of (x,y) sizes in inches. Default is based on data
+ shape.
+ dpi (int): Dots per inch argument passed to plotting functions.
+ Default: 125.
+ savefile (str): If specified, the plotted figure is saved under
+ this filename.
+ **kwargs: Additional keyword arguments provided to plotting
+ functions. Only works if imagetype is input data array. The
+ string image types generally have preset options.
+
+ """
+ # Set up figure size.
+ ysize = screen_height*0.8/dpi
+
+ if (bounds is None) and (figsize is None):
+ xsize = ysize*self.dim[1]/self.dim[0] + 2
+ figsize=(xsize, ysize)
+ elif figsize is None:
+ if len(bounds) == 2:
+ bounds = (bounds[0], bounds[1], 0, self.dim[1])
+ xsize = ysize*(bounds[3]-bounds[2])/(bounds[1]-bounds[0]) + 2
+ figsize=(xsize, ysize)
+
+
+ if isinstance(imagetype,str):
+ # Which type of image to display?
+ if ('/hv' in imagetype) and ((imagetype in self.f) or ('products/'+imagetype in self.f)):
+ if imagetype in self.f:
+ data = self.f[imagetype]
+ else:
+ data = self.f['products/'+imagetype]
+
+ vmin = 0 if vmin is None else vmin
+ vmax = 50 if vmax is None else vmax
+ cmap = 'Greens' if cmap is None else cmap
+ if ('name' in data.attrs) and ('units' in data.attrs):
+ kapok.vis.show_linear(data, vmin=vmin, vmax=vmax, cbar_label=data.attrs['name']+' ('+data.attrs['units']+')', bounds=bounds, cmap=cmap, figsize=figsize, dpi=dpi, savefile=savefile)
+ elif ('name' in data.attrs):
+ kapok.vis.show_linear(data, vmin=vmin, vmax=vmax, cbar_label=data.attrs['name'], bounds=bounds, cmap=cmap, figsize=figsize, dpi=dpi, savefile=savefile)
+ else:
+ kapok.vis.show_linear(data, vmin=vmin, vmax=vmax, cbar_label=imagetype, bounds=bounds, cmap=cmap, figsize=figsize, dpi=dpi, savefile=savefile)
+
+ elif ('/ext' in imagetype) and ((imagetype in self.f) or ('products/'+imagetype in self.f)):
+ if imagetype in self.f:
+ data = self.f[imagetype]
+ else:
+ data = self.f['products/'+imagetype]
+
+ vmin = 0 if vmin is None else vmin
+ vmax = 0.6 if vmax is None else vmax
+ cmap = 'viridis' if cmap is None else cmap
+ if ('name' in data.attrs) and ('units' in data.attrs):
+ if 'Np/m' in data.attrs['units']:
+ nptodb = 20/np.log(10) # convert to dB/m for display
+ kapok.vis.show_linear(data[:]*nptodb, vmin=vmin, vmax=vmax, cbar_label=data.attrs['name']+' (dB/m)', bounds=bounds, cmap=cmap, figsize=figsize, dpi=dpi, savefile=savefile)
+ elif 'dB/m' in data.attrs['units']:
+ kapok.vis.show_linear(data[:], vmin=vmin, vmax=vmax, cbar_label=data.attrs['name']+' (dB/m)', bounds=bounds, cmap=cmap, figsize=figsize, dpi=dpi, savefile=savefile)
+ else:
+ kapok.vis.show_linear(data[:], vmin=vmin, vmax=vmax, cbar_label=data.attrs['name']+' ('+data.attrs['units']+')', bounds=bounds, cmap=cmap, figsize=figsize, dpi=dpi, savefile=savefile)
+ elif ('name' in data.attrs):
+ kapok.vis.show_linear(data[:], vmin=vmin, vmax=vmax, cbar_label=data.attrs['name'], bounds=bounds, cmap=cmap, figsize=figsize, dpi=dpi, savefile=savefile)
+ else:
+ kapok.vis.show_linear(data[:], vmin=vmin, vmax=vmax, cbar_label=imagetype, bounds=bounds, cmap=cmap, figsize=figsize, dpi=dpi, savefile=savefile)
+
+ elif ('/tdf' in imagetype) and ((imagetype in self.f) or ('products/'+imagetype in self.f)):
+ if imagetype in self.f:
+ data = self.f[imagetype]
+ else:
+ data = self.f['products/'+imagetype]
+
+ vmin = 0 if vmin is None else vmin
+ vmax = 1 if vmax is None else vmax
+ cmap = 'afmhot' if cmap is None else cmap
+
+ if np.any(np.iscomplex(data)):
+ kapok.vis.show_complex(data, bounds=bounds, cbar=True, cbar_label=data.attrs['name'], figsize=figsize, dpi=dpi, savefile=savefile)
+ else:
+ kapok.vis.show_linear(data, vmin=vmin, vmax=vmax, cbar_label=data.attrs['name'], bounds=bounds, cmap=cmap, figsize=figsize, dpi=dpi, savefile=savefile)
+
+ elif ('products/' in imagetype) and (imagetype in self.f):
+ data = self.f[imagetype]
+ cmap = 'viridis' if cmap is None else cmap
+ kapok.vis.show_linear(data, vmin=vmin, vmax=vmax, cbar_label=data.attrs['name']+' ('+data.attrs['units']+')', bounds=bounds, cmap=cmap, figsize=figsize, dpi=dpi, savefile=savefile)
+
+ elif ('pow' in imagetype) or ('power' in imagetype):
+ vmin = -25 if vmin is None else vmin
+ vmax = -3 if vmax is None else vmax
+ cmap = 'gray' if cmap is None else cmap
+ kapok.vis.show_power(self.power(pol=pol, tr=tr), bounds=bounds, cmap=cmap, vmin=vmin, vmax=vmax, figsize=figsize, dpi=dpi, savefile=savefile)
+
+ elif ('mag' in imagetype) and (('coh' in imagetype) or ('gamma' in imagetype)):
+ cmap = 'afmhot' if cmap is None else cmap
+ try:
+ kapok.vis.show_linear(np.abs(self.coh(pol=pol, bl=bl)), bounds=bounds, cmap=cmap, vmin=0, vmax=1, cbar_label='Coherence Magnitude', figsize=figsize, dpi=dpi, savefile=savefile)
+ except:
+ print('kapok.Scene.show | Error: Requested coherence cannot be displayed. Is the polarization identifier valid? Have you run .opt()?')
+
+ elif (('ph' in imagetype) or ('arg' in imagetype)) and (('coh' in imagetype) or ('gamma' in imagetype)):
+ try:
+ kapok.vis.show_linear(np.angle(self.coh(pol=pol, bl=bl)), bounds=bounds, vmin=-np.pi, vmax=np.pi, cmap='hsv', cbar_label='Phase (radians)', figsize=figsize, dpi=dpi, savefile=savefile)
+ except:
+ print('kapok.Scene.show | Error: Requested coherence cannot be displayed. Is the polarization identifier valid? Have you run .opt()?')
+
+ elif ('coh' in imagetype) or ('gamma' in imagetype):
+ try:
+ kapok.vis.show_complex(self.coh(pol=pol, bl=bl), bounds=bounds, cbar=True, figsize=figsize, dpi=dpi, savefile=savefile)
+ except:
+ print('kapok.Scene.show | Error: Requested coherence cannot be displayed. Is the polarization identifier valid? Have you run .opt()?')
+
+ elif ('pauli' in imagetype) or ('rgb' in imagetype):
+ i = tr*self.num_pol
+ vmin = -25 if vmin is None else vmin
+ vmax = -3 if vmax is None else vmax
+ tm = makehermitian(self.cov[:,:,i:i+self.num_pol,i:i+self.num_pol])
+ kapok.vis.show_paulirgb(tm, bounds=bounds, vmin=vmin, vmax=vmax, figsize=figsize, dpi=dpi, savefile=savefile)
+
+ elif ('inc' in imagetype):
+ vmin = 25 if vmin is None else vmin
+ vmax = 65 if vmax is None else vmax
+ cmap = 'viridis' if cmap is None else cmap
+ kapok.vis.show_linear(np.degrees(self.inc), cmap=cmap, vmin=vmin, vmax=vmax, cbar_label='Incidence Angle (degrees)', bounds=bounds, figsize=figsize, dpi=dpi, savefile=savefile)
+
+ elif ('kz' in imagetype) or ('vertical wavenumber' in imagetype):
+ cmap = 'viridis' if cmap is None else cmap
+
+ if self.num_baselines > 1:
+ kapok.vis.show_linear(self.kz[bl], cmap=cmap, vmin=vmin, vmax=vmax, cbar_label=r'$k_{z}$ (rad/m)', bounds=bounds, figsize=figsize, dpi=dpi, savefile=savefile)
+ else:
+ kapok.vis.show_linear(self.kz, cmap=cmap, vmin=vmin, vmax=vmax, cbar_label=r'$k_{z}$ (rad/m)', bounds=bounds, figsize=figsize, dpi=dpi, savefile=savefile)
+
+ elif ('dem' in imagetype):
+ cmap = 'gist_earth' if cmap is None else cmap
+ kapok.vis.show_linear(self.dem, cmap=cmap, vmin=vmin, vmax=vmax, cbar_label=r'Elevation (m)', bounds=bounds, figsize=figsize, dpi=dpi, savefile=savefile)
+
+ elif ('close' in imagetype):
+ plt.close('all')
+
+ elif (imagetype in self.f):
+ data = self.f[imagetype]
+ cmap = 'viridis' if cmap is None else cmap
+
+ if ('name' in data.attrs) and ('units' in data.attrs):
+ kapok.vis.show_linear(data, vmin=vmin, vmax=vmax, cbar_label=data.attrs['name']+' ('+data.attrs['units']+')', bounds=bounds, cmap=cmap, figsize=figsize, dpi=dpi, savefile=savefile)
+ elif ('name' in data.attrs):
+ kapok.vis.show_linear(data, vmin=vmin, vmax=vmax, cbar_label=data.attrs['name'], bounds=bounds, cmap=cmap, figsize=figsize, dpi=dpi, savefile=savefile)
+ else:
+ kapok.vis.show_linear(data, vmin=vmin, vmax=vmax, cbar_label=imagetype, bounds=bounds, cmap=cmap, figsize=figsize, dpi=dpi, savefile=savefile)
+
+ else:
+ print('kapok.Scene.show | Unrecognized image type: "'+imagetype+'". Aborting.')
+
+ elif isinstance(imagetype, (collections.Sequence, np.ndarray)):
+ cmap = 'viridis' if cmap is None else cmap
+ kapok.vis.show_linear(imagetype, vmin=vmin, vmax=vmax, bounds=bounds, cmap=cmap, figsize=figsize, dpi=dpi, savefile=savefile, **kwargs)
+
+ else:
+ print('kapok.Scene.show | Unrecognized image type: "'+imagetype+'". Aborting.')
+
+ return
+
+
+ def power(self, pol=0, tr=0):
+ """Return the backscattered power, in linear units, for the specified
+ polarization and track number.
+
+ Arguments:
+ pol: The polarization of the desired power. Can be an
+ integer polarization index (0: HH, 1: HV, 2: VV), or a
+ list containing a polarization weight vector with three
+ complex elements, or a string. Allowed strings are 'HH',
+ 'HV', 'VV', 'HH+VV', and 'HH-VV'. Default: 0.
+ tr (int): Desired track index. Default: 0.
+
+ Returns:
+ pwr (array): An image of backscattered power, in linear units.
+
+ """
+ if isinstance(pol,str):
+ pol = pol.lower()
+
+ if isinstance(pol,str) and (pol == 'hh'):
+ pol = 0
+ elif isinstance(pol,str) and (pol == 'hv'):
+ pol = 1
+ elif isinstance(pol,str) and (pol == 'vv'):
+ pol = 2
+ elif isinstance(pol,str) and (pol == 'hh+vv'):
+ pol = [np.sqrt(0.5), 0, np.sqrt(0.5)]
+ elif isinstance(pol,str) and (pol == 'hh-vv'):
+ pol = [np.sqrt(0.5), 0, -np.sqrt(0.5)]
+
+ if pol in range(self.num_pol):
+ i = tr*self.num_pol + pol
+ pwr = self.cov[:,:,i,i]
+ elif len(pol) == self.num_pol:
+ i = tr*self.num_pol
+ tm = self.cov[:,:,i:i+self.num_pol,i:i+self.num_pol]
+ tm = makehermitian(tm)
+
+ wimage = np.ones((self.dim[0],self.dim[1],3,3),dtype='complex')
+ wimage[:,:] = np.array([[pol[0]*pol[0],pol[0]*pol[1],pol[0]*pol[2]],
+ [pol[1]*pol[0],pol[1]*pol[1],pol[1]*pol[2]],
+ [pol[2]*pol[0],pol[2]*pol[1],pol[2]*pol[2]]])
+ pwr = np.sum(tm*wimage, axis=(2,3))
+ else:
+ print('kapok.Scene.power | Unrecognized polarization identifier. Returning None.')
+ pwr = None
+
+ if np.any(np.iscomplex(pwr)):
+ return pwr
+ else:
+ return np.real(pwr)
+
+
+ def coh(self, pol=0, polb=None, bl=0, pix=None):
+ """Return the complex coherence for a specified polarization and
+ baseline.
+
+ Arguments:
+ pol: The polarization of the desired coherence. Can be an
+ integer polarization index (0: HH, 1: HV, 2: VV), or a
+ list containing a polarization weight vector with three
+ complex elements, or a string. Allowed strings are 'HH',
+ 'HV', 'VV', 'HH+VV', and 'HH-VV'. Can also set to 'high'
+ or 'pdhigh' or 'low' or 'pdlow' if you want the optimized
+ coherences. In this case, the polb argument will be
+ ignored. Note that the high/low ordering is an
+ assumption, and is not necessarily true unless the
+ ground phase has been determined, and the
+ coherences reordered as a result. Default: 0.
+ polb: If different master and slave track polarizations are
+ desired, specify the slave polarization here. Use same
+ form (int, str, or list) as pol. Default: None (polb=pol).
+ bl (int): Desired baseline index. Default: 0.
+ pix (int): If you only wish to calculate the coherence for a
+ single pixel, specify a tuple with the (azimuth,range) indices
+ of the pixel here.
+
+ Returns:
+ coh (array): A complex coherence image.
+
+ """
+ if polb is None:
+ polb = pol
+
+ if isinstance(pol,str):
+ pol = pol.lower()
+
+ if isinstance(pol,str) and (pol == 'hh'):
+ pol = 0
+ elif isinstance(pol,str) and (pol == 'hv'):
+ pol = 1
+ elif isinstance(pol,str) and (pol == 'vv'):
+ pol = 2
+ elif isinstance(pol,str) and (pol == 'hh+vv'):
+ pol = [np.sqrt(0.5), 0, np.sqrt(0.5)]
+ elif isinstance(pol,str) and (pol == 'hh-vv'):
+ pol = [np.sqrt(0.5), 0, -np.sqrt(0.5)]
+
+
+ if isinstance(polb,str):
+ polb = polb.lower()
+
+ if isinstance(polb,str) and (polb == 'hh'):
+ polb = 0
+ elif isinstance(polb,str) and (polb == 'hv'):
+ polb = 1
+ elif isinstance(polb,str) and (polb == 'vv'):
+ polb = 2
+ elif isinstance(polb,str) and (polb == 'hh+vv'):
+ polb = [np.sqrt(0.5), 0, np.sqrt(0.5)]
+ elif isinstance(polb,str) and (polb == 'hh-vv'):
+ polb = [np.sqrt(0.5), 0, -np.sqrt(0.5)]
+
+
+ if isinstance(pol,str) and ('high' in pol):
+ if self.pdcoh is None:
+ coh = None
+ elif (pix is None) and (self.num_baselines > 1):
+ coh = self.pdcoh[bl, 0]
+ elif (pix is None):
+ coh = self.pdcoh[0]
+ elif self.num_baselines > 1:
+ coh = self.pdcoh[bl,0,pix[0],pix[1]]
+ else:
+ coh = self.pdcoh[0,pix[0],pix[1]]
+ elif isinstance(pol,str) and ('low' in pol):
+ if self.pdcoh is None:
+ coh = None
+ elif (pix is None) and (self.num_baselines > 1):
+ coh = self.pdcoh[bl, 1]
+ elif (pix is None):
+ coh = self.pdcoh[1]
+ elif self.num_baselines > 1:
+ coh = self.pdcoh[bl,1,pix[0],pix[1]]
+ else:
+ coh = self.pdcoh[1,pix[0],pix[1]]
+ elif not isinstance(pol, (collections.Sequence, np.ndarray)) and (pol in range(self.num_pol)):
+ i,j = mb_cov_index(bl, pol=pol, pol2=polb, n_pol=self.num_pol)
+ if pix is None:
+ coh = self.cov[:,:,i,j] / np.sqrt(np.abs(self.cov[:,:,i,i]*self.cov[:,:,j,j]))
+ else:
+ coh = self.cov[pix[0],pix[1],i,j] / np.sqrt(np.abs(self.cov[pix[0],pix[1],i,i]*self.cov[pix[0],pix[1],j,j]))
+ elif isinstance(pol, (collections.Sequence, np.ndarray)) and (len(pol) == self.num_pol):
+ i,j = mb_cov_index(bl, pol=0, n_pol=self.num_pol)
+
+ if pix is None:
+ t11 = self.cov[:,:,i:i+self.num_pol,i:i+self.num_pol]
+ t22 = self.cov[:,:,j:j+self.num_pol,j:j+self.num_pol]
+ om = self.cov[:,:,i:i+self.num_pol,j:j+self.num_pol]
+
+ t11 = makehermitian(t11)
+ t22 = makehermitian(t22)
+
+ wimage = np.ones((self.dim[0],self.dim[1],3,3),dtype='complex')
+
+ wimage[:,:] = np.array([[pol[0]*pol[0],pol[0]*pol[1],pol[0]*pol[2]],
+ [pol[1]*pol[0],pol[1]*pol[1],pol[1]*pol[2]],
+ [pol[2]*pol[0],pol[2]*pol[1],pol[2]*pol[2]]])
+ t11 = np.sum(t11*wimage, axis=(2,3))
+
+ wimage[:,:] = np.array([[polb[0]*polb[0],polb[0]*polb[1],polb[0]*polb[2]],
+ [polb[1]*polb[0],polb[1]*polb[1],polb[1]*polb[2]],
+ [polb[2]*polb[0],polb[2]*polb[1],polb[2]*polb[2]]])
+ t22 = np.sum(t22*wimage, axis=(2,3))
+
+
+ wimage[:,:] = np.array([[pol[0]*polb[0],pol[0]*polb[1],pol[0]*polb[2]],
+ [pol[1]*polb[0],pol[1]*polb[1],pol[1]*polb[2]],
+ [pol[2]*polb[0],pol[2]*polb[1],pol[2]*polb[2]]])
+ om = np.sum(om*wimage, axis=(2,3))
+
+ coh = om / np.sqrt(np.abs(t11*t22))
+ else:
+ t11 = self.cov[pix[0],pix[1],i:i+self.num_pol,i:i+self.num_pol]
+ t22 = self.cov[pix[0],pix[1],j:j+self.num_pol,j:j+self.num_pol]
+ om = self.cov[pix[0],pix[1],i:i+self.num_pol,j:j+self.num_pol]
+
+ t11 = makehermitian(t11)
+ t22 = makehermitian(t22)
+
+ wimage = np.array([[pol[0]*pol[0],pol[0]*pol[1],pol[0]*pol[2]],
+ [pol[1]*pol[0],pol[1]*pol[1],pol[1]*pol[2]],
+ [pol[2]*pol[0],pol[2]*pol[1],pol[2]*pol[2]]])
+ t11 = np.sum(t11*wimage)
+
+ wimage = np.array([[polb[0]*polb[0],polb[0]*polb[1],polb[0]*polb[2]],
+ [polb[1]*polb[0],polb[1]*polb[1],polb[1]*polb[2]],
+ [polb[2]*polb[0],polb[2]*polb[1],polb[2]*polb[2]]])
+ t22 = np.sum(t22*wimage)
+
+
+ wimage = np.array([[pol[0]*polb[0],pol[0]*polb[1],pol[0]*polb[2]],
+ [pol[1]*polb[0],pol[1]*polb[1],pol[1]*polb[2]],
+ [pol[2]*polb[0],pol[2]*polb[1],pol[2]*polb[2]]])
+ om = np.sum(om*wimage)
+
+ coh = om / np.sqrt(np.abs(t11*t22))
+ else:
+ print('kapok.Scene.coh | Unrecognized polarization identifier. Returning None.')
+ coh = None
+
+ return coh
+
+
+ def region(self, az=None, rng=None, mode='basic', bl=0, savefile=None):
+ """Coherence region plotting.
+
+ Creates a plot showing the coherence region in the complex plane.
+ There are two modes. 'basic', the default, simply plots the
+ observed coherence region, the standard Lexicographic and Pauli
+ coherences, the optimized coherences, the line fit, and
+ the estimated ground coherence. 'interactive' creates a
+ coherence region with a UI which allows the user to specify
+ values for the RVoG model parameters and observe the effect
+ they have on the modelled coherences.
+
+ Arguments:
+ az (int): Azimuth index of the pixel to plot.
+ rng (int): Range index of the pixel to plot.
+ mode (str): Mode setting, either 'basic' or 'interactive'.
+ Default: 'basic' if az and rng are specified.
+ 'interactive' otherwise.
+ bl (int): Desired baseline index.
+ savefile (str): Path and filename to save the plot. Only
+ valid for mode == 'basic'.
+
+ """
+ import kapok.region
+
+ if (mode == 'basic') and (az is not None) and (rng is not None):
+ kapok.region.cohregion(self, az, rng, bl=bl, mlwin=self.ml_window, savefile=savefile)
+ else:
+ kapok.region.rvogregion(self, az=az, rng=rng, bl=bl)
+
+ return
+
+
+ def geo(self, data, outfile, outformat='ENVI', resampling='bilinear'):
+ """Output a geocoded raster.
+
+ Resampling from radar coordinates to latitude/longitude using
+ gdalwarp.
+
+ Arguments:
+ data: Either a 2D array containing the data to geocode, or a
+ string identifying an HDF5 dataset in the file.
+ If data is an array, it should have type float32.
+ If not, it will be converted to it. If resampling of
+ complex-valued parameters is needed, geocode the real and
+ imaginary parts separately using this function.
+ outfile (str): The destination filename for the geocoded file.
+ outformat (str): String identifying an output format
+ recognized by GDAL. Default is 'ENVI'. Other options
+ include 'GTiff' or 'KEA', etc. For reference, see
+ http://www.gdal.org/formats_list.html.
+ resampling (str): String identifying the resampling method.
+ Options include 'near', 'bilinear', 'cubic', 'lanczos',
+ and others. Default is 'bilinear'. For reference and
+ more options, see http://www.gdal.org/gdalwarp.html.
+
+ """
+ if isinstance(data, str):
+ data = self.get(data)
+
+ outpath, outfile = os.path.split(outfile)
+
+ kapok.geo.radar2ll(outpath, outfile, data, self.lat[:], self.lon[:], outformat=outformat, resampling=resampling)
+
+ return
+
+
+ def ingest(self, file, name, attrname=None, attrunits='', overwrite=False):
+ """Ingest ancillary data into Kapok HDF5 file.
+
+ Allows the user to import ancillary raster data in ENVI format such as
+ lidar, external DEMs, etc. This external raster data will be
+ resampled to the radar coordinates using bilinear interpolation,
+ then saved to the HDF5 file as datasets with the same dimensions as
+ the radar data. The ingested data can then be compared to the
+ radar-derived products or used in guided inversion functions, etc.
+
+ Data will be stored in the HDF5 file under 'ancillary/', where
+ is the string given in the name argument to this function.
+
+ N.B. The data to import should be in ENVI format, in WGS84 Geographic
+ (latitude, longitude) coordinates.
+
+ Arguments:
+ file (str): Path and filename to the external raster data (in
+ ENVI format). Will be loaded in GDAL.
+ name (str): Name of the HDF5 dataset which will be created to
+ store the ingested data.
+ attrname (str): Name which will be put into a 'name' attribute
+ of the dataset. Will be shown when displaying the data using
+ Scene.show(), etc. Default: Same as name.
+ attrunits (str): Units of the data. Will be shown on plots of the
+ data using Scene.show(), etc.
+ overwrite (bool): Set to True to overwrite an already existing
+ HDF5 dataset, if one already exists under the same name as the
+ name input argument. Default: Do not overwrite.
+
+ Returns:
+ data: A link to the newly created HDF5 dataset containing the
+ ingested data.
+
+ """
+ import osgeo.gdal as gdal
+
+ # Check If Group Exists:
+ if ('ancillary/'+name in self.f) and overwrite:
+ del self.f['ancillary/'+name]
+ elif ('ancillary/'+name in self.f) and (overwrite == False):
+ print('kapok.Scene.ingest | Ancillary data in "ancillary/'+name+'" already exists. If you wish to replace it, set overwrite keyword. Aborting.')
+ return None
+
+ # Load the data using GDAL and resample to radar coordinates:
+ data = gdal.Open(file, gdal.GA_ReadOnly)
+ geodata = data.GetGeoTransform()
+
+ origin = (geodata[3], geodata[0])
+ spacing = (geodata[5], geodata[1])
+
+ data = kapok.geo.ll2radar(data.ReadAsArray(), origin, spacing, self.lat[:], self.lon[:])
+
+ # Create the HDF5 dataset:
+ if np.any(np.iscomplex(data)):
+ data = self.f.create_dataset('ancillary/'+name, data=data, dtype='complex64', compression=self.compression, compression_opts=self.compression_opts)
+ else:
+ data = self.f.create_dataset('ancillary/'+name, data=data, dtype='float32', compression=self.compression, compression_opts=self.compression_opts)
+
+ if attrname is None:
+ attrname = name
+ data.attrs['name'] = attrname
+ data.attrs['units'] = attrunits
+
+ self.f.flush()
+
+ return data
\ No newline at end of file
diff --git a/kapok/lib/__init__.py b/kapok/lib/__init__.py
new file mode 100755
index 0000000..412eea1
--- /dev/null
+++ b/kapok/lib/__init__.py
@@ -0,0 +1,8 @@
+# -*- coding: utf-8 -*-
+"""Library containing utility/convenience functions."""
+
+from .coords import *
+from .interp import *
+from .matrix import *
+from .mb import *
+from .win import *
\ No newline at end of file
diff --git a/kapok/lib/coords.py b/kapok/lib/coords.py
new file mode 100755
index 0000000..3e77700
--- /dev/null
+++ b/kapok/lib/coords.py
@@ -0,0 +1,418 @@
+# -*- coding: utf-8 -*-
+"""Coordinate system and transformation library.
+
+ All units are in radians and meters.
+
+ Classes:
+ Ellipsoid
+ Peg: Longitude, Latitude, Heading, Local Radius, in [rad, rad, rad, m]
+ LLH: Longitude, Latitude, Height, in [rad, rad, h]
+ XYZ: ECEF/XYZ system (Z=North, X=prime meridian, Y), in [m, m, m]
+ SCH: Along-track (along Peg-heading), cross-track, and height, in
+ [m, m, m]
+ ENU: Local East, North, UP: x, y, z, relative to reference position
+ (Peg)
+
+ Notes:
+ 1. LLH are represented as Longitude, Latitude, and Height (right-hand
+ system, x-y-z).
+ 2. In this module Longitude and Latitude, as well as all other angles,
+ are in radians.
+ 3. Heading is from North, in clockwise direction.
+
+ References:
+ T. H. Meyer. Introduction to geometrical and physical geodesy:
+ foundations of geomatics. ESRI Press, Redlands, California, 2010.
+
+ Author: Maxim Neumann
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+
+import numpy as np
+from numpy import (array, sqrt, sin, cos, arcsin, arctan, arctan2, degrees)
+
+
+class Ellipsoid:
+ """Ellipsoid representation."""
+ def __init__ (self, semimajor_axis=None, eccentricity_sq=None,
+ semiminor_axis=None, select='WGS84', name=""):
+ """Expects 'semimajor_axis' and ('eccentricity_sq' or
+ 'semiminor_axis'), or a predefined ellipsoid with 'select'."""
+ if semimajor_axis is None:
+ if select == 'WGS84':
+ semimajor_axis = 6378137.
+ eccentricity_sq = 0.00669437999015
+ name = select
+ else:
+ print("Unknown select ellipsoid")
+ raise Exception
+ if eccentricity_sq is None and semiminor_axis is not None:
+ eccentricity_sq = 1. - (semiminor_axis / semimajor_axis)**2
+ self.a = self.semimajor_axis = semimajor_axis
+ self.e2 = self.eccentricity_sq = eccentricity_sq
+ self.e = self.eccentricy = sqrt(self.e2)
+ self.b = self.semiminor_axis = self.a * sqrt(1. - self.e2)
+ self.f = self.flattening = 1. - sqrt(1. - self.e2)
+ self.ep2 = self.ep_squared = self.e2 / (1. - self.e2)
+ self.name = name
+
+ def radius_east(self, lat):
+ """Radius of curvature in the east direction (lat in radians).
+ Also called 'Radius of curvature in the prime vertical' N."""
+ return self.a / sqrt(1. - self.e2 * sin(lat)**2)
+
+ def radius_north(self, lat):
+ """Radius of curvature in the north direction (lat in radians).
+ Also called 'Radius of curvature in the meridian' M."""
+ return (self.a*(1.-self.e2) / (1.-self.e2*sin(lat)**2)**1.5)
+
+ def radius_local(self, lat, hdg):
+ """Local radius of curvature along heading (lat, hdg in radians)
+ Heading is from North (y, lat)!
+ It is related to the 'Radius of curvature in the normal section',
+ except of the different definition for the hdg/azimuth angle
+ (shifted by 90 degrees).
+ """
+ er = self.radius_east(lat)
+ nr = self.radius_north(lat)
+ return er * nr / (er * cos(hdg)**2 + nr * sin(hdg)**2)
+
+
+# Default ellipsoid
+WGS84 = Ellipsoid(select="WGS84")
+
+
+class Peg:
+ """Peg representation.
+
+ Attributes
+ ----------
+ lon : radians
+ Longitude, in radians
+ lat : radians
+ Geodetic Latitude, in radians
+ hdg : radians
+ Heading, in radians, from North, probably in clockwise direction(?).
+ radius : m
+ Local Earth radius, in m
+ ellipsoid : Ellipsoid, optional
+ Ellipsoid object. Default is WGS-84.
+ """
+
+ def __init__(self, lon, lat, hdg, ellipsoid=WGS84):
+ self.lon = lon
+ self.lat = lat
+ self.hdg = hdg
+ self.radius = ellipsoid.radius_local(lat, hdg)
+ self.ellipsoid = ellipsoid
+ self._update_transformations()
+ def _update_transformations(self):
+ slon, clon = sin(self.lon), cos(self.lon)
+ slat, clat = sin(self.lat), cos(self.lat)
+ shdg, chdg = sin(self.hdg), cos(self.hdg)
+ xyzP_to_enu = array([[0, shdg, -chdg],
+ [0, chdg, shdg],
+ [1, 0, 0]])
+ enu_to_xyz = enu_to_xyz_matrix(self.lon, self.lat)
+ self.rotation_matrix = enu_to_xyz.dot(xyzP_to_enu)
+ re = self.ellipsoid.radius_east(self.lat)
+ p = array([re * clat * clon,
+ re * clat * slon,
+ re * (1.0 - self.ellipsoid.e2) * slat])
+ up = self.radius * enu_to_xyz[:,2] # just take the third up vector
+ self.translation_vector = p - up
+ def __call__(self):
+ return array([self.lon, self.lat, self.hdg])
+ def __repr__(self):
+ return("Peg Lon: {:.3f} deg; Lat: {:.3f}; Heading: {:.1f} deg"
+ .format(degrees(self.lon),degrees(self.lat),degrees(self.hdg)))
+
+
+class LLH:
+ """Longitude, geodetic Latitude, Height (lon, lat in radians).
+
+ Parameters
+ ----------
+ lon : float, array_like
+ Longitude, in radians([-180, 180])
+ lat : float, array_like
+ Geodetic latitude, in radians([-90, 90])
+ h : float, array_like
+ Height above ellipsoid, in meters
+ """
+ def __init__(self, lon, lat, h=None):
+ self.lon = lon
+ self.lat = lat
+ self.h = h if h is not None else (lon * 0.)
+ def __call__(self):
+ return array([self.lon, self.lat, self.h])
+ def __repr__(self):
+ return("Lon: {:.3f} deg; Lat: {:.3f}; Height: {:.1f} m"
+ .format(degrees(self.lon),degrees(self.lat),self.h))
+ def xyz(self, ellipsoid=WGS84):
+ """Transform to ECEF XYZ coordinates."""
+ r = ellipsoid.radius_east(self.lat)
+ x = (r + self.h) * cos(self.lat) * cos(self.lon)
+ y = (r + self.h) * cos(self.lat) * sin(self.lon)
+ z = (r * (1. - ellipsoid.e2) + self.h) * sin(self.lat)
+ return XYZ(x, y, z, ellipsoid)
+ def enu(self, o_xyz=None, o_llh=None, ellipsoid=WGS84):
+ """Transform to ENU, given ENU origin point o."""
+ if o_xyz is not None: ellipsoid = o_xyz.ellipsoid
+ return self.xyz(ellipsoid).enu(o_xyz=o_xyz,o_llh=o_llh)
+ def sch(self, peg):
+ """Transform to SCH coordinates, given Peg."""
+ return self.xyz(peg.ellipsoid).sch(peg)
+
+
+class XYZ:
+ """ECEF XYZ cartesian geocentric coordinates.
+
+ Parameters
+ ----------
+ x : float, array_like
+ In direction of prime meridian (lon=0, lat=0).
+ y : float, array_like
+ In direction lon=90, lat=0
+ z : float, array_like
+ Close to the rotation axis, with direction North (lat=90).
+ """
+ def __init__(self, x, y, z, ellipsoid=WGS84):
+ self.x = x
+ self.y = y
+ self.z = z
+ self.ellipsoid = ellipsoid
+ def __repr__(self):
+ return("x: {} y: {} z: {}".format(*self()))
+ def __call__(self):
+ return array([self.x, self.y, self.z])
+ def sch(self, peg):
+ """Transform to SCH coordinates, given Peg."""
+ xyzP = peg.rotation_matrix.T.dot(
+ array([self.x,self.y,self.z])-peg.translation_vector)
+ r = np.linalg.norm(xyzP)
+ h = r - peg.radius
+ c = peg.radius * arcsin(xyzP[2] / r)
+ s = peg.radius * arctan2(xyzP[1], xyzP[0])
+ return SCH(peg, s, c, h)
+ def llh(self):
+ lon = arctan2(self.y, self.x)
+ pr = sqrt(self.x**2 + self.y**2) # projected radius
+ alpha = arctan(self.z / (pr * sqrt(1.-self.ellipsoid.e2)))
+ lat = arctan(
+ (self.z + self.ellipsoid.ep2 * self.ellipsoid.b * sin(alpha)**3)
+ /(pr - self.ellipsoid.e2 * self.ellipsoid.a * cos(alpha)**3))
+ h = pr / cos(lat) - self.ellipsoid.radius_east(lat)
+ return LLH(lon,lat,h)
+ def enu(self, o_xyz=None, o_llh=None):
+ """Transform to ENU, given ENU origin point o (in XYZ!).
+ At least o_xyz or o_llh have to be provided!"""
+ if o_llh is None: o_llh = o_xyz.llh()
+ if o_xyz is None: o_xyz = o_llh.xyz(ellipsoid=self.ellipsoid)
+ enu_to_xyz = enu_to_xyz_matrix(o_llh.lon, o_llh.lat)
+ return ENU(*enu_to_xyz.T.dot(self()-o_xyz()),o_llh=o_llh,o_xyz=o_xyz)
+
+
+class ENU:
+ """ENU cartesian coordinate system.
+
+ East-North-Up (ENU) coordinate system: cartesian similar to XYZ, just
+ translated to origin point O, and rotated to align with the ENU axes.
+
+ Parameters
+ ----------
+ e : float
+ n : float
+ u : float
+ o_llh : LLH
+ Origin given in LLH.
+ o_xyz : XYZ
+ Origin given in XYZ.
+ """
+ def __init__(self, e, n, u, o_llh=None, o_xyz=None, ellipsoid=WGS84):
+ """At least one of the origin points, o_llh and o_xyz,
+ have to be provided."""
+ self.e = e
+ self.n = n
+ self.u = u
+ if o_llh is None: o_llh = o_xyz.llh()
+ if o_xyz is None: o_xyz = o_llh.xyz(ellipsoid)
+ self.o_llh = o_llh
+ self.o_xyz = o_xyz
+ def xyz(self):
+ enu_to_xyz = enu_to_xyz_matrix(self.o_llh.lon, self.o_llh.lat)
+ return XYZ(*enu_to_xyz.dot(self())+self.o_xyz,
+ ellipsoid=self.o_xyz.ellipsoid)
+ def llh(self):
+ return self.xyz().llh()
+
+
+class SCH:
+ """Radar-related spherical coordinate system.
+
+ It is referenced to the Peg position, determining the s and c directions,
+ and height values.
+
+ Parameters
+ ----------
+ peg: Peg
+ Peg object, determing the directions of s and c coordinates.
+ s : float, array_like
+ Along-track curved distance, at the ground, in m.
+ c : float, array_like
+ Cross-track curved distance, at the ground, in m. Positive is left of s.
+ h : float, array_like
+ Height above peg sphere (?), in m.
+
+ """
+ def __init__(self, peg, s=None, c=None, h=None):
+ self.peg = peg
+ self.s = s
+ self.c = c
+ self.h = h
+ def __repr__(self):
+ return("s: {} c: {} h: {}".format(*self()))
+ def __call__(self):
+ return array([self.s, self.c, self.h])
+ def llh(self):
+ """Transform to LLH coordinates."""
+ return self.xyz().llh()
+ def xyz(self):
+ """Transform SCH point to XYZ ECEF point."""
+ c_angle = self.c / self.peg.radius
+ s_angle = self.s / self.peg.radius
+ r = self.peg.radius + self.h
+ # from spherical to cartesian
+ xyz_local = array ([r * cos (c_angle) * cos (s_angle),
+ r * cos (c_angle) * sin (s_angle),
+ r * sin (c_angle)])
+ # from local xyz to ECEF xyz
+ xyz = self.peg.rotation_matrix.dot(xyz_local) + self.peg.translation_vector
+ return XYZ(xyz[0], xyz[1], xyz[2], self.peg.ellipsoid)
+
+
+class LookVectorSCH(SCH):
+ """Geometry of a look vector given in SCH coordinates.
+
+ Meant only as reference. This look vector is given from platform to target:
+ lv = sch_target - sch_platform
+
+ Note: by default, the full 3d, non-normalized, vector is considered. Either
+ project to incidence plane individually or use appropriate methods.
+
+ Parameterizing the look vector in SCH coordinates:
+ [ sin(inc_l) sin(az) ] [ S ]
+ \hat\l = [ sin(inc_l) cos(az) ] = [ C ]
+ [ -cos(inc_l) ] [ H ]
+ """
+ def __init__(self, sch):
+ SCH.__init__(self, sch.peg, sch.s, sch.c, sch.h)
+ def range(self):
+ if "r" not in self.__dict__:
+ self.r = np.linalg.norm(self())
+ return self.r
+ def incidence_plane_look_angle(self):
+ return np.arccos(-self.h/r)
+
+
+
+def enu_to_xyz_matrix(lon, lat):
+ """ENU to XYZ rotation matrix.
+
+ Also the rotation matrix from sch_hat to xyz_prime (with lon=S, lat=C,
+ both S and C in radians, i.e. s/r, and c/r).
+
+ """
+ slon, clon = sin(lon), cos(lon)
+ slat, clat = sin(lat), cos(lat)
+ enu_to_xyz = array([[-slon, -slat * clon, clat * clon],
+ [ clon, -slat * slon, clat * slon],
+ [ 0, clat, slat ]])
+ return enu_to_xyz
+
+
+def sch2enu(s, c, h, peglat, peglon, peghdg):
+ """Quick conversion from SCH to ENU coordinates.
+
+ Convert a point in the SCH coordinate system to ENU (East-North-Up)
+ coordinates, given the SCH peg location and heading.
+
+ Arguments:
+ s: Array containing S values, in meters.
+ c: Array containing C values, in meters.
+ h: Array containing H values, in meters.
+ peglat: Latitude of the SCH peg, in radians.
+ peglon: Longitude of the SCH peg, in radians.
+ peghdg: Heading of the SCH peg, in radians.
+
+ Returns:
+ enu: Array containing ENU values, in meters. Has dimensions (x,3)
+ if s, c, and h are arrays, where x is len(s). If s, c, and h are
+ scalar, enu has dimensions of (3).
+
+ """
+ s = np.array(s)
+ c = np.array(c)
+ h = np.array(h)
+
+ # Create origin peg object:
+ peg = np.array([peglon, peglat, peghdg])
+ peg = Peg(*peg)
+
+ # Make images of the S and C angles (s/peg.radius and c/peg.radius)
+ s_angle = s / peg.radius
+ c_angle = c / peg.radius
+ r = peg.radius + h
+ xl = r * np.cos(c_angle) * np.cos(s_angle)
+ yl = r * np.cos(c_angle) * np.sin(s_angle)
+ zl = r * np.sin(c_angle)
+
+ # From local XYZ to ECEF XYZ:
+ x = (peg.rotation_matrix[0,0]*xl + peg.rotation_matrix[0,1]*yl + peg.rotation_matrix[0,2]*zl) + peg.translation_vector[0]
+ y = (peg.rotation_matrix[1,0]*xl + peg.rotation_matrix[1,1]*yl + peg.rotation_matrix[1,2]*zl) + peg.translation_vector[1]
+ z = (peg.rotation_matrix[2,0]*xl + peg.rotation_matrix[2,1]*yl + peg.rotation_matrix[2,2]*zl) + peg.translation_vector[2]
+ del xl,yl,zl
+
+ # From ECEF XYZ to ENU:
+ originllh = LLH(peg()[0],peg()[1],0)
+ originxyz = originllh.xyz(ellipsoid=peg.ellipsoid)
+
+ x -= originxyz()[0]
+ y -= originxyz()[1]
+ z -= originxyz()[2]
+
+ enumatrix = enu_to_xyz_matrix(peg()[0], peg()[1])
+ enumatrix = enumatrix.T
+
+ e = enumatrix[0,0]*x + enumatrix[0,1]*y + enumatrix[0,2]*z
+ n = enumatrix[1,0]*x + enumatrix[1,1]*y + enumatrix[1,2]*z
+ u = enumatrix[2,0]*x + enumatrix[2,1]*y + enumatrix[2,2]*z
+
+ if len(e.shape) > 0:
+ enu = np.zeros((e.shape[0],3),dtype='float32')
+ enu[:,0] = e
+ enu[:,1] = n
+ enu[:,2] = u
+ else:
+ enu = np.zeros((3),dtype='float32')
+ enu[0] = e
+ enu[1] = n
+ enu[2] = u
+
+ return enu
\ No newline at end of file
diff --git a/kapok/lib/interp.py b/kapok/lib/interp.py
new file mode 100755
index 0000000..fe44cd8
--- /dev/null
+++ b/kapok/lib/interp.py
@@ -0,0 +1,79 @@
+# -*- coding: utf-8 -*-
+"""Interpolation functions.
+
+ Author: Michael Denbina
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import numpy as np
+
+
+def bilinear_interpolate(data, x, y):
+ """Function to perform bilinear interpolation on the input array data, at
+ the image coordinates given by input arguments x and y.
+
+ Arguments
+ data (array): 2D array containing raster data to interpolate.
+ x (array): the X coordinate values at which to interpolate (in array
+ indices, starting at zero). Note that X refers to the second
+ dimension of data (e.g., the columns).
+ y (array): the Y coordinate values at which to interpolate (in array
+ indices, starting at zero). Note that Y refers to the first
+ dimension of data (e.g., the rows).
+
+ Returns:
+ intdata (array): The 2D interpolated array, with same dimensions as
+ x and y.
+
+ """
+ x = np.asarray(x)
+ y = np.asarray(y)
+
+ # Get lower and upper bounds for each pixel.
+ x0 = np.floor(x).astype(int)
+ x1 = x0 + 1
+ y0 = np.floor(y).astype(int)
+ y1 = y0 + 1
+
+ # Clip the image coordinates to the size of the input data.
+ x0 = np.clip(x0, 0, data.shape[1]-1);
+ x1 = np.clip(x1, 0, data.shape[1]-1);
+ y0 = np.clip(y0, 0, data.shape[0]-1);
+ y1 = np.clip(y1, 0, data.shape[0]-1);
+
+ data_ll = data[ y0, x0 ] # lower left corner image values
+ data_ul = data[ y1, x0 ] # upper left corner image values
+ data_lr = data[ y0, x1 ] # lower right corner image values
+ data_ur = data[ y1, x1 ] # upper right corner image values
+
+ w_ll = (x1-x) * (y1-y) # weight for lower left value
+ w_ul = (x1-x) * (y-y0) # weight for upper left value
+ w_lr = (x-x0) * (y1-y) # weight for lower right value
+ w_ur = (x-x0) * (y-y0) # weight for upper right value
+
+ # Where the x or y coordinates are outside of the image boundaries, set one
+ # of the weights to nan, so that these values are nan in the output array.
+ w_ll[np.less(x,0)] = np.nan
+ w_ll[np.greater(x,data.shape[1]-1)] = np.nan
+ w_ll[np.less(y,0)] = np.nan
+ w_ll[np.greater(y,data.shape[0]-1)] = np.nan
+
+ intdata = w_ll*data_ll + w_ul*data_ul + w_lr*data_lr + w_ur*data_ur
+
+ return intdata
+
\ No newline at end of file
diff --git a/kapok/lib/matrix.py b/kapok/lib/matrix.py
new file mode 100755
index 0000000..9f70ce1
--- /dev/null
+++ b/kapok/lib/matrix.py
@@ -0,0 +1,49 @@
+# -*- coding: utf-8 -*-
+"""Covariance matrix helper functions.
+
+ Author: Michael Denbina
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import numpy as np
+
+
+def makehermitian(m):
+ """Given a matrix with elements below the diagonal equal to zero, fill
+ those elements assuming the matrix is Hermitian. Note: Changes array
+ in place! (But also returns it.)
+
+ Arguments:
+ m (array): Matrices to make Hermitian. Should have dimensions:
+ [az, rng, n, n]. n is the number of rows and columns in the
+ matrix (which need to be equal).
+
+ Returns:
+ m (array): Hermitian symmetric form of input.
+
+ """
+ if m.ndim == 4:
+ for row in range(1,m.shape[2]):
+ for col in range(0,row):
+ m[:,:,row,col] = np.conj(m[:,:,col,row])
+ else:
+ for row in range(1,m.shape[0]):
+ for col in range(0,row):
+ m[row,col] = np.conj(m[col,row])
+
+ return m
\ No newline at end of file
diff --git a/kapok/lib/mb.py b/kapok/lib/mb.py
new file mode 100755
index 0000000..6a929b8
--- /dev/null
+++ b/kapok/lib/mb.py
@@ -0,0 +1,91 @@
+# -*- coding: utf-8 -*-
+"""Multibaseline indexing functions.
+
+ Conventions:
+ Covariance matrix dimensions: [az, rg, pol*tr, pol*tr]
+ Baseline-independent data dimensions (e.g., inc): [az, rng]
+ Baseline-dependent data dimensions (e.g., kz): [bl, az, rng]
+ Phase diversity coherence dimensions: [bl, 2, az, rng]
+
+ Baselines are numbered such that adding new tracks does not change the
+ ordering of currently existing baselines.
+
+ Omega matrix locations for each baseline index (baselines considered
+ for i.
+
+"""
+import numpy as np
+
+
+def mb_n_baseline(n_tr):
+ """Returns number of baselines, based on given number of tracks"""
+ return int(n_tr * (n_tr-1) / 2)
+
+
+def mb_n_track(n_bl):
+ """Returns number of tracks, based on given number of baselines"""
+ return ((1 + np.sqrt(1 + 8*n_bl))/2).astype('int')
+
+
+def mb_tr_index(bl):
+ """Returns tuple of track indices for a specified baseline.
+
+ Based on the triangular number calculations.
+ """
+ j = np.floor((1+np.sqrt(1+8*(bl)))/2).astype(int)
+ i = (bl - j*(j-1)/2).astype(int)
+ return (i,j)
+
+
+def mb_bl_index(tr1, tr2):
+ """Returns the baseline index for given track indices.
+
+ By convention, tr1 < tr2. Otherwise, a warning is printed,
+ and same baseline returned.
+ """
+ if tr1 == tr2:
+ print("ERROR: no baseline between same tracks")
+ return None
+ if tr1 > tr2:
+ print("WARNING: tr1 exoected < than tr2")
+ mx = max(tr1, tr2)
+ bl = np.array(mx*(mx-1)/2 + min(tr1, tr2))
+ return bl.astype(int)
+
+
+def mb_cov_index(bl, pol=0, pol2=None, n_pol=3):
+ """Returns i,j covariance matrix indices for given baseline and pol index.
+
+ If polb is not given, then same polarization is assumed (e.g. HH-HH, vs. HH-VV)
+ """
+ t1, t2 = mb_tr_index(bl)
+ p1, p2 = pol, pol if pol2 is None else pol2
+
+ return (t1*n_pol + p1, t2*n_pol + p2)
\ No newline at end of file
diff --git a/kapok/lib/win.py b/kapok/lib/win.py
new file mode 100755
index 0000000..39de46e
--- /dev/null
+++ b/kapok/lib/win.py
@@ -0,0 +1,90 @@
+# -*- coding: utf-8 -*-
+"""Windowing library functions (rebinning and smoothing).
+
+ Author: Maxim Neumann
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import numpy as np
+import scipy.ndimage
+
+def mlook(data, mlwin):
+ """Multilook/rebin image to smaller image by averaging.
+
+ Arguments:
+ data: Array (up to 4D) containing data to multilook.
+ mlwin (tuple, int): Tuple of ints containing the smoothing window
+ sizes in each dimension.
+
+ Returns:
+ mldata: Array containing multilooked data.
+
+ """
+ if mlwin == (1,1):
+ return data
+
+ data = np.asarray(data)
+ n_dim = len(data.shape)
+
+ nshape = np.array(data.shape) // np.array(list(mlwin) + [1]*(n_dim-len(mlwin)))
+
+ sh = np.array([ [nshape[i], data.shape[i]//nshape[i]] for i,x in enumerate(nshape) ]).flatten()
+
+ if n_dim == 2:
+ if not any(np.mod(data.shape, nshape)):
+ return data.reshape(sh).mean(-1).mean(1)
+ else:
+ return data[0:sh[0]*sh[1],0:sh[2]*sh[3]].reshape(sh).mean(-1).mean(1)
+ elif n_dim == 3:
+ if not any(np.mod(data.shape, nshape)):
+ return data.reshape(sh).mean(1).mean(2).mean(3)
+ else:
+ return data[0:sh[0]*sh[1],0:sh[2]*sh[3],0:sh[4]*sh[5]]\
+ .reshape(sh).mean(1).mean(2).mean(3)
+ elif n_dim == 4:
+ if not any(np.mod(data.shape, nshape)):
+ return data.reshape(sh).mean(1).mean(2).mean(3).mean(4)
+ else:
+ return data[0:sh[0]*sh[1],0:sh[2]*sh[3],0:sh[4]*sh[5],0:sh[6]*sh[7]]\
+ .reshape(sh).mean(1).mean(2).mean(3).mean(4)
+ else:
+ print('Error in mlook: given number of dimensions not considered.')
+
+
+def smooth(data, smwin, **kwargs):
+ """Smoothing with a boxcar moving average. Uses
+ scipy.ndimage.uniform_filter.
+
+ Arguments:
+ data: Array containing data to smooth.
+ smwin (tuple, int): Tuple of ints containing the smoothing window
+ sizes in each dimension.
+
+ Returns:
+ smdata: Array containing boxcar averaged data.
+
+ """
+ if smwin == (1,1):
+ return data
+ elif type(data[0,0]) in [complex,np.complex64,np.complex128]:
+ res = np.empty(data.shape, dtype=complex)
+ res.real = scipy.ndimage.uniform_filter(np.real(data), smwin, **kwargs)
+ res.imag = scipy.ndimage.uniform_filter(np.imag(data), smwin, **kwargs)
+ return res
+ else:
+ return scipy.ndimage.uniform_filter(data, smwin, **kwargs)
diff --git a/kapok/region.py b/kapok/region.py
new file mode 100755
index 0000000..9325ddd
--- /dev/null
+++ b/kapok/region.py
@@ -0,0 +1,363 @@
+# -*- coding: utf-8 -*-
+"""Coherence Region Plotting
+
+ Module containing functions for coherence region plotting, including
+ interactive coherence regions that show the modelled coherences for
+ user-specified parameter values.
+
+ Author: Michael Denbina
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import numpy as np
+import matplotlib.pyplot as plt
+import matplotlib.widgets as widgets
+
+import kapok.cohopt
+import kapok.topo
+from kapok.lib import makehermitian, mb_cov_index
+
+
+sliders = [] # array to store slider objects for interactive coherence region (if we don't keep a reference to them, they can become unresponsive)
+
+
+def cohregion(scene, az, rng, bl=0, mlwin=None, title=None, savefile=None):
+ """Plot a coherence region for a given covariance matrix.
+
+ The following coherences are plotted: HH, HV, VV, HH+VV, HH-VV
+ (e.g., all the standard Lexicographic and Pauli coherences), as
+ different colored dots. The coherence region boundary itself is
+ plotted as a solid blue line. The high and low optimized coherences
+ are plotted as brown and dark green dots. The line fit through the
+ optimized coherences is plotted as a dashed green line, with the
+ estimated ground coherence shown as a black dot. The alternate
+ ground solution which wasn't chosen is shown as an orange dot.
+
+ Arguments:
+ scene (object): A kapok.Scene object containing covariance matrix and
+ other data.
+ az (int): Azimuth index of the plotted coherence region.
+ rng (int): Range index of the plotted coherence region.
+ bl (int): Baseline index of the plotted coherence region.
+ mlwin (tuple): Multilooking window size of the data. If
+ specified, the original SLC coordinates of the region will be
+ annotated on the plot.
+ title (str): Title string to put at the top of the plot.
+ savefile (str): Path and filename to save the figure, if desired.
+
+ """
+ row, col = mb_cov_index(bl)
+
+ tm = makehermitian(0.5*(scene.cov[az,rng,row:row+scene.num_pol,row:row+scene.num_pol]
+ + scene.cov[az,rng,col:col+scene.num_pol,col:col+scene.num_pol]))
+ om = scene.cov[az,rng,row:row+scene.num_pol,col:col+scene.num_pol]
+
+ gammahigh, gammalow, gammaall = kapok.cohopt.pdopt_pixel(tm, om)
+ gammahh = scene.coh(pol=0, bl=bl, pix=(az,rng))
+ gammahv = scene.coh(pol=1, bl=bl, pix=(az,rng))
+ gammavv = scene.coh(pol=2, bl=bl, pix=(az,rng))
+ gammahhpvv = scene.coh(pol=[1,0,1], bl=bl, pix=(az,rng))
+ gammahhmvv = scene.coh(pol=[1,0,-1], bl=bl, pix=(az,rng))
+
+ if scene.num_baselines > 1:
+ kz = scene.kz[bl,az,rng]
+ else:
+ kz = scene.kz[az,rng]
+
+
+ # Create the figure.
+ plt.figure()
+ fig = plt.gcf()
+ plt.hold(True)
+
+
+ # Circles with 0.25, 0.5, 0.75, and 1.0 radius.
+ unitcirc = plt.Circle((0,0),1,color='k',fill=False,linestyle='dashed')
+ threequartercirc = plt.Circle((0,0),0.75,color='k',fill=False,linestyle='dashed')
+ halfcirc = plt.Circle((0,0),0.5,color='k',fill=False,linestyle='dashed')
+ quartercirc = plt.Circle((0,0),0.25,color='k',fill=False,linestyle='dashed')
+ fig.gca().add_artist(unitcirc)
+ fig.gca().add_artist(threequartercirc)
+ fig.gca().add_artist(halfcirc)
+ fig.gca().add_artist(quartercirc)
+
+
+ # Do a line fit to get the ground coherences.
+ gammatemp = np.zeros((2,2,2),dtype='complex')
+ gammatemp[0,:,:] = gammahigh
+ gammatemp[1,:,:] = gammalow
+ ground, groundalt, volindex = kapok.topo.groundsolver(gammatemp, kz=kz, returnall=True, silent=True)
+ if volindex[0,0]: # swap high and low coherences
+ temp = gammahigh
+ gammahigh = gammalow
+ gammalow = temp
+
+ ground = ground[0,0]
+ groundalt = groundalt[0,0]
+
+ # Plot region.
+ plt.plot(np.real(gammaall),np.imag(gammaall),'-',markersize=8,label='Region')
+
+ # Plot the fitted line.
+ gammaline = np.array((ground,gammalow,gammahigh),dtype='complex')
+ plt.plot(np.real(gammaline),np.imag(gammaline),'--g',label='Line Fit')
+
+
+ # Plot Lexicographic and Pauli coherences.
+ plt.plot(np.real(gammahh),np.imag(gammahh),'.r',markersize=20,label='HH')
+ plt.plot(np.real(gammavv),np.imag(gammavv),'.b',markersize=20,label='VV')
+ plt.plot(np.real(gammahv),np.imag(gammahv),'.',color='LightGreen',markersize=20,label='HV')
+ plt.plot(np.real(gammahhpvv),np.imag(gammahhpvv),'.c',markersize=20,label='HH+VV')
+ plt.plot(np.real(gammahhmvv),np.imag(gammahhmvv),'.m',markersize=20,label='HH-VV')
+
+ # Plot optimized high and low coherences.
+ plt.plot(np.real(gammahigh),np.imag(gammahigh),'.',color='DarkGreen',markersize=20,label='PD High')
+ plt.plot(np.real(gammalow),np.imag(gammalow),'.',color='Maroon',markersize=20,label='PD Low')
+
+ # Plot ground coherences.
+ plt.plot(np.real(ground),np.imag(ground),'.k',markersize=20,label='Ground')
+ plt.plot(np.real(groundalt),np.imag(groundalt),'.',color='Orange',markersize=20,label='Alt. Ground')
+
+ # Text label SLC coordinates, if appropriate.
+ if mlwin is not None:
+ azslc = (mlwin[0]*az, mlwin[0]*az + (mlwin[0]-1))
+ rngslc = (mlwin[1]*rng, mlwin[1]*rng + (mlwin[1]-1))
+ plt.text(0.975,0.94,'SLC Coordinates', fontsize=10, horizontalalignment='right')
+ plt.text(0.975,0.89,'Azimuth: '+str(azslc[0])+'—'+str(azslc[1]), fontsize=10, horizontalalignment='right')
+ plt.text(0.975,0.84,'Range: '+str(rngslc[0])+'—'+str(rngslc[1]), fontsize=10,horizontalalignment='right')
+
+
+ # Plot Title
+ if title is None:
+ plt.title('Coherence Region for Pixel ('+str(az)+', '+str(rng)+')')
+ else:
+ plt.title(title)
+
+ plt.xlabel('Real')
+ plt.ylabel('Imaginary')
+
+
+
+ fig.gca().set_aspect('equal')
+ plt.xlim(-1,1)
+ plt.ylim(-1,1)
+ plt.legend(bbox_to_anchor=(1, 1), bbox_transform=plt.gcf().transFigure, numpoints=1)
+ if savefile is not None:
+ plt.savefig(savefile, dpi=200, bbox_inches='tight', pad_inches=0.1)
+
+ return
+
+
+def rvogregion(scene=None, az=None, rng=None, bl=0):
+ """Interactive coherence region plot with sliders for the RVoG model
+ parameters.
+
+ Create an interactive coherence region plot to observe the affect
+ of the RVoG model parameters on the modelled coherences. If a
+ Scene object and azimuth and range indices are provided, the
+ coherence region and associated coherences from the data will be
+ plotted, and the model parameters can be adjusted to see how the
+ model fits the data. If a Scene object is not provided, the
+ RVoG modelled coherences are still plotted, but without any
+ observed data. In this case, the function will use a fixed kz
+ value of 0.10 rad/m, a fixed incidence angle of 45 degrees, and
+ a fixed ground phase of 0.
+
+ The sliders allow the user to change the following parameter values:
+ hv (forest height, in meters), extinction (in dB/meter), the mu
+ (ground-to-volume scattering ratio) for the low coherence, and
+ alpha (the volumetric temporal decorrelation magnitude).
+
+ The modelled coherences are plotted in black. A dashed line
+ shows the coherence values for a range of forest height values,
+ starting at 0.01 m and increasing up towards the forest height
+ specified by the user. The volume coherence (mu = 0, no ground
+ contribution) is shown as a black X. This black X is connected
+ to the modelled low coherence (another black X) with a solid black
+ line.
+
+ Arguments:
+ scene (object): A kapok.Scene object containing covariance matrix
+ and other data. If not specified, no actual observed data
+ or coherence region will be plotted, but the modelled
+ coherences and UI will still be functional.
+ az (int): Azimuth index of the plotted coherence region.
+ rng (int): Range index of the plotted coherence region.
+ bl (int): Baseline index of the plotted coherence region.
+
+ """
+ # Create the figure.
+ fig, ax = plt.subplots()
+ plt.subplots_adjust(bottom=0.3)
+ plt.hold(True)
+
+
+ # Circles with 0.25, 0.5, 0.75, and 1.0 radius.
+ unitcirc = plt.Circle((0,0),1,color='k',fill=False,linestyle='dashed')
+ threequartercirc = plt.Circle((0,0),0.75,color='k',fill=False,linestyle='dashed')
+ halfcirc = plt.Circle((0,0),0.5,color='k',fill=False,linestyle='dashed')
+ quartercirc = plt.Circle((0,0),0.25,color='k',fill=False,linestyle='dashed')
+ fig.gca().add_artist(unitcirc)
+ fig.gca().add_artist(threequartercirc)
+ fig.gca().add_artist(halfcirc)
+ fig.gca().add_artist(quartercirc)
+
+
+ if (scene is not None) and (az is not None) and (rng is not None):
+ row, col = mb_cov_index(bl)
+
+ tm = makehermitian(0.5*(scene.cov[az,rng,row:row+scene.num_pol,row:row+scene.num_pol]
+ + scene.cov[az,rng,col:col+scene.num_pol,col:col+scene.num_pol]))
+ om = scene.cov[az,rng,row:row+scene.num_pol,col:col+scene.num_pol]
+
+ gammahigh, gammalow, gammaall = kapok.cohopt.pdopt_pixel(tm, om)
+ gammahh = scene.coh(pol=0, bl=bl, pix=(az,rng))
+ gammahv = scene.coh(pol=1, bl=bl, pix=(az,rng))
+ gammavv = scene.coh(pol=2, bl=bl, pix=(az,rng))
+ gammahhpvv = scene.coh(pol=[1,0,1], bl=bl, pix=(az,rng))
+ gammahhmvv = scene.coh(pol=[1,0,-1], bl=bl, pix=(az,rng))
+
+ if scene.num_baselines > 1:
+ kz = scene.kz[bl,az,rng]
+ else:
+ kz = scene.kz[az,rng]
+
+ inc = scene.inc[az,rng]
+
+ # Do a line fit to get the ground coherences.
+ gammatemp = np.zeros((2,2,2),dtype='complex')
+ gammatemp[0,:,:] = gammahigh
+ gammatemp[1,:,:] = gammalow
+ ground, groundalt, volindex = kapok.topo.groundsolver(gammatemp, kz=kz, returnall=True, silent=True)
+ if volindex[0,0]: # swap high and low coherences
+ temp = gammahigh
+ gammahigh = gammalow
+ gammalow = temp
+
+ ground = ground[0,0]
+ groundalt = groundalt[0,0]
+
+ # Plot region.
+ plt.plot(np.real(gammaall),np.imag(gammaall),'-',markersize=8,label='Region')
+
+ # Plot the fitted line.
+ gammaline = np.array((ground,gammalow,gammahigh),dtype='complex')
+ plt.plot(np.real(gammaline),np.imag(gammaline),'--g',label='Line Fit')
+
+ # Plot Lexicographic and Pauli coherences.
+ plt.plot(np.real(gammahh),np.imag(gammahh),'.r',markersize=20,label='HH')
+ plt.plot(np.real(gammavv),np.imag(gammavv),'.b',markersize=20,label='VV')
+ plt.plot(np.real(gammahv),np.imag(gammahv),'.',color='LightGreen',markersize=20,label='HV')
+ plt.plot(np.real(gammahhpvv),np.imag(gammahhpvv),'.c',markersize=20,label='HH+VV')
+ plt.plot(np.real(gammahhmvv),np.imag(gammahhmvv),'.m',markersize=20,label='HH-VV')
+
+ # Plot optimized high and low coherences.
+ plt.plot(np.real(gammahigh),np.imag(gammahigh),'.',color='DarkGreen',markersize=20,label='PD High')
+ plt.plot(np.real(gammalow),np.imag(gammalow),'.',color='Maroon',markersize=20,label='PD Low')
+
+ # Plot ground coherences.
+ plt.plot(np.real(ground),np.imag(ground),'.k',markersize=20,label='Ground')
+ plt.plot(np.real(groundalt),np.imag(groundalt),'.',color='Orange',markersize=20,label='Alt. Ground')
+
+ plt.title('Coherence Region for Pixel ('+str(az)+', '+str(rng)+')')
+ else:
+ ground = 1
+ kz = 0.10
+ inc = np.radians(45)
+
+
+ plt.xlabel('Real')
+ plt.ylabel('Imaginary')
+
+
+ nptodb = 20/np.log(10) # Nepers to dB Conversion Factor
+
+
+ # Set up parameters and starting RVoG modelled coherences.
+ hv = 20.0
+ hv_vector = np.linspace(1, hv, num=hv)
+ ext = 0.35
+ mu_high = 0
+ mu_low = 0.5
+ alpha = 1.0
+
+ # Calculate the RVoG coherences.
+ p1 = 2*ext/nptodb/np.cos(inc)
+ p2 = p1 + 1j*kz
+ gammav = (p1 / p2) * (np.exp(p2*hv_vector)-1) / (np.exp(p1*hv_vector)-1)
+ gammahigh = ground * (mu_high + alpha*gammav) / (mu_high + 1)
+ gammalow = ground * (mu_low + alpha*gammav[-1]) / (mu_low + 1)
+ rvoglocus = np.array([gammahigh[-1],gammalow],dtype='complex')
+
+ # Plot RVoG coherences.
+ l1 = plt.plot(np.real(gammahigh),np.imag(gammahigh), '--', color='Black')[0]
+ l2 = plt.plot(np.real(rvoglocus),np.imag(rvoglocus),'-xg', color='Black', label='RVoG Model')[0]
+
+ plt.axis([-1, 1, -1, 1])
+ ax.set_aspect('equal')
+
+ # UI Sliders
+ axcolor = 'lightgoldenrodyellow'
+ axhv = plt.axes([0.25, 0.20, 0.5, 0.02], axisbg=axcolor)
+ axext = plt.axes([0.25, 0.15, 0.5, 0.02], axisbg=axcolor)
+ axmulow = plt.axes([0.25, 0.1, 0.5, 0.02], axisbg=axcolor)
+ axalpha = plt.axes([0.25, 0.05, 0.5, 0.02], axisbg=axcolor)
+
+ slidehv = widgets.Slider(axhv, 'hv (m)', 1, 50.0, valinit=hv)
+ sliders.append(slidehv)
+ slideext = widgets.Slider(axext, 'Ext. (dB/m)', 1e-2, 1.0, valinit=ext)
+ sliders.append(slideext)
+ slidemulow = widgets.Slider(axmulow, 'Mu', 0.0, 1.0, valinit=mu_low)
+ sliders.append(slidemulow)
+ slidealpha = widgets.Slider(axalpha, 'Alpha', 0.0, 1.0, valinit=alpha)
+ sliders.append(slidealpha)
+
+ # Update Function Called When Sliders Are Changed
+ def update(val):
+ hv = slidehv.val
+ hv_vector = np.linspace(0.01, hv, num=hv)
+ ext = slideext.val
+ mu_low = slidemulow.val
+ alpha = slidealpha.val
+
+ # Calculate the RVoG coherences.
+ p1 = 2*ext/nptodb/np.cos(inc)
+ p2 = p1 + 1j*kz
+ gammav = (p1 / p2) * (np.exp(p2*hv_vector)-1) / (np.exp(p1*hv_vector)-1)
+ gammahigh = ground * (mu_high + alpha*gammav) / (mu_high + 1)
+ gammalow = ground * (mu_low + alpha*gammav[-1]) / (mu_low + 1)
+ rvoglocus = np.array([gammahigh[-1],gammalow],dtype='complex')
+
+ # Update plot.
+ l1.set_xdata(np.real(gammahigh))
+ l1.set_ydata(np.imag(gammahigh))
+
+ l2.set_xdata(np.real(rvoglocus))
+ l2.set_ydata(np.imag(rvoglocus))
+
+ fig.canvas.draw_idle()
+
+
+ slidehv.on_changed(update)
+ slideext.on_changed(update)
+ slidemulow.on_changed(update)
+ slidealpha.on_changed(update)
+
+ ax.legend(bbox_to_anchor=(1, 1), bbox_transform=plt.gcf().transFigure, numpoints=1)
+
+ return
\ No newline at end of file
diff --git a/kapok/rvog.py b/kapok/rvog.py
new file mode 100755
index 0000000..e2c231b
--- /dev/null
+++ b/kapok/rvog.py
@@ -0,0 +1,43 @@
+# -*- coding: utf-8 -*-
+"""Random Volume Over Ground (RVoG) Forest Model Inversion
+
+ Contains functions for the forward RVoG model, and inversion. RVoG model
+ is formulated to include real-valued volumetric temporal decorrelation,
+ as described in:
+
+ S. R. Cloude and K. P. Papathanassiou, "Three-stage inversion process
+ for polarimetric SAR interferometry," in IEE Proceedings - Radar, Sonar
+ and Navigation, vol. 150, no. 3, pp. 125-134, 2 June 2003.
+ doi: 10.1049/ip-rsn:20030449
+
+ Model inversion can be accessed procedurally through this module's
+ functions directly, or in an object-oriented fashion via the Scene class
+ method 'inv'.
+
+ Author: Michael Denbina
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import numpy as np
+
+try: # Import Cython Implementation
+ import pyximport; pyximport.install(setup_args={"include_dirs":np.get_include()})
+ from .rvogc import rvoginv, rvogfwdvol
+except ImportError: # Cython Import Failed
+ print('kapok.rvog | WARNING: Cython import failed. Running in native Python (will be slow!).')
+ from .rvogp import rvoginv, rvogfwdvol
\ No newline at end of file
diff --git a/kapok/rvogc.pyx b/kapok/rvogc.pyx
new file mode 100755
index 0000000..2bc3025
--- /dev/null
+++ b/kapok/rvogc.pyx
@@ -0,0 +1,392 @@
+# -*- coding: utf-8 -*-
+# cython: language_level=3
+"""Random Volume Over Ground (RVoG) Forest Model Inversion
+
+ Contains functions for the forward RVoG model, and inversion. Functions
+ written in Cython for increased speed. Imported by main rvog module.
+
+ Author: Michael Denbina
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import collections
+import time
+
+import numpy as np
+
+cimport numpy as np
+cimport cython
+np.import_array()
+np.import_ufunc()
+
+
+
+def rvogfwdvol(hv, ext, inc, kz):
+ """RVoG forward model volume coherence.
+
+ For a given set of model parameters, calculate the RVoG model coherence.
+
+ Arguments:
+ hv: Height of the forest volume, in meters.
+ ext: Wave extinction within the forest volume, in Np/m.
+ inc: Incidence angle, in radians.
+ kz: Interferometric vertical wavenumber, in radians/meter.
+
+ Returns:
+ gamma: Modelled complex coherence.
+
+ """
+ p1 = 2*ext*np.cos(inc)
+ p2 = p1 + 1j*kz
+
+ gammav = (p1 / p2) * (np.exp(p2*hv)-1) / (np.exp(p1*hv)-1)
+
+ # Check if scalar or array hv.
+ if isinstance(hv, (collections.Sequence, np.ndarray)):
+ hvscalar = False
+ else:
+ hvscalar = True
+
+ # Check for Zero Forest Height
+ if hvscalar and (hv <= 0):
+ gammav[:] = 1.0
+ else:
+ ind = (hv <= 0)
+ if np.any(ind):
+ gammav[ind] = 1.0
+
+ # Check for Non-Finite Volume Coherence (very large p1--extinction essentially infinite)
+ ind = ~np.isfinite(gammav)
+ if np.any(ind):
+ if hvscalar:
+ gammav[ind] = np.exp(1j*hv*kz[ind])
+ else:
+ gammav[ind] = np.exp(1j*hv[ind]*kz[ind])
+
+ return gammav
+
+
+def rvoginv(gamma, phi, inc, kz, ext=None, tdf=None, mu=0, mask=None,
+ limit2pi=True, hv_min=0, hv_max=50, hv_step=0.01, ext_min=0.0115,
+ ext_max=0.115):
+ """RVoG model inversion.
+
+ Calculate the RVoG model parameters which produce a modelled coherence
+ closest to a set of observed coherences. The model is formulated
+ using real-valued volumetric temporal decorrelation factor (tdf), with
+ physical parameters representing forest height (hv), extinction of
+ the radar waves within the forest canopy (ext), and the coherence of
+ the ground surface (phi), where arg(phi) is equal to the topographic
+ phase. In addition, the ground-to-volume amplitude ratio (mu) varies
+ as a function of the polarization.
+
+ In the single-baseline case, in order to reduce the number of unknowns
+ and ensure the model has a unique solution, we assume that mu for the
+ high coherence (from the phase diversity coherence optimization) is
+ fixed. By default it is set to zero, that is, we assume the high
+ coherence has no ground scattering component. We must then fix either
+ the extinction value, or the temporal decorrelation.
+
+ This function therefore requires either the ext or td keyword arguments
+ to be provided. The function will then optimize whichever of those two
+ parameters is not provided, plus the forest height. If neither
+ parameter is provided, tdf will be fixed to a value of 1.0 (no temporal
+ decorrelation).
+
+ Note that the ext, tdf, and mu keyword arguments can be provided as
+ a fixed single value (e.g., mu=0), as an array with the same
+ dimensions as gamma, or as a LUT of parameter values as a function
+ of the forest height parameter. In this case, a dict should be given
+ where dict['x'] contains the forest height values for each LUT bin,
+ and dict['y'] contains the parameter values. This LUT will then be
+ interpolated using numpy.interp to the forest height values by the
+ function.
+
+ Note that one cannot fix both ext and tdf using this function. The
+ function will always try to solve for one of these two parameters.
+
+ Arguments:
+ gamma (array): 2D complex-valued array containing the 'high'
+ coherences from the coherence optimization.
+ phi (array): 2D complex-valued array containing the ground
+ coherences (e.g., from kapok.topo.groundsolver()).
+ inc (array): 2D array containing the master track incidence
+ angle, in radians.
+ kz (array): 2D array containing the kz values, in radians/meter.
+ ext: Fixed values for the extinction parameter, in Nepers/meter.
+ If not specified, function will try to optimize the values of
+ ext and hv for fixed tdf. Default: None.
+ tdf: Fixed values for the temporal decorrelation factor, from 0
+ to 1. If not specified, the function will try to optimize
+ the values of tdf and hv. If both ext and tdf are left empty,
+ function will fix tdf to 1. Default: None.
+ mu: Fixed values for the ground-to-volume scattering ratio of
+ gamma. Default: 0.
+ mask (array): Boolean array. Pixels where (mask == True) will be
+ inverted, while pixels where (mask == False) will be ignored,
+ and hv set to -1.
+ limit2pi (bool): If True, function will not allow hv to go above
+ the 2*pi (ambiguity) height (as determined by the kz values).
+ If False, no such restriction. Default: True.
+ hv_min (float): Minimum allowed hv value, in meters.
+ Default: 0.
+ hv_max (float): Maximum allowed hv value, in meters.
+ Default: 50.
+ hv_step (float): Function will perform consecutive searches with
+ progressively smaller step sizes, until the step size
+ reaches a value below hv_step. Default: 0.01 m.
+ ext_min (float): Minimum extinction value, in Np/m.
+ Default: 0.0115 Np/m (~0.1 dB/m).
+ ext_max (float): Maximum extinction value, in Np/m.
+ Default: 0.115 Np/m (~1 dB/m).
+
+ Returns:
+ hvmap (array): Array of inverted forest height values, in meters.
+ extmap/tdfmap (array): If ext was specified, array of inverted tdf
+ values will be returned here. If tdf was specified, array
+ of inverted ext values will be returned.
+ converged (array): A 2D boolean array. For each pixel, if
+ |observed gamma - modelled gamma| <= 0.01, that pixel is
+ marked as converged. Otherwise, converged will be False for
+ that pixel. Pixels where converged == False suggest that the
+ RVoG model could not find a good fit for that pixel, and the
+ parameter estimates may be invalid.
+
+ """
+ print('kapok.rvog.rvoginv | Beginning RVoG model inversion. ('+time.ctime()+')')
+ dim = np.shape(gamma)
+
+ if mask is None:
+ mask = np.ones(dim, dtype='bool')
+
+ if np.all(limit2pi) or (limit2pi is None):
+ limit2pi = np.ones(dim, dtype='bool')
+ elif np.all(limit2pi == False):
+ limit2pi = np.zeros(dim, dtype='bool')
+
+
+ hv_samples = int((hv_max-hv_min+1)*3) # Initial Number of hv Bins in Search Grid
+ hv_vector = np.linspace(hv_min, hv_max, num=hv_samples)
+
+ if tdf is not None:
+ ext_samples = 60
+ ext_vector = np.linspace(ext_min, ext_max, num=ext_samples)
+ elif ext is None:
+ tdf = 1.0
+ ext_samples = 60
+ ext_vector = np.linspace(ext_min, ext_max, num=ext_samples)
+ else:
+ ext_vector = [-1]
+
+
+ # Use mask to clip input data.
+ gammaclip = gamma[mask]
+ phiclip = phi[mask]
+ incclip = inc[mask]
+ kzclip = kz[mask]
+ limit2piclip = limit2pi[mask]
+
+ if isinstance(mu, (collections.Sequence, np.ndarray)):
+ muclip = mu[mask]
+ elif isinstance(mu, dict):
+ print('kapok.rvog.rvoginv | Using LUT for mu as a function of forest height.')
+ muclip = None
+ else:
+ muclip = np.ones(gammaclip.shape, dtype='float32') * mu
+
+ if isinstance(ext, (collections.Sequence, np.ndarray)):
+ extclip = ext[mask]
+ elif isinstance(ext, dict):
+ print('kapok.rvog.rvoginv | Using LUT for extinction as a function of forest height.')
+ extclip = None
+ elif ext is not None:
+ extclip = np.ones(gammaclip.shape, dtype='float32') * ext
+ elif isinstance(tdf, (collections.Sequence, np.ndarray)):
+ tdfclip = tdf[mask]
+ elif isinstance(tdf, dict):
+ print('kapok.rvog.rvoginv | Using LUT for temporal decorrelation magnitude as a function of forest height.')
+ tdfclip = None
+ elif tdf is not None:
+ tdfclip = np.ones(gammaclip.shape, dtype='float32') * tdf
+
+
+ # Arrays to store the fitted parameters:
+ hvfit = np.zeros(gammaclip.shape, dtype='float32')
+
+ if ext is None:
+ extfit = np.zeros(gammaclip.shape, dtype='float32')
+ print('kapok.rvog.rvoginv | Solving for forest height and extinction, with fixed temporal decorrelation.')
+ else:
+ tdffit = np.zeros(gammaclip.shape, dtype='float32')
+ print('kapok.rvog.rvoginv | Solving for forest height and temporal decorrelation magnitude, with fixed extinction.')
+
+
+ # Variables for optimization:
+ mindist = np.ones(gammaclip.shape, dtype='float32') * 1e9
+ convergedclip = np.ones(gammaclip.shape,dtype='bool')
+ threshold = 0.01 # threshold for convergence
+
+ print('kapok.rvog.rvoginv | Performing repeated searches over smaller parameter ranges until hv step size is less than '+str(hv_step)+' m.')
+ print('kapok.rvog.rvoginv | Beginning pass #1 with hv step size: '+str(np.round(hv_vector[1]-hv_vector[0],decimals=3))+' m. ('+time.ctime()+')')
+
+
+ for n, hv_val in enumerate(hv_vector):
+ print('kapok.rvog.rvoginv | Progress: '+str(np.round(n/hv_vector.shape[0]*100,decimals=2))+'%. ('+time.ctime()+') ', end='\r')
+ for ext_val in ext_vector:
+ if isinstance(mu, dict):
+ muclip = np.interp(hv_val, mu['x'], mu['y'])
+
+ if ext is None:
+ if isinstance(tdf, dict):
+ tdfclip = np.interp(hv_val, tdf['x'], tdf['y'])
+
+ gammav_model = rvogfwdvol(hv_val, ext_val, incclip, kzclip)
+ gamma_model = phiclip * (muclip + tdfclip*gammav_model) / (muclip + 1)
+ dist = np.abs(gammaclip - gamma_model)
+ else:
+ if isinstance(ext, dict):
+ extclip = np.interp(hv_val, ext['x'], ext['y'])
+
+ gammav_model = rvogfwdvol(hv_val, extclip, incclip, kzclip)
+ tdf_val = np.abs((gammaclip*(muclip+1) - phiclip*muclip)/(phiclip*gammav_model))
+ gamma_model = phiclip * (muclip + tdf_val*gammav_model) / (muclip + 1)
+ dist = np.abs(gammaclip - gamma_model)
+
+ # If potential vegetation height is greater than
+ # 2*pi ambiguity height, and the limit2pi option
+ # is set to True, remove these as potential solutions:
+ ind_limit = limit2piclip & (hv_val > np.abs(2*np.pi/kzclip))
+ if np.any(ind_limit):
+ dist[ind_limit] = 1e10
+
+ # Best solution so far?
+ ind = np.less(dist,mindist)
+
+ # Then update:
+ if np.any(ind):
+ mindist[ind] = dist[ind]
+ hvfit[ind] = hv_val
+ if ext is None:
+ extfit[ind] = ext_val
+ else:
+ tdffit[ind] = tdf_val[ind]
+
+
+
+ hv_inc = hv_vector[1] - hv_vector[0]
+ if ext is None:
+ ext_inc = ext_vector[1] - ext_vector[0]
+ else:
+ ext_inc = 1e-10
+
+
+ itnum = 1
+ while (hv_inc > hv_step):
+ itnum += 1
+ hv_low = hvfit - hv_inc
+ hv_high = hvfit + hv_inc
+ hv_val = hv_low.copy()
+ hv_inc /= 10
+
+ if ext is None:
+ ext_low = extfit - ext_inc
+ ext_high = extfit + ext_inc
+ ext_val = ext_low.copy()
+ ext_inc /= 10
+ else:
+ ext_low = np.array(ext_min)
+ ext_high = np.array(ext_max)
+ ext_val = ext_low.copy()
+ ext_inc = 1e10
+
+ print('kapok.rvog.rvoginv | Beginning pass #'+str(itnum)+' with hv step size: '+str(np.round(hv_inc,decimals=3))+' m. ('+time.ctime()+')')
+ while np.all(hv_val < hv_high):
+ print('kapok.rvog.rvoginv | Progress: '+str(np.round((hv_val-hv_low)/(hv_high-hv_low)*100,decimals=2)[0])+'%. ('+time.ctime()+') ', end='\r')
+
+ while np.all(ext_val < ext_high):
+ if isinstance(mu, dict):
+ muclip = np.interp(hv_val, mu['x'], mu['y'])
+
+ if ext is None:
+ if isinstance(tdf, dict):
+ tdfclip = np.interp(hv_val, tdf['x'], tdf['y'])
+
+ gammav_model = rvogfwdvol(hv_val, ext_val, incclip, kzclip)
+ gamma_model = phiclip * (muclip + tdfclip*gammav_model) / (muclip + 1)
+ dist = np.abs(gammaclip - gamma_model)
+ else:
+ if isinstance(ext, dict):
+ extclip = np.interp(hv_val, ext['x'], ext['y'])
+
+ gammav_model = rvogfwdvol(hv_val, extclip, incclip, kzclip)
+ tdf_val = np.abs((gammaclip*(muclip+1) - phiclip*muclip)/(phiclip*gammav_model))
+ gamma_model = phiclip * (muclip + tdf_val*gammav_model) / (muclip + 1)
+ dist = np.abs(gammaclip - gamma_model)
+
+ # If potential vegetation height is greater than
+ # 2*pi ambiguity height, and the limit2pi option
+ # is set to True, remove these as potential solutions:
+ ind_limit = limit2piclip & (hv_val > np.abs(2*np.pi/kzclip))
+ if np.any(ind_limit):
+ dist[ind_limit] = 1e10
+
+ # Best solution so far?
+ ind = np.less(dist,mindist)
+
+ # Then update:
+ if np.any(ind):
+ mindist[ind] = dist[ind]
+ hvfit[ind] = hv_val[ind]
+ if ext is None:
+ extfit[ind] = ext_val[ind]
+ else:
+ tdffit[ind] = tdf_val[ind]
+
+
+ # Increment the extinction:
+ ext_val += ext_inc
+
+ # Increment the forest height:
+ hv_val += hv_inc
+ ext_val = ext_low.copy()
+
+
+ # Check convergence rate.
+ ind = np.less(mindist,threshold)
+ convergedclip[ind] = True
+ num_converged = np.sum(convergedclip)
+ num_total = len(convergedclip)
+ rate = np.round(num_converged/num_total*100,decimals=2)
+
+ print('kapok.rvog.rvoginv | Completed. Convergence Rate: '+str(rate)+'%. ('+time.ctime()+')')
+
+ # Rebuild masked arrays into original image size.
+ hvmap = np.ones(dim, dtype='float32') * -1
+ hvmap[mask] = hvfit
+
+ converged = np.ones(dim, dtype='float32') * -1
+ converged[mask] = convergedclip
+
+ if ext is None:
+ extmap = np.ones(dim, dtype='float32') * -1
+ extmap[mask] = extfit
+ return hvmap, extmap, converged
+ else:
+ tdfmap = np.ones(dim, dtype='float32') * -1
+ tdfmap[mask] = tdffit
+ return hvmap, tdfmap, converged
\ No newline at end of file
diff --git a/kapok/rvogc.pyxbld b/kapok/rvogc.pyxbld
new file mode 100755
index 0000000..6349da4
--- /dev/null
+++ b/kapok/rvogc.pyxbld
@@ -0,0 +1,5 @@
+def make_ext(modname, pyxfilename):
+ from distutils.extension import Extension
+ return Extension(name=modname,
+ sources=[pyxfilename],
+ extra_compile_args=['-w'])
\ No newline at end of file
diff --git a/kapok/rvogp.py b/kapok/rvogp.py
new file mode 100755
index 0000000..580edff
--- /dev/null
+++ b/kapok/rvogp.py
@@ -0,0 +1,414 @@
+# -*- coding: utf-8 -*-
+# cython: language_level=3
+"""Random Volume Over Ground (RVoG) Forest Model Inversion
+
+ Contains functions for the forward RVoG model, and inversion. This is
+ Python code which the rvog.py wrapper module defaults to when the Cython
+ import fails.
+
+ Author: Michael Denbina
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import collections
+import time
+
+import numpy as np
+
+
+def rvogfwdvol(hv, ext, inc, kz, rngslope=0.0):
+ """RVoG forward model volume coherence.
+
+ For a given set of model parameters, calculate the RVoG model coherence.
+
+ Arguments:
+ hv: Height of the forest volume, in meters.
+ ext: Wave extinction within the forest volume, in Np/m.
+ inc: Incidence angle, in radians.
+ kz: Interferometric vertical wavenumber, in radians/meter.
+ rngslope: Range-facing terrain slope angle, in radians. If not
+ specified, flat terrain is assumed.
+
+ Returns:
+ gamma: Modelled complex coherence.
+
+ """
+ # Check if scalar or array extinction.
+ if isinstance(ext, (collections.Sequence, np.ndarray)):
+ extscalar = False
+ else:
+ extscalar = True
+
+ # Check for Zero Extinction And Limit to Lower Bound of 1e-10 Np/m
+ if extscalar and (ext <= 1e-10):
+ ext = 1e-10
+ elif not extscalar:
+ ind = (ext <= 1e-10)
+ if np.any(ind):
+ ext[ind] = 1e-10
+
+
+ # Calculate volume coherence.
+ p1 = 2*ext*np.cos(rngslope)/np.cos(inc-rngslope)
+ p2 = p1 + 1j*kz
+
+ gammav = (p1 / p2) * (np.exp(p2*hv)-1) / (np.exp(p1*hv)-1)
+
+
+ # Check if scalar or array hv.
+ if isinstance(hv, (collections.Sequence, np.ndarray)):
+ hvscalar = False
+ else:
+ hvscalar = True
+
+ # Check for Zero Forest Height
+ if hvscalar and (hv <= 0):
+ gammav[:] = 1.0
+ elif not hvscalar:
+ ind = (hv <= 0)
+ if np.any(ind):
+ gammav[ind] = 1.0
+
+ # Check for Non-Finite Volume Coherence (indicates very large p1--extinction essentially infinite)
+ ind = ~np.isfinite(gammav)
+ if np.any(ind):
+ if hvscalar:
+ gammav[ind] = np.exp(1j*hv*kz[ind])
+ else:
+ gammav[ind] = np.exp(1j*hv[ind]*kz[ind])
+
+
+ return gammav
+
+
+def rvoginv(gamma, phi, inc, kz, ext=None, tdf=None, mu=0, rngslope=0.0,
+ mask=None, limit2pi=True, hv_min=0, hv_max=50, hv_step=0.01,
+ ext_min=0.0115, ext_max=0.115):
+ """RVoG model inversion.
+
+ Calculate the RVoG model parameters which produce a modelled coherence
+ closest to a set of observed coherences. The model is formulated
+ using real-valued volumetric temporal decorrelation factor (tdf), with
+ physical parameters representing forest height (hv), extinction of
+ the radar waves within the forest canopy (ext), and the coherence of
+ the ground surface (phi), where arg(phi) is equal to the topographic
+ phase. In addition, the ground-to-volume amplitude ratio (mu) varies
+ as a function of the polarization.
+
+ In the single-baseline case, in order to reduce the number of unknowns
+ and ensure the model has a unique solution, we assume that mu for the
+ high coherence (from the phase diversity coherence optimization) is
+ fixed. By default it is set to zero, that is, we assume the high
+ coherence has no ground scattering component. We must then fix either
+ the extinction value, or the temporal decorrelation.
+
+ This function therefore requires either the ext or td keyword arguments
+ to be provided. The function will then optimize whichever of those two
+ parameters is not provided, plus the forest height. If neither
+ parameter is provided, tdf will be fixed to a value of 1.0 (no temporal
+ decorrelation).
+
+ Note that the ext, tdf, and mu keyword arguments can be provided as
+ a fixed single value (e.g., mu=0), as an array with the same
+ dimensions as gamma, or as a LUT of parameter values as a function
+ of the forest height parameter. In this case, a dict should be given
+ where dict['x'] contains the forest height values for each LUT bin,
+ and dict['y'] contains the parameter values. This LUT will then be
+ interpolated using numpy.interp to the forest height values by the
+ function.
+
+ Note that one cannot fix both ext and tdf using this function. The
+ function will always try to solve for one of these two parameters.
+
+ Arguments:
+ gamma (array): 2D complex-valued array containing the 'high'
+ coherences from the coherence optimization.
+ phi (array): 2D complex-valued array containing the ground
+ coherences (e.g., from kapok.topo.groundsolver()).
+ inc (array): 2D array containing the master track incidence
+ angle, in radians.
+ kz (array): 2D array containing the kz values, in radians/meter.
+ ext: Fixed values for the extinction parameter, in Nepers/meter.
+ If not specified, function will try to optimize the values of
+ ext and hv for fixed tdf. Default: None.
+ tdf: Fixed values for the temporal decorrelation factor, from 0
+ to 1. If not specified, the function will try to optimize
+ the values of tdf and hv. If both ext and tdf are left empty,
+ function will fix tdf to 1. Default: None.
+ mu: Fixed values for the ground-to-volume scattering ratio of
+ gamma. Default: 0.
+ rngslope (array): Terrain slope angle in the ground range
+ direction, in radians. Default: 0 (flat terrain).
+ mask (array): Boolean array. Pixels where (mask == True) will be
+ inverted, while pixels where (mask == False) will be ignored,
+ and hv set to -1.
+ limit2pi (bool): If True, function will not allow hv to go above
+ the 2*pi (ambiguity) height (as determined by the kz values).
+ If False, no such restriction. Default: True.
+ hv_min (float): Minimum allowed hv value, in meters.
+ Default: 0.
+ hv_max (float): Maximum allowed hv value, in meters.
+ Default: 50.
+ hv_step (float): Function will perform consecutive searches with
+ progressively smaller step sizes, until the step size
+ reaches a value below hv_step. Default: 0.01 m.
+ ext_min (float): Minimum extinction value, in Np/m.
+ Default: 0.0115 Np/m (~0.1 dB/m).
+ ext_max (float): Maximum extinction value, in Np/m.
+ Default: 0.115 Np/m (~1 dB/m).
+
+ Returns:
+ hvmap (array): Array of inverted forest height values, in meters.
+ extmap/tdfmap (array): If ext was specified, array of inverted tdf
+ values will be returned here. If tdf was specified, array
+ of inverted ext values will be returned.
+ converged (array): A 2D boolean array. For each pixel, if
+ |observed gamma - modelled gamma| <= 0.01, that pixel is
+ marked as converged. Otherwise, converged will be False for
+ that pixel. Pixels where converged == False suggest that the
+ RVoG model could not find a good fit for that pixel, and the
+ parameter estimates may be invalid.
+
+ """
+ print('kapok.rvog.rvoginv | Beginning RVoG model inversion. ('+time.ctime()+')')
+ dim = np.shape(gamma)
+
+ if mask is None:
+ mask = np.ones(dim, dtype='bool')
+
+ if np.all(limit2pi) or (limit2pi is None):
+ limit2pi = np.ones(dim, dtype='bool')
+ elif np.all(limit2pi == False):
+ limit2pi = np.zeros(dim, dtype='bool')
+
+
+ hv_samples = int((hv_max-hv_min+1)*3) # Initial Number of hv Bins in Search Grid
+ hv_vector = np.linspace(hv_min, hv_max, num=hv_samples)
+
+ if tdf is not None:
+ ext_samples = 60
+ ext_vector = np.linspace(ext_min, ext_max, num=ext_samples)
+ elif ext is None:
+ tdf = 1.0
+ ext_samples = 60
+ ext_vector = np.linspace(ext_min, ext_max, num=ext_samples)
+ else:
+ ext_vector = [-1]
+
+
+ # Use mask to clip input data.
+ gammaclip = gamma[mask]
+ phiclip = phi[mask]
+ incclip = inc[mask]
+ kzclip = kz[mask]
+ limit2piclip = limit2pi[mask]
+
+ if isinstance(mu, (collections.Sequence, np.ndarray)):
+ muclip = mu[mask]
+ elif isinstance(mu, dict):
+ print('kapok.rvog.rvoginv | Using LUT for mu as a function of forest height.')
+ muclip = None
+ else:
+ muclip = np.ones(gammaclip.shape, dtype='float32') * mu
+
+ if isinstance(rngslope, (collections.Sequence, np.ndarray)):
+ rngslopeclip = rngslope[mask]
+ else:
+ rngslopeclip = np.ones(gammaclip.shape, dtype='float32') * rngslope
+
+ if isinstance(ext, (collections.Sequence, np.ndarray)):
+ extclip = ext[mask]
+ elif isinstance(ext, dict):
+ print('kapok.rvog.rvoginv | Using LUT for extinction as a function of forest height.')
+ extclip = None
+ elif ext is not None:
+ extclip = np.ones(gammaclip.shape, dtype='float32') * ext
+ elif isinstance(tdf, (collections.Sequence, np.ndarray)):
+ tdfclip = tdf[mask]
+ elif isinstance(tdf, dict):
+ print('kapok.rvog.rvoginv | Using LUT for temporal decorrelation magnitude as a function of forest height.')
+ tdfclip = None
+ elif tdf is not None:
+ tdfclip = np.ones(gammaclip.shape, dtype='float32') * tdf
+
+
+ # Arrays to store the fitted parameters:
+ hvfit = np.zeros(gammaclip.shape, dtype='float32')
+
+ if ext is None:
+ extfit = np.zeros(gammaclip.shape, dtype='float32')
+ print('kapok.rvog.rvoginv | Solving for forest height and extinction, with fixed temporal decorrelation.')
+ else:
+ tdffit = np.zeros(gammaclip.shape, dtype='float32')
+ print('kapok.rvog.rvoginv | Solving for forest height and temporal decorrelation magnitude, with fixed extinction.')
+
+
+ # Variables for optimization:
+ mindist = np.ones(gammaclip.shape, dtype='float32') * 1e9
+ convergedclip = np.ones(gammaclip.shape,dtype='bool')
+ threshold = 0.01 # threshold for convergence
+
+ print('kapok.rvog.rvoginv | Performing rekapoked searches over smaller parameter ranges until hv step size is less than '+str(hv_step)+' m.')
+ print('kapok.rvog.rvoginv | Beginning pass #1 with hv step size: '+str(np.round(hv_vector[1]-hv_vector[0],decimals=3))+' m. ('+time.ctime()+')')
+
+
+ for n, hv_val in enumerate(hv_vector):
+ print('kapok.rvog.rvoginv | Progress: '+str(np.round(n/hv_vector.shape[0]*100,decimals=2))+'%. ('+time.ctime()+') ', end='\r')
+ for ext_val in ext_vector:
+ if isinstance(mu, dict):
+ muclip = np.interp(hv_val, mu['x'], mu['y'])
+
+ if ext is None:
+ if isinstance(tdf, dict):
+ tdfclip = np.interp(hv_val, tdf['x'], tdf['y'])
+
+ gammav_model = rvogfwdvol(hv_val, ext_val, incclip, kzclip, rngslope=rngslopeclip)
+ gamma_model = phiclip * (muclip + tdfclip*gammav_model) / (muclip + 1)
+ dist = np.abs(gammaclip - gamma_model)
+ else:
+ if isinstance(ext, dict):
+ extclip = np.interp(hv_val, ext['x'], ext['y'])
+
+ gammav_model = rvogfwdvol(hv_val, extclip, incclip, kzclip, rngslope=rngslopeclip)
+ tdf_val = np.abs((gammaclip*(muclip+1) - phiclip*muclip)/(phiclip*gammav_model))
+ gamma_model = phiclip * (muclip + tdf_val*gammav_model) / (muclip + 1)
+ dist = np.abs(gammaclip - gamma_model)
+
+ # If potential vegetation height is greater than
+ # 2*pi ambiguity height, and the limit2pi option
+ # is set to True, remove these as potential solutions:
+ ind_limit = limit2piclip & (hv_val > np.abs(2*np.pi/kzclip))
+ if np.any(ind_limit):
+ dist[ind_limit] = 1e10
+
+ # Best solution so far?
+ ind = np.less(dist,mindist)
+
+ # Then update:
+ if np.any(ind):
+ mindist[ind] = dist[ind]
+ hvfit[ind] = hv_val
+ if ext is None:
+ extfit[ind] = ext_val
+ else:
+ tdffit[ind] = tdf_val[ind]
+
+
+
+ hv_inc = hv_vector[1] - hv_vector[0]
+ if ext is None:
+ ext_inc = ext_vector[1] - ext_vector[0]
+ else:
+ ext_inc = 1e-10
+
+
+ itnum = 1
+ while (hv_inc > hv_step):
+ itnum += 1
+ hv_low = hvfit - hv_inc
+ hv_high = hvfit + hv_inc
+ hv_val = hv_low.copy()
+ hv_inc /= 10
+
+ if ext is None:
+ ext_low = extfit - ext_inc
+ ext_high = extfit + ext_inc
+ ext_val = ext_low.copy()
+ ext_inc /= 10
+ else:
+ ext_low = np.array(ext_min)
+ ext_high = np.array(ext_max)
+ ext_val = ext_low.copy()
+ ext_inc = 1e10
+
+ print('kapok.rvog.rvoginv | Beginning pass #'+str(itnum)+' with hv step size: '+str(np.round(hv_inc,decimals=3))+' m. ('+time.ctime()+')')
+ while np.all(hv_val < hv_high):
+ print('kapok.rvog.rvoginv | Progress: '+str(np.round((hv_val-hv_low)/(hv_high-hv_low)*100,decimals=2)[0])+'%. ('+time.ctime()+') ', end='\r')
+
+ while np.all(ext_val < ext_high):
+ if isinstance(mu, dict):
+ muclip = np.interp(hv_val, mu['x'], mu['y'])
+
+ if ext is None:
+ if isinstance(tdf, dict):
+ tdfclip = np.interp(hv_val, tdf['x'], tdf['y'])
+
+ gammav_model = rvogfwdvol(hv_val, ext_val, incclip, kzclip, rngslope=rngslopeclip)
+ gamma_model = phiclip * (muclip + tdfclip*gammav_model) / (muclip + 1)
+ dist = np.abs(gammaclip - gamma_model)
+ else:
+ if isinstance(ext, dict):
+ extclip = np.interp(hv_val, ext['x'], ext['y'])
+
+ gammav_model = rvogfwdvol(hv_val, extclip, incclip, kzclip, rngslope=rngslopeclip)
+ tdf_val = np.abs((gammaclip*(muclip+1) - phiclip*muclip)/(phiclip*gammav_model))
+ gamma_model = phiclip * (muclip + tdf_val*gammav_model) / (muclip + 1)
+ dist = np.abs(gammaclip - gamma_model)
+
+ # If potential vegetation height is greater than
+ # 2*pi ambiguity height, and the limit2pi option
+ # is set to True, remove these as potential solutions:
+ ind_limit = limit2piclip & (hv_val > np.abs(2*np.pi/kzclip))
+ if np.any(ind_limit):
+ dist[ind_limit] = 1e10
+
+ # Best solution so far?
+ ind = np.less(dist,mindist)
+
+ # Then update:
+ if np.any(ind):
+ mindist[ind] = dist[ind]
+ hvfit[ind] = hv_val[ind]
+ if ext is None:
+ extfit[ind] = ext_val[ind]
+ else:
+ tdffit[ind] = tdf_val[ind]
+
+
+ # Increment the extinction:
+ ext_val += ext_inc
+
+ # Increment the forest height:
+ hv_val += hv_inc
+ ext_val = ext_low.copy()
+
+
+ # Check convergence rate.
+ ind = np.less(mindist,threshold)
+ convergedclip[ind] = True
+ num_converged = np.sum(convergedclip)
+ num_total = len(convergedclip)
+ rate = np.round(num_converged/num_total*100,decimals=2)
+
+ print('kapok.rvog.rvoginv | Completed. Convergence Rate: '+str(rate)+'%. ('+time.ctime()+')')
+
+ # Rebuild masked arrays into original image size.
+ hvmap = np.ones(dim, dtype='float32') * -1
+ hvmap[mask] = hvfit
+
+ converged = np.ones(dim, dtype='float32') * -1
+ converged[mask] = convergedclip
+
+ if ext is None:
+ extmap = np.ones(dim, dtype='float32') * -1
+ extmap[mask] = extfit
+ return hvmap, extmap, converged
+ else:
+ tdfmap = np.ones(dim, dtype='float32') * -1
+ tdfmap[mask] = tdffit
+ return hvmap, tdfmap, converged
\ No newline at end of file
diff --git a/kapok/sinc.py b/kapok/sinc.py
new file mode 100755
index 0000000..1927a13
--- /dev/null
+++ b/kapok/sinc.py
@@ -0,0 +1,165 @@
+# -*- coding: utf-8 -*-
+"""Sinc Forest Model Module
+
+ Forest height estimation using sinc coherence model and combined sinc
+ coherence and phase difference model. This is a basic model which
+ relates coherence magnitude and phase to forest height.
+
+ For reference on the model, see:
+
+ S. R. Cloude, "Polarization coherence tomography," Radio Science,
+ 41, RS4017, 2006. doi:10.1029/2005RS003436.
+
+ Author: Michael Denbina
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import numpy as np
+
+
+def sincinv(gamma, kz, tdf=None, mask=None):
+ """Sinc Forest Model Inversion
+
+ Function to estimate tree heights using the inverse sinc function of the
+ estimated volume coherence (e.g., HV, or gamma high from phase diversity
+ coherence optimization).
+
+ The model equation is hv = (2*sincinv(|gammav|))/(kz), where hv is
+ volume/forest height, gammav is the volume coherence, and kz is the
+ interferometric vertical wavenumber.
+
+ We assume that the inverse sinc function values for low coherence are
+ within the central peak of the sinc function.
+
+ The input arguments can be for a single pixel or the entire image,
+ provided they either have the same dimensions or one of them is a scalar.
+
+ Arguments:
+ gamma (array): The estimated volumetric coherence.
+ kz (array): The vertical wavenumber, in radians/meter.
+ tdf (array): The estimated real-valued temporal decorrelation factor,
+ if needed. The input gammav value will be corrected by assuming
+ that the observed coherence is equal to the true volumetric
+ coherence times tdf. Default: No temporal decorrelation.
+
+ Returns:
+ hv (array): The estimated volume/forest height, in meters.
+
+ """
+ # If no temporal decorrelation factor input, tdf = 1:
+ if tdf is None:
+ tdf = np.ones(gamma.shape)
+
+ # Build a LUT of sinc function values for the inversion.
+ # Get a vector of values (used as input to the np.sinc() function)
+ # from 1 down to 0, because np.sinc() is the normalized sinc
+ # function and we want to start at the first zero of the sinc function.
+ # We go in decreasing order because in order for np.interp() to work
+ # properly the LUT values must be increasing.
+ LUTreturn = np.linspace(1,0,num=201)
+ LUT = np.sinc(LUTreturn)
+
+ gamma = np.abs(gamma/tdf)
+ gamma[gamma > 1] = 1
+ gamma[gamma < 0] = 0
+
+
+ # Use np.interp to linearly interpolate the LUT to the input gammav value.
+ # We multiply by pi because numpy uses the normalized sinc function,
+ # sinc(x) = sin(pi*x)/(pi*x), and we need a phase from the inverse.
+ hv = (2*np.pi*np.interp(gamma,LUT,LUTreturn)) / np.abs(kz)
+
+ if mask is not None:
+ hv[np.invert(mask)] = -1
+
+ return hv
+
+
+def sincfwd(hv, kz):
+ """ sincfwd
+
+ Sinc coherence amplitude forward model. See sincinv() for more details.
+ This function can be used, for example, to calculate the expected volume
+ decorrelation for this model for a given set of forest heights.
+
+ Arguments:
+ hv (array): The volume/forest height, in meters.
+ kz (array): The vertical wavenumber, in radians/meter.
+
+ Returns:
+ gammav (array): The estimated volume coherence magnitude.
+
+ """
+ gammav = np.sinc((hv*np.abs(kz))/(2*np.pi))
+
+ return gammav
+
+
+
+def sincphaseinv(gamma, phi, kz, epsilon=None, tdf=None, mask=None):
+ """ sincphaseinv
+
+ Vegetation height inversion using a combination of sinc coherence
+ estimation and the height of the estimated volume phase center above
+ the ground.
+
+ We mask out pixels with low phase separation between gamma high and
+ gamma low, and set the vegetation height for these pixels to zero.
+
+ The parameter epsilon is used to weight the second coherence amplitude
+ term of the inversion. In the zero extinction case, epsilon = 0.5, while
+ for the infinite extinction case, epsilon = 0. The suggested
+ value in the Cloude (2006) paper for moderate extinction is 0.4.
+
+ Arguments:
+ gamma (array): Array of the estimated volumetric coherence for each
+ pixel.
+ phi (array): Estimated ground phases (e.g., from the functions in the
+ kapok.topo module).
+ kz (array): The vertical wavenumbers, in radians/meter.
+ epsilon (float): The weighting factor of the coherence amplitude
+ sinc inversion term. Default: 0.4.
+ tdf (array): The estimated temporal decorrelation factor, if needed.
+ The input gammav value will be corrected by assuming that the
+ observed coherence is equal to the true volumetric coherence times
+ tdf. Default: No temporal decorrelation.
+
+ Returns:
+ hv (array): The estimated forest height, in meters.
+
+ """
+ # Default epsilon value.
+ if epsilon is None:
+ epsilon = 0.4
+
+ # If temporal decorrelation factor is not provided, assume no temporal
+ # decorrelation:
+ if tdf is None:
+ tdf = np.ones(gamma.shape)
+
+ # Phase difference:
+ hp = np.angle((gamma/tdf)*np.exp(-1j*phi))/kz
+ hp[hp < 0] += 2*np.pi*np.abs(kz[hp < 0])
+
+ # Add sinc inversion term:
+ hv = hp + (epsilon*sincinv(gamma,kz,tdf))
+
+ if mask is not None:
+ hv[np.invert(mask)] = -1
+
+ return hv
\ No newline at end of file
diff --git a/kapok/topo.py b/kapok/topo.py
new file mode 100755
index 0000000..7999b4c
--- /dev/null
+++ b/kapok/topo.py
@@ -0,0 +1,217 @@
+# -*- coding: utf-8 -*-
+"""Topography Estimation Module
+
+ Estimating ground coherence and ground topographic phase using line
+ fitting of the observed PolInSAR coherences. For reference, see:
+
+ S. R. Cloude and K. P. Papathanassiou, "Three-stage inversion process
+ for polarimetric SAR interferometry," IEE Proceedings - Radar, Sonar
+ and Navigation, vol. 150, no. 3, pp. 125-134, 2 June 2003.
+ doi: 10.1049/ip-rsn:20030449
+
+ Author: Michael Denbina
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import collections
+import time
+
+import numpy as np
+
+
+def groundsolver(gamma, kz=None, groundmag=None, gammavol=None,
+ returnall=False, silent=False):
+ """Solve for the ground coherence using a line fit of the observed
+ coherences.
+
+ Arguments:
+ gamma (array): Array containing the complex coherences to line
+ fit. Should have dimensions (2, azimuth, range).
+ gamma[0,:,:] should contain one of the coherences to line fit,
+ and gamma[1,:,:] should contain the other (e.g., from phase
+ diversity coherence optimization).
+ kz: The kz values. If specified, the algorithm will choose
+ between the two ground coherence solutions by assuming that
+ the phase difference between the high coherence and the
+ ground is less than pi. This is generally a reasonable
+ assumption, and often if this requirement is not observed,
+ the coherence will be low anyway. If this behaviour is not
+ desired, see the gammvol argument for another method for
+ choosing between the ground coherences. Note that only the
+ sign of kz, not the magnitude, matters here. The input can
+ therefore either be the 2D array of kz values, or simply a
+ scalar with the same sign as the actual kz.
+ groundmag (array): Magnitude of the ground coherence.
+ gammavol (array): Array containing coherences that are assumed
+ to be closer to the volume-dominated coherence than the
+ ground-dominated coherence. If specified, the ground
+ solver will always choose the ground solution that is
+ farther (on the complex plane) from gammavol. Note:
+ Selection of the ground solution through the kz is
+ recommended (see above), as it is generally more
+ robust.
+ returnall (bool): If set to True, function will return the
+ ground solutions, as well as the other ground solution
+ not chosen, and an array identifying which of the two
+ input coherences in gamma are the volume-dominated
+ coherence. If False, only the chosen ground solution
+ will be returned.
+ silent (bool): If set to True, no output status will be
+ printed.
+
+ Returns:
+ ground (array): Array of complex-valued ground coherences.
+ groundalt (array): The other ground solutions which were not
+ chosen. Only returned if returnall == True.
+ volindex (array): 2D array containing the index of the high/volume
+ (smallest ground contribution) coherence for each pixel.
+ If gamma[0,azimuth,range] is closer to the vol coherence
+ than gamma[1,azimuth,range], volindex[azimuth,range] will
+ equal 0. Only returned if returnall == True.
+
+ """
+ if not silent:
+ print('kapok.topo.groundsolver | Solving for ground coherence. ('+time.ctime()+')')
+ # Get the two possible ground coherence solutions.
+ solutions = linefit(gamma, groundmag)
+
+ if kz is not None:
+ if not isinstance(kz, (collections.Sequence, np.ndarray)):
+ kz = np.ones((gamma.shape[1],gamma.shape[2]),dtype='float32') * kz
+
+ # Get the volume-dominated coherences corresponding to each ground solution. (Observed coherence farthest from ground.)
+ gammav = gamma.copy()
+ gammav[0] = np.where(np.abs(solutions[0] - gamma[0]) > np.abs(solutions[0] - gamma[1]), gamma[0], gamma[1])
+ gammav[1] = np.where(np.abs(solutions[1] - gamma[0]) > np.abs(solutions[1] - gamma[1]), gamma[0], gamma[1])
+
+ # Angular separation between volume coherence and ground -- is it same sign as kz?
+ sep = np.angle(gammav*np.conj(solutions))*np.sign(kz)
+
+ ground = np.where(sep[0] >= 0, solutions[0], solutions[1])
+ groundalt = np.where(sep[0] >= 0, solutions[1], solutions[0])
+ volindex = (np.abs(gamma[1] - ground) > np.abs(gamma[0] - ground))
+ elif gammavol is not None:
+ # Of the two observed coherences, assume the volume-dominated coherence is the one
+ # which is closer to the input gammavol array.
+ volindex = (np.abs(gamma[1] - gammavol) < np.abs(gamma[0] - gammavol))
+ gammav = np.where(volindex, gamma[1], gamma[0])
+
+ # Choose the ground that is farther from gammav.
+ ground = np.where(np.abs(gammav - solutions[0]) > np.abs(gammav - solutions[1]),solutions[0],solutions[1])
+ groundalt = np.where(np.abs(gammav - solutions[0]) > np.abs(gammav - solutions[1]),solutions[1],solutions[0])
+ else:
+ print('kapok.topo.groundsolver | Neither kz or estimated volume coherence specified. Unable to choose between ambiguous ground solutions. Aborting.')
+ ground = None
+ groundalt = None
+ volindex = None
+
+ if not silent:
+ print('kapok.topo.groundsolver | Complete. ('+time.ctime()+')')
+
+ if returnall:
+ return ground, groundalt, volindex
+ else:
+ return ground
+
+
+def linefit(gamma, groundmag=None):
+ """Fit a line through two observed complex coherences and return
+ the two possible ground coherence solutions.
+
+ Arguments:
+ gamma (array): Array with dimensions (2, azimuth, range)
+ containing the observed coherences to fit a line
+ through.
+ groundmag (array): The ground coherence magnitude. If not
+ specified, the function will assume the ground
+ coherence magnitude is equal to one. If specified,
+ this function will find the intersections between
+ the fitted line and a circle with radius equal to
+ gammag. If these intersections are within the
+ observed coherences, the solutions will be moved
+ along the line until they are on top of the closest
+ observed coherence. There will always be one
+ solution on either side of the observed coherence
+ region. If the value of gammag is such that
+ both intersections are on one side of the observed
+ coherences, then the coherence farther from the
+ observed coherences will be chosen, and the other
+ ground solution will be equal to the observed
+ coherence farthest from the first ground solution.
+ In general, this should be a rare situation to
+ occur, unless gammag is set to an unreasonably low
+ value.
+
+ Returns:
+ solutions (array): Array with the same dimensions as
+ gamma containing the two ground complex coherence
+ solutions for each pixel.
+
+ """
+ if groundmag is None:
+ groundmag = np.ones((gamma.shape[1],gamma.shape[2]),dtype='float32')
+ elif not isinstance(groundmag, (collections.Sequence, np.ndarray)):
+ groundmag = np.ones((gamma.shape[1],gamma.shape[2]),dtype='float32') * groundmag
+
+ groundmag[groundmag > 1] = 1.0
+
+ solutions = np.zeros(gamma.shape,dtype='complex64')
+
+ # Intersections between line through gamma and circle with radius groundmag:
+ a = np.square(np.abs(gamma[0] - gamma[1]))
+ b = 2*np.real(gamma[0]*np.conj(gamma[1])) - 2*np.square(np.abs(gamma[1]))
+ c = np.square(np.abs(gamma[1])) - np.square(np.abs(groundmag))
+
+ xa = (-1*b - np.sqrt(np.square(b) - 4*a*c))/(2*a)
+ xb = (-1*b + np.sqrt(np.square(b) - 4*a*c))/(2*a)
+
+ solutions[0] = xa*gamma[0] + (1-xa)*gamma[1]
+ solutions[1] = xb*gamma[0] + (1-xb)*gamma[1]
+
+ # Is the coherence magnitude given by groundmag lower than both observed
+ # coherences? (e.g., no valid intersection)
+ ind = (groundmag < np.abs(gamma[0])) & (groundmag < np.abs(gamma[1]))
+ if np.any(ind):
+ solutions[0][ind] = np.nan
+ solutions[1][ind] = np.nan
+
+ # Are any of the solutions within the observed coherence region?
+ ind = np.sign(np.angle(solutions*np.conj(gamma[1]))) == np.sign(np.angle(gamma[0]*np.conj(solutions)))
+ if np.any(ind):
+ solutions[ind] = np.nan
+
+
+ # Both solutions invalid:
+ ind = np.isnan(solutions[0]) & np.isnan(solutions[1])
+ if np.any(ind):
+ solutions[0][ind] = gamma[0][ind]
+ solutions[1][ind] = gamma[1][ind]
+
+ # First solution invalid.
+ ind = np.isnan(solutions[0]) & np.isfinite(solutions[1])
+ if np.any(ind):
+ gammareplace = np.where(np.abs(solutions[1]-gamma[0]) > np.abs(solutions[1]-gamma[1]),gamma[0],gamma[1])
+ solutions[0][ind] = gammareplace[ind]
+
+ # Other solution invalid.
+ ind = np.isnan(solutions[1]) & np.isfinite(solutions[0])
+ if np.any(ind):
+ gammareplace = np.where(np.abs(solutions[0]-gamma[0]) > np.abs(solutions[0]-gamma[1]),gamma[0],gamma[1])
+ solutions[1][ind] = gammareplace[ind]
+
+ return solutions
\ No newline at end of file
diff --git a/kapok/uavsar.py b/kapok/uavsar.py
new file mode 100755
index 0000000..74584cc
--- /dev/null
+++ b/kapok/uavsar.py
@@ -0,0 +1,36 @@
+# -*- coding: utf-8 -*-
+"""UAVSAR Data Import
+
+ Module for importing UAVSAR data. Imports the SLCs and calculates the
+ covariance matrix, imports the UAVSAR annotation (metadata) file, and
+ imports/calculates the necessary parameters for the viewing geometry
+ (incidence angle, kz). The imported data is saved as an HDF5 file
+ which can be loaded into a Scene object using the main Kapok module.
+
+ Author: Michael Denbina
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import numpy as np
+
+try: # Import Cython Implementation
+ import pyximport; pyximport.install(setup_args={"include_dirs":np.get_include()})
+ from .uavsarc import load, Ann
+except ImportError: # Cython Import Failed
+ print('kapok.uavsar | WARNING: Cython import failed. Running in native Python (will be slow!).')
+ from .uavsarp import load, Ann
\ No newline at end of file
diff --git a/kapok/uavsarc.pyx b/kapok/uavsarc.pyx
new file mode 100755
index 0000000..d5aad95
--- /dev/null
+++ b/kapok/uavsarc.pyx
@@ -0,0 +1,655 @@
+# -*- coding: utf-8 -*-
+# cython: language_level=3
+"""UAVSAR Data Import Cython Functions
+
+ Module for importing UAVSAR data. These are Cython functions imported by
+ the main kapok.uavsar module.
+
+ Author: Michael Denbina
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import os
+import os.path
+import time
+from glob import glob
+
+import numpy as np
+import h5py
+from scipy.ndimage.interpolation import zoom
+
+import kapok
+from kapok.lib import mlook, smooth, sch2enu
+
+cimport numpy as np
+cimport cython
+np.import_array()
+np.import_ufunc()
+
+
+
+def load(infile, outfile, mlwin=(20,5), smwin=(1,1), azbounds=None,
+ rngbounds=None, tracks=None, compression='gzip',
+ compression_opts=4, num_blocks=20, overwrite=False):
+ """Load a UAVSAR dataset into the Kapok format, and save it to target HDF5
+ file.
+
+ Arguments:
+ infile (str): Path and filename of a UAVSAR .ann file containing the
+ metadata for a UAVSAR SLC stack.
+ outfile (str): Path and filename for the saved HDF5 dataset.
+ mlwin: Tuple containing the multilooking window sizes in azimuth and
+ slant range (in that order). div=(12,3) results in multilooking
+ using a window of 12 pixels in azimuth and 3 pixels in slant range.
+ Within the window, all SLC pixels are averaged into a single
+ covariance matrix, reducing the size of the data. The size of the
+ incidence angle, latitude, longitude, and other rasters are also
+ reduced by the same factor. Default: (20,5).
+ smwin: Tuple containing boxcar moving average window sizes in azimuth
+ and slant range (in that order). Each covariance matrix will be
+ smoothed using this window, without reducing the number of pixels
+ in the data. Smoothing is performed after multilooking, if both
+ are specified. Default: (1,1).
+ azbounds: List containing starting and ending SLC azimuth index for
+ desired subset. Data outside these bounds will not be loaded.
+ Default is to import all data.
+ rngbounds: List containing starting and ending SLC range index for
+ desired subset. Data outside these bounds will not be loaded.
+ Default is to import all data.
+ tracks: List containing desired track indices to import. For example,
+ tracks=[0,1] will import only the first two tracks listed in the
+ annotation file. Default: All tracks imported.
+ compression (str): Compression keyword used when creating the HDF5
+ datasets to store the covariance matrix, incidence angle, kz,
+ and DEM heights. Default: 'gzip'.
+ compression_opts (int): Compression option value used when creating
+ the HDF5 datasets. Number from 0 to 9, with 9 being maximum
+ compression. Default: 4.
+ num_blocks (int): Number of blocks to use for splitting up the
+ covariance matrix calculation. Should be a positive integer
+ >= 1. Higher numbers use less memory, but will be slower.
+ Default: 15.
+ overwrite (bool): Set to True to overwrite an existing Kapok HDF5
+ file if necessary. Default: False.
+
+ Returns:
+ scene: A Kapok scene object pointing to the newly created HDF5 file.
+
+ """
+ # Load the annotation file.
+ try:
+ ann = Ann(infile)
+ except:
+ print('kapok.uavsar.load | Cannot load UAVSAR annotation file. Aborting.')
+ return
+
+
+ # Create the HDF5 file.
+ if overwrite:
+ try:
+ f = h5py.File(outfile,'w')
+ except:
+ print('kapok.uavsar.load | Cannot create new HDF5 file. Check if path is valid. Aborting.')
+ return
+ else:
+ try:
+ f = h5py.File(outfile,'x')
+ except:
+ print('kapok.uavsar.load | Cannot create new HDF5 file. Check if path is valid and ensure file does not already exist. Aborting.')
+ return
+
+
+ cdef unsigned int n
+
+ # Get SLC dimensions and number of segments.
+ rngsize_slc = ann.query('slc_1_1x1 Columns')
+ num_segments = ann.query('Number of Segments')
+ if num_segments > 1:
+ azsize_slc = np.zeros(num_segments,dtype='int32')
+ for n in range(num_segments):
+ azsize_slc[n] = ann.query('slc_'+str(n+1)+'_1x1 Rows')
+ else:
+ azsize_slc = ann.query('slc_1_1x1 Rows')
+
+
+ # Get track filenames and number of tracks.
+ temp = ann.query('stackline1')
+ num = 1
+ if temp is not None:
+ tracknames = [temp.split('_L090')[0]]
+ num += 1
+ temp = ann.query('stackline'+str(num))
+ while temp is not None:
+ tracknames.append(temp.split('_L090')[0])
+ num += 1
+ temp = ann.query('stackline'+str(num))
+ else:
+ print('kapok.uavsar.load | Cannot find track names in UAVSAR annotation file. Aborting.')
+ return
+
+
+ # Subset track names if desired tracks were specified:
+ tracknames = np.array(tracknames)
+ if tracks is not None:
+ tracks = np.array(tracks,dtype='int')
+ tracknames = tracknames[tracks]
+
+ num_tracks = len(tracknames) # Number of Tracks
+ num_bl = int(num_tracks * (num_tracks-1) / 2) # Number of Baselines
+ num_pol = int(3) # Number of Polarizations (HH, sqrt(2)*HV, VV)
+ num_cov_elements = num_tracks*num_pol # Number of Covariance Matrix Elements in Each Row
+
+ f.attrs['stack_name'] = ann.query('Stack Name')
+ f.attrs['site'] = ann.query('Site Description')
+ f.attrs['url'] = ann.query('URL')
+ f.attrs['sensor'] = 'UAVSAR'
+ f.attrs['processor'] = 'production'
+
+ print('kapok.uavsar.load | Stack ID: '+f.attrs['stack_name'])
+ print('kapok.uavsar.load | Site Description: '+f.attrs['site'])
+ print('kapok.uavsar.load | URL: '+f.attrs['url'])
+
+ print('kapok.uavsar.load | Importing metadata. ('+time.ctime()+')')
+
+ f.attrs['average_altitude'] = ann.query('Average Altitude')
+ f.attrs['image_starting_slant_range'] = ann.query('Image Starting Slant Range')*1000
+ f.attrs['slc_azimuth_pixel_spacing'] = ann.query('1x1 SLC Azimuth Pixel Spacing')
+ f.attrs['slc_slant_range_pixel_spacing'] = ann.query('1x1 SLC Range Pixel Spacing')
+ f.attrs['cov_azimuth_pixel_spacing'] = ann.query('1x1 SLC Azimuth Pixel Spacing') * mlwin[0]
+ f.attrs['cov_slant_range_pixel_spacing'] = ann.query('1x1 SLC Range Pixel Spacing') * mlwin[1]
+
+ f.attrs['num_tracks'] = num_tracks
+ f.attrs['num_baselines'] = num_bl
+ f.attrs['tracks'] = np.array(tracknames,dtype='S')
+
+ f.attrs['compression'] = compression
+ f.attrs['compression_opts'] = compression_opts
+
+ if (azbounds is not None) or (rngbounds is not None):
+ f.attrs['subset'] = True
+ else:
+ f.attrs['subset'] = False
+
+
+ # Check azimuth bounds for validity.
+ if azbounds is None:
+ azbounds = [0,np.sum(azsize_slc)]
+
+ if azbounds[1] <= azbounds[0]:
+ print('kapok.uavsar.load | Invalid azimuth bounds. Must be ascending. Aborting.')
+ return
+
+ if azbounds[0] < 0:
+ print('kapok.uavsar.load | Lower azimuth bound ('+str(azbounds[0])+') is less than zero. Setting lower azimuth bound to zero.')
+ azbounds[0] = 0
+
+ if azbounds[1] > np.sum(azsize_slc):
+ print('kapok.uavsar.load | Upper azimuth bound ('+str(azbounds[1])+') greater than number of SLC lines ('+str(azsize_slc)+').')
+ print('kapok.uavsar.load | Setting upper azimuth bound to '+str(azsize_slc)+'.')
+ azbounds[1] = np.sum(azsize_slc)
+
+
+ # Check range bounds for validity.
+ if rngbounds is None:
+ rngbounds = [0,rngsize_slc]
+
+ if rngbounds[1] <= rngbounds[0]:
+ print('kapok.uavsar.load | Invalid range bounds. Must be ascending. Aborting.')
+ return
+
+ if rngbounds[0] < 0:
+ print('kapok.uavsar.load | Lower range bound ('+str(rngbounds[0])+') is less than zero. Setting lower azimuth bound to zero.')
+ rngbounds[0] = 0
+
+ if rngbounds[1] > rngsize_slc:
+ print('kapok.uavsar.load | Upper range bound ('+str(rngbounds[1])+') greater than number of SLC columns ('+str(rngsize_slc)+').')
+ print('kapok.uavsar.load | Setting upper range bound to '+str(rngsize_slc)+'.')
+ rngbounds[1] = rngsize_slc
+
+
+ # Multi-looked, subsetted, image dimensions:
+ azsize = (azbounds[1]-azbounds[0]) // mlwin[0]
+ rngsize = (rngbounds[1]-rngbounds[0]) // mlwin[1]
+ f.attrs['dim'] = (azsize, rngsize)
+ f.attrs['dim_slc'] = (int(np.sum(azsize_slc)),rngsize_slc)
+ f.attrs['ml_window'] = mlwin
+ f.attrs['sm_window'] = smwin
+ f.attrs['azimuth_bounds_slc'] = azbounds
+ f.attrs['range_bounds_slc'] = rngbounds
+
+ # Path containing SLCs and other files (assume in same folder as .ann):
+ datapath = os.path.dirname(infile)
+ if datapath != '':
+ datapath = datapath + '/'
+
+ # Get filenames of SLCs for each track, in polarization order HH, HV, VV.
+ slcfiles = []
+ for seg in range(num_segments):
+ for tr in range(num_tracks):
+ for pol in ['HH','HV','VV']:
+ file = glob(datapath+tracknames[tr]+'*'+pol+'_*_s'+str(seg+1)+'_1x1.slc')
+
+ if len(file) == 1:
+ slcfiles.append(file[0])
+ elif len(file) > 1:
+ print('kapok.uavsar.load | Too many SLC files matching pattern: "'+datapath+tracknames[tr]+'*_'+pol+'_*_1x1.slc'+'". Aborting.')
+ return
+ else:
+ print('kapok.uavsar.load | Cannot find SLC file matching pattern: "'+datapath+tracknames[tr]+'*_'+pol+'_*_1x1.slc'+'". Aborting.')
+ return
+
+
+ # Initialize covariance matrix dataset in HDF5 file:
+ cov = f.create_dataset('cov', (azsize, rngsize, num_cov_elements, num_cov_elements), dtype='complex64', compression=compression, shuffle=True, compression_opts=compression_opts)
+
+
+ # Calculate covariance matrix.
+ az_vector = np.round(np.linspace(0, azsize, num=num_blocks+1)).astype('int')
+ az_vector[num_blocks] = azsize
+
+ cdef unsigned int seg_start, seg_end, row, col
+ cdef unsigned long azstart, azend, azstart_slc, azend_slc, azoffset_start, azoffset_end
+
+ for n, azstart in enumerate(az_vector[0:-1]):
+ azend = az_vector[n+1]
+ azstart_slc = azstart*mlwin[0] + azbounds[0]
+ azend_slc = azend*mlwin[0] + azbounds[0]
+ seg_start, azoffset_start = findsegment(azstart_slc, azsize_slc)
+ seg_end, azoffset_end = findsegment(azend_slc, azsize_slc)
+
+ print('kapok.uavsar.load | Calculating covariance matrix for rows '+str(azstart)+'-'+str(azend-1)+' / '+str(azsize-1)+' ('+str(np.round(azstart/azsize*100))+'%). ('+time.ctime()+')')
+
+ for slcnum in range(0,num_cov_elements):
+ print('kapok.uavsar.load | Loading SLCs: '+str(slcnum+1)+'/'+str(num_cov_elements)+'. ('+time.ctime()+') ', end='\r')
+ file = slcfiles[slcnum+(seg_start*num_cov_elements)]
+
+ if seg_start == seg_end:
+ slc = getslcblock(file, rngsize_slc, azoffset_start, azoffset_end, rngbounds=rngbounds)
+ else:
+ file2 = slcfiles[slcnum+(seg_end*num_cov_elements)]
+ slc = getslcblock(file, rngsize_slc, azoffset_start, azoffset_end, rngbounds=rngbounds, file2=file2, azsize=azsize_slc[seg_start])
+
+ if slcnum == 0:
+ slcstack = np.zeros((num_cov_elements,slc.shape[0],slc.shape[1]),dtype='complex64')
+
+ if (slcnum % 3) == 1: # HV Polarization
+ slcstack[slcnum] = np.sqrt(2)*slc
+ else: # HH or VV Polarization
+ slcstack[slcnum] = slc
+ else:
+ if (slcnum % 3) == 1: # HV Polarization
+ slcstack[slcnum] = np.sqrt(2)*slc
+ else: # HH or VV Polarization
+ slcstack[slcnum] = slc
+
+
+ for row in range(0,num_cov_elements):
+ for col in range(row,num_cov_elements):
+ print('kapok.uavsar.load | Calculating element: ('+str(row)+','+str(col)+'). ('+time.ctime()+') ', end='\r')
+ cov[azstart:azend,:,row,col] = mlook(slcstack[row]*np.conj(slcstack[col]),mlwin)
+
+ del slcstack
+
+
+ # Boxcar Smoothing:
+ if smwin != (1,1):
+ print('kapok.uavsar.load | Boxcar averaging covariance matrix. ('+time.ctime()+')')
+ for row in range(0,num_cov_elements):
+ for col in range(row,num_cov_elements):
+ cov[:,:,row,col] = smooth(cov[:,:,row,col],smwin)
+
+ cov.attrs['description'] = 'Covariance Matrix'
+ cov.attrs['basis'] = 'lexicographic'
+ cov.attrs['num_pol'] = 3
+ cov.attrs['pol'] = np.array(['HH', 'sqrt(2)*HV', 'VV'],dtype='S')
+ print('kapok.uavsar.load | Covariance matrix calculation completed. ('+time.ctime()+') ')
+
+
+ # Load LLH files.
+ llh = None
+ mlwin_lkv = (int(ann.query('Number of Azimuth Looks in 2x8 SLC')), int(ann.query('Number of Range Looks in 2x8 SLC')))
+
+ for seg in range(num_segments):
+ llhname = ann.query('llh_'+str(seg+1)+'_2x8')
+ file = glob(datapath+llhname)
+
+ if len(file) == 1:
+ llh_rows = int(ann.query('llh_'+str(seg+1)+'_2x8 Rows'))
+ llh_cols = int(ann.query('llh_'+str(seg+1)+'_2x8 Columns'))
+ if llh is None:
+ llh = np.memmap(file[0], dtype='float32', mode='r', shape=(llh_rows, llh_cols, 3))
+ else:
+ llh = np.vstack((llh, np.memmap(file[0], dtype='float32', mode='r', shape=(llh_rows, llh_cols, 3))))
+ elif len(file) > 1:
+ print('kapok.uavsar.load | Too many LLH files matching pattern: "'+datapath+llhname+'". Aborting.')
+ return
+ else:
+ print('kapok.uavsar.load | Cannot find LLH file matching pattern: "'+datapath+llhname+'". Aborting.')
+ return
+
+
+ # Initialize latitude dataset and import values:
+ print('kapok.uavsar.load | Importing latitude values. ('+time.ctime()+')')
+ lat = f.create_dataset('lat', (azsize, rngsize), dtype='float32', compression=compression, compression_opts=compression_opts)
+ lat[:] = mlook(zoom(llh[:,:,0],mlwin_lkv)[azbounds[0]:azbounds[1],rngbounds[0]:rngbounds[1]],mlwin)
+ lat.attrs['units'] = 'degrees'
+ lat.attrs['description'] = 'Latitude'
+
+ # Initialize longitude dataset and import values:
+ print('kapok.uavsar.load | Importing longitude values. ('+time.ctime()+')')
+ lon = f.create_dataset('lon', (azsize, rngsize), dtype='float32', compression=compression, compression_opts=compression_opts)
+ lon[:] = mlook(zoom(llh[:,:,1],mlwin_lkv)[azbounds[0]:azbounds[1],rngbounds[0]:rngbounds[1]],mlwin)
+ lon.attrs['units'] = 'degrees'
+ lon.attrs['description'] = 'Longitude'
+
+ # Initialize DEM height dataset and import values:
+ print('kapok.uavsar.load | Importing DEM heights. ('+time.ctime()+')')
+ dem = f.create_dataset('dem', (azsize, rngsize), dtype='float32', compression=compression, compression_opts=compression_opts)
+ dem[:] = mlook(zoom(llh[:,:,2],mlwin_lkv)[azbounds[0]:azbounds[1],rngbounds[0]:rngbounds[1]],mlwin)
+ dem.attrs['units'] = 'meters'
+ dem.attrs['description'] = 'Processor DEM'
+
+ del llh
+
+
+ # Initialize master track incidence angle dataset:
+ inc = f.create_dataset('inc', (azsize, rngsize), dtype='float32', compression=compression, compression_opts=compression_opts)
+ inc.attrs['units'] = 'radians'
+ inc.attrs['description'] = 'Master Track Incidence Angle'
+
+ # Initialize kz dataset:
+ if num_bl > 1:
+ kz = f.create_dataset('kz', (num_bl, azsize, rngsize), dtype='float32', compression=compression, compression_opts=compression_opts)
+ else:
+ kz = f.create_dataset('kz', (azsize, rngsize), dtype='float32', compression=compression, compression_opts=compression_opts)
+ kz.attrs['units'] = 'radians/meter'
+ kz.attrs['description'] = 'Interferometric Vertical Wavenumber'
+
+
+ # Load LKV files.
+ lkvmm = None
+ for seg in range(num_segments):
+ lkvname = ann.query('lkv_'+str(seg+1)+'_2x8')
+ file = glob(datapath+lkvname)
+
+ if len(file) == 1:
+ lkv_rows = int(ann.query('lkv_'+str(seg+1)+'_2x8 Rows'))
+ lkv_cols = int(ann.query('lkv_'+str(seg+1)+'_2x8 Columns'))
+ if lkvmm is None:
+ lkvmm = np.memmap(file[0], dtype='float32', mode='r', shape=(lkv_rows, lkv_cols, 3))
+ else:
+ lkvmm = np.vstack((lkvmm, np.memmap(file[0], dtype='float32', mode='r', shape=(lkv_rows, lkv_cols, 3))))
+ elif len(file) > 1:
+ print('kapok.uavsar.load | Too many LKV files matching pattern: "'+datapath+lkvname+'". Aborting.')
+ return
+ else:
+ print('kapok.uavsar.load | Cannot find LKV file matching pattern: "'+datapath+lkvname+'". Aborting.')
+ return
+
+
+ # Get SCH Peg from Annotation File
+ peglat = ann.query('Peg Latitude')
+ peglon = ann.query('Peg Longitude')
+ peghdg = ann.query('Peg Heading')
+ f.attrs['peg_latitude'] = peglat
+ f.attrs['peg_longitude'] = peglon
+ f.attrs['peg_heading'] = peghdg
+
+ # Save in attributes as degrees, but convert to radians for coordinate transformation functions.
+ peglat = np.radians(peglat)
+ peglon = np.radians(peglon)
+ peghdg = np.radians(peghdg)
+
+ # Get sensor wavelength from annotation file.
+ wavelength = ann.query('Center Wavelength')
+ wavelength /= 100 # convert from cm to m
+ f.attrs['wavelength'] = wavelength
+
+ # Starting S coordinate of SLCs, and S coordinate spacing (in meters).
+ sstart = ann.query('slc_1_1x1_mag.row_addr')
+ sspacing = ann.query('slc_1_1x1_mag.row_mult')
+
+ # S Coordinate Bounds for Desired Subset:
+ sbounds = azbounds*sspacing + sstart
+
+
+ # Kz Calculation for Each Baseline
+
+ # Statically Defined Variables
+ cdef np.ndarray[np.float64_t, ndim=3] lkv = np.array(lkvmm,dtype='float64')
+ del lkvmm
+ cdef np.ndarray[np.float64_t, ndim=2] masterlkv = np.zeros((rngsize_slc,3),dtype='float64')
+ cdef np.ndarray[np.float64_t, ndim=2] slavelkv = np.zeros((rngsize_slc,3),dtype='float64')
+ cdef np.ndarray[np.float64_t, ndim=2] lookcrossv = np.zeros((rngsize_slc,3),dtype='float64')
+
+ cdef np.ndarray[np.float64_t, ndim=2] inc_slc = np.zeros((azbounds[1]-azbounds[0],rngsize_slc),dtype='float64')
+ cdef np.ndarray[np.float32_t, ndim=2] kz_slc = np.zeros((azbounds[1]-azbounds[0],rngsize_slc),dtype='float32')
+
+ cdef np.ndarray[np.float64_t] velocityenu = np.array(sch2enu(1, 0, 0, peglat, peglon, peghdg)).astype('float64')
+ cdef np.ndarray[np.float64_t, ndim=2] proj_lkv_velocity = np.zeros((rngsize_slc,3),dtype='float64')
+
+ cdef np.ndarray[np.float64_t] tempinc = np.zeros((rngsize_slc),dtype='float64')
+ cdef np.ndarray[np.float64_t, ndim=2] tempdiff = np.zeros((rngsize_slc,3),dtype='float64')
+
+ cdef np.ndarray[np.float64_t, ndim=2] mbaseenu = np.zeros((azbounds[1]-azbounds[0],3),dtype='float64')
+ cdef np.ndarray[np.float64_t, ndim=2] sbaseenu = np.zeros((azbounds[1]-azbounds[0],3),dtype='float64')
+ cdef np.ndarray[np.float64_t] baseline = np.zeros((3),dtype='float64')
+ cdef np.ndarray[np.float64_t] baselinep = np.zeros((rngsize_slc),dtype='float64')
+ cdef np.ndarray[np.float64_t] baselinepsign = np.zeros((rngsize_slc),dtype='float64')
+
+ cdef unsigned int master, slave
+ cdef unsigned long az
+
+
+ # Main Kz/Incidence Calculation Loop
+ for master in range(0,num_tracks-1):
+ mbasefile = glob(datapath+tracknames[master]+'*HH*.baseline')
+
+ if len(mbasefile) == 1:
+ mbasesch = np.loadtxt(mbasefile[0])
+ elif len(mbasefile) > 1:
+ print('kapok.uavsar.load | Too many .baseline files matching pattern: "'+datapath+tracknames[master]+'*HH*.baseline'+'". Aborting.')
+ return
+ else:
+ print('kapok.uavsar.load | Cannot find .baseline file matching pattern: "'+datapath+tracknames[master]+'*HH*.baseline'+'". Aborting.')
+ return
+
+ istart = np.where(np.isclose(mbasesch[:,0],sbounds[0]))[0][0] # index of first azimuth line in subset
+ iend = np.where(np.isclose(mbasesch[:,0],sbounds[1]))[0][0] # index of last azimuth line in subset
+ mbaseenu[:] = sch2enu(mbasesch[istart:iend,1],mbasesch[istart:iend,2],mbasesch[istart:iend,3], peglat, peglon, peghdg)[0:mbaseenu.shape[0],:]
+
+ for slave in range(master+1,num_tracks):
+ print('kapok.uavsar.load | Calculating kz for tracks '+str(master)+' and '+str(slave)+'. ('+time.ctime()+')')
+
+ sbasefile = glob(datapath+tracknames[slave]+'*HH*.baseline')
+
+ if len(sbasefile) == 1:
+ sbasesch = np.loadtxt(sbasefile[0])
+ elif len(sbasefile) > 1:
+ print('kapok.uavsar.load | Too many .baseline files matching pattern: "'+datapath+tracknames[slave]+'*HH*.baseline'+'". Aborting.')
+ return
+ else:
+ print('kapok.uavsar.load | Cannot find .baseline file matching pattern: "'+datapath+tracknames[slave]+'*HH*.baseline'+'". Aborting.')
+ return
+
+ sbaseenu[:] = sch2enu(sbasesch[istart:iend,1],sbasesch[istart:iend,2],sbasesch[istart:iend,3], peglat, peglon, peghdg)[0:sbaseenu.shape[0],:]
+
+ for az in range(0,azbounds[1]-azbounds[0]):
+ lkvrowindex = (az+azbounds[0]) // mlwin_lkv[0]
+
+ masterlkv[:,0] = (zoom(lkv[lkvrowindex,:,0],mlwin_lkv[1]) - mbaseenu[az,0])[0:rngsize_slc]
+ masterlkv[:,1] = (zoom(lkv[lkvrowindex,:,1],mlwin_lkv[1]) - mbaseenu[az,0])[0:rngsize_slc]
+ masterlkv[:,2] = (zoom(lkv[lkvrowindex,:,2],mlwin_lkv[1]) - mbaseenu[az,0])[0:rngsize_slc]
+
+ # Project look vector onto velocity vector.
+ proj_lkv_velocity = np.sum(masterlkv*velocityenu,axis=1)[:,np.newaxis]*velocityenu/np.linalg.norm(velocityenu)
+
+ # Component of look vector orthogonal to velocity.
+ tempdiff = (masterlkv-proj_lkv_velocity)
+ inc_slc[az,:] = np.arccos(np.abs(tempdiff[:,2])/np.linalg.norm(tempdiff,axis=1))
+
+ lookcrossv[:,0] = masterlkv[:,1]*velocityenu[2] - masterlkv[:,2]*velocityenu[1]
+ lookcrossv[:,1] = masterlkv[:,2]*velocityenu[0] - masterlkv[:,0]*velocityenu[2]
+ lookcrossv[:,2] = masterlkv[:,0]*velocityenu[1] - masterlkv[:,1]*velocityenu[0]
+ lookcrossv *= -1
+
+ slavelkv[:,0] = masterlkv[:,0] + mbaseenu[az,0] - sbaseenu[az,0]
+ slavelkv[:,1] = masterlkv[:,1] + mbaseenu[az,0] - sbaseenu[az,0]
+ slavelkv[:,2] = masterlkv[:,2] + mbaseenu[az,0] - sbaseenu[az,0]
+
+ baseline = mbaseenu[az] - sbaseenu[az]
+
+ baselinepsign = np.sum(baseline*lookcrossv,axis=1)/np.sum(lookcrossv*lookcrossv,axis=1)
+ baselinep = np.linalg.norm((np.sum(baseline*lookcrossv,axis=1)/np.sum(lookcrossv*lookcrossv,axis=1))[:,np.newaxis]*lookcrossv,axis=1)
+
+ kz_slc[az] = (4*np.pi/wavelength) * baselinep / (np.linalg.norm(masterlkv,axis=1)*np.sin(inc_slc[az,:])) * np.sign(baselinepsign)
+
+
+ bl = int(slave*(slave-1)/2 + master)
+ if num_bl > 1:
+ kz[bl] = mlook(kz_slc[:,rngbounds[0]:rngbounds[1]], mlwin)
+ else:
+ kz[:] = mlook(kz_slc[:,rngbounds[0]:rngbounds[1]], mlwin)
+
+ if master == 0: # save incidence angle
+ print('kapok.uavsar.load | Saving incidence angle for track 0. ('+time.ctime()+')')
+ inc[:] = mlook(inc_slc[:,rngbounds[0]:rngbounds[1]], mlwin)
+
+ del kz_slc, inc_slc
+
+ # Close the file, then return it as a Scene object.
+ f.close()
+ return kapok.Scene(outfile)
+
+
+class Ann(object):
+ """Class for loading and interacting with a UAVSAR annotation file."""
+
+ def __init__(self, file):
+ """Load in the specified .ann file as a list of strings and
+ initialize.
+
+ Arguments:
+ file (str): UAVSAR annotation filename to load.
+
+ """
+ self.file = file
+ fd = open(self.file, 'r')
+ self.ann = fd.read().split('\n')
+ return
+
+
+ def query(self, keyword):
+ """Query the annotation file for the specified annotation keyword.
+
+ Arguments:
+ keyword (str): The keyword to query.
+
+ Returns:
+ value: The value of the specified keyword.
+
+ """
+ for n in range(len(self.ann)):
+ if self.ann[n].startswith(keyword):
+ try:
+ val = self.ann[n].rsplit('=')[-1].split(';')[0].split()[0]
+ val = np.array(val,dtype='float') # if we can convert the string to a number, do so
+ if (val - np.floor(val)) == 0:
+ val = np.array(val,dtype='int') # if it's an integer, convert it to one (e.g., number of samples)
+ return val
+ except ValueError: # if we can't convert the string to a number, leave it as a string
+ val = self.ann[n].split('=',maxsplit=1)[-1].split(';')[0].strip()
+ return val
+
+ return None
+
+
+def findsegment(az,azsize):
+ """For a given azimuth index, return the segment number and
+ the azimuth index within the given segment.
+
+ Arguments:
+ az: Azimuth index of interest.
+ azsize: List containing the azimuth size of each segment.
+
+ Returns:
+ seg: Segment number.
+ azoff: Azimuth index within the segment.
+
+ """
+ azstart = np.insert(np.cumsum(azsize), 0, 0)[0:-1]
+
+ if az <= np.sum(azsize):
+ seg = np.max(np.where(azstart <= az))
+ azoff = az - azstart[seg]
+ else:
+ seg = azstart.shape[0] - 1
+ azoff = azsize[seg]
+ print('kapok.uavsar.fingsegment | SLC row index of '+str(az)+' is larger than the size of the data. Returning maximum index.')
+
+ return seg, azoff
+
+
+def getslcblock(file, rngsize, azstart, azend, rngbounds=None, file2=None,
+ azsize=None):
+ """Load SLC data into a NumPy array buffer. If the file2 argument is
+ specified in the arguments, this function will treat the two files as
+ consecutive segments, and will join them.
+
+ Arguments:
+ file (str): Filename of the first SLC.
+ rngsize (int): Number of columns (range bins). Same for both SLCs.
+ azstart (int): Azimuth index at which to start the buffer, in the
+ first SLC.
+ azend (int): Azimuth index at which to end the buffer. If file2
+ is specified, this is an azimuth index in the second SLC. If
+ file2 is not specified, this is an azimuth index in the first SLC.
+ The row specified by azend is not actually included in the buffer,
+ as in the Python range() function. (azend-1) is the last line
+ included in the buffer. To load the entire SLC, azend should be
+ equal to the number of rows in SLC.
+ rngbounds (tuple, int): Starting and ending range bounds, if range
+ subsetting is desired.
+ file2 (str): Filename of the second SLC, if combining multiple
+ segments is desired.
+ azsize (int): Number of rows (azimuth bins) for the first SLC. Only
+ required if file2 is specified. Otherwise we only load in the
+ lines of the SLC before azend.
+
+ Returns:
+ block: NumPy array of complex64 datatype, containing the loaded SLC
+ data between the specified azimuth bounds.
+
+ """
+ if file2 is None:
+ byteoffset = rngsize * 8 * azstart
+ slc = np.memmap(file, dtype='complex64', mode='c', offset=byteoffset, shape=(azend-azstart,rngsize))
+ if rngbounds is not None:
+ slc = slc[:,rngbounds[0]:rngbounds[1]]
+ return slc
+ elif azsize is None:
+ print('kapok.uavsar.getslcblock: "file2" argument specified, but "azsize" argument missing. Aborting.')
+ return
+ else:
+ byteoffset = rngsize * 8 * azstart
+ slca = np.memmap(file, dtype='complex64', mode='c', offset=byteoffset, shape=(azsize-azstart,rngsize))
+ slcb = np.memmap(file2, dtype='complex64', mode='c', shape=(azend,rngsize))
+ if rngbounds is not None:
+ slca = slca[:,rngbounds[0]:rngbounds[1]]
+ slcb = slcb[:,rngbounds[0]:rngbounds[1]]
+ return np.vstack((slca,slcb))
\ No newline at end of file
diff --git a/kapok/uavsarc.pyxbld b/kapok/uavsarc.pyxbld
new file mode 100755
index 0000000..6349da4
--- /dev/null
+++ b/kapok/uavsarc.pyxbld
@@ -0,0 +1,5 @@
+def make_ext(modname, pyxfilename):
+ from distutils.extension import Extension
+ return Extension(name=modname,
+ sources=[pyxfilename],
+ extra_compile_args=['-w'])
\ No newline at end of file
diff --git a/kapok/uavsarp.py b/kapok/uavsarp.py
new file mode 100755
index 0000000..12396df
--- /dev/null
+++ b/kapok/uavsarp.py
@@ -0,0 +1,643 @@
+# -*- coding: utf-8 -*-
+# cython: language_level=3
+"""UAVSAR Data Import Cython Functions
+
+ Module for importing UAVSAR data. This is Python code which the uavsar.py
+ wrapper module defaults to when the Cython import fails.
+
+ Author: Michael Denbina
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import os
+import os.path
+import time
+from glob import glob
+
+import numpy as np
+import h5py
+from scipy.ndimage.interpolation import zoom
+
+import kapok
+from kapok.lib import mlook, smooth, sch2enu
+
+
+
+def load(infile, outfile, mlwin=(20,5), smwin=(1,1), azbounds=None,
+ rngbounds=None, tracks=None, compression='gzip',
+ compression_opts=4, num_blocks=20, overwrite=False):
+ """Load a UAVSAR dataset into the Kapok format, and save it to target HDF5
+ file.
+
+ Arguments:
+ infile (str): Path and filename of a UAVSAR .ann file containing the
+ metadata for a UAVSAR SLC stack.
+ outfile (str): Path and filename for the saved HDF5 dataset.
+ mlwin: Tuple containing the multilooking window sizes in azimuth and
+ slant range (in that order). div=(12,3) results in multilooking
+ using a window of 12 pixels in azimuth and 3 pixels in slant range.
+ Within the window, all SLC pixels are averaged into a single
+ covariance matrix, reducing the size of the data. The size of the
+ incidence angle, latitude, longitude, and other rasters are also
+ reduced by the same factor. Default: (20,5).
+ smwin: Tuple containing boxcar moving average window sizes in azimuth
+ and slant range (in that order). Each covariance matrix will be
+ smoothed using this window, without reducing the number of pixels
+ in the data. Smoothing is performed after multilooking, if both
+ are specified. Default: (1,1).
+ azbounds: List containing starting and ending SLC azimuth index for
+ desired subset. Data outside these bounds will not be loaded.
+ Default is to import all data.
+ rngbounds: List containing starting and ending SLC range index for
+ desired subset. Data outside these bounds will not be loaded.
+ Default is to import all data.
+ tracks: List containing desired track indices to import. For example,
+ tracks=[0,1] will import only the first two tracks listed in the
+ annotation file. Default: All tracks imported.
+ compression (str): Compression keyword used when creating the HDF5
+ datasets to store the covariance matrix, incidence angle, kz,
+ and DEM heights. Default: 'gzip'.
+ compression_opts (int): Compression option value used when creating
+ the HDF5 datasets. Number from 0 to 9, with 9 being maximum
+ compression. Default: 4.
+ num_blocks (int): Number of blocks to use for splitting up the
+ covariance matrix calculation. Should be a positive integer
+ >= 1. Higher numbers use less memory, but will be slower.
+ Default: 15.
+ overwrite (bool): Set to True to overwrite an existing Kapok HDF5
+ file if necessary. Default: False.
+
+ Returns:
+ scene: A Kapok scene object pointing to the newly created HDF5 file.
+
+ """
+ # Load the annotation file.
+ try:
+ ann = Ann(infile)
+ except:
+ print('kapok.uavsar.load | Cannot load UAVSAR annotation file. Aborting.')
+ return
+
+
+ # Create the HDF5 file.
+ if overwrite:
+ try:
+ f = h5py.File(outfile,'w')
+ except:
+ print('kapok.uavsar.load | Cannot create new HDF5 file. Check if path is valid. Aborting.')
+ return
+ else:
+ try:
+ f = h5py.File(outfile,'x')
+ except:
+ print('kapok.uavsar.load | Cannot create new HDF5 file. Check if path is valid and ensure file does not already exist. Aborting.')
+ return
+
+
+
+ # Get SLC dimensions and number of segments.
+ rngsize_slc = ann.query('slc_1_1x1 Columns')
+ num_segments = ann.query('Number of Segments')
+ if num_segments > 1:
+ azsize_slc = np.zeros(num_segments,dtype='int32')
+ for n in range(num_segments):
+ azsize_slc[n] = ann.query('slc_'+str(n+1)+'_1x1 Rows')
+ else:
+ azsize_slc = ann.query('slc_1_1x1 Rows')
+
+
+ # Get track filenames and number of tracks.
+ temp = ann.query('stackline1')
+ num = 1
+ if temp is not None:
+ tracknames = [temp.split('_L090')[0]]
+ num += 1
+ temp = ann.query('stackline'+str(num))
+ while temp is not None:
+ tracknames.append(temp.split('_L090')[0])
+ num += 1
+ temp = ann.query('stackline'+str(num))
+ else:
+ print('kapok.uavsar.load | Cannot find track names in UAVSAR annotation file. Aborting.')
+ return
+
+
+ # Subset track names if desired tracks were specified:
+ tracknames = np.array(tracknames)
+ if tracks is not None:
+ tracks = np.array(tracks,dtype='int')
+ tracknames = tracknames[tracks]
+
+ num_tracks = len(tracknames) # Number of Tracks
+ num_bl = int(num_tracks * (num_tracks-1) / 2) # Number of Baselines
+ num_pol = int(3) # Number of Polarizations (HH, sqrt(2)*HV, VV)
+ num_cov_elements = num_tracks*num_pol # Number of Covariance Matrix Elements in Each Row
+
+ f.attrs['stack_name'] = ann.query('Stack Name')
+ f.attrs['site'] = ann.query('Site Description')
+ f.attrs['url'] = ann.query('URL')
+ f.attrs['sensor'] = 'UAVSAR'
+ f.attrs['processor'] = 'production'
+
+ print('kapok.uavsar.load | Stack ID: '+f.attrs['stack_name'])
+ print('kapok.uavsar.load | Site Description: '+f.attrs['site'])
+ print('kapok.uavsar.load | URL: '+f.attrs['url'])
+
+ print('kapok.uavsar.load | Importing metadata. ('+time.ctime()+')')
+
+ f.attrs['average_altitude'] = ann.query('Average Altitude')
+ f.attrs['image_starting_slant_range'] = ann.query('Image Starting Slant Range')*1000
+ f.attrs['slc_azimuth_pixel_spacing'] = ann.query('1x1 SLC Azimuth Pixel Spacing')
+ f.attrs['slc_slant_range_pixel_spacing'] = ann.query('1x1 SLC Range Pixel Spacing')
+ f.attrs['cov_azimuth_pixel_spacing'] = ann.query('1x1 SLC Azimuth Pixel Spacing') * mlwin[0]
+ f.attrs['cov_slant_range_pixel_spacing'] = ann.query('1x1 SLC Range Pixel Spacing') * mlwin[1]
+
+ f.attrs['num_tracks'] = num_tracks
+ f.attrs['num_baselines'] = num_bl
+ f.attrs['tracks'] = np.array(tracknames,dtype='S')
+
+ f.attrs['compression'] = compression
+ f.attrs['compression_opts'] = compression_opts
+
+ if (azbounds is not None) or (rngbounds is not None):
+ f.attrs['subset'] = True
+ else:
+ f.attrs['subset'] = False
+
+
+ # Check azimuth bounds for validity.
+ if azbounds is None:
+ azbounds = [0,np.sum(azsize_slc)]
+
+ if azbounds[1] <= azbounds[0]:
+ print('kapok.uavsar.load | Invalid azimuth bounds. Must be ascending. Aborting.')
+ return
+
+ if azbounds[0] < 0:
+ print('kapok.uavsar.load | Lower azimuth bound ('+str(azbounds[0])+') is less than zero. Setting lower azimuth bound to zero.')
+ azbounds[0] = 0
+
+ if azbounds[1] > np.sum(azsize_slc):
+ print('kapok.uavsar.load | Upper azimuth bound ('+str(azbounds[1])+') greater than number of SLC lines ('+str(azsize_slc)+').')
+ print('kapok.uavsar.load | Setting upper azimuth bound to '+str(azsize_slc)+'.')
+ azbounds[1] = np.sum(azsize_slc)
+
+
+ # Check range bounds for validity.
+ if rngbounds is None:
+ rngbounds = [0,rngsize_slc]
+
+ if rngbounds[1] <= rngbounds[0]:
+ print('kapok.uavsar.load | Invalid range bounds. Must be ascending. Aborting.')
+ return
+
+ if rngbounds[0] < 0:
+ print('kapok.uavsar.load | Lower range bound ('+str(rngbounds[0])+') is less than zero. Setting lower azimuth bound to zero.')
+ rngbounds[0] = 0
+
+ if rngbounds[1] > rngsize_slc:
+ print('kapok.uavsar.load | Upper range bound ('+str(rngbounds[1])+') greater than number of SLC columns ('+str(rngsize_slc)+').')
+ print('kapok.uavsar.load | Setting upper range bound to '+str(rngsize_slc)+'.')
+ rngbounds[1] = rngsize_slc
+
+
+ # Multi-looked, subsetted, image dimensions:
+ azsize = (azbounds[1]-azbounds[0]) // mlwin[0]
+ rngsize = (rngbounds[1]-rngbounds[0]) // mlwin[1]
+ f.attrs['dim'] = (azsize, rngsize)
+ f.attrs['dim_slc'] = (int(np.sum(azsize_slc)),rngsize_slc)
+ f.attrs['ml_window'] = mlwin
+ f.attrs['sm_window'] = smwin
+ f.attrs['azimuth_bounds_slc'] = azbounds
+ f.attrs['range_bounds_slc'] = rngbounds
+
+ # Path containing SLCs and other files (assume in same folder as .ann):
+ datapath = os.path.dirname(infile)
+ if datapath != '':
+ datapath = datapath + '/'
+
+ # Get filenames of SLCs for each track, in polarization order HH, HV, VV.
+ slcfiles = []
+ for seg in range(num_segments):
+ for tr in range(num_tracks):
+ for pol in ['HH','HV','VV']:
+ file = glob(datapath+tracknames[tr]+'*'+pol+'_*_s'+str(seg+1)+'_1x1.slc')
+
+ if len(file) == 1:
+ slcfiles.append(file[0])
+ elif len(file) > 1:
+ print('kapok.uavsar.load | Too many SLC files matching pattern: "'+datapath+tracknames[tr]+'*_'+pol+'_*_1x1.slc'+'". Aborting.')
+ return
+ else:
+ print('kapok.uavsar.load | Cannot find SLC file matching pattern: "'+datapath+tracknames[tr]+'*_'+pol+'_*_1x1.slc'+'". Aborting.')
+ return
+
+
+ # Initialize covariance matrix dataset in HDF5 file:
+ cov = f.create_dataset('cov', (azsize, rngsize, num_cov_elements, num_cov_elements), dtype='complex64', compression=compression, shuffle=True, compression_opts=compression_opts)
+
+
+ # Calculate covariance matrix.
+ az_vector = np.round(np.linspace(0, azsize, num=num_blocks+1)).astype('int')
+ az_vector[num_blocks] = azsize
+
+ for n, azstart in enumerate(az_vector[0:-1]):
+ azend = az_vector[n+1]
+ azstart_slc = azstart*mlwin[0] + azbounds[0]
+ azend_slc = azend*mlwin[0] + azbounds[0]
+ seg_start, azoffset_start = findsegment(azstart_slc, azsize_slc)
+ seg_end, azoffset_end = findsegment(azend_slc, azsize_slc)
+
+ print('kapok.uavsar.load | Calculating covariance matrix for rows '+str(azstart)+'-'+str(azend-1)+' / '+str(azsize-1)+' ('+str(np.round(azstart/azsize*100))+'%). ('+time.ctime()+')')
+
+ for slcnum in range(0,num_cov_elements):
+ print('kapok.uavsar.load | Loading SLCs: '+str(slcnum+1)+'/'+str(num_cov_elements)+'. ('+time.ctime()+') ', end='\r')
+ file = slcfiles[slcnum+(seg_start*num_cov_elements)]
+
+ if seg_start == seg_end:
+ slc = getslcblock(file, rngsize_slc, azoffset_start, azoffset_end, rngbounds=rngbounds)
+ else:
+ file2 = slcfiles[slcnum+(seg_end*num_cov_elements)]
+ slc = getslcblock(file, rngsize_slc, azoffset_start, azoffset_end, rngbounds=rngbounds, file2=file2, azsize=azsize_slc[seg_start])
+
+ if slcnum == 0:
+ slcstack = np.zeros((num_cov_elements,slc.shape[0],slc.shape[1]),dtype='complex64')
+
+ if (slcnum % 3) == 1: # HV Polarization
+ slcstack[slcnum] = np.sqrt(2)*slc
+ else: # HH or VV Polarization
+ slcstack[slcnum] = slc
+ else:
+ if (slcnum % 3) == 1: # HV Polarization
+ slcstack[slcnum] = np.sqrt(2)*slc
+ else: # HH or VV Polarization
+ slcstack[slcnum] = slc
+
+
+ for row in range(0,num_cov_elements):
+ for col in range(row,num_cov_elements):
+ print('kapok.uavsar.load | Calculating element: ('+str(row)+','+str(col)+'). ('+time.ctime()+') ', end='\r')
+ cov[azstart:azend,:,row,col] = mlook(slcstack[row]*np.conj(slcstack[col]),mlwin)
+
+ del slcstack
+
+
+ # Boxcar Smoothing:
+ if smwin != (1,1):
+ print('kapok.uavsar.load | Boxcar averaging covariance matrix. ('+time.ctime()+')')
+ for row in range(0,num_cov_elements):
+ for col in range(row,num_cov_elements):
+ cov[:,:,row,col] = smooth(cov[:,:,row,col],smwin)
+
+ cov.attrs['description'] = 'Covariance Matrix'
+ cov.attrs['basis'] = 'lexicographic'
+ cov.attrs['num_pol'] = 3
+ cov.attrs['pol'] = np.array(['HH', 'sqrt(2)*HV', 'VV'],dtype='S')
+ print('kapok.uavsar.load | Covariance matrix calculation completed. ('+time.ctime()+') ')
+
+
+ # Load LLH files.
+ llh = None
+ mlwin_lkv = (int(ann.query('Number of Azimuth Looks in 2x8 SLC')), int(ann.query('Number of Range Looks in 2x8 SLC')))
+
+ for seg in range(num_segments):
+ llhname = ann.query('llh_'+str(seg+1)+'_2x8')
+ file = glob(datapath+llhname)
+
+ if len(file) == 1:
+ llh_rows = int(ann.query('llh_'+str(seg+1)+'_2x8 Rows'))
+ llh_cols = int(ann.query('llh_'+str(seg+1)+'_2x8 Columns'))
+ if llh is None:
+ llh = np.memmap(file[0], dtype='float32', mode='r', shape=(llh_rows, llh_cols, 3))
+ else:
+ llh = np.vstack((llh, np.memmap(file[0], dtype='float32', mode='r', shape=(llh_rows, llh_cols, 3))))
+ elif len(file) > 1:
+ print('kapok.uavsar.load | Too many LLH files matching pattern: "'+datapath+llhname+'". Aborting.')
+ return
+ else:
+ print('kapok.uavsar.load | Cannot find LLH file matching pattern: "'+datapath+llhname+'". Aborting.')
+ return
+
+
+ # Initialize latitude dataset and import values:
+ print('kapok.uavsar.load | Importing latitude values. ('+time.ctime()+')')
+ lat = f.create_dataset('lat', (azsize, rngsize), dtype='float32', compression=compression, compression_opts=compression_opts)
+ lat[:] = mlook(zoom(llh[:,:,0],mlwin_lkv)[azbounds[0]:azbounds[1],rngbounds[0]:rngbounds[1]],mlwin)
+ lat.attrs['units'] = 'degrees'
+ lat.attrs['description'] = 'Latitude'
+
+ # Initialize longitude dataset and import values:
+ print('kapok.uavsar.load | Importing longitude values. ('+time.ctime()+')')
+ lon = f.create_dataset('lon', (azsize, rngsize), dtype='float32', compression=compression, compression_opts=compression_opts)
+ lon[:] = mlook(zoom(llh[:,:,1],mlwin_lkv)[azbounds[0]:azbounds[1],rngbounds[0]:rngbounds[1]],mlwin)
+ lon.attrs['units'] = 'degrees'
+ lon.attrs['description'] = 'Longitude'
+
+ # Initialize DEM height dataset and import values:
+ print('kapok.uavsar.load | Importing DEM heights. ('+time.ctime()+')')
+ dem = f.create_dataset('dem', (azsize, rngsize), dtype='float32', compression=compression, compression_opts=compression_opts)
+ dem[:] = mlook(zoom(llh[:,:,2],mlwin_lkv)[azbounds[0]:azbounds[1],rngbounds[0]:rngbounds[1]],mlwin)
+ dem.attrs['units'] = 'meters'
+ dem.attrs['description'] = 'Processor DEM'
+
+ del llh
+
+
+ # Initialize master track incidence angle dataset:
+ inc = f.create_dataset('inc', (azsize, rngsize), dtype='float32', compression=compression, compression_opts=compression_opts)
+ inc.attrs['units'] = 'radians'
+ inc.attrs['description'] = 'Master Track Incidence Angle'
+
+ # Initialize kz dataset:
+ if num_bl > 1:
+ kz = f.create_dataset('kz', (num_bl, azsize, rngsize), dtype='float32', compression=compression, compression_opts=compression_opts)
+ else:
+ kz = f.create_dataset('kz', (azsize, rngsize), dtype='float32', compression=compression, compression_opts=compression_opts)
+ kz.attrs['units'] = 'radians/meter'
+ kz.attrs['description'] = 'Interferometric Vertical Wavenumber'
+
+
+ # Load LKV files.
+ lkvmm = None
+ for seg in range(num_segments):
+ lkvname = ann.query('lkv_'+str(seg+1)+'_2x8')
+ file = glob(datapath+lkvname)
+
+ if len(file) == 1:
+ lkv_rows = int(ann.query('lkv_'+str(seg+1)+'_2x8 Rows'))
+ lkv_cols = int(ann.query('lkv_'+str(seg+1)+'_2x8 Columns'))
+ if lkvmm is None:
+ lkvmm = np.memmap(file[0], dtype='float32', mode='r', shape=(lkv_rows, lkv_cols, 3))
+ else:
+ lkvmm = np.vstack((lkvmm, np.memmap(file[0], dtype='float32', mode='r', shape=(lkv_rows, lkv_cols, 3))))
+ elif len(file) > 1:
+ print('kapok.uavsar.load | Too many LKV files matching pattern: "'+datapath+lkvname+'". Aborting.')
+ return
+ else:
+ print('kapok.uavsar.load | Cannot find LKV file matching pattern: "'+datapath+lkvname+'". Aborting.')
+ return
+
+
+ # Get SCH Peg from Annotation File
+ peglat = ann.query('Peg Latitude')
+ peglon = ann.query('Peg Longitude')
+ peghdg = ann.query('Peg Heading')
+ f.attrs['peg_latitude'] = peglat
+ f.attrs['peg_longitude'] = peglon
+ f.attrs['peg_heading'] = peghdg
+
+ # Save in attributes as degrees, but convert to radians for coordinate transformation functions.
+ peglat = np.radians(peglat)
+ peglon = np.radians(peglon)
+ peghdg = np.radians(peghdg)
+
+ # Get sensor wavelength from annotation file.
+ wavelength = ann.query('Center Wavelength')
+ wavelength /= 100 # convert from cm to m
+ f.attrs['wavelength'] = wavelength
+
+ # Starting S coordinate of SLCs, and S coordinate spacing (in meters).
+ sstart = ann.query('slc_1_1x1_mag.row_addr')
+ sspacing = ann.query('slc_1_1x1_mag.row_mult')
+
+ # S Coordinate Bounds for Desired Subset:
+ sbounds = azbounds*sspacing + sstart
+
+
+ # Kz Calculation for Each Baseline
+
+ # Statically Defined Variables
+ lkv = np.array(lkvmm,dtype='float64')
+ del lkvmm
+ masterlkv = np.zeros((rngsize_slc,3),dtype='float64')
+ slavelkv = np.zeros((rngsize_slc,3),dtype='float64')
+ lookcrossv = np.zeros((rngsize_slc,3),dtype='float64')
+
+ inc_slc = np.zeros((azbounds[1]-azbounds[0],rngsize_slc),dtype='float64')
+ kz_slc = np.zeros((azbounds[1]-azbounds[0],rngsize_slc),dtype='float32')
+
+ velocityenu = np.array(sch2enu(1, 0, 0, peglat, peglon, peghdg)).astype('float64')
+ proj_lkv_velocity = np.zeros((rngsize_slc,3),dtype='float64')
+
+ tempinc = np.zeros((rngsize_slc),dtype='float64')
+ tempdiff = np.zeros((rngsize_slc,3),dtype='float64')
+
+ mbaseenu = np.zeros((azbounds[1]-azbounds[0],3),dtype='float64')
+ sbaseenu = np.zeros((azbounds[1]-azbounds[0],3),dtype='float64')
+ baseline = np.zeros((3),dtype='float64')
+ baselinep = np.zeros((rngsize_slc),dtype='float64')
+ baselinepsign = np.zeros((rngsize_slc),dtype='float64')
+
+
+ # Main Kz/Incidence Calculation Loop
+ for master in range(0,num_tracks-1):
+ mbasefile = glob(datapath+tracknames[master]+'*HH*.baseline')
+
+ if len(mbasefile) == 1:
+ mbasesch = np.loadtxt(mbasefile[0])
+ elif len(mbasefile) > 1:
+ print('kapok.uavsar.load | Too many .baseline files matching pattern: "'+datapath+tracknames[master]+'*HH*.baseline'+'". Aborting.')
+ return
+ else:
+ print('kapok.uavsar.load | Cannot find .baseline file matching pattern: "'+datapath+tracknames[master]+'*HH*.baseline'+'". Aborting.')
+ return
+
+ istart = np.where(np.isclose(mbasesch[:,0],sbounds[0]))[0][0] # index of first azimuth line in subset
+ iend = np.where(np.isclose(mbasesch[:,0],sbounds[1]))[0][0] # index of last azimuth line in subset
+ mbaseenu[:] = sch2enu(mbasesch[istart:iend,1],mbasesch[istart:iend,2],mbasesch[istart:iend,3], peglat, peglon, peghdg)[0:mbaseenu.shape[0],:]
+
+ for slave in range(master+1,num_tracks):
+ print('kapok.uavsar.load | Calculating kz for tracks '+str(master)+' and '+str(slave)+'. ('+time.ctime()+')')
+
+ sbasefile = glob(datapath+tracknames[slave]+'*HH*.baseline')
+
+ if len(sbasefile) == 1:
+ sbasesch = np.loadtxt(sbasefile[0])
+ elif len(sbasefile) > 1:
+ print('kapok.uavsar.load | Too many .baseline files matching pattern: "'+datapath+tracknames[slave]+'*HH*.baseline'+'". Aborting.')
+ return
+ else:
+ print('kapok.uavsar.load | Cannot find .baseline file matching pattern: "'+datapath+tracknames[slave]+'*HH*.baseline'+'". Aborting.')
+ return
+
+ sbaseenu[:] = sch2enu(sbasesch[istart:iend,1],sbasesch[istart:iend,2],sbasesch[istart:iend,3], peglat, peglon, peghdg)[0:sbaseenu.shape[0],:]
+
+ for az in range(0,azbounds[1]-azbounds[0]):
+ lkvrowindex = (az+azbounds[0]) // mlwin_lkv[0]
+
+ masterlkv[:,0] = (zoom(lkv[lkvrowindex,:,0],mlwin_lkv[1]) - mbaseenu[az,0])[0:rngsize_slc]
+ masterlkv[:,1] = (zoom(lkv[lkvrowindex,:,1],mlwin_lkv[1]) - mbaseenu[az,0])[0:rngsize_slc]
+ masterlkv[:,2] = (zoom(lkv[lkvrowindex,:,2],mlwin_lkv[1]) - mbaseenu[az,0])[0:rngsize_slc]
+
+ # Project look vector onto velocity vector.
+ proj_lkv_velocity = np.sum(masterlkv*velocityenu,axis=1)[:,np.newaxis]*velocityenu/np.linalg.norm(velocityenu)
+
+ # Component of look vector orthogonal to velocity.
+ tempdiff = (masterlkv-proj_lkv_velocity)
+ inc_slc[az,:] = np.arccos(np.abs(tempdiff[:,2])/np.linalg.norm(tempdiff,axis=1))
+
+ lookcrossv[:,0] = masterlkv[:,1]*velocityenu[2] - masterlkv[:,2]*velocityenu[1]
+ lookcrossv[:,1] = masterlkv[:,2]*velocityenu[0] - masterlkv[:,0]*velocityenu[2]
+ lookcrossv[:,2] = masterlkv[:,0]*velocityenu[1] - masterlkv[:,1]*velocityenu[0]
+ lookcrossv *= -1
+
+ slavelkv[:,0] = masterlkv[:,0] + mbaseenu[az,0] - sbaseenu[az,0]
+ slavelkv[:,1] = masterlkv[:,1] + mbaseenu[az,0] - sbaseenu[az,0]
+ slavelkv[:,2] = masterlkv[:,2] + mbaseenu[az,0] - sbaseenu[az,0]
+
+ baseline = mbaseenu[az] - sbaseenu[az]
+
+ baselinepsign = np.sum(baseline*lookcrossv,axis=1)/np.sum(lookcrossv*lookcrossv,axis=1)
+ baselinep = np.linalg.norm((np.sum(baseline*lookcrossv,axis=1)/np.sum(lookcrossv*lookcrossv,axis=1))[:,np.newaxis]*lookcrossv,axis=1)
+
+ kz_slc[az] = (4*np.pi/wavelength) * baselinep / (np.linalg.norm(masterlkv,axis=1)*np.sin(inc_slc[az,:])) * np.sign(baselinepsign)
+
+
+ bl = int(slave*(slave-1)/2 + master)
+ if num_bl > 1:
+ kz[bl] = mlook(kz_slc[:,rngbounds[0]:rngbounds[1]], mlwin)
+ else:
+ kz[:] = mlook(kz_slc[:,rngbounds[0]:rngbounds[1]], mlwin)
+
+ if master == 0: # save incidence angle
+ print('kapok.uavsar.load | Saving incidence angle for track 0. ('+time.ctime()+')')
+ inc[:] = mlook(inc_slc[:,rngbounds[0]:rngbounds[1]], mlwin)
+
+ del kz_slc, inc_slc
+
+ # Close the file, then return it as a Scene object.
+ f.close()
+ return kapok.Scene(outfile)
+
+
+class Ann(object):
+ """Class for loading and interacting with a UAVSAR annotation file."""
+
+ def __init__(self, file):
+ """Load in the specified .ann file as a list of strings and
+ initialize.
+
+ Arguments:
+ file (str): UAVSAR annotation filename to load.
+
+ """
+ self.file = file
+ fd = open(self.file, 'r')
+ self.ann = fd.read().split('\n')
+ return
+
+
+ def query(self, keyword):
+ """Query the annotation file for the specified annotation keyword.
+
+ Arguments:
+ keyword (str): The keyword to query.
+
+ Returns:
+ value: The value of the specified keyword.
+
+ """
+ for n in range(len(self.ann)):
+ if self.ann[n].startswith(keyword):
+ try:
+ val = self.ann[n].rsplit('=')[-1].split(';')[0].split()[0]
+ val = np.array(val,dtype='float') # if we can convert the string to a number, do so
+ if (val - np.floor(val)) == 0:
+ val = np.array(val,dtype='int') # if it's an integer, convert it to one (e.g., number of samples)
+ return val
+ except ValueError: # if we can't convert the string to a number, leave it as a string
+ val = self.ann[n].split('=',maxsplit=1)[-1].split(';')[0].strip()
+ return val
+
+ return None
+
+
+def findsegment(az,azsize):
+ """For a given azimuth index, return the segment number and
+ the azimuth index within the given segment.
+
+ Arguments:
+ az: Azimuth index of interest.
+ azsize: List containing the azimuth size of each segment.
+
+ Returns:
+ seg: Segment number.
+ azoff: Azimuth index within the segment.
+
+ """
+ azstart = np.insert(np.cumsum(azsize), 0, 0)[0:-1]
+
+ if az <= np.sum(azsize):
+ seg = np.max(np.where(azstart <= az))
+ azoff = az - azstart[seg]
+ else:
+ seg = azstart.shape[0] - 1
+ azoff = azsize[seg]
+ print('kapok.uavsar.fingsegment | SLC row index of '+str(az)+' is larger than the size of the data. Returning maximum index.')
+
+ return seg, azoff
+
+
+def getslcblock(file, rngsize, azstart, azend, rngbounds=None, file2=None,
+ azsize=None):
+ """Load SLC data into a NumPy array buffer. If the file2 argument is
+ specified in the arguments, this function will treat the two files as
+ consecutive segments, and will join them.
+
+ Arguments:
+ file (str): Filename of the first SLC.
+ rngsize (int): Number of columns (range bins). Same for both SLCs.
+ azstart (int): Azimuth index at which to start the buffer, in the
+ first SLC.
+ azend (int): Azimuth index at which to end the buffer. If file2
+ is specified, this is an azimuth index in the second SLC. If
+ file2 is not specified, this is an azimuth index in the first SLC.
+ The row specified by azend is not actually included in the buffer,
+ as in the Python range() function. (azend-1) is the last line
+ included in the buffer. To load the entire SLC, azend should be
+ equal to the number of rows in SLC.
+ rngbounds (tuple, int): Starting and ending range bounds, if range
+ subsetting is desired.
+ file2 (str): Filename of the second SLC, if combining multiple
+ segments is desired.
+ azsize (int): Number of rows (azimuth bins) for the first SLC. Only
+ required if file2 is specified. Otherwise we only load in the
+ lines of the SLC before azend.
+
+ Returns:
+ block: NumPy array of complex64 datatype, containing the loaded SLC
+ data between the specified azimuth bounds.
+
+ """
+ if file2 is None:
+ byteoffset = rngsize * 8 * azstart
+ slc = np.memmap(file, dtype='complex64', mode='c', offset=byteoffset, shape=(azend-azstart,rngsize))
+ if rngbounds is not None:
+ slc = slc[:,rngbounds[0]:rngbounds[1]]
+ return slc
+ elif azsize is None:
+ print('kapok.uavsar.getslcblock: "file2" argument specified, but "azsize" argument missing. Aborting.')
+ return
+ else:
+ byteoffset = rngsize * 8 * azstart
+ slca = np.memmap(file, dtype='complex64', mode='c', offset=byteoffset, shape=(azsize-azstart,rngsize))
+ slcb = np.memmap(file2, dtype='complex64', mode='c', shape=(azend,rngsize))
+ if rngbounds is not None:
+ slca = slca[:,rngbounds[0]:rngbounds[1]]
+ slcb = slcb[:,rngbounds[0]:rngbounds[1]]
+ return np.vstack((slca,slcb))
\ No newline at end of file
diff --git a/kapok/vis.py b/kapok/vis.py
new file mode 100755
index 0000000..2e65566
--- /dev/null
+++ b/kapok/vis.py
@@ -0,0 +1,334 @@
+# -*- coding: utf-8 -*-
+"""Visualization and display functions.
+
+ Author: Michael Denbina
+
+ Copyright 2016 California Institute of Technology. All rights reserved.
+ United States Government Sponsorship acknowledged.
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+"""
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+
+def show_linear(data, bounds=None, vmin=None, vmax=None, cmap='viridis',
+ cbar=True, cbar_label=None, xlabel='Range Index', ylabel='Azimuth Index',
+ figsize=None, dpi=125, savefile=None, **kwargs):
+ """Display data in linear units (e.g., tree heights, kz).
+
+ Arguments:
+ data (array): 2D array containing the values to display.
+ bounds (tuple): Tuple containing (azimuth start, azimuth end, range
+ start, range end) bounds in that order. Only the subset of the
+ data within bounds will be displayed. For a full swath subset,
+ two element bounds can be given: (azimuth start, azimuth end).
+ vmin (float): Minimum value for colormap. Default: None.
+ vmax (float): Maximum value for colormap. Default: None.
+ cmap: Colormap. Default: 'viridis'.
+ cbar (bool): Set to False to not show colorbar.
+ cbar_label (str): Text label on the colorbar.
+ xlabel (str): Text label on the x axis.
+ ylabel (str): Text label on the y axis.
+ figsize (tuple): figsize used to create the matplotlib figure.
+ dpi (int): DPI (dots per inch) used in the matplotlib figure.
+ savefile (str): If specified, the plotted figure is saved under this
+ filename.
+
+ """
+ if figsize is not None:
+ plt.figure(figsize=figsize, dpi=dpi)
+ else:
+ plt.figure()
+
+ if bounds is None:
+ plt.imshow(np.real(data), vmin=vmin, vmax=vmax, cmap=cmap, aspect=1, interpolation='nearest', **kwargs)
+ else:
+ if len(bounds) == 2:
+ bounds = (bounds[0], bounds[1], 0, data.shape[1])
+
+ plt.imshow(np.real(data[bounds[0]:bounds[1],bounds[2]:bounds[3]]), extent=(bounds[2],bounds[3],bounds[1],bounds[0]), vmin=vmin, vmax=vmax, cmap=cmap, aspect=1, interpolation='nearest', **kwargs)
+
+ if cbar and (cbar_label is not None):
+ plt.colorbar(label=cbar_label)
+ elif cbar:
+ plt.colorbar()
+
+ plt.xlabel(xlabel)
+ plt.ylabel(ylabel)
+ plt.tight_layout()
+
+ if savefile is not None:
+ plt.savefig(savefile, dpi=dpi, bbox_inches='tight', pad_inches=0.1)
+
+
+
+def show_power(data, bounds=None, vmin=-25, vmax=-3, cmap='gray',
+ cbar=True, cbar_label='Backscatter (dB)', xlabel='Range Index',
+ ylabel='Azimuth Index', figsize=None, dpi=125, savefile=None):
+ """Display a power image (e.g., backscatter) in dB units.
+
+ Arguments:
+ data (array): 2D array containing the power for each pixel,
+ in linear units. Converted to dB for display.
+ bounds (tuple): Tuple containing (azimuth start, azimuth end, range
+ start, range end) bounds in that order. Only the subset of the
+ data within bounds will be displayed. For a full swath subset,
+ two element bounds can be given: (azimuth start, azimuth end).
+ vmin (float): Minimum dB value for colormap. Default: -21.
+ vmax (float): Maximum dB value for colormap. Default: 0.
+ cmap: Colormap. Default: 'afmhot'.
+ cbar (bool): Set to False to not show colorbar.
+ cbar_label (str): Text label on the colorbar.
+ xlabel (str): Text label on the x axis.
+ ylabel (str): Text label on the y axis.
+ figsize (tuple): figsize used to create the matplotlib figure.
+ dpi (int): DPI (dots per inch) used in the matplotlib figure.
+ savefile (str): If specified, the plotted figure is saved under this
+ filename.
+
+ """
+ if figsize is not None:
+ plt.figure(figsize=figsize, dpi=dpi)
+ else:
+ plt.figure()
+
+ if bounds is not None:
+ if len(bounds) == 2:
+ bounds = (bounds[0], bounds[1], 0, data.shape[1])
+
+ data = data[bounds[0]:bounds[1],bounds[2]:bounds[3]]
+
+ data = np.real(data)
+ data[data <= 0] = 1e-10
+ data = 10*np.log10(data)
+
+ if bounds is None:
+ plt.imshow(data, vmin=vmin, vmax=vmax, cmap=cmap, aspect=1, interpolation='nearest')
+ else:
+ plt.imshow(data, extent=(bounds[2],bounds[3],bounds[1],bounds[0]), vmin=vmin, vmax=vmax, cmap=cmap, aspect=1, interpolation='nearest')
+
+ if cbar and (cbar_label is not None):
+ plt.colorbar(label=cbar_label)
+ elif cbar:
+ plt.colorbar()
+
+ plt.xlabel(xlabel)
+ plt.ylabel(ylabel)
+ plt.tight_layout()
+
+ if savefile is not None:
+ plt.savefig(savefile, dpi=dpi, bbox_inches='tight', pad_inches=0.1)
+
+
+
+def show_complex(data, bounds=None, cbar=False, xlabel='Range Index',
+ ylabel='Azimuth Index', figsize=None, dpi=125, savefile=None):
+ """Display a complex-valued image (e.g., coherence) using the HSV color
+ system, with the phase as the hue, and the magnitude as saturation and
+ value.
+
+ Arguments:
+ data (array): 2D complex array containing coherence or other
+ complex values to display.
+ bounds (tuple): Tuple containing (azimuth start, azimuth end, range
+ start, range end) bounds in that order. Only the subset of the
+ data within bounds will be displayed. For a full swath
+ subset, two element bounds can be given: (azimuth start,
+ azimuth end).
+ cbar (bool): Set to True to display a colorbar for the phases
+ only (the hues, with full saturation and value).
+ xlabel (str): Text label on the x axis.
+ ylabel (str): Text label on the y axis.
+ figsize (tuple): figsize used to create the matplotlib figure.
+ dpi (int): DPI (dots per inch) used in the matplotlib figure.
+ savefile (str): If specified, the plotted figure is saved under this
+ filename.
+
+ """
+ # Subsetting
+ if bounds is not None:
+ if len(bounds) == 2:
+ bounds = (bounds[0], bounds[1], 0, data.shape[1])
+
+ data = data[bounds[0]:bounds[1],bounds[2]:bounds[3]]
+
+ # HSV based on magnitude and phase of data.
+ h = np.clip(np.angle(data)/(2*np.pi) + 0.5,0,1)
+ s = np.clip(np.abs(data),0,1)
+ v = np.clip(np.abs(data),0,1)
+
+ # HSV to RGB Conversion
+ red = np.zeros((data.shape[0],data.shape[1]),dtype='float32')
+ green = np.zeros((data.shape[0],data.shape[1]),dtype='float32')
+ blue = np.zeros((data.shape[0],data.shape[1]),dtype='float32')
+
+ ind = (s == 0)
+ if np.any(ind):
+ red[ind] = v[ind]
+ green[ind] = v[ind]
+ blue[ind] = v[ind]
+
+ a = (h*6.0).astype('int')
+ f = (h*6.0) - a
+ p = v*(1.0 - s)
+ q = v*(1.0 - s*f)
+ t = v*(1.0 - s*(1.0-f))
+ a = a % 6
+
+ ind = (a == 0)
+ if np.any(ind):
+ red[ind] = v[ind]
+ green[ind] = t[ind]
+ blue[ind] = p[ind]
+
+ ind = (a == 1)
+ if np.any(ind):
+ red[ind] = q[ind]
+ green[ind] = v[ind]
+ blue[ind] = p[ind]
+
+ ind = (a == 2)
+ if np.any(ind):
+ red[ind] = p[ind]
+ green[ind] = v[ind]
+ blue[ind] = t[ind]
+
+ ind = (a == 3)
+ if np.any(ind):
+ red[ind] = p[ind]
+ green[ind] = q[ind]
+ blue[ind] = v[ind]
+
+ ind = (a == 4)
+ if np.any(ind):
+ red[ind] = t[ind]
+ green[ind] = p[ind]
+ blue[ind] = v[ind]
+
+ ind = (a == 5)
+ if np.any(ind):
+ red[ind] = v[ind]
+ green[ind] = p[ind]
+ blue[ind] = q[ind]
+
+
+ if figsize is not None:
+ plt.figure(figsize=figsize, dpi=dpi)
+ else:
+ plt.figure()
+
+ if bounds is None:
+ plt.imshow(np.dstack((red,green,blue)), aspect=1, interpolation='nearest')
+ else:
+ plt.imshow(np.dstack((red,green,blue)), extent=(bounds[2],bounds[3],bounds[1],bounds[0]), aspect=1, interpolation='nearest')
+
+ if cbar is True:
+ if bounds is None:
+ plt.imshow(red, aspect=1, interpolation='nearest', cmap='hsv', vmin=-np.pi, vmax=np.pi, alpha=0.0)
+ else:
+ plt.imshow(red, extent=(bounds[2],bounds[3],bounds[1],bounds[0]), aspect=1, interpolation='nearest', cmap='hsv', vmin=-np.pi, vmax=np.pi, alpha=0.0)
+ cbar = plt.colorbar(label='Phase (radians)')
+ cbar.set_alpha(1)
+ cbar.draw_all()
+
+ plt.xlabel(xlabel)
+ plt.ylabel(ylabel)
+
+ plt.tight_layout()
+
+ if savefile is not None:
+ plt.savefig(savefile, dpi=dpi, bbox_inches='tight', pad_inches=0.1)
+
+
+
+def show_paulirgb(cov, bounds=None, vmin=-25, vmax=-3, xlabel='Range Index',
+ ylabel='Azimuth Index', figsize=None, dpi=125, savefile=None):
+ """Display a Pauli RGB color composite image from a covariance matrix.
+
+ Color mapping is as follows. Red: 0.5*(HH-VV). Green: 2*HV.
+ Blue: 0.5*(HH+VV).
+
+ Arguments:
+ cov (array): Array containing a single track's
+ polarimetric covariance matrix with dimensions (az, rng, 3, 3).
+ bounds (tuple): Tuple containing (azimuth start, azimuth end, range
+ start, range end) bounds in that order. Only the subset of the
+ data within bounds will be displayed. For a full swath subset,
+ two element bounds can be given: (azimuth start, azimuth end).
+ vmin (int): Minimum value in dB of color range.
+ vmax (int): Maximum value in dB of color range.
+ xlabel (str): Text label on the x axis.
+ ylabel (str): Text label on the y axis.
+ figsize (tuple): figsize used to create the matplotlib figure.
+ dpi (int): DPI (dots per inch) used in the matplotlib figure.
+ savefile (str): If specified, the plotted figure is saved under
+ this filename.
+
+ """
+ if bounds is not None:
+ if len(bounds) == 2:
+ bounds = (bounds[0], bounds[1], 0, cov.shape[1])
+
+ cov = cov[bounds[0]:bounds[1],bounds[2]:bounds[3]]
+
+ rgb = np.zeros((cov.shape[0],cov.shape[1],3))
+
+ # Red: (HH-VV)/2
+ w = np.array([1,0,-1]/np.sqrt(2), dtype='complex64')
+ wimage = np.array([[w[0]*w[0],w[0]*w[1],w[0]*w[2]],
+ [w[1]*w[0],w[1]*w[1],w[1]*w[2]],
+ [w[2]*w[0],w[2]*w[1],w[2]*w[2]]], dtype='complex64')
+ rgb[:,:,0] = np.real(np.sum(cov*wimage, axis=(2,3)))
+
+ # Green: (2*HV)
+ w = np.array([0,np.sqrt(2),0], dtype='complex64')
+ wimage = np.array([[w[0]*w[0],w[0]*w[1],w[0]*w[2]],
+ [w[1]*w[0],w[1]*w[1],w[1]*w[2]],
+ [w[2]*w[0],w[2]*w[1],w[2]*w[2]]], dtype='complex64')
+ rgb[:,:,1] = np.real(np.sum(cov*wimage, axis=(2,3)))
+
+ # Blue: (HH+VV)/2
+ w = np.array([1,0,1]/np.sqrt(2), dtype='complex64')
+ wimage = np.array([[w[0]*w[0],w[0]*w[1],w[0]*w[2]],
+ [w[1]*w[0],w[1]*w[1],w[1]*w[2]],
+ [w[2]*w[0],w[2]*w[1],w[2]*w[2]]], dtype='complex64')
+ rgb[:,:,2] = np.real(np.sum(cov*wimage, axis=(2,3)))
+
+ rgb[rgb <= 0] = 1e-10
+ rgb = 10*np.log10(rgb)
+
+ rgb = (rgb-vmin)/(vmax-vmin)
+ rgb[rgb < 0] = 0
+ rgb[rgb > 1] = 1
+
+
+ if figsize is not None:
+ plt.figure(figsize=figsize, dpi=dpi)
+ else:
+ plt.figure()
+
+ if bounds is None:
+ plt.imshow(rgb, aspect=1, interpolation='nearest')
+ else:
+ plt.imshow(rgb, extent=(bounds[2],bounds[3],bounds[1],bounds[0]), aspect=1, interpolation='nearest')
+
+ plt.xlabel(xlabel)
+ plt.ylabel(ylabel)
+ plt.tight_layout()
+
+ if savefile is not None:
+ plt.savefig(savefile, dpi=dpi, bbox_inches='tight', pad_inches=0.1)
\ No newline at end of file
diff --git a/scripts/basic_processing_example.py b/scripts/basic_processing_example.py
new file mode 100755
index 0000000..a75f4d0
--- /dev/null
+++ b/scripts/basic_processing_example.py
@@ -0,0 +1,122 @@
+import os
+import os.path
+
+import numpy as np
+
+import kapok
+
+
+# Below is a path and filename pointing to the annotation (.ann) metadata file
+# for a UAVSAR stack:
+annfile = '/data/stacks/ecuador2013/1/Guayaq_18203_13042_005_130318_L090HH_02_BC.ann'
+
+# This is the path and filename pointing to the HDF5 file where the imported
+# data and derived parameters should be stored:
+datafile = '/data/kapokfile.hdf5'
+
+# This is an output path pointing to a folder where plotted figures and
+# geocoded output products will be saved:
+outpath = '/data/kapok_output/'
+
+# Dimensions of the multi-looking window applied to the data.
+# First index is the azimuth size, second index is the range size.
+mlwin = [20,5]
+
+# If the output path does not exist, create it.
+if not os.path.exists(outpath):
+ os.makedirs(outpath)
+
+
+# First, get the Kapok Scene object. If the file already exists, load it.
+# Otherwise, import from UAVSAR data.
+if os.path.isfile(datafile):
+ scene = kapok.Scene(datafile)
+else:
+ import kapok.uavsar
+ scene = kapok.uavsar.load(annfile,datafile,mlwin=mlwin,num_blocks=5)
+
+
+
+# Interactive Coherence Region Plot for Pixel With Coordinates (2500,50)
+scene.region(2500,50,mode='interactive')
+
+# Perform phase diversity coherence optimization. This can easily be
+# performed using the Scene object's .opt method.
+# The resulting optimized coherences are saved into the HDF5 file.
+# After optimization, they are accessible using Scene.pdcoh.
+scene.opt()
+
+# Display and save some basic overview images.
+# Plotting of raster images is done through the Scene object's .show method.
+scene.show('paulirgb', savefile=outpath+'paulirgb.png') # Pauli RGB color composite.
+scene.show('coh', pol='high', bl=0, savefile=outpath+'coh_high_bl0.png') # Image of the high coherence.
+scene.show('coh', pol='low', bl=0, savefile=outpath+'coh_low_bl0.png') # Image of the low coherence.
+scene.show('coh mag', pol='high', bl=0, savefile=outpath+'coh_high_mag_bl0.png') # Magnitude image of the high cohernece.
+scene.show('kz', savefile=outpath+'kz_bl0.png') # Image of the Kz Values derived from the platform and viewing geometry.
+
+
+# Instead of displaying the whole image, we can display and save some images for a subset of the scene bounded by azimuth indices 2000-3500.
+scene.show('paulirgb',bounds=(2000,3500),savefile=outpath+'paulirgb_az_2000_3500.png')
+scene.show('power',pol='HV',bounds=(2000,3500),savefile=outpath+'hvpower_az_2000_3500.png') # Backscattered HV power, in dB.
+scene.show('coh', pol='high', bounds=(2000,3500), savefile=outpath+'coh_high_bl0_az_2000_3500.png')
+scene.show('coh', pol='low', bounds=(2000,3500), savefile=outpath+'coh_low_bl0_az_2000_3500.png')
+
+
+# The following closes all open figures. Useful if we are plotting a lot of
+# things, and saving them to files, and do not want them to clutter the
+# screen after the plotting is finished:
+scene.show('close')
+
+
+# Now, we create a mask which identifies low HV backscatter areas.
+mask = scene.power('HV') # Get the HV backscattered power (in linear units).
+mask[mask <= 0] = 1e-10 # Get rid of zero-valued power.
+mask = 10*np.log10(mask) # Convert to dB.
+mask = mask > -22 # Find pixels above/below -22 dB threshold.
+
+# If this mask is provided to the model inversion, only pixels with HV
+# sigma-nought over -22 dB will be considered valid pixels for the forest
+# height estimation. This will also save some computation time, since
+# these pixels will be skipped over by the algorithm.
+
+
+# RVoG Inversion
+# Model inversion is performed through the .inv method of the Scene object.
+# The name and desc keywords allow us to name and give a short description of
+# the estimated forest heights. The forest heights are saved to the HDF5 file,
+# and are tagged with many identifying attributes.
+rvog = scene.inv('rvog', name='rvog', desc='RVoG, hv and ext. free parameters, no temporal decorrelation.', mask=mask, overwrite=True)
+
+# If we had wanted to do sinc model inversion, we could do so using
+# scene.inv('sinc'). There are also many other options for the model
+# inversion process (with different options being valid for different
+# models). See the scene.inv function header for more details.
+
+# Since we named the results of this inversion 'rvog' using the name keyword
+# of the .inv method, the estimated parameters are now stored in the HDF5 file
+# in the group: /products/rvog/. The estimated forest height is stored in the
+# dataset 'products/rvog/hv'. The estimated extinction parameter values are
+# stored in 'products/rvog/ext'. The estimated complex ground coherence is
+# stored in 'products/rvog/ground'.
+
+
+# Display and save an image of the estimated forest heights for a subset:
+scene.show('rvog/hv', bounds=(2000,3500), vmax=30, savefile=outpath+'rvog_hv_az_2000_3500.png')
+
+
+# Output geocoded forest height map as an ENVI grd/hdr file.
+scene.geo('rvog/hv', outpath+'rvog.grd')
+
+
+# If we want, we can also smooth the forest heights before output using a
+# boxcar average. This reduces spatial resolution, but also the noise in the
+# estimates.
+# Note that by default, forest heights for pixels where (mask == False) are
+# set to -1 (void). If we want them to be zero instead, we can multiply by
+# the mask:
+from kapok.lib import smooth
+scene.geo(smooth(scene.get('rvog/hv')*mask,[3,3]), outpath+'rvog_smoothed.grd')
+
+
+# Delete the scene object (which also closes the HDF5 file).
+del scene
\ No newline at end of file