Doris-5.0.3Beta/000077500000000000000000000000001312547014700133775ustar00rootroot00000000000000Doris-5.0.3Beta/LICENSE.txt000066400000000000000000001045051312547014700152270ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . Doris-5.0.3Beta/MANIFEST.in000066400000000000000000000004151312547014700151350ustar00rootroot00000000000000include *.txt include install/*.xml include install/*.txt include prepare_stack/*.xml recursive-include docs *.txt include sar_tools/* include envisat_tools/* include doris_core/* include bin/* include envisat_tools/epr_api-2.2/* include envisat_tools/epr_api-2.2/src/*Doris-5.0.3Beta/README.txt000066400000000000000000000143141312547014700151000ustar00rootroot00000000000000=========== Doris v5 Beta =========== The new Doris version, Doris 5, is developed to process a stack of Sentinel-1 images, as well as all the already familiar functionality of Doris 4. This is a beta version. Therefore, you still may experience some problems. Please report them to us. But even better, try to fix them! We are very happy to discuss with you how you can contribute to this project! The new Doris version consists of 2 parts: - The doris_core directory cantaining the Doris core code, which is similar to the original Doris code and is written in C. This code is mainly used to create individual interferograms based on different steps. - The doris_stack directory containing scripts written in Python. These scripts automate the processing of a single master stack of Sentinel-1 images. The scripts manage the processing of the bursts of a sentinel 1 image, contain algorithms specific to processing sentinel 1 images and support parallelisation of the processing of the bursts. The functionality of these scripts can be further extended to support more sensors and modes. In addition, you will find a stack preparation script, to automatically download the burst you need for your Area of Interest which you defined by a shape file, automatically download the SRTM DEM associated with this area, and setup your processing structure. Installation =========== See the INSTALL file in the install directory. This file descripes the installation of the C libraries, python libraries and some utility software. Creating Sentinel-1 datastacks ============================= Create a folder structure ----------------------------- After installing the software you can create your first doris datastack. To do so you have to prepare the following: - Create folders to download radar data and orbit files. In a further stage these files can be downloaded automatically, but it is also possible to do it yourself manually. - Create a folder where you can store intermediate DEM results. Data will be downloaded automatically, so you only have to create the folder itself. Note that these automatic downloads are based on SRTM data and are therefore limited to 60 degrees south and north of the equator. - Create a .shp file with your area of interest. You can use different software packages, but ArcGIS and QGIS (free) are the most convenient for this purpose. Or you could download from one of the websites that offer free shapefiles for administrative boundaries (for example: http://www.diva-gis.org/Data) - Finally, create the folder where you want to process your datastack. Be aware that to process your data you will need at least 100 GB of free space on your disc. Register for Sentinel and SRTM downloads ---------------------------------------- Additionally, you will need an account for downloading Sentinel-1 and SRTM data. You can use the following links to create an account. (How to link them to your code is described in the INSTALL file) - To register for Sentinel-1 data download use: https://scihub.copernicus.eu/dhus/#/self-registration - To register for SRTM download use: https://urs.earthdata.nasa.gov/users/new/ Run the stack preparation script ---------------------------------------- Move to the prepare_stack directory: cd prepare_stack Run the python script: python prepare_datastack.py This code will ask you to define the different folders you created before. The script will ask you whether you want to run your code in parallel. Generally, this is recommended as it speeds up your processing speed. Note that either the number of cores and your RAM can be limiting (one process will use about 4GB of RAM). Because it is not possible to mix different orbits in one datastack it will also ask you which orbit you want to use and whether it is ascending or descending. Please check this beforehand on the ESA website (https://scihub.copernicus.eu) Finally, the code will ask you the start date, end date and master date: - start date > What is the first image (in time) you want to process? - end date > What is the last image (in time) you want to process? (Tip: This date can be in the far future if you just want to download all images till now) - master data > This image will be used as the master of your stack. Other images will be resampled to the geometry of this master image. After finishing this script, the new datastack is automatically created together with a DEM of the area. This can take a while in case the download speeds are low or your area is large. Editing the data stack settings (generally not needed) ---------------------------------------------------- You can enter the folder to find, the newly created DEM, your .shp file, configuration files (inputfiles) and the stack. Further there is the doris_input.xml file where all configuration settings for your datastack are stored. This file is created in the folder where you will process your datastack. So, if you want to change this configuration afterwards, you can make some changes there. Processing ========================================= In the main folder of your datastack you will have three bash files: create_dem.sh > To create a DEM for your area. This is already done if you used the automatic DEM generation download_sentinel.sh > This will run the a download of sentinel images for the specified track over your area of interest. Only dates between your start and end date are considered. This script will also download the needed precise or restituted orbit files. You can call this scripts using bash After downloading your DEM, radar data and orbit files you can start your processing by the following command: bash doris_stack.sh or, if your server uses qsub (for parallel processing) qsub doris_stack.sh If you want to extend your datastack later on, you can run the scripts again for the same datastack. It will check which files are new and only process them. This software is therefore perfectly fit for continues monitoring. Be sure that you do not change your master image in between, as this will break your code. Enjoy, TUDELFT RADAR GROUP 2017 doris_users@tudelft.nlDoris-5.0.3Beta/__init__.py000066400000000000000000000000001312547014700154760ustar00rootroot00000000000000Doris-5.0.3Beta/bin/000077500000000000000000000000001312547014700141475ustar00rootroot00000000000000Doris-5.0.3Beta/bin/README000077500000000000000000000053231312547014700150350ustar00rootroot00000000000000Dear reader, This directory contains some scripting utitities to be used in conjunction with the doris software. Most are explained in the manual, and also see the synopsis below. These programs have been written by me. Bert Kampes #%// BK 05-Sep-2003 ----------------------------------------------------- ascii2ascii_UTM : Convert a 3 column ascii table from WGS lon/lat/hei to UTM {X,Y,hei} triplets. This script is an example how the proj software can be used, but it can be used as is as well as input in GMT. ascii2ps : Convert a 3 column ascii table to a postscript file. GMT is used to do this. The main output besides the plot is the interpolation to a regular grid. See the GMT programs xyz2grd and surface. This script is intented as an example to be adapted to your needs. baseline.doris : Old? probably to run doris from the prompt and obtain the perpendicular baseline based on the orbits. coregpm.doris : Old. script to iteratively run doris until the coregistration parameters have been computed with good fit. Use the card CPM_MAXITER instead. cpx2ps : Call GMT to convert a complex file, like an interferogram to a postscript plot. I rather use cpxfiddle nowadays. helpdoris : man page like formatter with all options to doris. lonlathei2ascii : Convert binary doris output to a 3 column ascii file. phasefilt.doris : Script to filter an interferogram from the prompt, creating dummy calls to doris. plotcpm : Script used in doris to plot the result of the coregistration polynomial modeling. plotoffsets : Script used in doris to plot the result of the FINE step. run : General script to run doris with. viewanddel : General script to view temporary created postscripts. ---------------------------------------- 2582 2008-09-06 20:08 ascii2ascii_UTM 8867 2008-09-06 20:08 ascii2ps 2282 2008-09-06 20:08 baseline.doris.csh 5506 2008-12-24 14:18 baseline.doris.sh 17191 2008-12-23 16:58 construct_dem.sh 11108 2008-09-06 20:08 coregpm.doris 20028 2008-09-06 20:08 cpx2ps 1812 2009-02-05 18:36 doris.process-reset.sh 1788 2008-09-06 20:08 heightamb 26873 2008-09-06 20:08 helpdoris 3295 2008-09-06 20:08 lonlathei2ascii 5484 2008-09-06 20:08 phasefilt.doris 17927 2008-12-24 14:34 plotcpm 17402 2008-09-06 20:08 plotoffsets 17255 2008-09-06 20:08 plotoffsets.bruno 2771 2009-04-14 14:58 README 64419 2009-04-14 12:48 run 4841 2009-04-13 13:21 tsx_dump_data.py 10496 2009-04-14 16:29 tsx_dump_header2doris_noxpath.py 9621 2009-04-14 16:11 tsx_dump_header2doris.py 2516 2008-09-06 20:08 viewanddel Doris-5.0.3Beta/bin/README_CSK.txt000077500000000000000000000007101312547014700163460ustar00rootroot00000000000000Hi Mahmut, Please find attached the python scripts for reading the cosmo-skymed (CSK) data and header. To execute these python scripts, please perform the following installations (in the below order): 1. HDF5 Package (http://www.hdfgroup.org/downloads/index.html) 2. NumPy Python Packages (http://new.scipy.org/download.html) 3. H5Py Python Packages (http://new.scipy.org/download.html) Let me know if you have any questions. Regards, Prabu. Doris-5.0.3Beta/bin/ascii2ascii_UTM000077500000000000000000000050261312547014700170100ustar00rootroot00000000000000#!/bin/csh -f ### ascii2ascii_UTM -- Use proj to transform doris output phi/lam/hei to utm x,y,h ## ascii 3 column file input to ascii 3 column file output. ### Example script to generate x,y,h ### next call could be ascii2postscript for plotting with GMT ### Bert Kampes, 14-Aug-2003 ### $Id: ascii2ascii_UTM,v 1.2 2003/08/14 13:56:28 kampes Exp $ ################################################################ set PRG = `basename "$0"` set VER = "v1.0 Doris software" set AUT = "bert kampes, (c)1999-2003" echo "$PRG $VER, $AUT" echo " " ### Handle wrong input set WRONG = "0" set WGSFILE = "$1" set ZONE = "$2" set OUTFILE = "$3" if ( $#argv < 3 ) set WRONG = "1" #--------------------------- if ( $WRONG == "1" ) then cat << __EOFHD USAGE: $PRG ascii3column +zone=utmzone This program transforms the WGS84 "longitude latitude height" 3 column ascii file of Doris (created with philamh2ascii) to UTM coordinates using proj. (longitude=lambda, latitude=phi) First use program lonlathei2ascii to create the 3 column ascii input file. THe UTM zone needs to be specified as in the example. Alternatively, one could specify +lon_0=-114 for example (see proj manual). This script can serve as an example. If you want to have another projection, see the manual of proj and cs2cs how to do this. EXAMPLE: $PRG lonlathei.dat +utm_zone=33 xyz_utm.dat See also: http://www.remotesensing.org/proj __EOFHD exit 1 endif ### call proj, no datum shift for utm # order is lon lat by default, use -r to change to lat/lon #To convert the wgs84 coordinates lat=52.00 lon=14.00 to utm zone33 #x,y coordinates use (zone automatically deterrmined, else e.g., +zone=32): #proj +proj=utm +zone=33 +ellps=WGS84 << EOF #14.0 52.0 #EOF ###################################### #set INFILE = temp.lonlat.wgs #set OUTFILE = temp.xy.utm #echo "creating $INFILE with awk" #awk '{print $1, $2}' $XYZFILE > $INFILE # above is not necessary, seems proj copies other columns. brilliant. set INFILE = $WGSFILE echo "creating $OUTFILE with proj" proj +proj=utm +ellps=WGS84 $ZONE $INFILE > $OUTFILE #set OUTFILE2 = temp.xyz.utm #echo "creating $OUTFILE2 with paste" #paste $OUTFILE `awk '{print $3}' $XYZFILE` > $OUTFILE2 #awk '{print $3}' $XYZFILE > $OUTFILE2.tmp #paste $OUTFILE $OUTFILE2.tmp > $OUTFILE2 #rm -f $OUTFILE2.tmp ### now you can offer this xyz file for plotting with GMT! echo " " #echo "Created: $XYZFILE (3 column ascii wgs84 lon lat hei)" echo "Created: $OUTFILE (3 column ascii UTM x y hei)" ### EOF. Doris-5.0.3Beta/bin/ascii2grdAutoMinMaxHDR000077500000000000000000000127031312547014700202500ustar00rootroot00000000000000#!/bin/csh -f ### ascii2grdAutoMinMaxHDR -- transform 3 col ascii in GMT grd (float) format ### with pixel size forced to 0,0009 degrees, that is about 25m ### and remove the header, then create an ENVI header ### It execute first minmax to get the min/max coord. ### It requires the GMT fct 'nearneighbor' that may pose prblms on some systems ### ARG = ascii file to transform ### Adjust script for UTM or Lon/Lat and output as Small or Big Endian ### $Id: ascii2grd,v 1.1 2007/04/19 NdOreye $ ################################################################ set PRG = `basename "$0"` set VER = "v1.0 doris script utilities" set AUT = "nicolas doreye, (c)2006" echo "$PRG $VER, $AUT" echo " " ### Handle wrong input set WRONG = "0" set ASCII = "$1" if ( $#argv < 1 ) set WRONG = "1" #--------------------------- if ( $WRONG == "1" ) then cat << __EOFHD USAGE: $PRG ascii3column This program transforms the 3 column ascii file of Doris (created with LonLat???2ascii) to GMT grd file then remove the header in order to be opened by ENVI for instance, then create the appropriate header First run the program lonlat???2ascii to create the 3 column ascii input file EXAMPLE: $PRG lonlatSomething.dat See also: http://www.remotesensing.org/proj __EOFHD exit 1 endif echo "-----------------------------" echo " compute Min Max Lon and Lat" echo "-----------------------------" ### this part is taken from B Kampes script asci2ps ### Get min/max and increment from data itselves. ### Assume lat/lon is formatted as %7.4f? ### Not robust yet? echo "finding out minmax in ascii column data - may take some time !" set minmax = `minmax $ASCII` echo $minmax set WEST = `echo $minmax | cut -d '<' -f2 | cut -d'/' -f1` set EAST = `echo $minmax | cut -d '<' -f2 | cut -d'/' -f2 | cut -d'>' -f1` set SOUTH = `echo $minmax | cut -d '<' -f3 | cut -d'/' -f1` set NORTH = `echo $minmax | cut -d '<' -f3 | cut -d'/' -f2 | cut -d'>' -f1` set MINHEI = `echo $minmax | cut -d '<' -f4 | cut -d'/' -f1` set MAXHEI = `echo $minmax | cut -d '<' -f4 | cut -d'/' -f2 | cut -d'>' -f1` echo " " ### handle 1e+06 format gracefully? #set EAST = `echo $EAST | awk '{printf "%.20f", $1}'` #set WEST = `echo $WEST | awk '{printf "%.20f", $1}'` #set SOUTH = `echo $SOUTH | awk '{printf "%.20f", $1}'` #set NORTH = `echo $NORTH | awk '{printf "%.20f", $1}'` echo "Using the following parameters:" echo "-------------------------------" echo "WEST: $WEST" echo "EAST: $EAST" echo "SOUTH: $SOUTH" echo "NORTH: $NORTH" echo "MINHEI: $MINHEI" echo "MAXHEI: $MAXHEI" echo " " echo "convert ascii to grd with GMT command nearneighbor using $WEST/$EAST/$SOUTH/$NORTH" # nearneighbor $ASCII -G$ASCII.grd -R$WEST/$EAST/$SOUTH/$NORTH -I25e=/25e= -S0.0009 -V # nearneighbor $ASCII -G$ASCII.grd -R$WEST/$EAST/$SOUTH/$NORTH -I0.006n=/0.006n= -S0.012m -V nearneighbor $ASCII -G$ASCII.grd -R$WEST/$EAST/$SOUTH/$NORTH -I0.001=/0.001= -S0.001 -V #AO # nearneighbor $ASCII -G$ASCII.grd -R$WEST/$EAST/$SOUTH/$NORTH -I0.000224804 -S0.0009 -V # xyz2grd $ASCII -G$ASCII.grd -I0.000224804= -R$WEST/$EAST/$SOUTH/$NORTH set OUTFILE = $ASCII.grd echo "-----------------------------" echo "removing header from $OUTFILE" echo "-----------------------------" set OUTFILE_NoHdr = $ASCII.nvi grdreformat $OUTFILE $ASCII.nvi=bf -N -V echo "-----------------------------" echo "Created: $OUTFILE.nvi without hdr (GMT grid @ 0,0009 degrees i.e. about 25m)" echo "-----------------------------" echo "-----------------------------" echo "Create ENVI header" echo "-----------------------------" echo "attention: if wants UTM in cm, first run Mathematica notebook and watch out for the alphabumeric characters" set DATE = `date` #set grdinfo = `grdinfo $ASCII.grd` #echo $grdinfo #set x_inc = `echo $grdinfo | cut -d ':' -f14 | cut -d ' ' -f2` #set nX = `echo $grdinfo | cut -d ':' -f16 | cut -d ' ' -f2` #set y_inc = `echo $grdinfo | cut -d ':' -f20 | cut -d ' ' -f2` #set nY = `echo $grdinfo | cut -d ':' -f22 | cut -d ' ' -f2` grdinfo $ASCII.grd > temp set x_inc = `grep x_inc temp | gawk '{print $7}'` set nX = `grep nx temp | gawk '{print $11}'` set y_inc = `grep y_inc temp | gawk '{print $7}'` set nY = `grep y_inc temp | gawk '{print $11}'` rm temp echo echo 'nx= ' $nX echo 'x_inc= ' $x_inc echo 'ny= ' $nY echo 'y_inc= '$y_inc echo # Header: echo 'ENVI' >> $ASCII.hdr echo 'description = { ' >> $ASCII.hdr echo ' Header created auto from gridinfo (gmt) and ' $OUTFILE.NoHdr ' on [' $DATE ']}' >> $ASCII.hdr echo 'samples = ' $nX >> $ASCII.hdr echo 'lines = ' $nY >> $ASCII.hdr echo 'bands = 1' >> $ASCII.hdr echo 'header offset = 0' >> $ASCII.hdr echo 'file type = ENVI Standard' >> $ASCII.hdr echo 'data type = 4' >> $ASCII.hdr echo 'interleave = bsq' >> $ASCII.hdr echo 'sensor type = Unknown' >> $ASCII.hdr # select the output format: small or big Endian? echo 'byte order = 0' >> $ASCII.hdr echo ' computed on a Little Endian machine' echo # echo "-----------------------------" # echo 'UTM FORMAT' # echo "-----------------------------" # echo 'map info = {UTM, 1.000, 1.000, 715175.972, 9883485.359, 3.0940000000e+001, 3.0740000000e+001, 35, South, WGS-84, units=Meters}' >> $ASCII.hdr echo "-----------------------------" echo 'LON/LAT FORMAT' echo "-----------------------------" echo 'map info = {Geographic Lat/Lon, 1.0000, 1.0000, ' $WEST ', ' $NORTH ', ' $x_inc ', ' $y_inc ', WGS-84, units=Degrees}' >> $ASCII.hdr echo 'wavelength units = Unknown' >> $ASCII.hdr echo '' >> $ASCII.hdr ### EOF. Doris-5.0.3Beta/bin/ascii2ps000077500000000000000000000217621312547014700156220ustar00rootroot00000000000000#!/bin/csh -f ### ascii2ps -- Generate postscript from 3 column ascii file. ### Example script to generate grd file from phi lambda height ### output of Doris InSAR software. ### Ramon Hanssen, Bert Kampes, 07-Dec-2000. ### a good idea would be to use gmtconvert instead of the ascii input. ### $Id: ascii2ps,v 1.6 2004/09/15 10:49:03 kampes Exp $ ### MCC - some GMT v4 compatiblity ################################################################ set PRG = `basename "$0"` set VER = "v1.1 Doris software" #set AUT = "bert kampes, (c)1999-2003" set AUT = "TUDELFT, (c)1999-2009" echo "$PRG $VER, $AUT" echo " " ### Handle wrong input set WRONG = "0" ### Input files: 3 column ascii lon/lat/hei triplets. set XYZFILE = "$1" if ( $#argv < 1 ) set WRONG = "1" if ( $WRONG == "1" ) then cat << __EOFHD USAGE: $PRG 3col_asciifile Create a postscript file of the data in the 3 column ASCII input file containing "lon lat hei" triplets (output of lonlathei2ascii program). GMT is used to interpolate these irregularly distributed data to a grid. This script is intended to be transparent and understandable. Please adapt this script to your own needs. (lambda=longitude). For example, here one could easily set the correct approximate height of the terrain. The output is a postscript file named "temp.ps". The steps foreseen to be taken are: [before running this, create a three column ascii file with lon lat hei using philamh2ascii program. AND optionally convert this 3 column file to UTM coordinates using ascii2ascii_UTM ] 2) Call GMT program xyz2grd to perform interpolation of this data. the number of points in the output grid is 300. 3) call GMT program cpt to create a color table 4) call GMT program to create a postscript file 5) call ghostview to view output. This script can serve as an example. If you want to have another resolution output grid, for example exactly 100x100 meters, then you will have to change this script. With the public domain software PROJ.4, you can easily convert the WGS coordinates (Doris output) to X,Y values, and then use this script. See the script ascii2ascii_UTM for an example how to do this for WGS to UTM coordinates conversion. DEPENDENCIES: GMT tools (gmtset, minmax, xyz2grd, grd2cpt, psbasemap psscale, grdgradient, psmask, grdimage, pscoast) standard UNIX (echo, csh, rm, etc.) ghostview EXAMPLE: $PRG lonlathei.dat $PRG xyz_UTM.dat SEE ALSO: cpxfiddle, http://gmt.soest.hawaii.edu/ __EOFHD exit 1 endif ### Program variables. set CMAP = sealand set CPTFILE = temp.cpt set GRDFILE = temp.grd set PSFILE = temp.eps #use paper=a4+ for eps, a4 for ps rm -f $PSFILE rm -f $CPTFILE $GRDFILE #--------------------------- # GMT defaults override #--------------------------- gmtset MEASURE_UNIT cm \ PAPER_MEDIA a4+ \ PAGE_ORIENTATION portrait \ ANOT_FONT Helvetica \ ANOT_FONT_SIZE 10p \ ANOT_OFFSET 0.2c \ BASEMAP_AXES WeSn \ LABEL_FONT Helvetica \ LABEL_FONT_SIZE 10 \ UNIX_TIME_POS -2c/-2c #--------------------------- #### program philamh2ascii replaces code below #### if file temp.xyz exists already, maybe you do not want to wait again? #### but for now, always recompute it. #if ( "1" == "2" ) then #### Convert binary files to ascii row; trick cpxfiddle with -w1. #echo " Convert LONGITUDES in binary real4 file" \"${LON}\" "to ascii table" # #cpxfiddle -w1 -qnormal -fcr4 $LON | awk '{printf "%3.4f\n%3.4f\n",$1,$2}' > qlon # # using new r4 option to cpxfiddle # cpxfiddle -w1 -qnormal -fr4 $LON > qlon #echo " Convert LATITUDES in binary real4 file" \"${LAT}\" "to ascii table" # cpxfiddle -w1 -qnormal -fr4 $LAT > qlat #echo " Convert HEIGHTS in binary real4 file" \"${HEI}\" "to ascii table" # cpxfiddle -w1 -qnormal -fr4 $HEI > qhei # #### Create xyz file, delete temp files. #echo "Paste LAT/LON/HEI to xyzfile" \"${XYZFILE}\" # paste qlon qlat qhei > $XYZFILE.tmp #echo "removing -999 from input (unwrap problem, or other problem)" # grep -v '\-999' $XYZFILE.tmp > $XYZFILE # rm -f qlon qlat qhei $XYZFILE.tmp #endif ### Get min/max and increment from data itselves. ### Assume lat/lon is formatted as %7.4f? ### Not robust yet? echo "finding out minmax in ascii column data" set minmax = `minmax $XYZFILE` echo minmax $minmax set WEST = `echo $minmax | cut -d '<' -f2 | cut -d'/' -f1` set EAST = `echo $minmax | cut -d '<' -f2 | cut -d'/' -f2 | cut -d'>' -f1` set SOUTH = `echo $minmax | cut -d '<' -f3 | cut -d'/' -f1` set NORTH = `echo $minmax | cut -d '<' -f3 | cut -d'/' -f2 | cut -d'>' -f1` set MINHEI = `echo $minmax | cut -d '<' -f4 | cut -d'/' -f1` set MAXHEI = `echo $minmax | cut -d '<' -f4 | cut -d'/' -f2 | cut -d'>' -f1` echo " " ### handle 1e+06 format gracefully? #set EAST = `echo $EAST | awk '{printf "%.20f", $1}'` #set WEST = `echo $WEST | awk '{printf "%.20f", $1}'` #set SOUTH = `echo $SOUTH | awk '{printf "%.20f", $1}'` #set NORTH = `echo $NORTH | awk '{printf "%.20f", $1}'` echo "Using the following parameters:" echo "-------------------------------" echo "WEST: $WEST" echo "EAST: $EAST" echo "SOUTH: $SOUTH" echo "NORTH: $NORTH" echo "MINHEI: $MINHEI" echo "MAXHEI: $MAXHEI" ### try to figure out if we have UTM coordinates ### assume utm if north is big.. or small set CARTESIAN = `echo "$NORTH $SOUTH" | awk '{if(($1>200)||($2<-200)){print"1"}else{print"0"}}'` echo "CARTESIAN = $CARTESIAN" # # numgrd should be multiple of 100? # number of points in output grid in 1 direction set NUMGRD = "200" #set IX = `echo $WEST $EAST $NUMGRD | awk '{print ($2-$1)/($3-1)}'` #set IX = `echo $WEST $EAST $NUMGRD | awk '{print ($2-$1)/$3}'` #set IY = `echo $SOUTH $NORTH $NUMGRD | awk '{print ($2-$1)/$3}'` ### report of Bruno Crippa that awk is not precise enough, use bc: #%// BK 24-Nov-2002 #set IX = `echo "scale=20; ( $EAST - $WEST ) / $NUMGRD" | bc -l` #set IY = `echo "scale=20; ( $NORTH - $SOUTH ) / $NUMGRD" | bc -l` # but why not? (awk handles at least 1.2342e+06) set IX = `echo $WEST $EAST $NUMGRD | awk '{printf "%.20f", ($2-$1)/$3}'` set IY = `echo $SOUTH $NORTH $NUMGRD | awk '{printf "%.20f", ($2-$1)/$3}'` # #set RANGE = `minmax -I$IX/$IY $XYZFILE` set RANGE = "-R$WEST/$EAST/$SOUTH/$NORTH" set IXkm = `echo "scale=3; $IX * 40000 / 360" | bc -l` set IYkm = `echo "scale=3; $IY * 40000 / 360" | bc -l` echo "RANGE: " $RANGE if ( "$CARTESIAN" == "1" ) then echo "Sample interval X: $IX degrees, or $IXkm km at equator" echo "Sample interval Y: $IY degrees, or $IYkm km at equator" else echo "Sample interval X: $IX m" echo "Sample interval Y: $IY m" endif ### OR, use minmax to get range, much better... #set IX = 200 #set IY = 200 #set RANGE = `minmax -I$IX $XYZFILE` #echo "IX = $IX [m]" #echo "IY = $IY [m]" #echo "RANGE = $RANGE" ### Create grd file with xyz2grd (better use surface). echo "do xyz2grd" xyz2grd $XYZFILE -G$GRDFILE -I$IX/$IY $RANGE #awk '{print $1, $2, $3+1000.0}' $XYZFILE | surface -G$GRDFILE -I$IX/$IY $RANGE -T0.75 #surface $XYZFILE -G$GRDFILE -I$IX/$IY $RANGE -T0.75 #echo "for unwrapped ifg, converting to cm slant range displacement" #grdmath $GRDFILE 1.4 MUL PI DIV = temp.grd2; mv temp.grd2 $GRDFILE #echo "setting min_z --> 0" #echo "you may not want this" # grdmath $GRDFILE $MINHEI SUB = temp.grd2; mv temp.grd2 $GRDFILE #set MINHEI = 0.0 #set MAXHEI = `echo $MINHEI $MAXHEI | awk '{printf "%f", $2 - $1}'` ### Create colormap from data with grd2cpt. #set CPTFILE = /home/fmr/d4/hanssen/gmt_scripts/colortables/minpipi.cpt #set CPTFILE = /home/fmr/d4/hanssen/gmt_scripts/colortables/mass.cpt echo "creating colormapping..." set INCHEI = `echo $MINHEI $MAXHEI 255 | awk '{print($2-$1)/$3}'` echo "grd2cpt $GRDFILE -C$CMAP -Z -S$MINHEI/$MAXHEI/$INCHEI" #grd2cpt $GRDFILE -C$CMAP -Z -S$MINHEI/$MAXHEI/$INCHEI >! $CPTFILE grd2cpt $GRDFILE -C$CMAP -Z >! $CPTFILE ### Actually start GMT plotting. # proj better use correct scaling for x/y set proj = "-JX15" set ticks = "-Bf0.1a1.0/f0.1a1.0" if ( "$CARTESIAN" == "1" ) set ticks = "-Bf5000.0a40000.0/f5000.0a40000.0" echo "proj = $proj" echo "ticks = $ticks" echo "psbasemap $proj $RANGE $ticks -U -K " psbasemap $proj $RANGE $ticks -U -K >! $PSFILE echo "psscale -I1 -D12.5/-1.2/5/0.4h -C$CPTFILE -B1000:a:/:m: -O -K " psscale -I1 -D12.5/-1.2/5/0.4h -C$CPTFILE -B1000:a:/:m: -O -K >> $PSFILE echo "grdgradient" grdgradient $GRDFILE -A0 -Nt -G$GRDFILE.gradient echo "skipping psmask" #echo "psmask" #psmask $XYZFILE -I$IX $proj $RANGE -K -O -S100 >> $PSFILE echo "grdimage" grdimage $GRDFILE $proj -I$GRDFILE.gradient -C$CPTFILE -R -B -K -O >> $PSFILE echo "pscoast (last call)" pscoast $proj -R -B -Dh -W1 -S0/0/255 -O >> $PSFILE ############################################################################ ### View result #if ( $PSFILE > 1kb ) ... #set GV = ghostview set GV = gv echo "using gv to view file: $PSFILE" #echo "using ghostview to view file: $PSFILE" $GV $PSFILE ### EOF. Doris-5.0.3Beta/bin/ascii2ps.gmt-v3000077500000000000000000000212431312547014700167300ustar00rootroot00000000000000#!/bin/csh -f ### ascii2ps -- Generate postscript from 3 column ascii file. ### Example script to generate grd file from phi lambda height ### output of Doris InSAR software. ### Ramon Hanssen, Bert Kampes, 07-Dec-2000. ### a good idea would be to use gmtconvert instead of the ascii input. ### $Id: ascii2ps,v 1.6 2004/09/15 10:49:03 kampes Exp $ ################################################################ set PRG = `basename "$0"` set VER = "v1.0 Doris software" set AUT = "bert kampes, (c)1999-2003" echo "$PRG $VER, $AUT" echo " " ### Handle wrong input set WRONG = "0" ### Input files: 3 column ascii lon/lat/hei triplets. set XYZFILE = "$1" if ( $#argv < 1 ) set WRONG = "1" if ( $WRONG == "1" ) then cat << __EOFHD USAGE: $PRG 3col_asciifile Create a postscript file of the data in the 3 column ASCII input file containing "lon lat hei" triplets (output of lonlathei2ascii program). GMT is used to interpolate these irregularly distributed data to a grid. This script is intended to be transparent and understandable. Please adapt this script to your own needs. (lambda=longitude). For example, here one could easily set the correct approximate height of the terrain. The output is a postscript file named "temp.ps". The steps foreseen to be taken are: [before running this, create a three column ascii file with lon lat hei using philamh2ascii program. AND optionally convert this 3 column file to UTM coordinates using ascii2ascii_UTM ] 2) Call GMT program xyz2grd to perform interpolation of this data. the number of points in the output grid is 300. 3) call GMT program cpt to create a color table 4) call GMT program to create a postscript file 5) call ghostview to view output. This script can serve as an example. If you want to have another resolution output grid, for example exactly 100x100 meters, then you will have to change this script. With the public domain software PROJ.4, you can easily convert the WGS coordinates (Doris output) to X,Y values, and then use this script. See the script ascii2ascii_UTM for an example how to do this for WGS to UTM coordinates conversion. DEPENDENCIES: GMT tools (gmtset, minmax, xyz2grd, grd2cpt, psbasemap psscale, grdgradient, psmask, grdimage, pscoast) standard UNIX (echo, csh, rm, etc.) ghostview EXAMPLE: $PRG lonlathei.dat $PRG xyz_UTM.dat SEE ALSO: cpxfiddle, http://gmt.soest.hawaii.edu/ __EOFHD exit 1 endif ### Program variables. set CMAP = sealand set CPTFILE = temp.cpt set GRDFILE = temp.grd set PSFILE = temp.eps #use paper=a4+ for eps, a4 for ps rm -f $PSFILE rm -f $CPTFILE $GRDFILE #--------------------------- # GMT defaults override #--------------------------- gmtset MEASURE_UNIT cm \ PAPER_MEDIA a4+ \ PAGE_ORIENTATION portrait \ ANOT_FONT Helvetica \ ANOT_FONT_SIZE 10p \ ANOT_OFFSET 0.2c \ BASEMAP_AXES WeSn \ LABEL_FONT Helvetica \ LABEL_FONT_SIZE 10 \ UNIX_TIME_POS -2c/-2c #--------------------------- #### program philamh2ascii replaces code below #### if file temp.xyz exists already, maybe you do not want to wait again? #### but for now, always recompute it. #if ( "1" == "2" ) then #### Convert binary files to ascii row; trick cpxfiddle with -w1. #echo " Convert LONGITUDES in binary real4 file" \"${LON}\" "to ascii table" # #cpxfiddle -w1 -qnormal -fcr4 $LON | awk '{printf "%3.4f\n%3.4f\n",$1,$2}' > qlon # # using new r4 option to cpxfiddle # cpxfiddle -w1 -qnormal -fr4 $LON > qlon #echo " Convert LATITUDES in binary real4 file" \"${LAT}\" "to ascii table" # cpxfiddle -w1 -qnormal -fr4 $LAT > qlat #echo " Convert HEIGHTS in binary real4 file" \"${HEI}\" "to ascii table" # cpxfiddle -w1 -qnormal -fr4 $HEI > qhei # #### Create xyz file, delete temp files. #echo "Paste LAT/LON/HEI to xyzfile" \"${XYZFILE}\" # paste qlon qlat qhei > $XYZFILE.tmp #echo "removing -999 from input (unwrap problem, or other problem)" # grep -v '\-999' $XYZFILE.tmp > $XYZFILE # rm -f qlon qlat qhei $XYZFILE.tmp #endif ### Get min/max and increment from data itselves. ### Assume lat/lon is formatted as %7.4f? ### Not robust yet? echo "finding out minmax in ascii column data" set minmax = `minmax $XYZFILE` echo $minmax set WEST = `echo $minmax | cut -d '<' -f2 | cut -d'/' -f1` set EAST = `echo $minmax | cut -d '<' -f2 | cut -d'/' -f2 | cut -d'>' -f1` set SOUTH = `echo $minmax | cut -d '<' -f3 | cut -d'/' -f1` set NORTH = `echo $minmax | cut -d '<' -f3 | cut -d'/' -f2 | cut -d'>' -f1` set MINHEI = `echo $minmax | cut -d '<' -f4 | cut -d'/' -f1` set MAXHEI = `echo $minmax | cut -d '<' -f4 | cut -d'/' -f2 | cut -d'>' -f1` echo " " ### handle 1e+06 format gracefully? #set EAST = `echo $EAST | awk '{printf "%.20f", $1}'` #set WEST = `echo $WEST | awk '{printf "%.20f", $1}'` #set SOUTH = `echo $SOUTH | awk '{printf "%.20f", $1}'` #set NORTH = `echo $NORTH | awk '{printf "%.20f", $1}'` echo "Using the following parameters:" echo "-------------------------------" echo "WEST: $WEST" echo "EAST: $EAST" echo "SOUTH: $SOUTH" echo "NORTH: $NORTH" echo "MINHEI: $MINHEI" echo "MAXHEI: $MAXHEI" ### try to figure out if we have UTM coordinates ### assume utm if north is big.. or small set CARTESIAN = `echo "$NORTH $SOUTH" | awk '{if(($1>200)||($2<-200)){print"1"}else{print"0"}}'` echo "CARTESIAN = $CARTESIAN" # # numgrd should be multiple of 100? # number of points in output grid in 1 direction set NUMGRD = "200" #set IX = `echo $WEST $EAST $NUMGRD | awk '{print ($2-$1)/($3-1)}'` #set IX = `echo $WEST $EAST $NUMGRD | awk '{print ($2-$1)/$3}'` #set IY = `echo $SOUTH $NORTH $NUMGRD | awk '{print ($2-$1)/$3}'` ### report of Bruno Crippa that awk is not precise enough, use bc: #%// BK 24-Nov-2002 #set IX = `echo "scale=20; ( $EAST - $WEST ) / $NUMGRD" | bc -l` #set IY = `echo "scale=20; ( $NORTH - $SOUTH ) / $NUMGRD" | bc -l` # but why not? (awk handles at least 1.2342e+06) set IX = `echo $WEST $EAST $NUMGRD | awk '{printf "%.20f", ($2-$1)/$3}'` set IY = `echo $SOUTH $NORTH $NUMGRD | awk '{printf "%.20f", ($2-$1)/$3}'` # #set RANGE = `minmax -I$IX/$IY $XYZFILE` set RANGE = "-R$WEST/$EAST/$SOUTH/$NORTH" set IXkm = `echo "scale=3; $IX * 40000 / 360" | bc -l` set IYkm = `echo "scale=3; $IY * 40000 / 360" | bc -l` echo "RANGE: " $RANGE if ( "$CARTESIAN" == "1" ) then echo "Sample interval X: $IX degrees, or $IXkm km at equator" echo "Sample interval Y: $IY degrees, or $IYkm km at equator" else echo "Sample interval X: $IX m" echo "Sample interval Y: $IY m" endif ### OR, use minmax to get range, much better... #set IX = 200 #set IY = 200 #set RANGE = `minmax -I$IX $XYZFILE` #echo "IX = $IX [m]" #echo "IY = $IY [m]" #echo "RANGE = $RANGE" ### Create grd file with xyz2grd (better use surface). echo "do xyz2grd" xyz2grd $XYZFILE -G$GRDFILE -I$IX/$IY $RANGE #awk '{print $1, $2, $3+1000.0}' $XYZFILE | surface -G$GRDFILE -I$IX/$IY $RANGE -T0.75 #surface $XYZFILE -G$GRDFILE -I$IX/$IY $RANGE -T0.75 #echo "for unwrapped ifg, converting to cm slant range displacement" #grdmath $GRDFILE 1.4 MUL PI DIV = temp.grd2; mv temp.grd2 $GRDFILE #echo "setting min_z --> 0" #echo "you may not want this" # grdmath $GRDFILE $MINHEI SUB = temp.grd2; mv temp.grd2 $GRDFILE #set MINHEI = 0.0 #set MAXHEI = `echo $MINHEI $MAXHEI | awk '{printf "%f", $2 - $1}'` ### Create colormap from data with grd2cpt. #set CPTFILE = /home/fmr/d4/hanssen/gmt_scripts/colortables/minpipi.cpt #set CPTFILE = /home/fmr/d4/hanssen/gmt_scripts/colortables/mass.cpt echo "creating colormapping..." set INCHEI = `echo $MINHEI $MAXHEI 255 | awk '{print($2-$1)/$3}'` grd2cpt $GRDFILE -C$CMAP -Z -S$MINHEI/$MAXHEI/$INCHEI >! $CPTFILE ### Actually start GMT plotting. # proj better use correct scaling for x/y set proj = "-JX15" set ticks = "-Bf0.1a1.0/f0.1a1.0" if ( "$CARTESIAN" == "1" ) set ticks = "-Bf5000.0a40000.0/f5000.0a40000.0" echo "proj = $proj" echo "ticks = $ticks" echo "psbasemap" psbasemap $proj $RANGE $ticks -U -K >! $PSFILE echo "psscale" psscale -I1 -D12.5/-1.2/5/0.4h -C$CPTFILE -B1000a -O -K >> $PSFILE echo "grdgradient" grdgradient $GRDFILE -A0 -Nt -G$GRDFILE.gradient echo "skipping psmask" #echo "psmask" #psmask $XYZFILE -I$IX $proj $RANGE -K -O -S100 >> $PSFILE echo "grdimage" grdimage $GRDFILE $proj -I$GRDFILE.gradient -C$CPTFILE -R -B -K -O >> $PSFILE echo "pscoast (last call)" pscoast $proj -R -B -Dh -W1 -S0/0/255 -O >> $PSFILE ############################################################################ ### View result #if ( $PSFILE > 1kb ) ... set GV = ghostview echo "using ghostview to view file: $PSFILE" $GV $PSFILE ### EOF. Doris-5.0.3Beta/bin/baseline.doris.csh000077500000000000000000000043521312547014700175560ustar00rootroot00000000000000#!/bin/csh -f # baseline.fast #%// BK 27-Oct-2000 #%// $Revision: 3.5 $ $Date: 2003/04/14 06:35:15 $ ###################################################################### set PRG = `basename "$0"` set VER = "v1.1, FMR software" set AUT = "Bert Kampes, (c)2000" echo "$PRG $VER, $AUT"\\n ### Handle input if ( $#argv < 2 ) then # cat << __EOFHD | more -de cat << __EOFHD | more PROGRAM: $PRG -- Obtain baseline parameterization from orbits. SYNOPSIS: $PRG master.res slave.res OPTIONS: master.res master result file from doris, precise orbits. slave.res slave result file from doris, precise orbits. Basically a dummy run is performed, only to get DUMPBASELINE. Then from the standard output the appropriate sections are written. The DUMPBASELINE card is used, computing the baseline at a grid 15x10, then fitting a polynomial through these values (Bperp, theta and range). EXAMPLE: $PRG master.res slave.res __EOFHD exit 1 endif ### Correct input. set MASTERFILE = "$1" set SLAVEFILE = "$2" ### Create dummy input file(s). set TMPDIR = "/tmp" set DORISIN = $TMPDIR/$user.$$.in set DORISOUT = $TMPDIR/$user.$$.out set LOGFILE = $TMPDIR/$user.$$.log set PRODFILE = $TMPDIR/$user.$$.prod ### cat << __EOFHD >! $DORISIN c *********************************************************** c File created by: $PRG $VER c Author: $AUT c This is an input file for Doris to perform baseline estimation c from prompt. c *********************************************************** c comment ___general options___ c SCREEN info MEMORY 5 OVERWRITE OFF BATCH ON LISTINPUT OFF DUMPBASELINE 15 10 PROCESS coarseorb LOGFILE $LOGFILE M_RESFILE $MASTERFILE S_RESFILE $SLAVEFILE I_RESFILE $PRODFILE c c c STOP __EOFHD ### Run Doris, module XXX, use DUMPBASELINE card. doris $DORISIN > $DORISOUT ### Grep the results from redirected stdout. ### first obtain line number set L = `grep -n compbaseline $DORISOUT | cut -f1 -d':' | tail -1` ### number of lines of interest @ NL = 22 ### lastline @ LL = $L + $NL @ NL++ ### Display results. clear head -n $LL $DORISOUT | tail -n $NL ### Tidy up. #rm -rf $TMPDIR rm -f $DORISIN rm -f $DORISOUT rm -f $LOGFILE rm -f $PRODFILE ### EOF. Doris-5.0.3Beta/bin/baseline.doris.sh000077500000000000000000000126021312547014700174100ustar00rootroot00000000000000#!/bin/bash -f ## ## baseline.doris.sh ## ## Made by Petar Marinkovic ## Login ## ## Started on Tue Jul 18 17:11:53 2006 Petar Marinkovic ## Last update Tue Jul 18 17:24:33 2006 Petar Marinkovic ## ## DESCRIPTION: ## ## CHANGE.LOG: ## ## [BK 27-Oct-2000, 00:00]: initial version in csh ~ baseline.doris ## ## [BK 14-Apr-2003, 06:35]: ?? ## ## [BK 18-Jul-2006, 16:00]: script rewrite in bash, doris_v318 ## supported, averaging the values over grid ## ## TODO: ## ## [MA 20071022, 16:30]: some more attributes is introduce for comparision with Descw ## : compatiblity with older doris versions improved ##\ PRG=`basename "$0"` VER="v1.2, DEOS software" AUT="Bert Kampes, Petar Marinkovic and Mahmut Arikan (c)2007" # echo "$PRG $VER, $AUT"\\n ### Handle input if [[ $# < 2 ]]; then cat << EOF PROGRAM: ${PRG} -- Obtain baseline parameterization from orbits. SYNOPSIS: ${PRG} master.res slave.res OPTIONS: master.res master result file from doris, precise orbits. slave.res slave result file from doris, precise orbits. Basically a dummy run is performed, only to get DUMPBASELINE. Then from the standard output the appropriate sections are written. The DUMPBASELINE card is used, computing the baseline at a grid 15x10, then fitting a polynomial through these values (Bperp, theta and range). EXAMPLE: ${PRG} master.res slave.res EOF exit 1 fi ### Correct input. MASTERFILE=${1} SLAVEFILE=${2} if [[ -n ${USER} ]]; then USER=$( whoami ) fi ### Create dummy input file(s). #TMPDIR="/tmp" TMPDIR=/tmp #TMPDIR=tmp # MA DORIS=${DORIS:-$(which doris)} # MA: if defined use externally define DORIS. Also possible to write ${DORIS:=$(which doris)} alone. DORISIN=${TMPDIR}/${USER}.$$.in DORISOUT=${TMPDIR}/${USER}.$$.out LOGFILE=${TMPDIR}/${USER}.$$.log PRODFILE=${TMPDIR}/${USER}.$$.prod TMPFILE=${TMPDIR}/${USER}.$$.tmp # [PM]: do not like new temp file ### cat << EOF > ${DORISIN} c *********************************************************** c File created by: $PRG $VER c Author: $AUT c This is an input file for Doris to perform baseline estimation c from prompt. c *********************************************************** c comment ___general options___ c SCREEN info MEMORY 5 OVERWRITE OFF BATCH ON LISTINPUT OFF DUMPBASELINE 15 10 PROCESS coarseorb LOGFILE $LOGFILE M_RESFILE $MASTERFILE S_RESFILE $SLAVEFILE I_RESFILE $PRODFILE c c c STOP EOF # Run Doris, module XXX, use DUMPBASELINE card. $DORIS $DORISIN > $DORISOUT 2> /dev/null awk '/Bpar/ {print $5}' ${DORISOUT} > ${TMPFILE}.bpar awk '/Bperp/ {print $NF}' ${DORISOUT} > ${TMPFILE}.bperp awk '/Height ambiguity/ {print $NF}' ${DORISOUT} > ${TMPFILE}.hamb awk '/Look angle|theta \(deg\)/ {print $NF}' ${DORISOUT} > ${TMPFILE}.look # average values computed on the grid specified by DUMPBASELINE card BPAR=$( awk 'BEGIN{s=0;}{s=s+$1;}END{print s/NR;}' ${TMPFILE}.bpar ) BPERP=$( awk 'BEGIN{s=0;}{s=s+$1;}END{print s/NR;}' ${TMPFILE}.bperp ) HAMB=$( awk 'BEGIN{s=0;}{s=s+$1;}END{print s/NR;}' ${TMPFILE}.hamb ) LOOK=$( awk 'BEGIN{s=0;}{s=s+$1;}END{print s/NR;}' ${TMPFILE}.look ) BTEMP=$( awk '/Btemp/{print $3}' ${PRODFILE} ) ; # Mahmut additional attributes, mostly based on slave MISSION=$( awk '{FS=":"}/Product type specifier/{ split($3,a,"."); gsub(/ /,"",$2); if(a[1]== "ERS-1"){print "E1" }else if(a[1]== "ERS-2"){print "E2"}else if($2=="ASAR"){print "N1"}else{print "NA"}}' \ ${SLAVEFILE} ) # MA, I picked slave since you can also do master master to get 0 basline info #DATE=$( [[ "$MISSION" != "N1" ]] && awk '/Volume_set_identifier/{ print substr($2,1,8)}' ${SLAVEFILE} || awk -F "_" '/Volume file:/{ print substr($3,7)}' ${SLAVEFILE} ) # change for ERS due buggy VDF files DATE=$( awk '/First_pixel_azimuth_time/{ print substr($3,1,11)}' ${SLAVEFILE} ) ORBIT=$( awk '/Scene identification:/{printf "%05d", $4}' ${SLAVEFILE} ) mfDC=$( awk '{FS=":"}/Xtrack_f_DC_constant/{gsub(/ /,"",$2); printf "%s\n", $2}' ${MASTERFILE} ) sfDC=$( awk '{FS=":"}/Xtrack_f_DC_constant/{gsub(/ /,"",$2); printf "%s\n", $2}' ${SLAVEFILE} ) dfDC=$( awk -v m="$mfDC" -v s="$sfDC" 'BEGIN{print s-m }' ) # w.r.t master s_cLON=$( awk '/Scene_centre_longitude/ {printf "%5.3f\n", $2}' ${SLAVEFILE}) s_cLAT=$( awk '/Scene_centre_latitude/ {printf "%5.3f\n", $2}' ${SLAVEFILE}) #INFO=$( awk '/^precise_orbits:/{ print ($2 == "1") ? "preciseorb" : "annotated"}' ${SLAVEFILE} ) INFO=$( awk '/^precise_orbits:/{ yes=$2 }; ( yes == "1" && $2 ~ "Orbit_dir:"){ po= $3 }END{ if( yes == "1" ){ print ( po != "" ) ? po : "preciseorb" }else{ print "annotated"} }' ${SLAVEFILE} ) ; # Orbit_dir tag printed by orbits.precise.sh to .res echo -e "Mission: \t\t ${MISSION} " echo -e "Date: \t\t\t ${DATE}" echo -e "Orbit: \t\t\t ${ORBIT}" echo -e "Bpar [m]: \t\t ${BPAR}" echo -e "Bperp [m]: \t\t ${BPERP}" echo -e "Btemp [days]: \t\t ${BTEMP}"; # MA added echo -e "fDC [Hz]: \t\t $( awk -v o="${sfDC}" 'BEGIN{printf "%.3f", o}' )"; # MA added echo -e "dfDC [Hz]: \t\t $( awk -v o="${dfDC}" 'BEGIN{printf "%.3f", o}' )"; # MA added echo -e "Center Lon [deg]: \t ${s_cLON}" echo -e "Center Lat [deg]: \t ${s_cLAT}" echo -e "Look.angl [deg]: \t ${LOOK}" echo -e "Height.amb [m]: \t ${HAMB}" echo -e "INFO: \t\t\t $INFO" ### Tidy up. #rm -rf $TMPDIR rm -f $DORISIN rm -f $DORISOUT rm -f $LOGFILE rm -f $PRODFILE rm -f $TMPFILE.bpar rm -f $TMPFILE.bperp rm -f $TMPFILE.hamb rm -f $TMPFILE.look exit 0 ### EOF. Doris-5.0.3Beta/bin/coregpm.doris000077500000000000000000000255441312547014700166620ustar00rootroot00000000000000#!/bin/csh -f ### # coregpm.fast: run doris step COREGPM from prompt. # basicaly a backup interf.res is created and doris works # with this file until the client is satisfied with the results. # then this file is copied to the original for the processing. # This is due to that doris does not like it when a step is repeated. ### # Rens Swart * 14 February 2001 # Bert Kampes, 14-Feb-2001 #%// BK 19-Feb-2001: made .faster... # $Revision: 3.5 $ $Date: 2003/04/14 06:35:15 $ ### ### Some variables. set PRG = `basename "$0"` set VER = "v1.0, FMR software" set AUT = "Rens Swart (c)2001" set CLS = "clear" if ( ! -x `which $CLS` ) set CLS = "" $CLS echo "$PRG $VER, $AUT"\\n ### TODO: # -autoloop if input = n5 (batch) # while numloops < 6, and max(err)>0.3 and max(wtest) 0 ) ### Run executable. # change infile, remove plot?, garantee things? echo "Calling Doris: $LOOPCNT (output in file: $REDIRFILE)" $DORIS $DORIS_IN >>& $REDIRFILE if ( $status ) then echo "Doris exited with error. Exiting as well..."\\n exit 1 endif if ( "$DORIS_QUIET" == "0" ) then more $REDIRFILE endif ### Ask whether plot results should be run: echo "??? Plot results? ([y]/n)" set KEY = $< if ( "$KEY" != "n" ) then #sleep 1 echo "Start plotting, close with 'q'" set IFILE = "CPM_Data" if ( ! -r $IFILE ) then echo "Plotting input file: $IFILE cannot be read, continuing..." else # See script plotcpm for more info. (BK) gmtset MEASURE_UNIT cm \ PAPER_MEDIA a4+ \ PAGE_ORIENTATION portrait \ ANOT_FONT Helvetica \ ANOT_FONT_SIZE 10p \ ANOT_OFFSET 0.2c \ BASEMAP_AXES WeSn \ LABEL_FONT Helvetica \ LABEL_FONT_SIZE 10 \ UNIX_TIME_POS -2c/-2c set OFILE1 = dummy1.$$.ps set TMPFILE = tmpfile.plot.$$ ### remove trailing comment lines (10) tail -n +11 $IFILE >! $TMPFILE set MAXERR=`awk 'BEGIN{m=sqrt($7*$7)}{{if(sqrt($7*$7)>m){m=sqrt($7*$7)}}}END{print m+.05}'<$TMPFILE` set TITLE = "Azimuth_direction" set PROJ = "-JX15/8" set XLABEL = "Correlation" set YLABEL = "abs(e)" set GMTFLAGS = "-K -N -R0/1/0/$MAXERR $PROJ -U -Sx.2 -B.1:"$XLABEL":/.1:"$YLABEL"::."$TITLE": -P -W4/255/0/0" awk '{print $6, sqrt($7*$7)}' $TMPFILE | psxy $GMTFLAGS >! $OFILE1 ### Add the window numbers. set GMTFLAGS = "-N -R0/1/0/$MAXERR $PROJ -P -O -K" awk '{printf "%lg %s 10 0 0 5 %lg\n", $6+.003, sqrt($7*$7)+.003, $1}' $TMPFILE | pstext $GMTFLAGS >> $OFILE1 ### Do the same plot for Range direction. (shift up with -Y) set MAXERR=`awk 'BEGIN{m=sqrt($8*$8)}{{if(sqrt($8*$8)>m){m=sqrt($8*$8)}}}END{print m+.05}'<$TMPFILE` set TITLE="Range_direction" set GMTFLAGS="-O -K -Y11 -N -R0/1/0/$MAXERR $PROJ -Sx.2 -B.1:"$XLABEL":/.1:"$YLABEL"::."$TITLE": -P -W4/255/0/0" awk '{ {print $6, sqrt($8*$8)} }' $TMPFILE | psxy $GMTFLAGS >> $OFILE1 set GMTFLAGS = "-N -R0/1/0/$MAXERR $PROJ -P -O" awk '{ {printf "%lg %s 10 0 0 5 %lg\n", $6+.003, sqrt($8*$8)+.003, $1} }' $TMPFILE | pstext $GMTFLAGS >> $OFILE1 viewanddel $OFILE1 rm -f $TMPFILE endif endif ### Check maxdeviation inversion in Doris (from logfile). set NORMALMAX = "0.0001" # maximum deviation from unity for stable inversion. set MAXDEV = `grep deviation $LOGFILE | awk 'END{print $6}'` if ( "X$MAXDEV" == "X" ) then echo "Check for maximum deviation not found, continuing" else set MAXDEVOK = `echo $MAXDEV $NORMALMAX | awk '{if ($1>$2){print 1}else{print 0}}'` if ( "$MAXDEV" == "NaN" ) set MAXDEVOK = "0" if ( "$MAXDEVOK" != "0" ) then echo \\n"Warning: Deviation from unity: $MAXDEV > $NORMALMAX " echo "Press to continue." set KEY = $< endif endif ### Obtain largest w-test from log. # Get last group of statistics; get line number. set LINENO = `grep -n _Start_comp_coregpm $LOGFILE | tail -n1 | cut -f 1 -d:` tail -n +$LINENO $LOGFILE | head -n14 >! $WTESTFILE # Get w-test amplitudes and window numbers. set MAXWTESTS = `grep statistic $WTESTFILE | awk '{print $8}'` set WINDOWS = `grep window $WTESTFILE | awk '{print $4}'` # Determine largest w test statistic: range or azimuth? get window number. set MAXWAZIMLARGER = `echo $MAXWTESTS | awk '{if($1>$2){print 1}else{print 0}}'` if ($MAXWAZIMLARGER) then set WINDOW1 = $WINDOWS[1] set WINDOW2 = $WINDOWS[2] set MAXWTEST = $MAXWTESTS[1] else set WINDOW1 = $WINDOWS[2] set WINDOW2 = $WINDOWS[1] set MAXWTEST = $MAXWTESTS[2] endif ### Test redundancy still OK... ### Test wtest<20: stop ### Disable window with largest w-test. set WINDOWLIST = "$WINDOW1" $CLS echo " " cat $WTESTFILE echo \\n"------------------------------"\ \\n"Select windows to remove from estimation:"\ \\n" largest w-test: window number: $WINDOW1"\ \\n" largest w-test in both directions: $WINDOW1 and $WINDOW2"\ \\n" w1 w2 w3 ... specifies list to remove"\ \\n" quit"\\n set KEY = "$<" if ( "X$KEY" == "X" ) then set WINDOWLIST = "$WINDOW1" else if ( "X$KEY" == "Xb" ) then set WINDOWLIST = "$WINDOW1 $WINDOW2" # Check uniqueness (how auto?). if ( "X$WINDOW1" == "X$WINDOW2" ) then echo "Same window1 and 2, ignoring window2." set WINDOWLIST = "$WINDOW1" endif else if ( "X$KEY" == "Xq" ) then break else set WINDOWLIST = "$KEY" endif ### Loop that removes specified windows. foreach WINDOW ( $WINDOWLIST ) echo "Disabling window number: $WINDOW" # Select coregpm section to prevent incidental hits and search for window nr set WINDOWLINE = `awk '/Start_fine_coreg/,/End_fine_coreg/' $INTERF_BAK | \ awk -v w=$WINDOW '{if ($1 == w) {print $0}}'` #echo WINDOWLINE: $WINDOWLINE # Process lines, test also on second column for safety reasons. # This only works if it writes to file different from the one it searches in # (of course, BK, 19-feb-2001, ??) awk -v w1=$WINDOWLINE[1] -v w2=$WINDOWLINE[2] -v loop=$LOOPCNT '{ \ if ($1 == w1 && $2 == w2) {printf "%4i%6i%6i%10.2f%10.2f 0.000%1i %6.2f disabled\n", $1,$2,$3,$4,$5,loop,$6} \ else {print $0}}' $INTERF_BAK >! $INTERF_RES # Move forced to backup file: we work with that in the next loop. cp -f $INTERF_RES $INTERF_BAK end @ LOOPCNT++ end ### Tidy up rm -f $WTESTFILE $INTERF_BAK .gmtcommands echo "Thank you for using $PRG"\\n echo "Output in result file: "\"$INTERF_RES\" echo "Original result file copied to: "\"$INTERF_ORIG\"\\n echo "redirected doris output in: "\"$REDIRFILE\"\\n echo "??? Can I remove the latter two files? ([y]/n)" set KEY = $< if ( "X$KEY" != "Xn" ) then rm -f $INTERF_ORIG $REDIRFILE endif ### EOF Doris-5.0.3Beta/bin/cpx2ps000077500000000000000000000470741312547014700153300ustar00rootroot00000000000000#!/bin/csh -f ### # Script to plot magnitude/or phase of complex file (pix interleaved) # (major row order, pixel interleaved, 2B=short) with GMT # based on scripts by: Falk Amelung, Ramon Hanssen. # requires: c++ program cpxfiddle # scheme: # 1. echo binary file to screen, pipe to xyz2grd # 2. xyz2grd (gmt) # 3. grdimage (gmt) # 4. scalebar (psscale gmt) # 5. title filename (psxy gmt) ### RCS ### # $Revision: 3.5 $ $Date: 2003/04/14 06:25:52 $ # BK 10-May-2000 # # option for float file, simple plot only, use cat, -fr4 # TODO: -C input cpt file ipv. output name... #%// BK 19-Jun-2000 # TODO: magnitude image: histeq, also in bg plot plotoffsets #%// BK 09-Apr-2001 ### set PRG = `basename "$0"` set VER = "v2.1, FMR software" set AUT = "Bert Kampes, (c)1999-2000" echo "$PRG $VER, $AUT" \\n ### Set defaults, check later set FIRSTLINE = "1" # -l default set FIRSTPIXEL = "1" # -L default set LASTLINE = "0" # -p correct later if not user set set LASTPIXEL = "0" # -P correct later if not user set set EXP = "1.0" # -e default set SCALE = "1.0" # -s default set FFORMAT = "cr4" # -f default mph file set OUTPUT = "mag" # -q do magnitude set XSUB = "1" # -X sub sampling factor default set YSUB = "1" # -Y sub sampling factor default set XMULTILOOK = "1" # -M multilook factor default set YMULTILOOK = "1" # -M multilook factor default set MIRROR = "" # -m default none passed to prog set VERBOSE = "0" # -V set DEBUG = "" # -V passed to progs @ LINELENGTH = 0 # GMT gmtset MEASURE_UNIT cm \ PAPER_MEDIA a4+ \ PAGE_ORIENTATION portrait \ ANOT_FONT Helvetica \ ANOT_FONT_SIZE 10p \ ANOT_OFFSET 0.2c \ BASEMAP_AXES WeSn \ LABEL_FONT Helvetica \ LABEL_FONT_SIZE 10 \ UNIX_TIME_POS -2c/-2c #set TITLE = "none" # -T title set TITLE = "" # -T title set XSIZE = "16" # -z largest paper size in cm (?) set YSIZE = "0" # -z largest paper size in cm (?) set CPTNAME = "0" # -C cpt lookup name set CPTZ = "" # -Z discontinuous table by default set SCALEBAR = "0" # -S largest paper size in cm (?) set LEAVEOPEN = "0" # -K set ONLYONEGMT = "1" # default only grdimage set TIMESTAMP = "0" # -U # Script variables set CALLGV = "1" # -g default gv set PSFILE = "$$.eps" # -o postscript output (default) set GRDFILE = "$$.grd" # -G netCDF grd file (default) set CPTFILE = "$$.cpt" # created (default) ### Handle input. set HELP = "0" set OPTIONS = "w:e:s:l:L:p:P:f:q:F:G:c:C:o:z:T:m:M:hKSUVZg" set argv = `getopt $OPTIONS $*` # Check any input, getopts ok? if ( "$?argv" == "0" ) then echo "Sorry, no input or parse error." exit 1 endif # Process commandline arguments while ( "$1" != "--" ) switch ( $1 ) # Help case '-h': set HELP = "1" breaksw # linelength,width case '-w': @ LINELENGTH = "$2" shift breaksw # exponent case '-e': set EXP = "$2" shift breaksw # scale case '-s': set SCALE = "$2" shift breaksw # firstline case '-l': set FIRSTLINE = "$2" shift breaksw # lastline case '-L': set LASTLINE = "$2" shift breaksw # firstpixel case '-p': set FIRSTPIXEL = "$2" shift breaksw # lastpixel case '-P': set LASTPIXEL = "$2" shift breaksw # input format case '-f': set FFORMAT = "$2" if ( "$FFORMAT" != "ci2" & \ "$FFORMAT" != "r4" & \ "$FFORMAT" != "cr4" & \ "$FFORMAT" != "cr8" ) then echo " +++ "WARNING: -f \"$FFORMAT\" not recognized, continuing with \"cr4\" set FFORMAT = "cr4" endif shift breaksw # what to output case '-q': set OUTPUT = "$2" if ( "$OUTPUT" != "mag" & \ "$OUTPUT" != "phase" & \ "$OUTPUT" != "real" & \ "$OUTPUT" != "imag" & \ "$OUTPUT" != "normal" ) then echo " +++ "WARNING: -q \"$OUTPUT\" not recognized, continuing with \"mag\" set OUTPUT = "mag" endif shift breaksw # subsampling -Fx/y case '-F': set XSUB = `echo "$2" | cut -f1 -d'/'` set YSUB = `echo "$2" | cut -f2 -d'/'` shift breaksw # multilooking -Mx/y case '-M': set XMULTILOOK = `echo "$2" | cut -f1 -d'/'` set YMULTILOOK = `echo "$2" | cut -f2 -d'/'` shift breaksw # color table case '-c': set CPTNAME = "$2" shift breaksw # mirroring case '-m': set MIRROR = "-m $2" if ( "$MIRROR" != "-m YX" & \ "$MIRROR" != "-m XY" & \ "$MIRROR" != "-m X" & \ "$MIRROR" != "-m Y" ) then echo " +++ "WARNING: \"$MIRROR\" not recognized, continuing with no mirroring. set MIRROR = "" endif shift breaksw # color table case '-Z': set CPTZ = "-Z" breaksw # paper size case '-z': set XSIZE = "$2" shift breaksw # scale bar case '-S': set SCALEBAR = "1" set ONLYONEGMT = "0" breaksw # leave eps open after finish case '-K': set LEAVEOPEN = "1" breaksw # title case '-T': #set TITLE = "$TITLE $2" set TITLE = $2 set TITLE = "-B/:.${TITLE}:" shift breaksw # timestamp case '-U': set TIMESTAMP = "1" breaksw # verbose case '-V': set VERBOSE = "1" set DEBUG = "-V" echo " *** Verbose set" breaksw # postscript file name (output) case '-o': set PSFILE = $2 shift breaksw # grd file name (output) case '-G': set GRDFILE = $2 shift breaksw # cpt file name (output) case '-C': set CPTFILE = $2 shift breaksw # dogv case '-g': set CALLGV = "0" breaksw # not recognized pass to GMT default: echo option: $1 echo " +++ non existing option, I will give help later." set HELP="1" endsw shift # next flag end # while shift # skip the -- set CPXFILE = $1 if ( "$HELP" == "0" & "X$CPXFILE" == "X" ) then echo " +++ WARNING: infile missing" set HELP = "1" endif if ( "$HELP" == "0" ) then if ( ! -e $CPXFILE ) then echo " +++ WARNING: CPXFILE: $CPXFILE cannot be found" set HELP = "1" endif endif # Mandatory options if ( "$HELP" == "0" & $LINELENGTH == 0 ) then echo " +++ WARNING: -w width option missing" set HELP = "1" endif ### Set internal script variables # Check user input -c if ( "$CPTNAME" == "0" ) then # not specified by user if ( "$OUTPUT" == "mag" ) then set CPTNAME = "gray" # cpt lookup name else if ( "$OUTPUT" == "phase" ) then #set CPTNAME = "sealand" # cpt lookup name set CPTNAME = "rainbow" # cpt lookup name else # real/imag #set CPTNAME = "sealand" # default set CPTNAME = "rainbow" # default endif endif # Check if help is asked if ( "$HELP" == "1" ) then #cat << __EOFHD | more -de cat << __EOFHD | more PROGRAM: $PRG -- Produce various eps codes from complex data files. SYNOPSIS: $PRG -w width [-f format==$FFORMAT] [-q out==$OUTPUT] [-e exp==$EXP] [-s sc==$SCALE] [-l 1] [-L alllines] [-p 1] [-P width] [-M$XMULTILOOK/$YMULTILOOK | -F$XSUB/$YSUB] [-m mirror] [-T title] [-c cptname==$CPTNAME] [-z size==$XSIZE] [-o epsfile] [-G grdfile] [-C cptfile] [-gKSUVZ] [-h elp] [--] cpxfile cpxfiddle options: -w width of complexfile in complex pixels -f format of complex input file. ci2|cr4|cr8 ($FFORMAT is default) r4 now also possible, though it limites other options. do not use subsampling, mirroring etc, file is cat-ed. -q output what is to be computed mag|phase|real|imag|normal ($OUTPUT is default) -e exp compute scale*output^exp -s scale compute scale*output^exp -l firstline cut out complexfile from firstline -L lastline cut out complexfile upto lastline -p firstpixel cut out complexfile from firstpixel -P lastpixel cut out complexfile upto lastpixel -m X Y XY mirror option. -M 1/1 multilook factor in X/Y direction -F 1/1 subsample Factor in X/Y direction GMT options: -T title title to plot (one word only for now) default no title -c colortable name of color table (see grd2cpt) if -q mag then gray table is default if -q other then $CPTNAME table is default -S add a scale bar (psscale) -Z continuous color table (grd2cpt) -K Leave postscript file open after last call to GMT -z cm largest size of paper -U Place UNIX time stamp and filename in output General options: -g Do not call gv to view result. -o output postscript file, default=$$.eps (pid) -G output grd file, default=$$.eps (pid) If specified, file is not removed at end If file exists, prompted for reuse. -C output cpt file, default=$$.cpt (pid) If specified, file is not removed at end If file exists, prompted for reuse. -V erbose give verbose information -h elp this help complexfile inputfile, major row order pixel interleaved EXAMPLES: Generate a postscript file with phase of complex interferogram in file cpxint.raw (complex 2x4B floats) that has 998 range pixels: $PRG -w 998 -qphase -fcr4 -- cpxint.raw The same but with a scale bar, timestamp, and no title: $PRG -w 998 -qphase -fcr4 -Tnone -U -S -- cpxint.raw To plot the magnitude to the power 0.3 of a file in the format complex short integers (2x2B) use: $PRG -w 998 -qmag -fci2 -e0.3 -- cpxint.raw To see a large file it is convenient to set a large size (-z). This file cannot be printed, but viewing it with gv is nice: $PRG -w 998 -qphase -z200 -- cpxint.raw To plot the phase of a hgt file, first create a tmp file with the program hgt2file (hgtfile infile linelength tmpfile [ampflag]) Next, run $PRG with appropriate flags for a float file, e.g. (Note that this limits some options in scaling etc.): $PRG -w 998 -crainbow -fr4 -- tmpfile BUGS: When mirroring and multilooking/subsampling sometimes the number of lines/pixels of the output is computed incorrectly. Simply don't use multilooking/subsampling... Please mail bugs/comments to kampes@geo.tudelft.nl SEE ALSO: cpxfiddle, GMT __EOFHD exit 1 endif if ( $VERBOSE ) then echo " *** Color table name: $CPTNAME (-c option, grd2cpt)" endif # cpxfiddle internal variables set OFORMAT = "-o float" # binary to stdout ### Check files set REUSEGRD = "0" set REUSECPT = "0" if ( -e $PSFILE ) then if ( $VERBOSE ) \ echo " *** Removing existing postscript output: $PSFILE" rm -f $PSFILE endif if ( -e $GRDFILE ) then echo " --- Press enter to remove grd file: $GRDFILE"\\n\ "r to reuse it"\\n\ "CTRL-C to quit" set key = $< if ( "$key" == "r" ) then if ( $VERBOSE ) echo " *** Re-using grdfile: $GRDFILE" set REUSEGRD = "1" else if ( $VERBOSE ) echo " *** Removing grdfile: $GRDFILE" rm -f $GRDFILE endif endif if ( -e $CPTFILE ) then echo " --- Press enter to remove cpt file: $CPTFILE"\\n\ "r to reuse it"\\n\ "CTRL-C to quit" set key = $< if ( "$key" == "r" ) then if ( $VERBOSE ) echo " *** Re-using cptfile: $CPTFILE" set REUSECPT = "1" else if ( $VERBOSE ) echo " *** Removing cptfile: $CPTFILE" rm -f $CPTFILE endif endif ### Compute dimensions paper/file # sizes file set BYTES = "8" # bytes per pixel (re+im) if ( "$FFORMAT" == "ci2") then set BYTES = "4" # bytes per pixel (re+im) else if ( "$FFORMAT" == "cr8") then set BYTES = "16" # bytes per pixel (re+im) else if ( "$FFORMAT" == "r4") then set BYTES = "4" # bytes per pixel, use cat endif set FSIZE = `ls -l $CPXFILE | awk '{print $5}'` @ FILELINES = `echo "scale=0; $FSIZE/$LINELENGTH/$BYTES" | bc -l` if ( $VERBOSE ) then echo " *** LINELENGTH: $LINELENGTH FILESIZE: $FSIZE" echo " *** BYTES per cpx pixel: $BYTES FILELINES computed: $FILELINES" endif # # Check user input or set default if ( "$LASTLINE" == "0" ) then set LASTLINE = "$FILELINES" # default endif if ( "$LASTPIXEL" == "0" ) then set LASTPIXEL = "$LINELENGTH" # default endif # ### Set program variables. set PROG = "cpxfiddle" set PROGOPTS = "-w$LINELENGTH -e$EXP -s$SCALE -S$XSUB/$YSUB -M$XMULTILOOK/$YMULTILOOK -l$FIRSTLINE -L$LASTLINE -p$FIRSTPIXEL -P$LASTPIXEL -f$FFORMAT $OFORMAT -q$OUTPUT $MIRROR $DEBUG $CPXFILE" # if ( $VERBOSE ) echo " *** Options for ${PROG}:"\\n $PROGOPTS # Set GMT options, difference in subsampling/multilook for numpix. if ( "$XMULTILOOK" != "1" ) then if ( "$XSUB" != "1" ) then echo " +++ WARNING: Sorry, not possible multilooking and subsampling." exit endif set XSUB = "$XMULTILOOK" endif if ( "$YMULTILOOK" != "1" ) then if ( "$YSUB" != "1" ) then echo " +++ WARNING: Sorry, not possible multilooking and subsampling." exit endif set YSUB = "$YMULTILOOK" endif set INC = "-I$XSUB/$YSUB" set IFORMAT = "-Zf" # binary float values # add lowerleft?? for real plot? # can be done with grdedit -A # # correct for GMT, subsampling output = ceil ((P-p+1)/sub) # correct for GMT, multilook output = floor ((P-p+1)/ml) #set RANGE = "-R$FIRSTPIXEL/$LASTPIXEL/$FIRSTLINE/$LASTLINE" # outputlines after subsampling = ceil((P-p+1)/sub) # outputlines after multilooking = floor((P-p+1)/sub) #%// BK 02-Oct-2000 # functions ceil and floor have to be used?, ceil!=floor+1 !!! # but ceil == floor(b-1/sub)+1 ??? (where b=$2-$1+1) (?) # Seems that some csh (linux) do not like it if `` goes over eol. with \ #%// BK 11-Dec-2000 set NUMX = `echo "$FIRSTPIXEL $LASTPIXEL $XSUB" | awk '{b=$2-$1+1}{if (int(b/$3)==b/$3){print int(b/$3)}else {print(int(b/$3))+1}}'` set NUMY = `echo "$FIRSTLINE $LASTLINE $YSUB" | awk '{b=$2-$1+1}{if (int(b/$3)==b/$3){print int(b/$3)}else {print(int(b/$3))+1}}'` if ( "$XMULTILOOK" != "1" ) then set NUMX = `echo "$FIRSTPIXEL $LASTPIXEL $XSUB" | awk '{print int(($2-$1+1)/$3)}'` endif if ( "$YMULTILOOK" != "1" ) then set NUMY = `echo "$FIRSTLINE $LASTLINE $YSUB" | awk '{print int(($2-$1+1)/$3)}'` #set NUMY = `echo "$FIRSTLINE $LASTLINE $YSUB" | awk '{printf "%i", (($2-$1+1)/$3)}'` endif #%// BK 02-Oct-2000 set EAST = `echo "$FIRSTPIXEL+($NUMX-1)*$XSUB" | bc -l` set NORTH = `echo "$FIRSTLINE+($NUMY-1)*$YSUB" | bc -l` # #BK 16MAY better use actual papersize, not file dimensions (cut out allowed) @ OUTPUTLINES = $NUMY @ OUTPUTWIDTH = $NUMX # size paper, largest size $XSIZE #if ( $FILELINES > $LINELENGTH ) then if ( $OUTPUTLINES > $OUTPUTWIDTH ) then if ( $VERBOSE ) echo " *** More output lines than pixels" set YSIZE = $XSIZE set XSIZE = `echo "scale=3; $OUTPUTWIDTH/$OUTPUTLINES*$YSIZE" | bc -l` else if ( $VERBOSE ) echo " *** More output pixels than lines" set YSIZE = `echo "scale=3; $OUTPUTLINES/$OUTPUTWIDTH*$XSIZE" | bc -l` endif if ( $VERBOSE ) echo " *** Papersize: XSIZE: $XSIZE YSIZE: $YSIZE" # # BK 18-May-2000 if ( "$OUTPUT" == "normal" ) then set EAST = `echo "2*($FIRSTPIXEL+($NUMX-1)*$XSUB)" | bc -l` endif set RANGE = "-R$FIRSTPIXEL/$EAST/$FIRSTLINE/$NORTH" ### Prog binary dumps to stdout, xyz2grd makes grd file for GMT. if ( $REUSEGRD ) then if ( $VERBOSE ) echo " *** Using existing grd file: $GRDFILE" else if ( $VERBOSE ) echo " *** Creating new grd file: $GRDFILE" if ( "$FFORMAT" == "r4") then if ( $VERBOSE ) echo " *** Catting float file to xyz2grd" cat $CPXFILE | xyz2grd -G$GRDFILE $RANGE $INC $IFORMAT else if ( $VERBOSE ) echo " *** Options for xyz2grd:"\\n -G$GRDFILE $RANGE $INC $IFORMAT $PROG $PROGOPTS | xyz2grd -G$GRDFILE $RANGE $INC $IFORMAT endif endif set ZMIN = `grdinfo -C $GRDFILE | cut -f6` set ZMAX = `grdinfo -C $GRDFILE | cut -f7` set NINTERVALS = "4" # actually n+1... user input? set ZINT = `echo "$ZMIN $ZMAX $NINTERVALS" | awk '{printf "%10.2g", ($2-$1)/$3}'` if ( $VERBOSE ) then echo " *** zmin zmax #intervals zinterval: $ZMIN $ZMAX $NINTERVALS $ZINT" endif ### grdhisteq if ( "$OUTPUT" == "mag" ) then echo "consider doing grdequalize here?" endif ### grd2cpt # Select color table (loop index, select from 10?). set CPTS = "" if ( $REUSECPT ) then if ( $VERBOSE ) echo " *** Using existing cpt file: $CPTFILE" else if ( $VERBOSE ) echo " *** Creating new cpt file: $CPTFILE" ### use -S if phase? if ( "$OUTPUT" == "phase" ) then ### 40 intervals set PI = "3.1416" set CPTS = "-S-$PI/$PI/0.157" endif ### BK 4-apr-2001: cut off mag>threshold ### but it seems to work fine asis, so leave it... # if ( "$OUTPUT" == "mag" ) then # ### threshold = -LZMIN/ZMEAN*XXX/NN intervals # set PI = "3.1416" # set CPTS = "-S-$PI/$PI/0.157" # endif if ( $VERBOSE ) echo " *** Calling: grd2cpt $GRDFILE $CPTZ $CPTS -C$CPTNAME $DEBUG" grd2cpt $GRDFILE $CPTZ $CPTS -C$CPTNAME $DEBUG >! $CPTFILE endif ### GMT general flags if ( $TIMESTAMP ) then set TIMESTAMPLLX = "-0.5" set TIMESTAMPLLY = "-0.5" # place timestamp little lower if also scalebar if ( $SCALEBAR ) set TIMESTAMPLLY = "-2.0" #set TIMESTAMP = -U/-0.5/-1.5/\"${CPXFILE:t}\" set TIMESTAMP = -U/$TIMESTAMPLLX/$TIMESTAMPLLY/\"${PRG}\:_${CPXFILE:t}\" if ( $VERBOSE ) echo " *** Timestamp: $TIMESTAMP" else set TIMESTAMP = "" endif set GMTFIRST = "-K" # append more later set GMTMIDDLE = "-K -O" # append more later and overlay set GMTCLOSE = "-O" # overlay set GMTFLAGS = "$GMTFIRST $DEBUG" if ( "$LEAVEOPEN" == "0" & "$ONLYONEGMT" == "1" ) \ set GMTFLAGS = "$DEBUG" ### grdimage ### Consider using -Iamp.grd for magnitude/phase display if ( $VERBOSE ) echo " *** Grdimage creates postscript file: $PSFILE" if ( $VERBOSE ) echo " *** Title: $TITLE" set SIZE = "-JX$XSIZE/$YSIZE" # bounding box size grdimage $GRDFILE $SIZE -C$CPTFILE $TITLE -P $GMTFLAGS $TIMESTAMP >! $PSFILE set GMTFLAGS = "$GMTMIDDLE $DEBUG" ### add ? #pwd | psxy $RANGE $SIZE -X0 -Y0 -K >> $PSFILE ### psscale this must be the last call to GMT if ( ! $LEAVEOPEN ) set GMTFLAGS = "$GMTCLOSE $DEBUG" if ( $SCALEBAR ) then if ( $VERBOSE ) echo " *** Adding scale bar (psscale)." set SCBOPTS = " " # set SCBLENGTH = `echo "scale=0; $YSIZE*0.6" | bc -l` set SCBWIDTH = "0.25h" # horizontal bar 0.25 cm set SCBLLX = `echo "scale=1; $XSIZE*0.45" | bc -l` set SCBLLY = "-0.4" #set SCBANNOT = "-B${ZINT}:magnitude:/:mag:" set SCBANNOT = "-B${ZINT}:magnitude:" if ( "$OUTPUT" == "phase" ) set SCBANNOT = "-B3.14:phase:/:rad:" set SCBOPTS = "-L" # equal sized # lower left corner position wrt. frame? #set SCBPOS='-D3/-0.5/6/0.25h' set SCBPOS = "-D$SCBLLX/$SCBLLY/$SCBLENGTH/$SCBWIDTH" #ok: set ANNOT='-B50::/:m:' psscale -C$CPTFILE $SCBPOS $SCBANNOT $SCBOPTS $GMTFLAGS >> $PSFILE endif ### View. if ( $CALLGV ) then echo " *** View with gv: $PSFILE" gv -bg white -fg black $PSFILE & endif ### Tidy up if ( "$GRDFILE" == "$$.grd" ) then if ( $VERBOSE ) echo " *** Removing tmp grdfile: $GRDFILE" rm -f $GRDFILE endif if ( "$CPTFILE" == "$$.cpt" ) then if ( $VERBOSE ) echo " *** Removing tmp cptfile: $CPTFILE" rm -f $CPTFILE endif if ( $VERBOSE ) then echo " *** Ouput postscript in: $PSFILE" echo \\n" *** Thank you for using $PRG" endif ### EOF Doris-5.0.3Beta/bin/csk_dump_data.py000077500000000000000000000173321312547014700173300ustar00rootroot00000000000000#!/usr/bin/env python #-----------------------------------------------------------------# # A python code for cropping Cosmo-skymed HDF5 file for Doris. # # Author: TUDelft - 2010 # Maintainer: Prabu Dheenathayalan # #-----------------------------------------------------------------# import os,sys,time import numpy, h5py # for hdf5 python support from array import array codeRevision=1.0 # this code revision number def usage(): print 'INFO : @(#)Doris InSAR software, $Revision: %s $, $Author: TUDelft $' % codeRevision print print 'Usage : csk_dump_data.py [l0 lN p0 pN] [-res RESFILE]' print print ' inputfile is the input Cosmo-skymed HDF5 filename : master.hd5' print ' outputfile is the output filename : master.slc' print ' l0 is the first azimuth line (starting at 1)' print ' lN is the last azimuth line' print ' p0 is the first range pixel (starting at 1)' print ' pN is the last range pixel' print ' RESFILE DORIS result file that is to be updated for crop metadata (optional)' print print ' This software is part of Doris InSAR software package.\n' print '(c) 1999-2010 Delft University of Technology, the Netherlands.\n' try: inputFileName = sys.argv[1] outputFileName = sys.argv[2] except: print '\nError : Unrecognized input or missing arguments\n\n' usage() sys.exit(1) # accessing the HDF5 product file f = h5py.File(inputFileName, 'r') sbi = f.get('/S01/SBI') if f.parent.__contains__('/') == False or f.parent.__contains__('/S01') == False or f.parent.__contains__('/S01/SBI') == False : print 'ERROR: Wrong HDF5 format!' data = array('h') data = sbi[:,:,:] Number_of_lines_original = sbi.shape[0] Number_of_pixels_original = sbi.shape[1] sbi = None resFile = None for element in range(len(sys.argv)): option = sys.argv[element]; if option == '-res': resFile = str(sys.argv[element+1]) del sys.argv[element+1] del sys.argv[element] break if len(sys.argv) == 3: outputWinFirstLine = None outputWinLastLine = None outputWinFirstPix = None outputWinLastPix = None elif len(sys.argv) > 3 and len(sys.argv) < 9: outputWinFirstLine = int(sys.argv[3])-1 # gdal srcwin starting at 0 outputWinLastLine = int(sys.argv[4]) # Lastline --> yoff (later) outputWinFirstPix = int(sys.argv[5])-1 # gdal srcwin starting at 0 outputWinLastPix = int(sys.argv[6]) # Lastpix --> yoff (later) elif len(sys.argv) > 3 and len(sys.argv) < 7: print 'Unrecognized input' usage() sys.exit(1) else: outputWinFirstLine = None outputWinLastLine = None outputWinFirstPix = None outputWinLastPix = None # need to check to provide this functionality or to throw error saying "crop size unknown" # if crop size is not mentioned crop the complete image #if outputWinFirstLine == None or outputWinLastLine == None or outputWinFirstPix == None or outputWinLastPix == None : # outputWinFirstLine = 0 # outputWinLastLine = Number_of_lines_original-1 # outputWinFirstPix = 0 # outputWinLastPix = Number_of_pixels_original-1 # print 'crop parameters not provided,so cropping the whole image' if outputWinFirstLine == None or outputWinLastLine == None or outputWinFirstPix == None or outputWinLastPix == None : print '%s: running failed: crop size unknown !' % (sys.argv[0]) sys.exit(1) if outputWinLastLine-outputWinFirstLine+1 <0 or outputWinLastPix-outputWinFirstPix+1 <=0 : print '%s running failed: crop dimensions are not invalid !' % (sys.argv[0]) sys.exit(1) # compute crop dimensions if outputWinFirstLine==0: NLinesCrop = outputWinLastLine elif outputWinFirstLine+1==outputWinLastLine: NLinesCrop = 1 else: NLinesCrop = outputWinLastLine-outputWinFirstLine if outputWinFirstPix==0: NPixelsCrop = outputWinLastPix elif outputWinFirstPix+1==outputWinLastPix: NPixelsCrop = 1 else: NPixelsCrop = outputWinLastPix-outputWinFirstPix # write the data in Complex Short format (CInt16) - if available need to replace this code using gdal with HDF support temp = 0 fid = open(outputFileName, "wl") for n in range(outputWinFirstLine, outputWinLastLine): # logic to just print if int(outputWinLastLine-outputWinFirstLine)/10 <= 0 and temp < 10: sys.stdout.write("0...10...20...30...40...50...60...70...80...90...") temp = 10 elif n % (outputWinLastLine-outputWinFirstLine)/10 == 0 and temp<10: sys.stdout.write('%s...'%(temp*10)) temp = temp+1 # read the hdf5 data and write to file data_line = data[n,range(outputWinFirstPix,outputWinLastPix),:] data_line.tofile(fid) data_line = None sys.stdout.write("100% - done.\n") fid.close() # explicitly writing the hdr file headerFileStream = open(os.path.splitext(outputFileName)[0]+'.hdr','w') headerFileStream.write('IMAGE_FILE_FORMAT = MFF\n') #HARDCODED!!! headerFileStream.write('FILE_TYPE = IMAGE\n') #HARDCODED!!! headerFileStream.write('IMAGE_LINES = %s\n' % (NLinesCrop)) headerFileStream.write('LINE_SAMPLES = %s\n' % (NPixelsCrop)) headerFileStream.write('FILE_TYPE = IMAGE\n') #HARDCODED!!! headerFileStream.write('BYTE_ORDER = LSB\n') #HARDCODED!!! headerFileStream.write('END\n') # check whether the resfile exist!!! if resFile is not None: print resFile # load header headerFileStream = open(os.path.splitext(outputFileName)[0]+'.hdr','r') for line in headerFileStream: pair = line.split() if len(pair) > 1: vars()[pair[0]] = pair[2] # set IMAGE_LINES and LINE_SAMPLES # check whether the file exist outStream = open(resFile,'a') outStream.write('\n') outStream.write('*******************************************************************\n') outStream.write('*_Start_crop: HDF5 \n') outStream.write('*******************************************************************\n') outStream.write('Data_output_file: %s\n' % outputFileName) outStream.write('Data_output_format: complex_short\n') # hardcoded if outputWinFirstPix is not None: outStream.write('First_line (w.r.t. original_image): %s\n' % (outputWinFirstLine+1)) # back to Doris convention outStream.write('Last_line (w.r.t. original_image): %s\n' % outputWinLastLine) outStream.write('First_pixel (w.r.t. original_image): %s\n' % (outputWinFirstPix+1)) outStream.write('Last_pixel (w.r.t. original_image): %s\n' % outputWinLastPix) elif outputWinFirstPix is None: outStream.write('First_line (w.r.t. original_image): 1\n') outStream.write('Last_line (w.r.t. original_image): %s\n' % IMAGE_LINES) outStream.write('First_pixel (w.r.t. original_image): 1\n') outStream.write('Last_pixel (w.r.t. original_image): %s\n' % LINE_SAMPLES) outStream.write('*******************************************************************\n') outStream.write('* End_crop:_NORMAL\n') outStream.write('*******************************************************************\n') outStream.write('\n') outStream.write(' Current time: %s\n' % time.asctime()) outStream.write('\n') # close output file outStream.close() # replace crop tag in result file sourceText = "crop: 0" replaceText = "crop: 1" inputStream = open(resFile,'r') textStream = inputStream.read() inputStream.close() outputStream = open(resFile, "w") outputStream.write(textStream.replace(sourceText, replaceText)) outputStream.close() #EOF Doris-5.0.3Beta/bin/csk_dump_header2doris.py000077500000000000000000000266071312547014700207770ustar00rootroot00000000000000#!/usr/bin/env python #-----------------------------------------------------------------# # A python code for parsing CSK HDF5 file into python data structures # and from there into DORIS res file structure # # Author: TUDelft - 2010 # Maintainer: Prabu Dheenathayalan # #-----------------------------------------------------------------# import numpy, h5py, sys, math, time, string # numpy and h5py required for HDF5 python support codeRevision=1.0 # this code revision number def usage(): print 'INFO : @(#)Doris InSAR software, $Revision: %s $, $Author: TUDelft $' % codeRevision print print 'Usage : python csk_dump_header2doris.py csk_HDF5_product > OutputFileName' print ' where csk_HDF5_product is the input filename' print print ' This software is part of Doris InSAR software package.\n' print '(c) 1999-2010 Delft University of Technology, the Netherlands.\n' try: inputFileName = sys.argv[1] except: print '\nError : Unrecognized input or missing arguments\n\n' usage() sys.exit(1) # accessing the HDF5 product file f = h5py.File(inputFileName, 'r') s01 = f.get('/S01') sbi = s01.get('SBI') b001 = s01.get('B001') qlk = s01.get('QLK') if f.parent.__contains__('/') == False or f.parent.__contains__('/S01') == False or f.parent.__contains__('/S01/SBI') == False or f.parent.__contains__('/S01/B001') == False or f.parent.__contains__('/S01/QLK') == False : print 'ERROR: Wrong HDF5 format!' # reading the attributes VolumeFile = f.attrs.__getitem__('Product Filename') Volume_ID = f.attrs.__getitem__('Programmed Image ID') Volume_identifier = f.attrs.__getitem__('Product Specification Document') Volume_set_identifier='dummy' NumberOfRecordsInRefFile='dummy' SAR_PROCESSOR = f.attrs.__getitem__('L1A Software Version') ProductTypeSpecifier = f.attrs.__getitem__('Product Type') LogicalVolumeGeneratingFacility = f.attrs.__getitem__('Processing Centre') LogicalVolumeCreationDate='dummy' LocationAndDateTimeOfProductCreation = f.attrs.__getitem__('Product Generation UTC') SceneIdentification = f.attrs.__getitem__('Orbit Number') orbitDir = f.attrs.__getitem__('Orbit Direction') sceneMode = f.attrs.__getitem__('Acquisition Mode') SceneLocation = 'dummy' LeaderFile = f.attrs.__getitem__('Product Filename') SAT_ID=f.attrs.__getitem__('Satellite ID') SensorPlatformMissionIdentifier = f.attrs.__getitem__('Mission ID') SceneCentreGeodeticCoordinates = f.attrs.__getitem__('Scene Centre Geodetic Coordinates') Scene_centre_latitude=SceneCentreGeodeticCoordinates[0] Scene_centre_longitude=SceneCentreGeodeticCoordinates[1] Scene_centre_heading = f.attrs.__getitem__('Scene Orientation') Radar_wavelength = f.attrs.__getitem__('Radar Wavelength') Radar_frequency = f.attrs.__getitem__('Radar Frequency') Swath_no = f.attrs.__getitem__('Subswaths Number') Polarisation = s01.attrs.__getitem__('Polarisation') ReferenceUTC = f.attrs.__getitem__('Reference UTC') relZDAFTime = sbi.attrs.__getitem__('Zero Doppler Azimuth First Time') # precision of this variable need to be checked w.r.t tsx if string.atoi(ReferenceUTC[20:])*10 != 0: ZDAFTime_msecsOfDay = round((string.atoi(ReferenceUTC[11:13])*60*60+string.atoi(ReferenceUTC[14:16])*60+string.atoi(ReferenceUTC[17:19])+pow(string.atoi(ReferenceUTC[20:])*10,(-(len(ReferenceUTC)-20)))+relZDAFTime)*1000) else: ZDAFTime_msecsOfDay = round((string.atoi(ReferenceUTC[11:13])*60*60+string.atoi(ReferenceUTC[14:16])*60+string.atoi(ReferenceUTC[17:19])+relZDAFTime)*1000) ZDAFTime_HH = math.floor(ZDAFTime_msecsOfDay/(60*60*1000)) ZDAFTime_MM = math.floor(ZDAFTime_msecsOfDay % (60*60*1000)/(60*1000)) ZDAFTime_SS = math.floor(ZDAFTime_msecsOfDay%(60*1000)/1000) ZDAFTime_TTT = round(ZDAFTime_msecsOfDay%1000) First_pixel_azimuth_time = str('%s %s:%s:%s.%s' % (time.strftime("%d-%b-%Y",time.strptime(ReferenceUTC.split()[0],"%Y-%m-%d")),str(int(ZDAFTime_HH)),str(int(ZDAFTime_MM)),str(int(ZDAFTime_SS)),str(int(ZDAFTime_TTT)))) PRF = s01.attrs.__getitem__('PRF') Total_azimuth_band_width = s01.attrs.__getitem__('Azimuth Focusing Bandwidth') Weighting_azimuth = f.attrs.__getitem__('Azimuth Focusing Weighting Function') Xtrack_f_DC = f.attrs.__getitem__('Centroid vs Range Time Polynomial') Xtrack_f_DC_constant = Xtrack_f_DC[0] Xtrack_f_DC_linear = Xtrack_f_DC[1] Xtrack_f_DC_quadratic = Xtrack_f_DC[2] Range_time_to_first_pixel = sbi.attrs.__getitem__('Zero Doppler Range First Time')*1000 RSR = s01.attrs.__getitem__('Sampling Rate')/pow(10, 6) Total_range_band_width = s01.attrs.__getitem__('Range Focusing Bandwidth')/pow(10, 6) Weighting_range = f.attrs.__getitem__('Range Focusing Weighting Function') NUMBER_OF_DATAPOINTS = f.attrs.__getitem__('Number of State Vectors') StateVectorsTimes = f.attrs.__getitem__('State Vectors Times') if string.atoi(ReferenceUTC[20:])*10 != 0: Time_Datapoints = (string.atoi(ReferenceUTC[11:13])*60*60+string.atoi(ReferenceUTC[14:16])*60+string.atoi(ReferenceUTC[17:19])+pow(string.atoi(ReferenceUTC[20:])*10,(-(len(ReferenceUTC)-20)))+StateVectorsTimes) % (60*60*24) else: Time_Datapoints = (string.atoi(ReferenceUTC[11:13])*60*60+string.atoi(ReferenceUTC[14:16])*60+string.atoi(ReferenceUTC[17:19])+StateVectorsTimes) % (60*60*24) ECEFSatellitePosition = f.attrs.__getitem__('ECEF Satellite Position') ECEFSatelliteVelocity = f.attrs.__getitem__('ECEF Satellite Velocity') nrows = len(ECEFSatellitePosition[:, 0]) ncols = len(ECEFSatellitePosition[0, :]) if nrows == 3: X_Datapoints=ECEFSatellitePosition[0,:] Y_Datapoints=ECEFSatellitePosition[1,:] Z_Datapoints=ECEFSatellitePosition[2,:] X_Velocity=ECEFSatelliteVelocity[0,:] Y_Velocity=ECEFSatelliteVelocity[1,:] Z_Velocity=ECEFSatelliteVelocity[2,:] else: X_Datapoints=ECEFSatellitePosition[:,0] Y_Datapoints=ECEFSatellitePosition[:,1] Z_Datapoints=ECEFSatellitePosition[:,2] X_Velocity=ECEFSatelliteVelocity[:,0] Y_Velocity=ECEFSatelliteVelocity[:,1] Z_Velocity=ECEFSatelliteVelocity[:,2] Datafile = f.attrs.__getitem__('Product Filename') if sbi.shape[0]== 2: Number_of_lines_original = sbi.shape[2] Number_of_pixels_original = sbi.shape[1] else: Number_of_lines_original = sbi.shape[0] Number_of_pixels_original = sbi.shape[1] # --------------------------------------------------------------------------------------------------------- # print the extracted attributes dummyVar = 'DUMMY' print('\ncsk_dump_header2doris.py v%s, doris software, 2010\n' % codeRevision) print('*******************************************************************') print('*_Start_readfiles:') print('*******************************************************************') print('Volume file: %s' % VolumeFile) print('Volume_ID: %s' % Volume_ID) print('Volume_identifier: %s' % Volume_identifier) print('Volume_set_identifier: %s' % Volume_set_identifier) print('(Check)Number of records in ref. file: %s' % NumberOfRecordsInRefFile) print('SAR_PROCESSOR: %s L1A %s' % (SensorPlatformMissionIdentifier,SAR_PROCESSOR)) print('SWATH: %s' % Swath_no) print('PASS: %s' % orbitDir) print('IMAGING_MODE: %s %s' % (sceneMode,Polarisation)) print('RADAR_FREQUENCY (Hz): %s' % Radar_frequency) print('') #print('Product type specifier: %s' % ProductTypeSpecifier) # returns SCS_B print('Product type specifier: %s %s' % (SensorPlatformMissionIdentifier, ProductTypeSpecifier)) print('Logical volume generating facility: %s' % LogicalVolumeGeneratingFacility) print('Logical volume creation date: %s' % LogicalVolumeCreationDate) print('Location and date/time of product creation: %s' % LocationAndDateTimeOfProductCreation) #print('Scene identification: Orbit: %s %s Mode: %s' % (SceneIdentification,orbitDir,sceneMode)) print('Scene identification: Orbit: %s' % SceneIdentification) print('Scene location: lat: %.4f lon: %.4f' % (float(Scene_centre_latitude),float(Scene_centre_longitude))) print('') print('Leader file: %s' % LeaderFile) #print('Sensor platform mission identifier: %s' % SensorPlatformMissionIdentifier) print('Sensor platform mission identifier: %s' % SAT_ID) print('Scene_centre_latitude: %s' % Scene_centre_latitude) print('Scene_centre_longitude: %s' % Scene_centre_longitude) print('Scene_centre_heading: %s' % Scene_centre_heading) #print('Radar_wavelength (m): 0.031') #HARDCODED!!! print('Radar_wavelength (m): %s' % Radar_wavelength) print('First_pixel_azimuth_time (UTC): %s' % First_pixel_azimuth_time) print('Pulse_Repetition_Frequency (computed, Hz): %s' % PRF) print('Total_azimuth_band_width (Hz): %s' % Total_azimuth_band_width) print('Weighting_azimuth: %s' % string.upper(Weighting_azimuth)) print('Xtrack_f_DC_constant (Hz, early edge): %s' % Xtrack_f_DC_constant) print('Xtrack_f_DC_linear (Hz/s, early edge): %s' % Xtrack_f_DC_linear) print('Xtrack_f_DC_quadratic (Hz/s/s, early edge): %s' % Xtrack_f_DC_quadratic) print('Range_time_to_first_pixel (2way) (ms): %0.15f' % (float(Range_time_to_first_pixel))) print('Range_sampling_rate (computed, MHz): %0.6f' % (float(RSR))) print('Total_range_band_width (MHz): %s' % (float(Total_range_band_width))) print('Weighting_range: %s' % string.upper(Weighting_range)) print('') print('*******************************************************************') print('Datafile: %s' % Datafile) print('Dataformat: %s' % 'HDF5') # hardcoded!!! print('Number_of_lines_original: %s' % str(Number_of_lines_original)) print('Number_of_pixels_original: %s' % str(Number_of_pixels_original)) print('*******************************************************************') print('* End_readfiles:_NORMAL') print('*******************************************************************') print('') print('') print('*******************************************************************') print('*_Start_leader_datapoints') print('*******************************************************************') print(' t(s) X(m) Y(m) Z(m) X_V(m/s) Y_V(m/s) Z_V(m/s)') print('NUMBER_OF_DATAPOINTS: %s' % str(NUMBER_OF_DATAPOINTS)) print('') for i in range(NUMBER_OF_DATAPOINTS): print(' %s %s %s %s %s %s %s' % (int(Time_Datapoints[i]),\ X_Datapoints[i],\ Y_Datapoints[i],\ Z_Datapoints[i],\ X_Velocity[i],\ Y_Velocity[i],\ Z_Velocity[i])) print('') print('*******************************************************************') print('* End_leader_datapoints:_NORMAL') print('*******************************************************************') #EOF Doris-5.0.3Beta/bin/doris.adddummystep.sh000077500000000000000000000045531312547014700203340ustar00rootroot00000000000000#!/bin/bash ## ## ## AUTHOR: Freek van Leijen, based on original doris.rmstep.sh script by Mahmut Arikan ## EMAIL: F.J.vanLeijen@tudelft.nl ## VERSION: v1.0 ## DATE: 20141024 ## ## TUDelft, Radar Group - 2014 ## ## ## adds a dummy process in a Doris .res file ## #sed -in -e '/coarse_correl/,/End_process_control/s/1/0/gp' -e '/Start_coarse_correl/,$d' 08956_09958.res #$d indicates until last line. case $# in 2) # process_name res files lineno=$(awk '/'$1':/{print NR-1}' $2); # get me the line number of the process line - 1 [[ "$lineno" == "" ]] && echo -e "No such entry: $1 in $2 .\n" && exit 127 if [ "`uname`" == "Darwin" ]; then # MAC_OSX sed -i .bak2 -e '/^'$1'/s/0/1/g' $2 else # other platforms sed -i -e '/^'$1'/s/0/1/g' $2 fi echo " " >> $2 echo "*******************************************************************" >> $2 echo "*_Start_"$1":" >> $2 echo "*******************************************************************" >> $2 echo "Dummy" >> $2 echo "*******************************************************************" >> $2 echo "* End_"$1":_NORMAL" >> $2 echo "*******************************************************************" >> $2 ;; *) echo -e "\nUSAGE: ${0##*/} <.res> \n"; echo -e " EX: ${0##*/} coarse_correl master_slave.res \n "; echo -e " ${0##*/} resample slave.res \n "; echo -e "Doris process names by order: 1. precise_orbits 14. resample 2. crop 15. interfero 3. sim_amplitude 16. comp_refphase 4. master_timing 17. subtr_refphase 5. filt_azi 18. comp_refdem 6. filt_range 19. subtr_refdem 7 oversample 20. coherence 8. coarse_orbits 21. filtphase 9. coarse_correl 22. unwrap 10. fine_coreg 23. slant2h 11. timing_error 24. geocoding 12. dem_assist 25. dinsar 13. comp_coregpm 26. " ; echo -e "\n Thank you for using Doris!\n TU Delft - DEOS Radar Group 2011 \n"; exit 0;; esac Doris-5.0.3Beta/bin/doris.rmstep.sh000077500000000000000000000040241312547014700171370ustar00rootroot00000000000000#!/bin/bash ## ## ## AUTHOR: Mahmut Arikan ## EMAIL: M.Arikan@TUDelft.nl ## VERSION: v1.5 ## DATE: 20060612 ## UPDATE: 20090519 ## ## TUDelft, DEOS Radar Group - 2006 ## ## ## reset doris steps in the result files, ## up to the processing step you want ## #sed -in -e '/coarse_correl/,/End_process_control/s/1/0/gp' -e '/Start_coarse_correl/,$d' 08956_09958.res #$d indicates until last line. case $# in 2) # process_name res files lineno=$(awk '/_Start_'$1'/{print NR-1}' $2); # get me the line number of the process line - 1 [[ "$lineno" == "" ]] && echo -e "No such entry: $1 in $2 .\n" && exit 127 if [ "`uname`" == "Darwin" ]; then # MAC_OSX sed -i .bak2 -e '/^'$1'/,/End_process_control/s/1/0/g' -e ''${lineno}',$ d' $2 else # other platforms sed -i -e '/^'$1'/,/End_process_control/s/1/0/g' -e ''${lineno}',$ d' $2 fi #sed -i -e '/^'$1'/,/End_process_control/s/1/0/g' -e '/Start_'$1'/,$d' $2 ;; ;; *) echo -e "\nUSAGE: ${0##*/} <.res> \n"; echo -e " EX: ${0##*/} coarse_correl master_slave.res \n "; echo -e " ${0##*/} resample slave.res \n "; echo -e "Doris process names by order: 1. precise_orbits 14. resample 2. crop 15. interfero 3. sim_amplitude 16. comp_refphase 4. master_timing 17. subtr_refphase 5. filt_azi 18. comp_refdem 6. filt_range 19. subtr_refdem 7 oversample 20. coherence 8. coarse_orbits 21. filtphase 9. coarse_correl 22. unwrap 10. fine_coreg 23. slant2h 11. timing_error 24. geocoding 12. dem_assist 25. dinsar 13. comp_coregpm 26. " ; echo -e "\n Thank you for using Doris!\n TU Delft - DEOS Radar Group 2011 \n"; exit 0;; esac Doris-5.0.3Beta/bin/doris.slant2h4master.sh000077500000000000000000000040341312547014700205010ustar00rootroot00000000000000#!/bin/bash # # # Author: Mahmut Arikan # # TUDelft 2007 # # Trick Doris to use radarcoded SRTM heights to gecode. iFile=$1 radarcodedDEM=$2 # Functions goodfunc(){ grep _Start_slant2h $iFile && echo slant2h info already there, pls check && exit 0; #m_s=`awk '/INTERFEROGRAM RESULTFILE/{print substr($3,1,11)}' *_*.res` m_s=master l0=`grep First_line master.res | awk 'END{print $4}'` LN=`grep Last_line master.res | awk 'END{print $4}'` p0=`grep First_pixel master.res | awk 'END{print $4}'` PN=`grep Last_pixel master.res | awk 'END{print $4}'` #mlA=`grep Multilookfactor_azimuth_direction master.res | awk 'END{print $2}'` #mlR=`grep Multilookfactor_range_direction master.res | awk 'END{print $2}'` mlA=1 mlR=1 cat << END >> $iFile ******************************************************************* *_Start_slant2h: ******************************************************************* Method: schwabisch Data_output_file: Outdata/${m_s}_S2H.float Data_output_format: real4 First_line (w.r.t. original_master): $l0 Last_line (w.r.t. original_master): $LN First_pixel (w.r.t. original_master): $p0 Last_pixel (w.r.t. original_master): $PN Multilookfactor_azimuth_direction: $mlA Multilookfactor_range_direction: $mlR Ellipsoid (name,a,b): WGS84 6.37814e+06 6.35675e+06 ******************************************************************* * End_slant2h:_NORMAL ******************************************************************* END echo $iFile is updated tail -n 35 $iFile # cd Outdata && ln -s ../refDemLP.raw ${m_s}_S2H.float && echo "File: Outdata/${m_s}_S2H.float --> refDemLP.raw" #cd Outdata && ln -s refdem_hei.raw ${m_s}_S2H.float && echo "File: Outdata/${m_s}_S2H.float --> refDemLP.raw" cd Outdata && ln -sf ${radarcodedDEM} ${m_s}_S2H.float && echo "File: Outdata/${m_s}_S2H.float --> ${radarcodedDEM}" } case $# in 2) goodfunc ;; *) echo -e "Usage: ${0##*/} \n" ;; esac Doris-5.0.3Beta/bin/gammaReadfiles.csh000077500000000000000000000202021312547014700175460ustar00rootroot00000000000000#!/bin/csh -f ################################################################### # gammaReadfiles.csh # 1) Process the RAW data to SLC with GAMMA. Provide *.slc.par file. # 2) Convert dumped header of envisat to a doris resultfile # section "readfiles". # this includes the orbit in this section. # This script is based on the envisat_dumpheader2doris.csh by # Bert Kampes 16-JUN-2003 # Modified for gamma by Batuhan Osmanoglu. ################################################################### set PRG = `basename "$0"` set VER = "v1.1, doris software" set AUT = "Batuhan Osmanoglu 2009, Bert Kampes, (c)2003" # moved later in the file echo " " # moved later in the file echo "$PRG $VER, $AUT" # Handle wrong input if ( $#argv != 3 ) then cat << __EOFHD USAGE:$PRG processParameterFile sensorParameterFile slcFile where processParameterFile is the gamma SLC processing par file (pXXX.slc.par, or XXX.pslcpar) sensorParameterFile is the gamma sensor par file (ERS1_ESA.par, or System.par) slcfile is the complex SAR image file in 2 bytes integer format (CI2). EXAMPLE: $PRG p20070105.slc.par System.par 20070105.slc __EOFHD exit 1 endif ### Handle input set PARFILE = $1 set SYSFILE = $2 set SLCFILE = $3 set TMPFILE = gammaReadfiles.tmp ### find out if nawk is available, since awk seems not to know atan2? set AWK = awk; echo 1 | /usr/xpg4/bin/awk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = '/usr/xpg4/bin/awk' echo 1 | gawk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = 'gawk' echo 1 | nawk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = 'nawk' echo "Using as awk program: $AWK" ### set LOCALE to decimal.point style #kampes@newton[18:22]: setenv LC_NUMERIC pl #kampes@newton[18:22]: echo "5300000000.0" | awk '{print 299792458.0/$1}' #0,0565646 #kampes@newton[18:22]: setenv LC_NUMERIC C #kampes@newton[18:22]: echo "5300000000.0" | awk '{print 299792458.0/$1}' #0.0565646 #we could check first with: locale -ck decimal_point #setenv LC_ALL POSIX setenv LC_ALL C setenv LC_NUMERIC C ### Get parameters from dumped header file. set today = `date` set sceneDate = `$AWK '/^date/{printf "%d%02d%02d\n", $2,$3,$4}' $PARFILE` set sceneDate = `date -d $sceneDate +%d-%b-%Y` doris -ver >& $TMPFILE set version = `cat $TMPFILE | grep "Software version" | cut -f2 -d:` set dummy = "dummy" set product = `$AWK '/^title/{print $2}' $PARFILE` set checkNumLines = `$AWK '/^azimuth_pixels/{print $2}' $PARFILE` #Product Type (satellite info is missing in gamma files.) set productType = `$AWK '/^sensor_name/{print $2}' $SYSFILE` set sarProcessor = "GAMMA" set frequency = `$AWK '/^SAR_center_frequency/{printf "%.6f", $2}' $SYSFILE` set midLat = `$AWK '/^scene_center_latitude/{print $2}' $PARFILE` set midLon = `$AWK '/^scene_center_longitude/{print $2}' $PARFILE` set pass = `$AWK '/^map_coordinate_1:/{lat1=$2};/^map_coordinate_3:/{if ($2>lat1) print "ASCENDING"; else print "DESCENDING"}' $PARFILE` #check first and last latitude. set wavelength = `$AWK '/^SAR_center_frequency/{printf "%.6f", 2.997e+8/$2}' $SYSFILE` set firstLineTime = `$AWK '/^raw_data_start_time/{printf "%02d:%02d:%2.6f", $2, $3, $4}' $PARFILE` set firstLineTimeSec = `hhmmss2sec.py $firstLineTime` # firstLineTimeSec needs to get corrected for the offset. set azimuth_offset = `$AWK '/^azimuth_offset/{print $2}' $PARFILE` set firstLineTimeSec = `echo ${firstLineTimeSec} ${azimuth_offset} | $AWK '{printf "%.8f", $1+$2};'` set firstLineTime = `sec2hhmmss.py $firstLineTimeSec` #set prf = `$AWK '/^start_time/{flt=$2};/^end_time/{llt=$2};/^azimuth_lines/{print $2/(llt-flt)}' $PARFILE` set prf = `$AWK '/^pulse_repetition_frequency/{printf "%.6f", $2}' $PARFILE` set lastLineTimeSec = `echo $firstLineTimeSec $checkNumLines $prf | $AWK '{printf "%.8f", $1+$2/$3};'` set lastLineTime = `sec2hhmmss.py $lastLineTimeSec` set abw = `$AWK '/^pulse_repetition_frequency/{prf=$2};/^azimuth_bandwidth_fraction/{printf "%.6f", prf*$2}' $PARFILE` set FDC0 = `$AWK '/^doppler_polynomial/{printf "%.6f", $2}' $PARFILE` set FDC1 = `$AWK '/^doppler_polynomial/{printf "%.6f", $3}' $PARFILE` set FDC2 = `$AWK '/^doppler_polynomial/{printf "%.6f", $4}' $PARFILE` # Two Way TravelTime in ms (hence *1e+3) set TWT = `$AWK '/^echo_time_delay/{printf "%.6f", $2*1e+3}' $PARFILE` # correct TWT for range extension (hence *1e+3) #correct for chirp extension (near range extension time changes first pixel time.) set near_range_extension = `$AWK '/^near_range_extension/{print $2}' $PARFILE` set RSR = `$AWK '/^ADC_sampling_frequency/{printf "%.6f", $2/1e+6}' $SYSFILE` set TWT = `echo $TWT ${near_range_extension} ${RSR}| $AWK '{printf "%.8f", $1-$2/($3*1e+3)};'` set RBW = `$AWK '/^chirp_bandwidth/{printf "%.6f", $2/1e+6}' $SYSFILE` set NUMSTATEVECTORS = `$AWK '/^number_of_state_vectors/{print $2}' $PARFILE` set numlines = `$AWK '/^azimuth_pixels/{print $2}' $PARFILE` set numpixels = `$AWK '/^range_pixels/{print $2}' $PARFILE` ### modify some of the values if ( "$productType" =~ "IS*" ) then set productType = "ASAR" else if ( "$productType" =~ "ERS*" ) then set productType = "ERS" else if ( "$productType" == "PALSAR" ) then set productType = "ALOS" endif ### create a result section to a tmp file. cat << __EOFHD ******************************************************************* *_Start_readfiles: ******************************************************************* Volume file: $product Volume_ID: $dummy Volume_identifier: $dummy Volume_set_identifier: $dummy (Check)Number of records in ref. file: $checkNumLines Product type specifier: $productType SAR_PROCESSOR: $sarProcessor SWATH: $dummy PASS: $pass RADAR_FREQUENCY (HZ): $frequency Logical volume generating facility: $dummy Logical volume creation date: $dummy Location and date/time of product creation: $dummy Scene identification: ORBIT $dummy Scene location: FRAME $dummy Leader file: $product Sensor platform mission identifer: $productType Scene_centre_latitude: $midLat Scene_centre_longitude: $midLon Radar_wavelength (m): $wavelength First_pixel_azimuth_time (UTC): $sceneDate $firstLineTime TIME TO LAST LINE: compute prf: $sceneDate $lastLineTime Pulse_Repetition_Frequency (computed, Hz): $prf Total_azimuth_band_width (Hz): $abw Weighting_azimuth: $dummy Xtrack_f_DC_constant (Hz, early edge): $FDC0 Xtrack_f_DC_linear (Hz/s, early edge): $FDC1 Xtrack_f_DC_quadratic (Hz/s/s, early edge): $FDC2 Range_time_to_first_pixel (2way) (ms): $TWT Range_sampling_rate (computed, MHz): $RSR Total_range_band_width (MHz): $RBW Weighting_range: $dummy ******************************************************************* *_Start_leader_datapoints ******************************************************************* t(s) X(m) Y(m) Z(m) NUMBER_OF_DATAPOINTS: $NUMSTATEVECTORS __EOFHD # Dump the state vectors in the required format... $AWK '/^time_of_first_state_vector/{t=$2};/^state_vector_interval/{dt=$2;c=0};/^state_vector_position/{ printf "%.6f\t%.3f\t%.3f\t%.3f\n", t+(c++)*dt, $2, $3, $4 }' $PARFILE # Dump the closing section... cat << __EOFHD ******************************************************************* * End_leader_datapoints:_NORMAL ******************************************************************* Datafile: $SLCFILE Number_of_lines_original: $numlines Number_of_pixels_original: $numpixels ******************************************************************* * End_readfiles:_NORMAL ******************************************************************* __EOFHD rm -rf $TMPFILE ###EOF #sleep 1 Doris-5.0.3Beta/bin/getorb_rs2.py000077500000000000000000000162641312547014700166050ustar00rootroot00000000000000#!/usr/bin/env python #from IPython.Debugger import Tracer; debug_here = Tracer() # #-----------------------------------------------------------------# # A python code for parsing RS2 XML file into python data structures # and from there into DORIS res file structure # # Author: TUDelft - 2011 # Maintainer: Piers Van der Torren # License: GPL # #-----------------------------------------------------------------# import os, re from datetime import datetime, timedelta #import argparse import optparse codeRevision=1.0 # this is the code revision number def orbit_MDA(filename): """read MDA orbitfile and return generator with points """ with open(filename) as orbfile: line = orbfile.readline().strip() while line != '': if len(line) == 24 and not line.startswith(';'): try: pnt = [ datetime.strptime(line, '%Y-%j-%H:%M:%S.%f') ] pnt.append(orbfile.readline().strip()) pnt.append(orbfile.readline().strip()) yield pnt except ValueError: pass line = orbfile.readline().strip() def orbit_filter(orbit,fromdate,todate): """filter orbitpoints and convert to DORIS orbit format """ for pnt in orbit: if fromdate < pnt[0] < todate: yield('{0} {1} {2}'.format(pnt[0].hour*3600+pnt[0].minute*60+pnt[0].second+pnt[0].microsecond/1000000.0, pnt[1], pnt[2])) def load_resfile(filename): """Load DORIS result file as nested dictionary with sections and key-value pairs """ with open(filename) as resfile: resdata = resfile.read() # split res string in structures of the form: # .name: name of a brocessing block # .args: everything after _Start_ # .data: text between _Start_ and End_ # .status: everything after End_ regex = re.compile( r'\n[*]*[ \t]*\n[*]_Start_(?P\w+):?[ \t]*' + \ r'(?P[^\n]*)\n[*]*[ \t]*\n' + \ r'(?P.*?)\n' + \ r'[*]*[ \t]*\n[*] End_\1:(?P\w+)\n[*]*[ \t]*', re.DOTALL ) # regex without star lines #regex = re.compile( r'\n[*]_Start_(?P\w+):?[ \t]*' + \ # r'(?P[^\n]*)\n' + \ # r'(?P.*?)\n' + \ # r'[*] End_\1:(?P\w+)\n', re.DOTALL ) blocks = {} for block in regex.finditer( resdata ): blocks[block.group('name')] = block.group('data') for block2 in regex.finditer( block.group('data') ): blocks[block2.group('name')] = block.group('data') # split block.data in two fields: # #1=key, excluding the terminating colon # #2=value, leading whitespace stripped, # plus adjacent non key:value lines. regex = re.compile( r'\n(?P[^\n:]+):' + \ r'[ \t]*(?P[^\n]*[^:]*)' + \ r'(?=\n[^\n:]+:|\n[*])', re.DOTALL ) res = {} for key in blocks: res[key] = {} for token in regex.finditer( blocks[key] ): pairkey = re.sub('[^a-zA-Z0-9]+', '', token.group('key')) res[key][pairkey] = token.group('value').strip() return res def add_to_resfile(filename, section, data, args='', status='_NORMAL'): """Add new section to a DORIS result file. Write section header, data, and footer, and adjust process control flag. """ with open(filename) as resfile: resdata = resfile.read() process_control = re.search(r'\n{0}:[ \t]*[01]'.format(section), resdata).span()[1] if resdata[process_control-1] != '0': raise Exception('already has precise orbits according to process control flags') header = '*'*67 + '\n*_Start_' + section + ':' + args + '\n' + '*'*67 + '\n' footer = '*'*67 + '\n* End_' + section + ':' + status + '\n' + '*'*67 + '\n' resdata = resdata[:process_control-1] + '1' + resdata[process_control:] + \ '\n' + header + data + '\n' + footer with open(filename, 'w') as resfile: resfile.write(resdata) def clear_resfile_section(filename, section): """Clear a section in a DORIS result file. Remove the section, and set process control flag to 0 if it exists. """ with open(filename) as resfile: resdata = resfile.read() process_control = re.search(r'\n{0}:[ \t]*[01]'.format(section), resdata) if process_control: process_control = process_control.span()[1] if resdata[process_control-1] == '1': resdata = resdata[:process_control-1] + '0' + resdata[process_control:] regex = re.compile( r'\n[*]*[ \t]*\n[*]_Start_{0}:?[ \t]*'.format(section) + \ r'(?P[^\n]*)\n[*]*[ \t]*\n' + \ r'(?P.*?)\n' + \ r'[*]*[ \t]*\n[*] End_{0}:(?P\w+)\n[*]*[ \t]*\n'.format(section), re.DOTALL ) sectionspan = regex.search(resdata).span() resdata = resdata[:sectionspan[0]] + resdata[sectionspan[1]:] with open(filename, 'w') as resfile: resfile.write(resdata) def indate(str): """convert string to date, trying several formats """ for format in ['%y%m%d%H%M%S', '%Y%m%d%H%M%S']: try: return datetime.strptime(str, format) except ValueError: pass raise ValueError('Date not understood: {0}'.format(str)) #def main(): # parse commandline arguments parser = optparse.OptionParser(description='getorb-like tool extraction of radarsat orbits.') parser.add_option('--dir', help='a directory containing RS2 orbits') parser.add_option('--extratime', type=int, default=16, help='extra time before and after acquisition [s]') parser.add_option('--resfile', help='resfile to which to add precise orbits') args = parser.parse_args()[0] print('Getting precise orbits for Radarsat2\norbit dir: {dir}\nresfile: {resfile}\nextratime: {extratime}'\ .format(dir=args.dir,extratime=args.extratime,resfile=args.resfile)) # read res file for neccesary metadata res = load_resfile( args.resfile ) # get orbit number from line # Scene identification: Orbit: 08084 2009-07-02T05:52:34.496664Z orbit = int(res['readfiles']['Sceneidentification'][7:12]) # first pixel azimuth time date = datetime.strptime(res['readfiles']['FirstpixelazimuthtimeUTC'], '%d-%b-%Y %H:%M:%S.%f') orbitfile = os.path.join( args.dir, '{0:05d}_def.orb'.format(orbit) ) extratime = timedelta(seconds=args.extratime) fromdate = date - extratime todate = date + extratime + timedelta(seconds=4) # add 4 seconds as approximate acquisition time # get orbit section orbit_points = list(orbit_filter(orbit_MDA(orbitfile), fromdate, todate)) # save the orbit if more than 4 orbit points are found if len(orbit_points) > 4: add_to_resfile( args.resfile, 'precise_orbits', 't(s) X(m) Y(m) Z(m) X_V(m/s) Y_V(m/s) Z_V(m/s)\n' + \ 'NUMBER_OF_DATAPOINTS: {0}\n'.format(len(orbit_points)) + \ '\n'.join(orbit_points) ) # remove the leader orbit from the resfile clear_resfile_section( args.resfile, 'leader_datapoints') else: print('No matching orbits found, tried orbit file {0}'.format(orbitfile)) Doris-5.0.3Beta/bin/heightamb000077500000000000000000000033741312547014700160340ustar00rootroot00000000000000#!/usr/bin/csh -f #%// BK 25-May-2000 #%// $Revision: 1.1 $ $Date: 2005/07/28 09:27:00 $ ### Initialize center pixel ######################### set lambda = 0.0565646 set R = 850000.0 set theta = 23.0 ### Info ############################################ set PRG = `basename "$0"` set VER = "v1.1, BK software" set AUT = "Bert Kampes, (c)1999-2000" echo "$PRG $VER, $AUT" echo " " echo " Computes indicative height ambiguity for flat terrain" echo " as function of perpendicular baseline. A larger Bperp" echo " yields more sensitivity to height, i.e., a decreasing" echo " height ambiguity (the height difference corresponding" echo " to a 2pi phase difference (a fringe))." echo " " echo "Program parameters (ERS):" echo "-------------------------" echo " lambda: $lambda [m]" echo " R1: $R [m]" echo " theta: $theta [deg]" set theta = `echo "(a(1.0)/45.0)*$theta" | bc -l` echo " theta: $theta [rad]" echo " terrain slope: 0.0 [rad]" echo " " echo "EXAMPLES:" echo " $PRG" echo " $PRG 100" echo " $PRG 25 50 100 200 400 800" ### Check interactive or batch ###################### if ( $#argv == 0 ) then echo " " echo "Input perp. Baseline [m]: " #sin is not known in standard awk # awk '{ \ # ha=('$lambda' * '$R' * sin( '$theta' )/(-2.0 * $1 ) ) \ # print "Height ambiguity = " ha "\n"\ # }' set b = $< set ha = `echo "$lambda * $R * s ( $theta ) / ( -2.0 * $b )" | bc -l` echo " " echo "Bperp = $b [m] ---> Height ambiguity = $ha [m/2pi]" ### Handle input arguments. else foreach b ( $* ) set ha = `echo "$lambda * $R * s ( $theta ) / ( -2.0 * $b )" | bc -l` echo " " echo "Bperp = $b [m] ---> Height ambiguity = $ha [m/2pi]" end echo " " endif ### EOF Doris-5.0.3Beta/bin/helpdoris000077500000000000000000000653501312547014700160770ustar00rootroot00000000000000#!/bin/sh ##!/bin/ksh # processor.helpfile # simulate man like help for processor options # # History # 03/03/99 Initial version - [BK] Bert Kampes # 19/03/99 Added troff and printout # 03/11/00 Changed to /usr/bin/ksh for Linux default (?) # 07/02/02 Changed to /usr/sh for Cygwin # 15/10/11 less escape code fix [MA] # 15/10/11 Fixed some old comments [MA] # ## RCS at end of file ##### ####################### # expand tabs before formatting. # . .IP " " -2 # .TH "$bn " "1" "$line" # .ds )H $sswname # .ds ]W Release 0.0: March 1999 # select printer, default geodesy 4th floor if [ "X$PRINTER" != "X" ]; then THEPRINTER="$PRINTER" elif [ "X$LPDEST" != "X" ]; then THEPRINTER="$LPDEST" else THEPRINTER="d5simx4de" fi VERSION="3.6++" bn=`basename $0` # name of this file swname="Doris (Delft Object-oriented Radar Interferometric Software) - TU Delft" sswname="Doris" # short software name ################################################################################## BERTLINE() { echo " +---------------+-----------------------------------------------+---------- " } BERTLINES() { echo .RE 1 echo echo echo $line echo " keyword #arg default (man/opt)" echo $line } line=`BERTLINE` # function to print line lines=`BERTLINES` # function to print lines ################################################################################## MANPG() { cat << MANEOF .DA "$bn" \- find out options for processor software; print it out. Version: $VERSION - TUDelft Usage: .RS 3 .B $bn [ .ul word / .B -p ] .br .B processor -h .ul [word] .RS 3.2 .ul word start $bn with searching for .ul word. .br .B -p print this helpfile to printer: $THEPRINTER. .RS 3 press .B h for help on pager (search, mark, forward, backwards, etc.) $lines .ul General cards .TP 4 .B c 0 opt .B .br .B C .br .B comment .br .B COMMENT .br .B # .br .B // .br Any text after these keys is ignored. .TP 4 .B BEEP 1 WARNING \\ Controls level of beeping. Options are: .br .ul ERROR only beeps on error. .br .ul WARNING beeps on errors and warnings. .br .ul PROGRESS beeps on errors, warnings and progress. .br .ul ON Enables beeping, level is highest (PROGRESS). .br .ul OFF disables beeping. .TP 4 .B PREVIEW 1 OFF \\ Controls generation of SUNraster preview files (uses cpxfiddle system call). .br .ul ON Enables preview generation. SUNraster files are created after most steps where it is appropriate. This is done by writing a small shell script in the current directory, which then is executed. This script can later be executed by the user again. .br .ul XV Same as ON, but additionally calls the program xv to view the results. .br .ul OFF disables preview generation. .TP 4 .B SCREEN 1 debug \\ Controls level of output to standard out. .br .ul ERROR only error are written to stout. .br .ul WARNING errors and warnings. .br .ul PROGRESS errors, warnings and progress. .br .ul INFO errors, warnings, progress and info. .br .ul DEBUG errors, warnings, progress, info, debug. .br .ul TRACE errors, warnings, progress, info, debug, trace. tracing shows all visited functions. If you compile a debug version of doris, a lot more is traced, also in the matrix class. .TP 4 .B BATCH 0 or 1 off \\ Specifies non-interactive processing. .br If .ul ONLYPROCESS mode then always in batch. .br If (only 1) .ul PROCESS card then this card is signifiant. .br .ul ON do non-interactive processing, except when problems are signalled. .br .ul OFF do interactive processing. .TP 4 .B LISTINPUT 0 or 1 on \\ copying inputoptionsfile to logfile. .br .ul ON do copy the input file to the logfile. .br .ul OFF do not copy the input file to the logfile. .TP 4 .B OVERWRITE 0 or 1 off \\ Overwrite existing data output files if they exist. .br .ul ON overwrite. .br .ul OFF do not overwrite. .TP 4 .B ELLIPSOID 1 or 2 wgs84 Change ellipsoid. NOT OK in version $VERSION .br .ul WGS84 use wgs84. .br .ul GRS80 use grs80. .br .ul BESSEL use bessel. .br .ul a b use specified semi major/minor. .TP 4 .B MEMORY 1 250 \\ Specify available memory (integer MB). .TP 4 .B ORB_INTERP 2 POLYFIT deg \\ Interpolation method for orbits. Default polynomial fit of maximum degree (interpolation). If there are more than 6 datapoints the degree is 5 by default. Optionally with the second argument the degree can be given. Alternatively SPLINE can be used (natural cubic splines). .TP 4 .B DUMPBASELINE 2 0 0 \\ Dump the baseline parameters as INFO variables to stdout evaluated on a grid of x lines and y pixels (dimensions of current master). Also write a 2d model of degree 1 to stdout for perpendicular baseline. This is only done if the precise orbits are available. .TP 4 .B LOGFILE 1 log.out \\ Name of log output file. .TP 4 .B M_RESFILE 1 master_result.out \\ Name of result master output file. .TP 4 .B S_RESFILE 1 slave_result.out \\ Name of result slave output file. .TP 4 .B I_RESFILE 1 interferogram.out \\ Name of result interferogram output file. .TP 4 .B ONLYPROCESS 1 opt/man \\ Only process a specified step. .br A ONLYPROCESS or PROCESS card is mandatory. .ul M_READFILES Read parameters from volume, leader, data file (null file) for Master. .br .ul S_READFILES Read parameters from volume, leader and data file (null) for Slave .br .ul M_CROP Read in slc data file, write data to pixel interleaved internal format (raster). .br .ul S_CROP Read in slc data file, write data to pixel interleaved internal format (raster). .br .ul M_PORBITS Compute precise orbits with getorb for Master. .br .ul S_PORBITS Compute precise orbits with getorb for Slave. .br .ul M_FILTAZI Filter master image in azimuth direction. .br .ul S_FILTAZI Filter slave image in azimuth direction. .br .ul COARSEORB Coarse coregistration based on precise orbits. .br .ul COARSECORR Coarse coregistration based on correlation. .br .ul FINE Fine coregistration. .br .ul COREGPM Compute coregistration parameters. .br .ul RESAMPLE Interpolate slave image to master grid. .br .ul FILTRANGE Adaptive range filter master/slave (after resampling). .br .ul INTERFERO Compute complex interferogram; Subtract reference phase here or later. Optionally use oversampling. .br .ul COMPREFPHA Compute reference interferogram of mathematic body (ellipsoid), model this with a 2d polynoial. .br .ul COHERENCE Compute complex coherence image. Subtract reference phase here or later. Possible use complex interferogram. .br .ul SUBTRREFPHA Subtract reference phase computed in step COMPREFPHA from complex intereferogram. .br .ul COMPREFDEM Compute reference interferogram of DEM. for now gtopo30 only. .br .ul SUBTRREFDEM Subtract reference interferogram of DEM (step COMPREFDEM) from complex interferogram. .br .ul FILTPHASE Filter interferogram. .br .ul UNWRAP Unwrap interferogram . For now use external routines, e.g., Ghiglia/Pritt , Snaphu .br .ul DINSAR Differential interferometry (3 or 4 pass). .br .ul SLANT2H Convert to height system. .br .ul GEOCODE Put in xyz system. .TP 4 .B PROCESS 1 opt/man \\ Process the specified step, see ONLYPROCESS. .br (more than one PROCESS card may be specified). .br. (cards are overwritten by ONLYPROCESS). .TP 4 .B STOP 0 man \\ End interpretation inputoptionsfile. $lines .ul step reading files Mandatory for *_READFILES .TP 4 .B M_IN_METHOD 1 ERS \\ identifyer what is to be read ASAR, Radarsat 1/2, ERS1/2, Envisat ASAR, JERS, ALOS, Terrasar-X and Cosmoskymed. JERS and ALOS uses ERS programs. .TP 4 .B M_IN_VOL 1 man \\ Filename of volumefile master (not used for ASAR). .TP 4 .B M_IN_LEA 1 man \\ Filename of leaderfile master (not used for ASAR). .TP 4 .B M_IN_NULL 1 man \\ Filename of nullfile master (not used for ASAR). .br (may be dummy name, not actually used). .TP 4 .B M_IN_DAT 1 man \\ Filename of datafile master. .TP 4 .B S_IN_VOL 1 \\ see .ul M_IN_VOL .TP 4 .B S_IN_LEA 1 \\ see .ul M_IN_LEA .TP 4 .B S_IN_NULL 1 \\ see .ul M_IN_NULL .TP 4 .B S_IN_DAT 1 \\ see .ul M_IN_DAT $lines .ul 1 step conversion SLC format to internal format on disk Mandatory for *_CROP .TP 4 .B M_CROP_ID 1 step01 \\ Identification of this step. This card does nothing. .TP 4 .B M_CROP_IN 1 man \\ Filename of input data in slc format. .TP 4 .B M_CROP_OUT 1 man \\ Filename of output in raw format. .TP 4 .B M_DBOW 4 total image (Master database output window) .br min line, max line, min pix, max pix. .br line=1: first line. .TP 4 .B S_CROP_ID 1 see .ul 1 M_CROP_ID .TP 4 .B S_CROP_IN 1 see .ul 1 M_CROP_IN .TP 4 .B S_CROP_OUT 1 see .ul 1 M_CROP_OUT .TP 4 .B S_DBOW 4 see .ul 1 M_DBOW $lines .ul step Precise Orbits (Uses getorb DEOS). Mandatory for proces *_PORBITS .TP 4 .B M_ORBDIR 1 man \\ Name of directory for ODR precise orbit files (getorb). .TP 4 .B M_ORB_INTERVAL 1 1 Time interval between ephemerides in seconds. .TP 4 .B M_ORB_EXTRATIME 1 3 Time in seconds before first and after last line to get ephemerides. Natural splines are used to interpolate the orbits, therefor some points before and after are required for good interpolation. .TP 4 .B M_ORB_DUMP 1 0.1 Dump interpolated ephemerides to file "masterorbit.dat" with specified delta t in seconds. .TP 4 .B S_ORBDIR 1 man \\ see .ul 1 M_ORBDIR $lines .ul step azimuth filtering mandatory for proces: M_FILTAZI and S_FILTAZI .TP 4 .B AF_BLOCKSIZE 1 1024 fftlength per buffer. (power of 2, the larger the better). .TP 4 .B AF_HAMMING 1 0.75 De-weight and re-weight spectrum at new Doppler centroid freq. .TP 4 .B AF_OVERLAP 1 BLOCK/8 Overlap in azimuth direction between buffers. .TP 4 .B AF_OUT_MASTER 1 "master.afiltered" Output data file name (mph complex r4) for master. .TP 4 .B AF_OUT_SLAVE 1 "slave.afiltered" Output data file name (mph complex r4) for slave. .TP 4 .B AF_OUT_FORMAT 1 cr4 Output format either cr4 or ci2. ci2 introduces an error (?) but reduces size of file by factor 2. $lines .ul 1 coarse coregistration based on precise orbits. Mandatory for proces COARSEORB .TP 4 .B No Options for this step $lines .ul 1 coarse correlation (coregistration) Mandatory for proces COARSECORR .TP 4 .B CC_METHOD 1 MAGFFT \\ .ul 1 MAGFFT correlation in spectral domain based on fft's. .br .ul 1 MAGSPACE correlation in space domain. .TP 4 .B CC_NWIN 1 10 Number of windows for correlation .TP 4 .B CC_IN_POS 1 opt Filename with positions of windows for computation (line,pixel) at each line. If this card is specified, CC_NWIN is ignored. .TP 4 .B CC_WINSIZE 2 64 64 Number of lines pixels of correlation windows .br NOT TRUE: for MAGFFT: defaults to 1024, 1024 .TP 4 .B CC_ACC 2 40 10 Search accuracy lines pixels. .br for MAGFFT: automatically .5*WINSIZE -L/2,L/2 .TP 4 .B CC_INITOFF 2 0 0 Initial offset lines pixels. .br .ul 1 ORBIT or orbit requests to read initial offset from file (placed there by coarseorb). $lines .ul step fine coregistration Mandatory for proces FINE .TP 4 .B FC_METHOD 1 MAGFFT .ul 1 MAGFFT coherence in spectral domain with fft's of magnitude images. .ul 1 MAGSPACE coherence in space domain. .TP 4 .B FC_NWIN 1 101 Number of windows for correlation. .TP 4 .B FC_IN_POS 1 opt Filename with positions of windows for computation (line,pixel) at each line. If this card is specified, FC_NWIN is ignored. .TP 4 .B FC_WINSIZE 2 32 32 Number of lines pixels of correlation windows. .TP 4 .B FC_ACC 2 4 4 Search accuracy lines pixels. .br for ???FFT: automatically -L/2,L/2 .TP 4 .B FC_INITOFF 2 0 0 Initial offset lines pixels. .br .ul 1 COARSECORR requests to read initial offset from file (placed there by coarsecorr). .TP 4 .B FC_OSFACTOR 2 16 Oversampling factor for interpolation of correlation. $lines .ul step computation of coregistration parameters. mandatory for proces: COREGPM .TP 4 .B CPM_THRESHOLD 1 0.3 Threshold correlation for selection windows. .TP 4 .B CPM_DEGREE 1 1 Degree of model. .TP 4 .B CPM_WEIGHT 1 none Select a priori covariance matrix. .br .ul 1 NONE no weighting is applied. .br .ul 1 LINEAR correlation is used for weighting. .TP 4 .B CPM_MAXITER 1 10 Maximum number of windows to remove automatically with outlier tests. .TP 4 .B CPM_NOPLOT 0 false If present no plots are made. $lines .ul step computation of reference interferogram (flat earth correction) mandatory for proces: COMPREFPHA (f.k.a. FLATEARTH) .TP 4 .B FE_METHOD 1 porbits Method selector for computations. .br .ul 1 PORBITS use precise orbits .br .ul 1 METHOD2 use ??? .TP 4 .B FE_DEGREE 1 5 Degree of 2D-polynomial. .TP 4 .B FE_NPOINTS 1 501 Number of points for estimation of polynomial $lines .ul 1 step: resampling of slave to master grid mandatory for proces: RESAMPLE .TP 4 .B RS_METHOD 1 cc4p Method selector for computations. .br .ul 1 RECT .br .ul 1 TRI .br .ul 1 CC4P .br .ul 1 CC6P .br .ul 1 TS6P .br .ul 1 TS8P .br .ul 1 TS16P .TP 4 .B RS_OUT_FILE 1 s_resampled.raw Name of output file resampled slave. .TP 4 .B RS_OUT_FORMAT 1 cr4 Output format either cr4 or ci2. ci2 introduces an error but reduces size of file by factor 2. .TP 4 .B RS_DBOW 4 entire overlap Database output window. .br arguments: min.line max.line min.pixel max.pixel in original master system. If specified window is outside overlap master, zeros are written in the slave. .TP 4 .B RS_SHIFTAZI 1 ON Switch to shift the azimuth spectrum of the data to zero freq. before resampling, and back to its Doppler Centroid frequency after resampling. $lines .ul step range filtering of (complex) master and slave (resampled) mandatory for proces: FILTRANGE .TP 4 .B RF_METHOD 1 adaptive Method selector for rangefiltering. either adaptive or porbits. .br .TP 4 .B RF_SLOPE 1 0.0 Mean terrain slope for method porbits. .br .TP 4 .B RF_FFTLENGTH 1 64 Length of adaptive block with constant slope. Resolution in range is for ERS approximately 20 meters. Default for method orbit is 1024. .br .TP 4 .B RF_NLMEAN 1 (odd) 15 Number of lines for taking mean powerspectrum of complex interferogram to reduce noise for better peak estimation. Only for method adaptive. .br .TP 4 .B RF_HAMMING 1 0.75 Alpha of hamming function for weighting. An alpha of 1.0 yields a rectangular filter, an alpha of 0. gives more power to the low frequencies. .br .TP 4 .B RF_THRESHOLD 1 5.0 Threshold for range filtering on SNR of peak estimation. SNR is defined as fftlength*power of peak divided by the power of the other frequencies. Only for method adaptive. .br .TP 4 .B RF_OVERSAMPLE 0 or 1 ON Perform oversampling of master and slave before computing interferogram. Only for method adaptive. .br .ul ON do oversampling. .br .ul OFF do not do oversampling. .TP 4 .B RF_WEIGHTCORR 0 or 1 OFF Optionally weight the powerspectrum of complex interferogram to account for decreasing number of overlapping frequencies for higher frequencies. The (Hamming) shape of the spectrum is not acounted for. The effect of this card may be neglible. Only for method adaptive. .br .ul ON do weight. .br .ul OFF do not weight. .TP 4 .B RF_OUT_MASTER 80char master.rfilter Data output file name for filtered slave. .br .TP 4 .B RF_OUT_SLAVE 80char slave.rfilter Data output file name for filtered slave. .br .TP 4 .B RF_OUT_FORMAT 80char cr4 | ci2 Data output format either complex real4 values or casted to short integers. (for both output files) .br $lines .ul step computation of (complex) interferogram mandatory for proces: INTERFERO .TP 4 .B INT_METHOD 1 man Method selector: old or oversample. The latter is not implemented yet. .br .TP 4 .B INT_OUT_CINT 1 opt Filename of complex data output file complex interferogram. .br (This file can be viewed with dismph). .TP 4 .B INT_OUT_FE 1 opt Filename of real data output file interferogram (phase) of correction/ reference phase (flatearth correction). This is the unwrapped fase, evaluated at the points of the multilooked grid. .br If this card is present it flags to save this file. .TP 4 .B INT_OUT_INT 1 opt Filename of real data output file containing the (wrapped) phase of complex interferogram. .br If this card is present it flags to save this file. .TP 4 .B INT_MULTILOOK 2 5 1 Multilooking factors in azimuth (line) and range (pixel) direction. $lines .ul step subtraction of reference interferogram (flat earth correction) mandatory for proces: SUBTRREFPHA .TP 4 .B SRP_METHOD 1 polynomial Method selector for subtraction. Either compute ref. phase here or evaluate polynomail from step COMPREFPHA. .TP 4 .B SRP_OUT_CINT 1 cint.minrefpha.raw Output file name for complex interferogram. .TP 4 .B SRP_MULTILOOK 1 or 2 1 1 Multilook factors in azimuth and range direction. Default is equal factors. .TP 4 .B SRP_OUT_CINT 1 cint.minrefpha.raw Output file name for complex interferogram. $lines .ul step phase filtering of complex interferogram mandatory for proces: FILTPHASE .TP 4 .B PF_METHOD 1 goldstein Method selector for phase filtering (goldstein or spatialconv or spectral), .TP 4 .B PF_BLOCKSIZE 1 32 Size per block. For goldstein method. .TP 4 .B PF_ALPHA 1 0.2 Weighting factor for spectrum [0,1] <-> [no,max]. Sf = S*(A/max(A)).^PF_ALPHA Where Sf is the complex filtered spectrum, S is the complex spectrum of the interferogram, and A is the real smoothed amplitude of S. The result is the ifft2d of Sf. For goldstein method. .TP 4 .B PF_OVERLAP 1 3 Use 2*PF_OVERLAP the same data for consecutive blocks/buffers. For goldstein method. .TP 4 .B PF_KERNEL var. 3 1 1 1 KERNEL function for goldstein and spatialconv method. First specify the number of arguments, then the values. Kernel is always normalized by Doris. Default kernel for goldstein is [1 2 3 2 1], and default for spatialconv is [1 1 1]. For goldstein's method this kernel is used to smooth the amplitude of the spectrum, by which the original spectrum is weighted (by smoothamplspectrum.^alpha, see PF_ALPHA). To avoid weighting, use kernel [1]. .TP 4 .B PF_IN_KERNEL2D 1 filename File name for ascii file with 2D KERNEL function. For spatialconv and spectral method. A header line should precede the kernel, containing: height width scale, e.g., 3 3 0.1111111 1 1 1 1 1 1 1 1 1 .TP 4 .B PF_OUT_FILE 1 cint.gf.alpha output file name. For method spatialconv, default is cint.filtered. .TP 4 .B PF_IN_FILE 2 filename numlines Perform filtering on this file (complex float, mph) that has N lines. $lines .ul step computation of reference DEM (phase) mandatory for proces: COMPREFDEM Most information can be found in de .HDR file of the gtopo30 DEM. .TP 4 .B CRD_METHOD 1 gtopo30 Method selector. not used in version $VERSION. .TP 4 .B CRD_IN_DEM 1 man File name of input DEM (gtopo30 only). .TP 4 .B CRD_IN_FORMAT 1 i16 Format specifier for DEM used. Either i16, r4, or r8 for shorts, floats or doubles. .TP 4 .B CRD_IN_SIZE 2 6000 4800 Number of rows/cols of input DEM. .TP 4 .B CRD_IN_DELTA 1 or 2 0.00833333333333333333 Grid spacing of input DEM in decimal degrees. .TP 4 .B CRD_IN_UL 2 89.995833333333333 -19.995833333333333333333 WGS84 coordinates of leftupper corner. In decimal degrees, latitude longitude. .TP 4 .B CRD_IN_NODATA 1 -9999 Identifier which number to regard as Not a Number in input DEM. .TP 4 .B CRD_INCLUDE_FE 1 OFF Card to switch on to include 'flat earth' in this step. .TP 4 .B CRD_DENSE 1 4 Factor for extra dense oversampling of DEM. .TP 4 .B CRD_OUT_DEM 1 opt If specified, a short file is dumped containing cut out of input DEM. .TP 4 .B CRD_OUT_DEMI 1 opt If specified, a float file is dumped containing bicubic interpolated dem. .TP 4 .B CRD_OUT_FILE 1 refdem.raw Filename of output file containing reference DEM. $lines .ul step subtraction of reference DEM (phase) mandatory for proces: SUBTRREFDEM .TP 4 .B SRD_OUT_CINT 1 cint.minrefdem.raw Output file name for complex interferogram. $lines .ul step computation of (complex) coherence image mandatory for proces: COHERENCE .TP 4 .B COH_METHOD 1 man Method selector: old or new. The latter is not implemented yet. .br .TP 4 .B COH_OUT_CCOH 1 opt Filename of complex data output file coherence. .br If this card is present it flags to save this file. .TP 4 .B COH_OUT_COH 1 opt Filename of real data output file coherence image. .br If this card is present it flags to save this file. .TP 4 .B COH_MULTILOOK 2 10 2 Multilooking factors in azimuth (line) and range (pixel) direction. .TP 4 .B COH_WINSIZE 2 coh_multilook Windowsize for coherence computation. $lines .ul step unwrap mandatory for proces: UNWRAP .TP 4 .B UW_METHOD 1 ?? Method selector: not implemented in doris v1.2 .TP 4 .B UW_??? ??? $lines .ul 1 step differential interferometry Mandatory for DINSAR .TP 4 .B DI_OUT_FILE 1 differentialinterf.raw File name of output with differential phase (complex) .TP 4 .B DI_IN_TOPOSLAVE 1 man .TP 4 .B DI_IN_TOPOINT 1 man .TP 4 .B DI_IN_TOPOMASTER 1 same as defo .TP 4 .B DI_OUT_SCALED 1 opt $lines .ul step slant to height conversion mandatory for proces: SLANT2H .TP 4 .B S2H_METHOD 1 ambiguity Method selector: ambiguity, schwabisch or rodriguez .TP 4 .B S2H_NPOINTS 1 200 schwabisch method: Number of points to be used for estimation of 2d polynomial. .TP 4 .B S2H_DEGREE1D 1 2 schwabisch method: Degree of 1d polynomial. .br .TP 4 .B S2H_NHEIGHTS 1 s2h_degree1d+1 schwabisch method: number of heights to evaluate reference phase on. .br Overdetermined problem if Nheights > degree1d+1. .TP 4 .B S2H_DEGREE2D 1 5 schwabisch method: Degree of 2d polynomial for the coefficients of 1d polynomial. .br .TP 4 .B S2H_OUT_HEI 1 hei.raw File name of data output file with heights. .TP 4 .B S2H_OUT_PHI 1 phi.raw ambiguity method: File name of data output file with heights. .TP 4 .B S2H_OUT_LAM 1 lam.raw ambiguity method: File name of data output file with heights. $lines .ul step geocoding (interpolation to regular grid?) mandatory for proces: GEOCODE .TP 4 .B GEO_OUT_LAM 1 lambda.raw Filename of outputfile longitude. .br .TP 4 .B GEO_OUT_PHI 1 phi.raw Filename of outputfile latitude. .br .SS Files ? .SS See also rm_err_??.c .br plotscript .br expand() .br run .br checklist.tex .br less .br ? MANEOF } ################################################################################## # -b only for debugging, ... comment out #if [ "$1" = "-b" ]; then # #echo "man2ps should be invoked or something." # #printout to ps and exit # MANPG | nroff -man | more # exit 1 #fi # # Print out this helpfile with keywords if [ "$1" = "-p" ]; then MANPG | nroff -man -Tlj | lp -d$THEPRINTER -onb -od -oA4 exit 1 fi # Find out pager if [ "X$PAGER" = "X" ]; then echo "Please set environment variable PAGER. For example in csh:" echo " setenv PAGER more" PAGER="more" if [ ! "X$1" = "X" ]; then PAGER="$PAGER +/$1" fi fi if [ "$PAGER" = "less" ]; then if [ "$1" = "" ]; then PAGER="less -d -e -i -r -# .8 " else PAGER="less -d -e -i -r -p$1" fi fi #if [ ! -x `whence $PAGER` ]; then # echo "$PAGER not found or environment variable PAGER not set" # exit 1 #fi # Print to screen MANPG | nroff -man | $PAGER exit 0 # END ## RCS info ##### # $Source: /users/kampes/DEVELOP/DORIS/bin/RCS/helpdoris,v $ # $Revision: 3.10 $ # $Author: kampes $ # $Date: 2003/08/28 14:17:09 $ # $Log: helpdoris,v $ # Revision 3.10 2003/08/28 14:17:09 kampes # *** empty log message *** # # Revision 3.9 2003/08/14 08:45:58 kampes # added jers info # # Revision 3.8 2003/06/24 08:32:38 kampes # release version # # Revision 3.7 2003/06/16 07:04:51 kampes # v3.6 # # Revision 3.6 2003/04/14 07:10:29 kampes # added screen trace, m_in_method ers # # Revision 3.5 2003/04/14 06:35:15 kampes # doris release 3.5 # # Revision 1.1 2003/04/14 06:04:40 kampes # Initial revision # # Revision 1.25 2000/12/07 13:53:36 13:53:36 kampes (B.M.Kampes) # release 3 # # Revision 1.24 2000/10/24 13:46:10 13:46:10 kampes (B.M.Kampes) # doris2.6 # # Revision 1.17 2000/04/05 11:37:07 11:37:07 kampes (B.M.Kampes) # range filtering # # Revision 1.16 2000/02/16 17:44:33 17:44:33 kampes (B.M.Kampes) # new cards, refdem, check release 2.2 # # Revision 1.15 2000/02/09 11:22:29 11:22:29 kampes (B.M.Kampes) # new cards # # Revision 1.12 99/12/13 16:49:25 16:49:25 kampes (B.M.Kampes) # small # # Revision 1.10 99/12/02 11:34:43 11:34:43 kampes (B.M.Kampes) # place to space. # # Revision 1.8 99/11/02 11:41:11 11:41:11 kampes (B.M.Kampes) # doris v1.2 s2h geocoding # # Revision 1.6 99/10/06 16:14:47 16:14:47 kampes (B.M.Kampes) # proces to process # # Revision 1.5 99/09/21 09:11:31 09:11:31 kampes (B.M.Kampes) # removed cmplx to mag for fine # # Revision 1.4 99/09/15 14:56:46 14:56:46 kampes (B.M.Kampes) # deleted section geocoding etc. # # Revision 1.3 99/09/15 14:46:46 14:46:46 kampes (B.M.Kampes) # updated print option # # Revision 1.2 99/09/13 16:00:32 16:00:32 kampes (B.M.Kampes) # initial check in # Doris-5.0.3Beta/bin/hhmmss2sec.py000077500000000000000000000011271312547014700166010ustar00rootroot00000000000000#!/usr/bin/env python import os,sys,time def usage(): print '\nUsage: python hhmmss2sec.py time' print ' where time in the form HH:MM:SS.sss .' print ' ' print ' Example ' print ' ./hhmmss2sec.py 16:36:40.393 ' print ' 59800.393000 ' print ' ' print ' See Also' print ' sec2hhmmss.py' try: timeOfDay = sys.argv[1] except: print 'Unrecognized input' usage() sys.exit(1) timeOfDay= sys.argv[1].split(':') hh = float(timeOfDay[0]); mm = float(timeOfDay[1]); ss = float(timeOfDay[2]); secOfDay=hh*3600+mm*60+ss print "%f" %(secOfDay) Doris-5.0.3Beta/bin/lonlatCoh2ascii000077500000000000000000000064361312547014700171240ustar00rootroot00000000000000#!/bin/csh -f ### lonlatCoh2ascii -- Generate 3 column ASCII file x y z ### Example script to generate grd file from lambda phi Coh ### ### output of Doris InSAR software. ### $Id: lonlatCoh2ascii,v 1.4 2006/06/22 NdO Exp $ ### $Maintainer: Anneleen Oyen ################################################################ set PRG = `basename "$0"` set VER = "v1.0 Doris software" set AUT = "TUDelft, (c)1999-2011" echo "$PRG $VER, $AUT" echo " " ### Handle wrong input set WRONG = "0" ### Input files. set LON = "$1" set LAT = "$2" set COH = "$3" set XYCOHFILE = "$4" if ( ! -f "$LAT" ) set WRONG = "1" if ( ! -f "$LON" ) set WRONG = "1" if ( ! -f "$COH" ) set WRONG = "1" if ( $#argv < 4 ) set WRONG = "1" if ( $WRONG == "1" ) then cat << __EOFHD SYNOPSIS: $PRG longitude_file latitude_file Coh_file output_Coh_file This csh-script creates a 3 column ASCII file with "lon lat coh" from the binary doris output (matrices) after step geocode. It filters out invalid data, indicated with "-999" by Doris. The output file can be used further with GMT to create a grd file. The format of the 3 input files are matrices in real4 float format. all of the same size. They describe the irregular geocoded position of the pixels in the interferogram, and the corresponding heights. The steps taken are within this script: 1) Create 3 temporary ASCII files with all data in a single large column using cpxfiddle program; 2) Create two 3 column ASCII file (lon lat ***) using "paste"; 3) remove -999 invalid data using "grep" 4) Tidy up, remove temp files. These steps may take a while. Obviously staying in binary format would be better. This script is intented to work on all platforms, and to be straightforward and understandable, rather than ingenious. DEPENDENCIES: cpxfiddle program, part of Doris distribution. grep utility, standard UNIX paste utility, standard UNIX Note that lambda=longitude; phi=latitude EXAMPLE: $PRG Outdata/lambda.raw Outdata/phi.raw Outdata/Coherence.raw lonlatcoh.dat SEE ALSO: cpxfiddle, paste, grep, http://gmt.soest.hawaii.edu/ __EOFHD exit 1 endif ### Probably smarter is gmtconvert, but OK. ################################### ### Convert binary files to ASCII row; trick cpxfiddle with -w1. echo " Convert LONGITUDES in binary real4 file" \"${LON}\" "to ASCII table" #cpxfiddle -w1 -qnormal -fcr4 $LON | awk '{printf "%3.4f\n%3.4f\n",$1,$2}' > qlon # using new r4 option to cpxfiddle # cpxfiddle -w1 -qnormal -fr4 $LON > qlon1 echo " Convert LATITUDES in binary real4 file" \"${LAT}\" "to ASCII table" # cpxfiddle -w1 -qnormal -fr4 $LAT > qlat1 echo " Convert COHERENCE in binary real4 file" \"${COH}\" "to ASCII table" cpxfiddle -w1 -qnormal -fr4 $COH > qcoh ### Create xyz file, delete temp files. ######################################## echo "Paste LON/LAT/COH to xyzfile" \"${XYCOHFILE}\" paste qlon1 qlat1 qcoh > $XYCOHFILE.tmp echo "removing -999 from input (if there was an unwrapping problem, or other problem)" grep -v '\-999' $XYCOHFILE.tmp > $XYCOHFILE # rm -f qlon1 qlat1 qcoh $XYCOHFILE.tmp rm -f $XYCOHFILE.tmp ### EOF. echo "finished..." Doris-5.0.3Beta/bin/lonlathei2ascii000077500000000000000000000063371312547014700171600ustar00rootroot00000000000000#!/bin/csh -f ### lonlathei2ascii -- Generate 3 column ASCII file x y z ### Example script to generate grd file from lambda phi height ### output of Doris InSAR software. ### $Id: lonlathei2ascii,v 1.4 2004/09/14 14:06:57 kampes Exp $ ################################################################ set PRG = `basename "$0"` set VER = "v1.0 Doris software" set AUT = "bert kampes, (c)1999-2003" echo "$PRG $VER, $AUT" echo " " ### Handle wrong input set WRONG = "0" ### Input files. set LON = "$1" set LAT = "$2" set HEI = "$3" set XYZFILE = "$4" if ( ! -f "$LAT" ) set WRONG = "1" if ( ! -f "$LON" ) set WRONG = "1" if ( ! -f "$HEI" ) set WRONG = "1" if ( $#argv < 4 ) set WRONG = "1" if ( $WRONG == "1" ) then cat << __EOFHD SYNOPSIS: $PRG longitude_file latitude_file height_file output_file This csh-script creates an 3 column ASCII file with "lon lat hei" from the binary doris output (matrices) after step geocode. It filters out invalid data, indicated with "-999" by Doris. The output file can be used further with GMT to create a grd file. The format of the 3 input files are matrices in real4 float format. all of the same size. They describe the irregular geocoded position of the pixels in the interferogram, and the corresponding heights. The steps taken are within this script: 1) Create 3 temporary ASCII files with all data in a single large column using cpxfiddle program; 2) Create a single 3 column ASCII file (lon lat hei) using "paste"; 3) remove -999 invalid data using "grep" 4) Tidy up, remove temp files. These steps may take a while. Obviously staying in binary format would be better. This script is intented to work on all platforms, and to be straightforward and understandable, rather than ingenious. DEPENDENCIES: cpxfiddle program, part of Doris distribution. grep utility, standard UNIX paste utility, standard UNIX Note that lambda=longitude; phi=latitude EXAMPLE: $PRG Outdata/lambda.raw Outdata/phi.raw Outdata/heights.raw lonlathei.dat SEE ALSO: cpxfiddle, paste, grep, http://gmt.soest.hawaii.edu/ __EOFHD exit 1 endif ### Probably smarter is gmtconvert, but OK. ################################### ### Convert binary files to ASCII row; trick cpxfiddle with -w1. echo " Convert LONGITUDES in binary real4 file" \"${LON}\" "to ASCII table" #cpxfiddle -w1 -qnormal -fcr4 $LON | awk '{printf "%3.4f\n%3.4f\n",$1,$2}' > qlon # using new r4 option to cpxfiddle cpxfiddle -w1 -qnormal -fr4 $LON > qlon echo " Convert LATITUDES in binary real4 file" \"${LAT}\" "to ASCII table" cpxfiddle -w1 -qnormal -fr4 $LAT > qlat echo " Convert HEIGHTS in binary real4 file" \"${HEI}\" "to ASCII table" cpxfiddle -w1 -qnormal -fr4 $HEI > qhei ### Create xyz file, delete temp files. ######################################## echo "Paste LON/LAT/HEI to xyzfile" \"${XYZFILE}\" paste qlon qlat qhei > $XYZFILE.tmp echo "removing -999 from input (if there was an unwrapping problem, or other problem)" grep -v '\-999' $XYZFILE.tmp > $XYZFILE rm -f qlon qlat qhei $XYZFILE.tmp ### EOF. echo "finished..." Doris-5.0.3Beta/bin/phasefilt.doris000077500000000000000000000125541312547014700172020ustar00rootroot00000000000000#!/bin/csh -f # phasefilt.fast for Doris software. # command line call to filter complex interferogram by several methods. #%// BK 27-Oct-2000 #%// $Revision: 3.5 $ $Date: 2003/04/14 06:35:15 $ ###################################################################### set PRG = `basename "$0"` set VER = "v1.1, FMR software" set AUT = "Bert Kampes, (c)2000" echo "$PRG $VER, $AUT"\\n ### TODO: -d debug version of doris ### -m methods: goldstein, running, cosinerolloff, hamming ### Initialize set HELP = "1" set TMPDIR = "/tmp" set METHOD = "goldstein" set NUMLINES = "0" set OFILE = "0" set BLOCKSIZE = "32" # default set ALPHA = "0.25" # default set OVERLAP = "3" # default (6 data the same) set KERNEL2D = "comment" # filename set KERNEL1D = "comment" # filename ### Handle input set OPTIONS = "l:o:a:b:e:m:k:K:" #set argv = `getopts $OPTIONS $*` set argv = `getopt $OPTIONS $*` # Check any input, getopts ok? if ( "$?argv" == "0" ) then echo "Sorry, no input or parse error." exit 1 endif ### Process commandline arguments while ( "$1" != "--" ) switch ( $1 ) # linelength,width case '-l': set HELP = "0" set NUMLINES = "$2" shift breaksw # method case '-m': set METHOD = "$2" set METHOD = `echo $METHOD | tr "[:upper:]" "[:lower:]"` if ( "$METHOD" != "goldstein" && "$METHOD" != "spatialconv" && "$METHOD" != "spectral") then echo METHOD: $METHOD not recognized, using \"goldstein\"\\n\ available methods are: goldstein, spatialconv, spectral set METHOD = "goldstein" endif shift breaksw # output file case '-o': set OFILE = "$2" shift breaksw # alpha filter parameter case '-a': set ALPHA = "$2" shift breaksw # blocksize case '-b': set BLOCKSIZE = "$2" shift breaksw # overlap between blocks case '-e': set OVERLAP = "$2" shift breaksw # # smoothing window # case '-s': # set SMOOTH = "$2" # shift # breaksw # 1d kernel file, -k 5/1/2/3/4/5 # how to deal with input with spaces? for now use underscore. case '-k': set KERNEL1D = `echo $2 | sed s'/_/ /g'` set KERNEL1D = "PF_KERNEL $KERNEL1D" #echo BBBBBBBBBBB #echo "0 1 2: $0 $1 $2" #echo "star $*" # set ARGS = `echo $* | cut -f1 -d'-'` # echo $ARGS # #set KERNEL1D = "PF_KERNEL $2" #exit shift breaksw # 2d kernel file case '-K': set KERNEL2D = "PF_IN_KERNEL2D $2" shift breaksw # not recognized default: echo option: $1 echo " +++ non existing option, exiting." exit endsw shift # next flag end # while shift # skip the -- set INFILE = $1 if ( ! -e "$INFILE" ) then echo "infile: $INFILE does not exist" set HELP = "1" endif ### Set defaults if ( "$OFILE" == "0" ) then set OFILE = $INFILE.filtered endif ### Handle wrong input if ( "$HELP" == "1" ) then # cat << __EOFHD | more -de cat << __EOFHD | more PROGRAM: $PRG -- Filter mph file using Doris. SYNOPSIS: $PRG -l numlines [-o $OFILE] [-a $ALPHA] [-e $OVERLAP] [-b $BLOCKSIZE] [-m $METHOD] [-k kernel | -K file] [--] infile OPTIONS: -l numlines Number of lines in inputfile. -m method method either: "goldstein", "spectral", or "spatialconv". -o filename Output file name. -a A Alpha filter parameter A e{0,1} (Goldstein method). -e E Use overlap of 2*E pixels, so partially the same complex data are used to estimate the spectrum. -b B Filter in blocks of size (B,B). Should be power of 2. -k kernel 1D KERNEL, use underscores for space. For example -k 5_1_2_3_4_5 -K file Name of ascii input file containing a 2D kernel for method spatialconv or spectral. 1 header line with: "height", "width" and "scalefactor", for example: 3 3 0.111111111111 1 1 1 1 1 1 1 1 1 infile Name of input file with numlines (complexr4). BUGS: - EXAMPLES: - SEE ALSO: Doris user's manual, e.g. online, at: www.geo.tudelft.nl/doris/ __EOFHD exit 1 endif ### Create dummy input file(s). set DORISIN = $TMPDIR/$user.$$.in set DORISOUT = $TMPDIR/$user.$$.out set LOGFILE = $TMPDIR/$user.$$.log set SLAVEFILE = $TMPDIR/$user.$$.slave set MASTERFILE = $TMPDIR/$user.$$.master set PRODFILE = $TMPDIR/$user.$$.prod echo TMPFILES: $DORISIN $DORISOUT ### cat << __EOFHD >! $DORISIN c *********************************************************** c File created by: $PRG $VER c Author: $AUT c This is an input file for Doris to perform phase filtering c from prompt. c *********************************************************** c comment ___general options___ c SCREEN progress MEMORY 5 OVERWRITE ON BATCH ON LISTINPUT OFF PROCESS filtphase LOGFILE $LOGFILE M_RESFILE $MASTERFILE S_RESFILE $SLAVEFILE I_RESFILE $PRODFILE c c PF_METHOD $METHOD PF_IN_FILE $INFILE $NUMLINES PF_OUT_FILE $OFILE PF_ALPHA $ALPHA PF_OVERLAP $OVERLAP PF_BLOCKSIZE $BLOCKSIZE $KERNEL1D $KERNEL2D c STOP __EOFHD ### Run Doris, module phasefilt. doris $DORISIN > $DORISOUT echo "Some more info in $DORISIN and $DORISOUT" ### EOF. Doris-5.0.3Beta/bin/plotcpm000077500000000000000000000432171312547014700155620ustar00rootroot00000000000000#!/bin/csh -f # Changed this to csh -f. The -f option has been added after a # report that this script failed for a tcsh user who had a .cshrc file. # For Cygwin users, link your tcsh to csh, i.e., ln -s /bin/tcsh /bin/csh, # or obtain a regular csh from somewhere. #%// BK 27-Apr-2002 # # plotcpm for gmt3-0 # used by Doris software for optional plotting of error vectors etc. # input is file with info of axis (x,y) ("CPM_Data") # BK 03/03/1999 (kampes@geo.tudelft.nl) # removed psxy -F option for gmt3.3.3 # BK 01-Feb-2000 # added option for background magnitude image (argv 6). # this requires some diskspace... # BK 16-May-2000 # added histogram of errors #%// BK 30-Jun-2000 ### RCS ##### #%// BK 17-May-2000 #%// $Revision: 3.9 $ $Date: 2003/11/27 16:36:04 $ # changed plot error vectors instead of offsets. # increased size plots with errors #%// BK 07-Feb-2001 # added unit vectors, changed number of plots, removed c (entimeter) option # since linux box crashed on it. #%// BK 15-Mar-2001 #%// MA June 2008 GMT compatibility updates ################ ### Allow Doris time to write output file. sleep 1 set PRG = `basename "$0"` set VER = "v1.3, FMR software" set AUT = "TUDelft Radar Group (c)1999-2008" #set AUT = "Bert Kampes && Mahmut Arikan (c)1999-2008" echo "$PRG $VER, $AUT" echo " " ### Handle input. set USAGE = "0" #synopsis set HELP = "0" #exit afterwards # arg 1 set IFILE = "CPM_Data" # args 2:5 (default) dimension of the 3rd plot. @ L0 = 1 #@ LN = 25000 @ LN = 30000 @ P0 = 1 #@ PN = 4900 @ PN = 5000 # args 6 for background plot set DOBG = "0" set SLCFORMAT = "" set SLCFILE = "" switch ( $#argv ) case '6': set DOBG = "1" set SLCFILE = "$6" # ||| fall through ||| # case '5': @ L0 = $2 @ LN = $3 @ P0 = $4 @ PN = $5 # ||| fall through ||| # case '1': set IFILE = $1 breaksw # --- no fall through --- # default: set HELP = "1" endsw #if ( $#argv < 6 ) set USAGE = "1" # Check input if ( ! -r "$IFILE" ) then echo " input file: $IFILE cannot be read." set HELP = "1" endif # Check if something went wrong if ( $HELP ) set USAGE = "1" if ( $USAGE ) then cat << __EOFHD $PRG -- program to plot data from Doris Usage: $PRG [[[ifile [linelo hi pixlo hi [slcfile]]] tip: $PRG CPM_Data 1 25000 1 4900 slcfile.raw __EOFHD endif if ( $HELP ) then cat << __EOFHD infile is a data file from doris, see this script for details. linelo is first line. linehi is last line. pixello is first pixel. pixello is last pixel. slcfile is filename of SLC data for background of magnitude. format must be ci2 or cr4 of SLC data. Defaults: ifile == CPM_Data linelo == 1 linehi == 25000 pixlo == 1 pixhi == 4900 If magnitude background calls to GMT and cpxfiddle. __EOFHD exit -1 endif ### find out if nawk is available, since awk seems not to know atan2? #set AWK = awk; # echo 1 | /usr/xpg4/bin/awk '{print 1}' >& /dev/null # if ( $status == 0 ) set AWK = '/usr/xpg4/bin/awk' # echo 1 | /usr/xpg4/bin/awk '{print 1}' >& /dev/null echo 1 | awk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = `which awk` echo 1 | nawk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = 'nawk' echo 1 | gawk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = 'gawk' echo "Using as awk program: $AWK" ### Initialize variables set OFILE1 = "dummy1.$$.ps" # distribution errors azi/range set OFILE2 = "dummy2.$$.ps" # 2d pic set OFILE3 = "dummy3.$$.ps" # histogram azimuth,range errors set TMPFILE = "tmpfile.plot" ### Clean up, should not exist anyway. rm -f $OFILE1 $OFILE2 $OFILE3 $TMPFILE ### Set GMT defaults # PAPER_MEDIA a4+ \ gmtset MEASURE_UNIT cm \ PAPER_MEDIA a4+ \ PAGE_ORIENTATION portrait \ ANOT_FONT Helvetica \ ANOT_FONT_SIZE 10p \ ANOT_OFFSET 0.2 \ ANNOT_FONT_SIZE_SECONDARY 10p \ BASEMAP_AXES WeSn \ LABEL_FONT Helvetica \ LABEL_FONT_SIZE 10 \ HEADER_FONT_SIZE 24p \ UNIX_TIME_POS -2/-2 ### remove heading comment lines (10) #tail -n +11 $IFILE >! $TMPFILE #%// BK 25-Sep-2001: following bug report by Irek Baran. on tail. $AWK '{if(NR>10)print $0}' $IFILE >! $TMPFILE ###Assumes data in input file $1: (CPM_Data) # 2 27 447 241.12 3.31 0.44 0.04 0.11 48.12 130.80 # 1: window number # 2: location x # 3: location y # 4: offset x # 5: offset y # 6: correlation # 7: error x # 8: error y # 9: abs(wtest x) # 10:abs(wtest y) ### Plotting options gmt: psxy/pstext # R: axis , use 0 to 1 # J: projection/size (cm, see default file) # V: verbose # U: timestamp # :: lat/lon not lon/lat input # S: symbol # N: if outside border do ? # B: boundary annotation # P: portrait # K: append to ps later ### Plot1: error_vs_correlation + window number ### get maxima in data # $6 : correlation # $7 : errors in azimuth # $8 : errors in range # ### Plot the points (azimuth). echo " +++ Plotting absolute offsets in azimuth +++" #set MAXERR=`$AWK 'BEGIN{m=$7}{{if($7>m){m=$7}}}END{print m+.05}'<$TMPFILE` set MAXERR=`$AWK '(NR==1){m = sqrt ( $7 * $7 )}{{if ( sqrt ( $7 * $7 ) > m ){m = sqrt ( $7 * $7 )}}}END{print m + 0.05}'<$TMPFILE` set TITLE = "Azimuth_direction" set PROJ = "-JX15/8" set XLABEL = "Correlation" set YLABEL = "abs(e)" set GMTFLAGS = "-K -N -R0/1/0/$MAXERR $PROJ -U -Sx.2 -B.1:"$XLABEL":/.1:"$YLABEL"::."$TITLE": -P -W4/255/0/0" $AWK '{print $6, sqrt ( $7 * $7 )}' $TMPFILE | psxy $GMTFLAGS >! $OFILE1 ### Add the window numbers. #set GMTFLAGS = "-N -R0/1/0/$MAXERR $PROJ -P -O" set GMTFLAGS = "-K -N -R0/1/0/$MAXERR $PROJ -P -O" $AWK '{printf "%lg %s 10 0 0 5 %lg\n", $6 + 0.003, sqrt ( $7 * $7 ) + 0.003, $1}' $TMPFILE | pstext $GMTFLAGS >> $OFILE1 ### ### ### Do the same plot for Range direction. echo " +++ Plotting absolute offsets in range +++" set MAXERR=`$AWK '(NR==1){m = sqrt ( $8 * $8 )}{{if ( sqrt ( $8 * $8 ) > m ){m = sqrt ( $8 * $8 )}}}END{print m + 0.05}'<$TMPFILE` set TITLE="Range_direction" set GMTFLAGS="-Y14 -O -K -N -R0/1/0/$MAXERR $PROJ -Sx.2 -B.1:"":/.1:"$YLABEL"::."$TITLE": -P -W4/255/0/0" $AWK '{print $6, sqrt ( $8 * $8 )}' $TMPFILE | psxy $GMTFLAGS >> $OFILE1 set GMTFLAGS = "-N -R0/1/0/$MAXERR $PROJ -P -O" $AWK '{printf "%lg %s 10 0 0 5 %lg\n", $6+.003, sqrt ( $8 * $8 ) + 0.003, $1}' $TMPFILE | pstext $GMTFLAGS >> $OFILE1 ### View this plot in bg, delete it when closed, and continue script. viewanddel $OFILE1 & ### Plot3: location of windows / wtests / error vectors # plotted are scaled observations (offsets) for pattern visualization # (rotated) scaled wtests, to see largest one # col1: window number # 2/3: positionL/P # 9/10: wtests #if ( "$5" == "" ) then # echo "usage: $0 infile minL maxL minP maxP" # echo " eg: $0 testdata.dat 0 25000 0 4900" # exit -1 #endif # Labeling of axis. echo \\n" +++ Plotting the observed offset vectors (normalized)" set TITLE = "offset_vectors+rotated_wtests" set XLABEL = "Azimuth" set YLABEL = "Range" # height=y=azimuth, assume 5*stretched @ WIDTH = ( ( $PN - $P0 ) + 1) @ HEIGHT = ( ( $LN - $L0 ) + 1) @ NUMPIXS = ( $WIDTH * $HEIGHT ) set SLCFORMAT = "cr4" if ( $DOBG ) then # filewidth should be used... @ SIZECI2 = $WIDTH * $HEIGHT * 4 #@ SIZECR4 = $WIDTH * $HEIGHT * 8 # [LEN] tcsh produces integer overflow with large files set SIZECR4 = ` awk 'BEGIN{print '$WIDTH' * '$HEIGHT' * 8}' ` set FSIZE = `ls -l $SLCFILE | $AWK '{print $6}'` if ( $FSIZE == $SIZECI2 ) then echo " *** File format ${SLCFILE}: complex short." set SLCFORMAT = ci2 else if ( $FSIZE == $SIZECR4 ) then echo " *** File format ${SLCFILE}: complex float." set SLCFORMAT = cr4 else echo " *** Sorry, no background, file format could not be determined." set DOBG = "0" endif endif # GMT @ TICKSL = $HEIGHT / 7 @ TICKSP = $WIDTH / 7 set RANGE = "-P -: -R$P0/$PN/$L0/$LN" set FRAME = "-B"$TICKSP":"$YLABEL":/"$TICKSL":"$XLABEL"::."$TITLE":" set XSIZE = "21" set YSIZE = "0" # size paper, largest size $XSIZE # strict stretching ERS1/2 only... @ HEIGHT = $HEIGHT / 5 if ( $HEIGHT > $WIDTH ) then set YSIZE = $XSIZE set XSIZE = `echo "scale=3; $WIDTH/$HEIGHT*$YSIZE" | bc -l` else set YSIZE = `echo "scale=3; $HEIGHT/$WIDTH*$XSIZE" | bc -l` endif echo " *** SIZE X,Y: $XSIZE $YSIZE" set SIZE = "-JX$XSIZE/$YSIZE" # put - before axis to flip, also values to be multiple by - #set SIZE = "-JX17" ### First plot background if requested. if ( $DOBG ) then echo " *** Making background plot of magnitude image" set SUBX = "1" set SUBY = "1" echo " *** Total number of pixels: $NUMPIXS" # try to limit tmp GRDFILE to 10MB (2.500.000 binary float pixels) if ( $NUMPIXS > 100000000 ) then # eg. 25.000 * 5.000 set SUBY = "15" # else > 10MB tmpfile set SUBX = "3" # else > 10MB tmpfile else if ( $NUMPIXS > 50000000 ) then # eg. 10.000 * 5000 set SUBY = "10" # else > 10MB tmpfile set SUBX = "2" # else > 10MB tmpfile else if ( $NUMPIXS > 12500000 ) then # eg. 1500 * 5000 set SUBY = "5" endif echo " *** Subsampling data with factors (x,y): $SUBX $SUBY" # ## echo creating magnitude file mag.raw # Assume whole file to be plotted (else not possible for now, call from doris) #set PROG = "cpxfiddle -w$WIDTH -f$SLCFORMAT -qmag -e0.2 -ofloat\ # -l$L0 -L$LN -p$P0 -P$PN -S$SUBX/$SUBY -- $SLCFILE" set PROG = "cpxfiddle -w$WIDTH -f$SLCFORMAT -qmag -e0.2 -ofloat -M$SUBX/$SUBY -- $SLCFILE" # correct for GMT, subsampling output = ceil ((P-p+1)/sub) #set RANGE = "-R$FIRSTPIXEL/$LASTPIXEL/$FIRSTLINE/$LASTLINE" # outputlines after subsampling = ceil((P-p+1)/sub) #subsampling #set NUMX = `echo "$P0 $PN $SUBX" | $AWK '{printf "%i", ($2-$1)/$3+1}'` #set NUMY = `echo "$L0 $LN $SUBY" | $AWK '{printf "%i", ($2-$1)/$3+1}'` #multilooking set NUMX = `echo "$P0 $PN $SUBX" | $AWK '{print int ( ( $2 - $1 + 1 ) / $3 )}'` set NUMY = `echo "$L0 $LN $SUBY" | $AWK '{print int ( ( $2 - $1 + 1 ) / $3 )}'` echo " *** Number of output pixels (x,y): $NUMX $NUMY" set EAST = `echo "$P0+($NUMX-1)*$SUBX" | bc -l` set NORTH = `echo "$L0+($NUMY-1)*$SUBY" | bc -l` set BKRANGE = "-R$P0/$EAST/$L0/$NORTH" echo " *** GMT range: $BKRANGE" set GRDFILE = $$.grd set INC = "-I$SUBX/$SUBY" set IFORMAT = "-Zf" # binary float values echo " *** Calling:"\\n" $PROG | xyz2grd -G$GRDFILE $BKRANGE $INC $IFORMAT" $PROG | xyz2grd -G$GRDFILE $BKRANGE $INC $IFORMAT # echo " *** Making (continuous) cpt table" set CPTFILE = $$.cpt set CPTNAME = gray echo " *** Calling:"\\n" grd2cpt $GRDFILE -C$CPTNAME >! $CPTFILE" grd2cpt $GRDFILE -C$CPTNAME >! $CPTFILE # # mirror grd file in horizontal plane set BKSIZE = "-JX$XSIZE/-$YSIZE" echo " *** GMT range option: $BKSIZE" echo " *** Calling:"\\n" grdimage $GRDFILE $BKSIZE -C$CPTFILE -P -K >! $OFILE2" grdimage $GRDFILE $BKSIZE -C$CPTFILE -P -K >! $OFILE2 # Tidy tidy tidy echo " *** Removing grd and cpt file: $GRDFILE $CPTFILE" rm -f $GRDFILE rm -f $CPTFILE # Set Overlay for next set GMTFLAGS = "-O" else set GMTFLAGS = "" endif ### Add rescaled wtests to plot as normalized ellips. echo " *** Plotting normalized w tests"\ " Semi major/minor are interchanged for visibility" # Find out maximum wtest (both directions). @ MAXW1=`$AWK 'BEGIN{m=$9}{{if ( $9 > m ){m = $9}}{if ( $10 > m ){m = $10}}}END{print int ( m )}'<$TMPFILE` # size is scale=1.5 +0.2... -> 2.2 cm largest set GMTFLAGS = "$GMTFLAGS -K -N $RANGE $SIZE -Se -W3/0/255/0 -Y5" #$AWK -v s=$MAXW1 \ # '{scale=1.5/s} \ # {printf "%.1f %.1f 0 %.2f %.2f\n", $2, $3, 0.2+scale*$9, 0.2+scale*$10}' \ # $TMPFILE | \ # psxy $GMTFLAGS >> $OFILE2 $AWK '{scale = 1.5/'$MAXW1'} \ {printf "%.1f %.1f 0 %.2f %.2f\n", $2, $3, 0.2 + scale * $9, 0.2 + scale * $10}' \ $TMPFILE | \ psxy $GMTFLAGS >> $OFILE2 ### Plot the location crosses. #/set GMTFLAGS = "-K -O -N $RANGE $FRAME $SIZE -U -Sx0.4 -W6/255/0/0" set GMTFLAGS = "-K -O -N $RANGE $FRAME $SIZE -U -Sx0.2 -W6/255/0/0" $AWK '{print $2, $3}' $TMPFILE | psxy $GMTFLAGS >> $OFILE2 if ( "1" == "1" ) then ### Plot normalized offset vectors. # -G fill # -Sv arrowwidth/headlength/headwidth [0.075/0.3/0.25] set GMTFLAGS = "-K -O -N $RANGE $SIZE -Sv0.04/0.25/0.125 -G0/0/255 -W2/0/0/0" set MEANL = `$AWK '{s += $4}END{print int ( ( s / NR ) )}'<$TMPFILE` # old fashion normalization set MEANP = `$AWK '{s += $5}END{print int ( ( s / NR ) )}'<$TMPFILE` # old fashion normalization echo "MEAN L P : $MEANL $MEANP" # set WL = $MEANL # set WP = $MEANP # MA new normalization set MAXL=`$AWK '(NR==1){m = $4 }{if ( $4 > m ) m = $4 }END{print m }'<$TMPFILE` set MINL=`$AWK '(NR==1){m = $4 }{if ( $4 < m ) m = $4 }END{print m }'<$TMPFILE` set MAXP=`$AWK '(NR==1){m = $5 }{if ( $5 > m ) m = $5 }END{print m }'<$TMPFILE` set MINP=`$AWK '(NR==1){m = $5 }{if ( $5 < m ) m = $5 }END{print m }'<$TMPFILE` echo "MAXMIN L P : $MAXL $MINL $MAXP $MINP " set WL = `$AWK 'BEGIN{ print '$MINL' }' ` set WP = `$AWK 'BEGIN{ print '$MINP' }' ` set NFL = `$AWK 'BEGIN{ print '$MAXL' - '$MINL' }' ` set NFP = `$AWK 'BEGIN{ print '$MAXP' - '$MINP' }' ` # plot arrows as they are, normalized by max length ? (always longest==3cm?) #no cause then offset 1000 <> 1001 is no difference while it is the same as 10<>11 # thus scale length by l-max #$AWK -v wl=$WL -v wp=$WP \ # '{ \ # {l=$4-wl-1} \ # {p=$5-wp-1} \ #$AWK '{ {l = $4 - '$WL' - 1.0} {p = $5 - '$WP' - 1.0} \ # old fashion normalization #$AWK '{ {l = $4 -402 } \ # {p = $5 -25 } \ # $AWK '{ {l = $4 -'$MEANL' } \ # {p = $5 -'$MEANP' } \ # most of the displayment is on range so unit vector for azimuth #$AWK '{ {l = ($4 - '$WL')/'$NFL' } \ # {p = ($5 - '$WP')/'$NFP'*('$NFP'/'$NFL') } \ $AWK '{ {l = $4 -'$MEANL' } \ {p = $5 -'$MEANP' } \ {l = l + 0.0000001} {p = p + 0.0000001} \ {dir = 57.3 * atan2 ( l , p )} \ {scale = 1} \ {len = scale * sqrt ( l * l + p * p )} \ {printf "%.1f %.1f %.1f %.1f\n", $2, $3, dir, len} \ }' \ $TMPFILE | \ #$TMPFILE > dump.txt && cat dump.txt | \ psxy $GMTFLAGS >> $OFILE2 else ### Plot error vectors, offset vectors can be plotted with 'plotoffsets'. # -G fill # -Sv arrowwidth/headlength/headwidth [0.075c/0.3c/0.25c] set GMTFLAGS = "-K -O -N $RANGE $SIZE -Sv0.04/0.25/0.125 -G0/0/255 -W2/0/0/0" # MA new normalization set MAXL=`$AWK '(NR==1){m = $7 }{if ( $7 > m ) m = $7 }END{print m }'<$TMPFILE` set MINL=`$AWK '(NR==1){m = $7 }{if ( $7 < m ) m = $7 }END{print m }'<$TMPFILE` set MAXP=`$AWK '(NR==1){m = $8 }{if ( $8 > m ) m = $8 }END{print m }'<$TMPFILE` set MINP=`$AWK '(NR==1){m = $8 }{if ( $8 < m ) m = $8 }END{print m }'<$TMPFILE` echo "MAXMIN offset of L P : $MAXL $MINL $MAXP $MINP " set NFL = `$AWK 'BEGIN{ print '$MAXL' - '$MINL' }' ` set NFP = `$AWK 'BEGIN{ print '$MAXP' - '$MINP' }' ` # plot arrows as they are, normalized by max length ? (always longest==3cm?) $AWK '{ \ {l = $7} \ {p = $8} \ {l = l + 0.0000001} {p = p + 0.0000001} \ {dir = 57.3 * atan2 ( l , p )} \ {scale = 1} \ {len = scale * sqrt ( l * l + p * p )} \ {printf "%.1f %.1f %.1f %.1f\n", $2, $3, dir, len} \ }' \ $TMPFILE | \ psxy $GMTFLAGS >> $OFILE2 # Plot unit vectors at the side echo " Adding unit offset vectors in lower left corner." # set GMTFLAGS = "-N -O -K $RANGE $SIZE -Sv0.04/0.25/0.125 -G255/0/255 -W2/255/0/255" set GMTFLAGS = "-N -O $RANGE $SIZE -Sv0.04/0.25/0.125 -G255/0/255 -W2/255/0/255" #### l p err_l err_p echo "$L0 $P0 1 0" | \ $AWK '{{l = $3 + 0.0000001}{p = $4 + 0.0000001}{dir = 57.3 * atan2 ( l , p )} \ {scale = 1} {len = scale * sqrt ( l * l + p * p )} \ {printf "%.1f %.1f %.1f %.1f\n", $1, $2, dir, len} \ }' | psxy $GMTFLAGS -K >> $OFILE2 echo "$L0 $P0 0 1" | \ $AWK '{{l = $3 + 0.0000001}{p = $4 + 0.0000001}{dir = 57.3 * atan2 ( l , p )} \ {scale = 1} {len = scale * sqrt ( l * l + p * p )} \ {printf "%.1f %.1f %.1f %.1f\n", $1, $2, dir, len} \ }' | psxy $GMTFLAGS >> $OFILE2 endif ### Add the window numbers (last call). ##pstext: (x, y, size(pts), angle(ccw), fontno, justify, text) ##set GMTFLAGS = "-O -N -G0/255/0 $RANGE $SIZE" set GMTFLAGS = "-O -N -G0/0/0 $RANGE $SIZE" ##green, 14pts, RightTop BottomLeft echo "## dont print point labels now!" #$AWK '{printf "%.1f %.1f 10 0 0 RT %s\n", $2, $3, $1}' $TMPFILE | \ # pstext $GMTFLAGS >> $OFILE2 # view postscript in background, delete it afterwards, continue script. viewanddel $OFILE2 & ### Figure 3 : histogram of offsets in azimuth, range echo " +++ Plotting histograms of least squares offsets +++" set TITLE = "Error_histogram_Azimuth_direction" set XLABEL = "Error" set YLABEL = "frequency" #set GMTFLAGS = "-K -JX10/5 -U -W0.1 -C -B0.1/5:"$XLABEL":/.1:"$YLABEL"::."$TITLE": -P -G0/0/255" set GMTFLAGS = "-K "$PROJ" -U -W0.1 -F -B0.1:"$XLABEL":/.1:"$YLABEL"::."$TITLE": -P -G0/0/255" $AWK '{print $7}' $TMPFILE | pshistogram $GMTFLAGS > $OFILE3 ### range set TITLE = "Error_histogram_Range_direction" # set GMTFLAGS = "-O -Y10 -JX10/5 -C -W0.1 -B0.1/5:"":/.1:"$YLABEL"::."$TITLE": -P -G0/0/255" set GMTFLAGS = "-O -Y14 "$PROJ" -F -W0.1 -B0.1:"$XLABEL":/.1:"$YLABEL"::."$TITLE": -P -G0/0/255" $AWK '{print $8}' $TMPFILE | pshistogram $GMTFLAGS >> $OFILE3 viewanddel $OFILE3 & ### Tidy up rm -f $TMPFILE echo " +++ Finished: $PRG +++"\\n exit 0 ### EOF Doris-5.0.3Beta/bin/plotcpm.erroffsets000077500000000000000000000430071312547014700177400ustar00rootroot00000000000000#!/bin/csh -f # Changed this to csh -f. The -f option has been added after a # report that this script failed for a tcsh user who had a .cshrc file. # For Cygwin users, link your tcsh to csh, i.e., ln -s /bin/tcsh /bin/csh, # or obtain a regular csh from somewhere. #%// BK 27-Apr-2002 # # plotcpm for gmt3-0 # used by Doris software for optional plotting of error vectors etc. # input is file with info of axis (x,y) ("CPM_Data") # BK 03/03/1999 (kampes@geo.tudelft.nl) # removed psxy -F option for gmt3.3.3 # BK 01-Feb-2000 # added option for background magnitude image (argv 6). # this requires some diskspace... # BK 16-May-2000 # added histogram of errors #%// BK 30-Jun-2000 ### RCS ##### #%// BK 17-May-2000 #%// $Revision: 3.9 $ $Date: 2003/11/27 16:36:04 $ # changed plot error vectors instead of offsets. # increased size plots with errors #%// BK 07-Feb-2001 # added unit vectors, changed number of plots, removed c (entimeter) option # since linux box crashed on it. #%// BK 15-Mar-2001 #%// MA June 2008 GMT compatibility updates ################ ### Allow Doris time to write output file. sleep 1 set PRG = `basename "$0"` set VER = "v1.3, FMR software" set AUT = "TUDelft Radar Group (c)1999-2008" #set AUT = "Bert Kampes && Mahmut Arikan (c)1999-2008" echo "$PRG $VER, $AUT" echo " " ### Handle input. set USAGE = "0" #synopsis set HELP = "0" #exit afterwards # arg 1 set IFILE = "CPM_Data" # args 2:5 (default) dimension of the 3rd plot. @ L0 = 1 #@ LN = 25000 @ LN = 30000 @ P0 = 1 #@ PN = 4900 @ PN = 5000 # args 6 for background plot set DOBG = "0" set SLCFORMAT = "" set SLCFILE = "" switch ( $#argv ) case '6': set DOBG = "1" set SLCFILE = "$6" # ||| fall through ||| # case '5': @ L0 = $2 @ LN = $3 @ P0 = $4 @ PN = $5 # ||| fall through ||| # case '1': set IFILE = $1 breaksw # --- no fall through --- # default: set HELP = "1" endsw #if ( $#argv < 6 ) set USAGE = "1" # Check input if ( ! -r "$IFILE" ) then echo " input file: $IFILE cannot be read." set HELP = "1" endif # Check if something went wrong if ( $HELP ) set USAGE = "1" if ( $USAGE ) then cat << __EOFHD $PRG -- program to plot data from Doris Usage: $PRG [[[ifile [linelo hi pixlo hi [slcfile]]] tip: $PRG CPM_Data 1 25000 1 4900 slcfile.raw __EOFHD endif if ( $HELP ) then cat << __EOFHD infile is a data file from doris, see this script for details. linelo is first line. linehi is last line. pixello is first pixel. pixello is last pixel. slcfile is filename of SLC data for background of magnitude. format must be ci2 or cr4 of SLC data. Defaults: ifile == CPM_Data linelo == 1 linehi == 25000 pixlo == 1 pixhi == 4900 If magnitude background calls to GMT and cpxfiddle. __EOFHD exit -1 endif ### find out if nawk is available, since awk seems not to know atan2? #set AWK = awk; # echo 1 | /usr/xpg4/bin/awk '{print 1}' >& /dev/null # if ( $status == 0 ) set AWK = '/usr/xpg4/bin/awk' # echo 1 | /usr/xpg4/bin/awk '{print 1}' >& /dev/null echo 1 | awk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = `which awk` echo 1 | nawk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = 'nawk' echo 1 | gawk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = 'gawk' echo "Using as awk program: $AWK" ### Initialize variables set OFILE1 = "dummy1.$$.ps" # distribution errors azi/range set OFILE2 = "dummy2.$$.ps" # 2d pic set OFILE3 = "dummy3.$$.ps" # histogram azimuth,range errors set TMPFILE = "tmpfile.plot" ### Clean up, should not exist anyway. rm -f $OFILE1 $OFILE2 $OFILE3 $TMPFILE ### Set GMT defaults # PAPER_MEDIA a4+ \ gmtset MEASURE_UNIT cm \ PAPER_MEDIA a4+ \ PAGE_ORIENTATION portrait \ ANOT_FONT Helvetica \ ANOT_FONT_SIZE 10p \ ANOT_OFFSET 0.2 \ ANNOT_FONT_SIZE_SECONDARY 10p \ BASEMAP_AXES WeSn \ LABEL_FONT Helvetica \ LABEL_FONT_SIZE 10 \ HEADER_FONT_SIZE 24p \ UNIX_TIME_POS -2/-2 ### remove heading comment lines (10) #tail -n +11 $IFILE >! $TMPFILE #%// BK 25-Sep-2001: following bug report by Irek Baran. on tail. $AWK '{if(NR>10)print $0}' $IFILE >! $TMPFILE ###Assumes data in input file $1: (CPM_Data) # 2 27 447 241.12 3.31 0.44 0.04 0.11 48.12 130.80 # 1: window number # 2: location x # 3: location y # 4: offset x # 5: offset y # 6: correlation # 7: error x # 8: error y # 9: abs(wtest x) # 10:abs(wtest y) ### Plotting options gmt: psxy/pstext # R: axis , use 0 to 1 # J: projection/size (cm, see default file) # V: verbose # U: timestamp # :: lat/lon not lon/lat input # S: symbol # N: if outside border do ? # B: boundary annotation # P: portrait # K: append to ps later ### Plot1: error_vs_correlation + window number ### get maxima in data # $6 : correlation # $7 : errors in azimuth # $8 : errors in range # ### Plot the points (azimuth). echo " +++ Plotting absolute errors azimuth +++" #set MAXERR=`$AWK 'BEGIN{m=$7}{{if($7>m){m=$7}}}END{print m+.05}'<$TMPFILE` set MAXERR=`$AWK '(NR==1){m = sqrt ( $7 * $7 )}{{if ( sqrt ( $7 * $7 ) > m ){m = sqrt ( $7 * $7 )}}}END{print m + 0.05}'<$TMPFILE` set TITLE = "Azimuth_direction" set PROJ = "-JX15/8" set XLABEL = "Correlation" set YLABEL = "abs(e)" set GMTFLAGS = "-K -N -R0/1/0/$MAXERR $PROJ -U -Sx.2 -B.1:"$XLABEL":/.1:"$YLABEL"::."$TITLE": -P -W4/255/0/0" $AWK '{print $6, sqrt ( $7 * $7 )}' $TMPFILE | psxy $GMTFLAGS >! $OFILE1 ### Add the window numbers. #set GMTFLAGS = "-N -R0/1/0/$MAXERR $PROJ -P -O" set GMTFLAGS = "-K -N -R0/1/0/$MAXERR $PROJ -P -O" $AWK '{printf "%lg %s 10 0 0 5 %lg\n", $6 + 0.003, sqrt ( $7 * $7 ) + 0.003, $1}' $TMPFILE | pstext $GMTFLAGS >> $OFILE1 ### ### ### Do the same plot for Range direction. echo " +++ Plotting absolute errors range +++" set MAXERR=`$AWK '(NR==1){m = sqrt ( $8 * $8 )}{{if ( sqrt ( $8 * $8 ) > m ){m = sqrt ( $8 * $8 )}}}END{print m + 0.05}'<$TMPFILE` set TITLE="Range_direction" set GMTFLAGS="-Y14 -O -K -N -R0/1/0/$MAXERR $PROJ -Sx.2 -B.1:"":/.1:"$YLABEL"::."$TITLE": -P -W4/255/0/0" $AWK '{print $6, sqrt ( $8 * $8 )}' $TMPFILE | psxy $GMTFLAGS >> $OFILE1 set GMTFLAGS = "-N -R0/1/0/$MAXERR $PROJ -P -O" $AWK '{printf "%lg %s 10 0 0 5 %lg\n", $6+.003, sqrt ( $8 * $8 ) + 0.003, $1}' $TMPFILE | pstext $GMTFLAGS >> $OFILE1 ### View this plot in bg, delete it when closed, and continue script. viewanddel $OFILE1 & ### Plot3: location of windows / wtests / error vectors # plotted are scaled observations (offsets) for pattern visualization # (rotated) scaled wtests, to see largest one # col1: window number # 2/3: positionL/P # 9/10: wtests #if ( "$5" == "" ) then # echo "usage: $0 infile minL maxL minP maxP" # echo " eg: $0 testdata.dat 0 25000 0 4900" # exit -1 #endif # Labeling of axis. echo \\n" +++ Plotting the observed offset vectors (normalized)" set TITLE = "error_vectors+rotated_wtests" set XLABEL = "Azimuth" set YLABEL = "Range" # height=y=azimuth, assume 5*stretched @ WIDTH = ( ( $PN - $P0 ) + 1) @ HEIGHT = ( ( $LN - $L0 ) + 1) @ NUMPIXS = ( $WIDTH * $HEIGHT ) set SLCFORMAT = "cr4" if ( $DOBG ) then # filewidth should be used... @ SIZECI2 = $WIDTH * $HEIGHT * 4 @ SIZECR4 = $WIDTH * $HEIGHT * 8 set FSIZE = `ls -l $SLCFILE | $AWK '{print $5}'` if ( $FSIZE == $SIZECI2 ) then echo " *** File format ${SLCFILE}: complex short." set SLCFORMAT = ci2 else if ( $FSIZE == $SIZECR4 ) then echo " *** File format ${SLCFILE}: complex float." set SLCFORMAT = cr4 else echo " *** Sorry, no background, file format could not be determined." set DOBG = "0" endif endif # GMT @ TICKSL = $HEIGHT / 7 @ TICKSP = $WIDTH / 7 set RANGE = "-P -: -R$P0/$PN/$L0/$LN" set FRAME = "-B"$TICKSP":"$YLABEL":/"$TICKSL":"$XLABEL"::."$TITLE":" set XSIZE = "21" set YSIZE = "0" # size paper, largest size $XSIZE # strict stretching ERS1/2 only... @ HEIGHT = $HEIGHT / 5 if ( $HEIGHT > $WIDTH ) then set YSIZE = $XSIZE set XSIZE = `echo "scale=3; $WIDTH/$HEIGHT*$YSIZE" | bc -l` else set YSIZE = `echo "scale=3; $HEIGHT/$WIDTH*$XSIZE" | bc -l` endif echo " *** SIZE X,Y: $XSIZE $YSIZE" set SIZE = "-JX$XSIZE/$YSIZE" # put - before axis to flip, also values to be multiple by - #set SIZE = "-JX17" ### First plot background if requested. if ( $DOBG ) then echo " *** Making background plot of magnitude image" set SUBX = "1" set SUBY = "1" echo " *** Total number of pixels: $NUMPIXS" # try to limit tmp GRDFILE to 10MB (2.500.000 binary float pixels) if ( $NUMPIXS > 100000000 ) then # eg. 25.000 * 5.000 set SUBY = "15" # else > 10MB tmpfile set SUBX = "3" # else > 10MB tmpfile else if ( $NUMPIXS > 50000000 ) then # eg. 10.000 * 5000 set SUBY = "10" # else > 10MB tmpfile set SUBX = "2" # else > 10MB tmpfile else if ( $NUMPIXS > 12500000 ) then # eg. 1500 * 5000 set SUBY = "5" endif echo " *** Subsampling data with factors (x,y): $SUBX $SUBY" # ## echo creating magnitude file mag.raw # Assume whole file to be plotted (else not possible for now, call from doris) #set PROG = "cpxfiddle -w$WIDTH -f$SLCFORMAT -qmag -e0.2 -ofloat\ # -l$L0 -L$LN -p$P0 -P$PN -S$SUBX/$SUBY -- $SLCFILE" set PROG = "cpxfiddle -w$WIDTH -f$SLCFORMAT -qmag -e0.2 -ofloat -M$SUBX/$SUBY -- $SLCFILE" # correct for GMT, subsampling output = ceil ((P-p+1)/sub) #set RANGE = "-R$FIRSTPIXEL/$LASTPIXEL/$FIRSTLINE/$LASTLINE" # outputlines after subsampling = ceil((P-p+1)/sub) #subsampling #set NUMX = `echo "$P0 $PN $SUBX" | $AWK '{printf "%i", ($2-$1)/$3+1}'` #set NUMY = `echo "$L0 $LN $SUBY" | $AWK '{printf "%i", ($2-$1)/$3+1}'` #multilooking set NUMX = `echo "$P0 $PN $SUBX" | $AWK '{print int ( ( $2 - $1 + 1 ) / $3 )}'` set NUMY = `echo "$L0 $LN $SUBY" | $AWK '{print int ( ( $2 - $1 + 1 ) / $3 )}'` echo " *** Number of output pixels (x,y): $NUMX $NUMY" set EAST = `echo "$P0+($NUMX-1)*$SUBX" | bc -l` set NORTH = `echo "$L0+($NUMY-1)*$SUBY" | bc -l` set BKRANGE = "-R$P0/$EAST/$L0/$NORTH" echo " *** GMT range: $BKRANGE" set GRDFILE = $$.grd set INC = "-I$SUBX/$SUBY" set IFORMAT = "-Zf" # binary float values echo " *** Calling:"\\n" $PROG | xyz2grd -G$GRDFILE $BKRANGE $INC $IFORMAT" $PROG | xyz2grd -G$GRDFILE $BKRANGE $INC $IFORMAT # echo " *** Making (continuous) cpt table" set CPTFILE = $$.cpt set CPTNAME = gray echo " *** Calling:"\\n" grd2cpt $GRDFILE -C$CPTNAME >! $CPTFILE" grd2cpt $GRDFILE -C$CPTNAME >! $CPTFILE # # mirror grd file in horizontal plane set BKSIZE = "-JX$XSIZE/-$YSIZE" echo " *** GMT range option: $BKSIZE" echo " *** Calling:"\\n" grdimage $GRDFILE $BKSIZE -C$CPTFILE -P -K >! $OFILE2" grdimage $GRDFILE $BKSIZE -C$CPTFILE -P -K >! $OFILE2 # Tidy tidy tidy echo " *** Removing grd and cpt file: $GRDFILE $CPTFILE" rm -f $GRDFILE rm -f $CPTFILE # Set Overlay for next set GMTFLAGS = "-O" else set GMTFLAGS = "" endif ### Add rescaled wtests to plot as normalized ellips. echo " *** Plotting normalized w tests"\ " Semi major/minor are interchanged for visibility" # Find out maximum wtest (both directions). @ MAXW1=`$AWK 'BEGIN{m=$9}{{if ( $9 > m ){m = $9}}{if ( $10 > m ){m = $10}}}END{print int ( m )}'<$TMPFILE` # size is scale=1.5 +0.2... -> 2.2 cm largest set GMTFLAGS = "$GMTFLAGS -K -N $RANGE $SIZE -Se -W3/0/255/0 -Y5" #$AWK -v s=$MAXW1 \ # '{scale=1.5/s} \ # {printf "%.1f %.1f 0 %.2f %.2f\n", $2, $3, 0.2+scale*$9, 0.2+scale*$10}' \ # $TMPFILE | \ # psxy $GMTFLAGS >> $OFILE2 $AWK '{scale = 1.5/'$MAXW1'} \ {printf "%.1f %.1f 0 %.2f %.2f\n", $2, $3, 0.2 + scale * $9, 0.2 + scale * $10}' \ $TMPFILE | \ psxy $GMTFLAGS >> $OFILE2 ### Plot the location crosses. #/set GMTFLAGS = "-K -O -N $RANGE $FRAME $SIZE -U -Sx0.4 -W6/255/0/0" set GMTFLAGS = "-K -O -N $RANGE $FRAME $SIZE -U -Sx0.2 -W6/255/0/0" $AWK '{print $2, $3}' $TMPFILE | psxy $GMTFLAGS >> $OFILE2 if ( "1" == "2" ) then ### Plot normalized offset vectors. # -G fill # -Sv arrowwidth/headlength/headwidth [0.075/0.3/0.25] set GMTFLAGS = "-K -O -N $RANGE $SIZE -Sv0.04/0.25/0.125 -G0/0/255 -W2/0/0/0" set MEANL = `$AWK '{s += $4}END{print int ( ( s / NR ) )}'<$TMPFILE` # old fashion normalization set MEANP = `$AWK '{s += $5}END{print int ( ( s / NR ) )}'<$TMPFILE` # old fashion normalization echo "MEAN L P : $MEANL $MEANP" # set WL = $MEANL # set WP = $MEANP # MA new normalization set MAXL=`$AWK '(NR==1){m = $4 }{if ( $4 > m ) m = $4 }END{print m }'<$TMPFILE` set MINL=`$AWK '(NR==1){m = $4 }{if ( $4 < m ) m = $4 }END{print m }'<$TMPFILE` set MAXP=`$AWK '(NR==1){m = $5 }{if ( $5 > m ) m = $5 }END{print m }'<$TMPFILE` set MINP=`$AWK '(NR==1){m = $5 }{if ( $5 < m ) m = $5 }END{print m }'<$TMPFILE` echo "MAXMIN L P : $MAXL $MINL $MAXP $MINP " set WL = `$AWK 'BEGIN{ print '$MINL' }' ` set WP = `$AWK 'BEGIN{ print '$MINP' }' ` set NFL = `$AWK 'BEGIN{ print '$MAXL' - '$MINL' }' ` set NFP = `$AWK 'BEGIN{ print '$MAXP' - '$MINP' }' ` # plot arrows as they are, normalized by max length ? (always longest==3cm?) #no cause then offset 1000 <> 1001 is no difference while it is the same as 10<>11 # thus scale length by l-max #$AWK -v wl=$WL -v wp=$WP \ # '{ \ # {l=$4-wl-1} \ # {p=$5-wp-1} \ #$AWK '{ {l = $4 - '$WL' - 1.0} {p = $5 - '$WP' - 1.0} \ # old fashion normalization #$AWK '{ {l = $4 -402 } \ # {p = $5 -25 } \ # $AWK '{ {l = $4 -'$MEANL' } \ # {p = $5 -'$MEANP' } \ # most of the displayment is on range so unit vector for azimuth #$AWK '{ {l = ($4 - '$WL')/'$NFL' } \ # {p = ($5 - '$WP')/'$NFP'*('$NFP'/'$NFL') } \ $AWK '{ {l = $4 -'$MEANL' } \ {p = $5 -'$MEANP' } \ {l = l + 0.0000001} {p = p + 0.0000001} \ {dir = 57.3 * atan2 ( l , p )} \ {scale = 1} \ {len = scale * sqrt ( l * l + p * p )} \ {printf "%.1f %.1f %.1f %.1f\n", $2, $3, dir, len} \ }' \ $TMPFILE | \ #$TMPFILE > dump.txt && cat dump.txt | \ psxy $GMTFLAGS >> $OFILE2 else ### Plot error vectors, offset vectors can be plotted with 'plotoffsets'. # -G fill # -Sv arrowwidth/headlength/headwidth [0.075c/0.3c/0.25c] set GMTFLAGS = "-K -O -N $RANGE $SIZE -Sv0.04/0.25/0.125 -G0/0/255 -W2/0/0/0" # MA new normalization set MAXL=`$AWK '(NR==1){m = $7 }{if ( $7 > m ) m = $7 }END{print m }'<$TMPFILE` set MINL=`$AWK '(NR==1){m = $7 }{if ( $7 < m ) m = $7 }END{print m }'<$TMPFILE` set MAXP=`$AWK '(NR==1){m = $8 }{if ( $8 > m ) m = $8 }END{print m }'<$TMPFILE` set MINP=`$AWK '(NR==1){m = $8 }{if ( $8 < m ) m = $8 }END{print m }'<$TMPFILE` echo "MAXMIN error of L P : $MAXL $MINL $MAXP $MINP " set NFL = `$AWK 'BEGIN{ print '$MAXL' - '$MINL' }' ` set NFP = `$AWK 'BEGIN{ print '$MAXP' - '$MINP' }' ` # plot arrows as they are, normalized by max length ? (always longest==3cm?) $AWK '{ \ {l = $7} \ {p = $8} \ {l = l + 0.0000001} {p = p + 0.0000001} \ {dir = 57.3 * atan2 ( l , p )} \ {scale = 1} \ {len = scale * sqrt ( l * l + p * p )} \ {printf "%.1f %.1f %.1f %.1f\n", $2, $3, dir, len} \ }' \ $TMPFILE | \ psxy $GMTFLAGS >> $OFILE2 # Plot unit vectors at the side echo " Adding unit error vectors in lower left corner." # set GMTFLAGS = "-N -O -K $RANGE $SIZE -Sv0.04/0.25/0.125 -G255/0/255 -W2/255/0/255" set GMTFLAGS = "-N -O $RANGE $SIZE -Sv0.04/0.25/0.125 -G255/0/255 -W2/255/0/255" #### l p err_l err_p echo "$L0 $P0 1 0" | \ $AWK '{{l = $3 + 0.0000001}{p = $4 + 0.0000001}{dir = 57.3 * atan2 ( l , p )} \ {scale = 1} {len = scale * sqrt ( l * l + p * p )} \ {printf "%.1f %.1f %.1f %.1f\n", $1, $2, dir, len} \ }' | psxy $GMTFLAGS -K >> $OFILE2 echo "$L0 $P0 0 1" | \ $AWK '{{l = $3 + 0.0000001}{p = $4 + 0.0000001}{dir = 57.3 * atan2 ( l , p )} \ {scale = 1} {len = scale * sqrt ( l * l + p * p )} \ {printf "%.1f %.1f %.1f %.1f\n", $1, $2, dir, len} \ }' | psxy $GMTFLAGS >> $OFILE2 endif ### Add the window numbers (last call). ##pstext: (x, y, size(pts), angle(ccw), fontno, justify, text) ##set GMTFLAGS = "-O -N -G0/255/0 $RANGE $SIZE" set GMTFLAGS = "-O -N -G0/0/0 $RANGE $SIZE" ##green, 14pts, RightTop BottomLeft echo "## dont print point labels now!" #$AWK '{printf "%.1f %.1f 10 0 0 RT %s\n", $2, $3, $1}' $TMPFILE | \ # pstext $GMTFLAGS >> $OFILE2 # view postscript in background, delete it afterwards, continue script. viewanddel $OFILE2 & ### Figure 3 : histogram of errors in azimuth, range echo " +++ Plotting histograms of least squares errors +++" set TITLE = "Error_histogram_Azimuth_direction" set XLABEL = "Error" set YLABEL = "frequency" #set GMTFLAGS = "-K -JX10/5 -U -W0.1 -C -B0.1/5:"$XLABEL":/.1:"$YLABEL"::."$TITLE": -P -G0/0/255" set GMTFLAGS = "-K "$PROJ" -U -W0.1 -F -B0.1:"$XLABEL":/.1:"$YLABEL"::."$TITLE": -P -G0/0/255" $AWK '{print $7}' $TMPFILE | pshistogram $GMTFLAGS > $OFILE3 ### range set TITLE = "Error_histogram_Range_direction" # set GMTFLAGS = "-O -Y10 -JX10/5 -C -W0.1 -B0.1/5:"":/.1:"$YLABEL"::."$TITLE": -P -G0/0/255" set GMTFLAGS = "-O -Y14 "$PROJ" -F -W0.1 -B0.1:"$XLABEL":/.1:"$YLABEL"::."$TITLE": -P -G0/0/255" $AWK '{print $8}' $TMPFILE | pshistogram $GMTFLAGS >> $OFILE3 viewanddel $OFILE3 & ### Tidy up rm -f $TMPFILE echo " +++ Finished: $PRG +++"\\n exit 0 ### EOF Doris-5.0.3Beta/bin/plotoffsets000077500000000000000000000424221312547014700164510ustar00rootroot00000000000000#!/bin/csh -f # Changed this to csh -f. The -f option has been added after a # report that this script failed for a tcsh user who had a .cshrc file. # For Cygwin users, link your tcsh to csh, i.e., ln -s /bin/tcsh /bin/csh, # or obtain a regular csh from somewhere. #%// BK 27-Apr-2002 # # plotoffsets for gmt3-3 # used by Doris software for plotting of offset vectors after fine. # plotting magnitude background may require some diskspace # (subx, suby..) # bg assumed to be in one file, size=(width*height); width=pN-p0+1 # BK 16-May-2000 # sleeps & calls viewanddel instead of gv, for Doris software. #%// BK 19-Jul-2000 ### RCS info ##### #%// BK 17-May-2000 #%// $Revision: 3.15 $ $Date: 2005/08/26 08:54:00 $ # Developers: # Bert Kampes # Lennert van den Berg ################ ################ # TODO: # -plot unit offset vectors # (this is pretty difficult, since normalized, what to plot, added it # in plotcpm for error vectors, bk 15 mar01) #%// BK 19-Jul-2000 ### Handle input. # give doris time to write result file sleep 1 set PRG = `basename "$0"` set VER = "v1.0, part of Doris InSAR software" set AUT = "TUDelft, (c)1999-2010" echo "$PRG $VER, $AUT" echo " " ### set USAGE = "0" #synopsis set HELP = "0" #exit afterwards set IFILE = "interferogram.out" # arg 1 default # args 2:5 (default) file dimension (plot dim.) @ L0 = 1 @ LN = 25000 @ P0 = 1 @ PN = 4900 set THRESHOLD = "0.4" # arg6 default set SLCFILE = "" # arg7 optional set SLCFORMAT = "" set DOBG = "0" # default (not possible w/o l0,lN,p0,pN switch ( $#argv ) case '7': set DOBG = "1" set SLCFILE = "$7" # ||| fall through ||| # case '6': set THRESHOLD = "$6" # ||| fall through ||| # case '5': @ L0 = $2 @ LN = $3 @ P0 = $4 @ PN = $5 # ||| fall through ||| # case '2': case '1': set IFILE = $1 breaksw # --- no fall through --- # default: set HELP = "1" endsw if ( $#argv == 2) set THRESHOLD = "$2" # Check input if ( ! -r "$IFILE" ) then echo " input file: $IFILE cannot be read." set HELP = "1" endif # Check if something went wrong set MORE = more; less >& /dev/null if ( $status == 0 ) set MORE = 'less -de' echo "Using as pager program: $MORE" if ( $HELP ) set USAGE = "1" if ( $USAGE ) then #cat << __EOF_USAGE | more -d cat << __EOF_USAGE | $MORE ----------------------------------------------------------------------- $PRG -- Program to plot offset vectors from Doris Position, correlation, and background image can be plotted. SYNOPSIS: $PRG ifile [linelo hi pixlo hi [threshold [slcfile]]] ifile: Resultfile from Doris [mandatory arg] linelo: First azimuth line. [default: 1] linehi: Last azimuth line. [default: 25000] pixlo: First range pixel. [default: 1] pixhi: Last range pixel. [default: 4900] threshold: Only plot estimated with correlation above threshold. [default: 0.4] slcfile: Complex raw file. Magnitude is used as background image. (format can be complex real4 or short int.) EXAMPLE: $PRG interferogram.out 1 25000 1 4900 0.4 slcfile.raw PROG may depend on gawk or nawk and not work with std awk... ----------------------------------------------------------------------- __EOF_USAGE endif if ( $HELP ) then #cat << __EOF_HELP | more -de cat << __EOF_HELP | $MORE ifile is the interferogram result file from the Doris software, see this script for details. Somewhere the fine output section should be present, containing lines such as: ******************************************************************* *_Start_fine_coreg ******************************************************************* Initial offsets (l,p): 212, 18 Window size for correlation (l,p): 80, 80 Max. offset that can be estimated: 40 Peak search ovs window (l,p): 16, 16 Oversampling factor: 32 Number_of_correlation_windows: 101 Number posL posP offsetL offsetP correlation 0 27 27 241.06 3.19 0.42 1 27 127 241.36 3.29 0.72 ... 99 4733 971 241.86 3.50 0.48 ******************************************************************* * End_fine_coreg:_NORMAL ******************************************************************* See also: cpxfiddle, GMT. __EOF_HELP exit -1 endif ### Initialize variables set TMPDIR = "." if ( ! -w "$TMPDIR" ) then set TMPDIR = "/tmp" endif if ( ! -w "$TMPDIR" ) then echo "Sorry, directory $TMPDIR seems not writable, exiting." exit -2 endif set PSFILE = $TMPDIR/tmpplot.ps set TMPFILE = $TMPDIR/tmpdata.plot rm -f $PSFILE $TMPFILE ### ifile is transformed to tmpfile with columns: # 1: window number # 2: location x # 3: location y # 4: offset x # 5: offset y # 6: correlation ### Create tmpfile with only data: grep fine section with awk and ### remove trailing comment lines (5) and tailing comment (2) ### ###1: *_Start_fine_coreg ###2: ******************************************************************* ###3: Oversampling factor: 16 ###4: Number_of_correlation_windows: 100 ###5: Number posL posP offsetL offsetP correlation ###6: 0 27 27 241.06 3.19 0.42 ### ... ###x: 99 4733 971 241.06 3.50 0.41 ###x+1: ###x+2: ******************************************************************* ###x+3: * End_fine_coreg:_NORMAL ###x+4: ******************************************************************* ### # ###################################################################### ### find out if nawk is available, since awk seems not to know atan2? set AWK = awk; echo 1 | /usr/xpg4/bin/awk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = '/usr/xpg4/bin/awk' echo 1 | gawk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = 'gawk' echo 1 | nawk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = 'nawk' echo "Using as awk program: $AWK" ###################################################################### ### 1. Grep between start stop pair: echo "TMPFILE BEING GENERATED: step1" $AWK '/Start_fine/, /End_fine/' $IFILE >! $TMPFILE.$$ ### 2. Get number of points (starting at window 0): @ NUMPOINTS = `$AWK '/Number_of/ {print $2}' $TMPFILE.$$` #### 3. Reduce file only to data: #tail -n +6 $TMPFILE.$$ | head -n $NUMPOINTS >! $TMPFILE #### 4. Remove above threshold (here is most easy...) #$AWK -v t=$THRESHOLD '$6>=t' $TMPFILE >! $TMPFILE.$$ #mv -f $TMPFILE.$$ $TMPFILE # #%// BK 25-Sep-2001: following bug report by Irek Baran. echo "TMPFILE BEING GENERATED: step2" #$AWK -v n=$NUMPOINTS -v t=$THRESHOLD '{if(NR>5&&NRt){print $0}}}' $TMPFILE.$$ > $TMPFILE #rm -f $TMPFILE.$$ #test how to pass arguments. failsave seems to be: #echo 111 | $AWK '{print '$t'}' #%// BK 16-Jun-2003 #$AWK '{if(NR>5&&NR<'$NUMPOINTS'+6){if ($6>'$THRESHOLD'){print $0}}}' $TMPFILE.$$ > $TMPFILE # v3.16: more info lines in resfile, skip more. $AWK '{if(NR>10&&NR<'$NUMPOINTS'+11){if ($6>'$THRESHOLD'){print $0}}}' $TMPFILE.$$ > $TMPFILE rm -f $TMPFILE.$$ echo "TMPFILE GENERATED" ### Check if we have points ########################################## @ NP = `$AWK '{l=NR};END{print l}' $TMPFILE` echo "$NP points above coherence threshold $THRESHOLD found." if ( $NP < 1 ) then echo "exiting..." rm -f $TMPFILE exit endif ###################################################################### ### Plot: location of windows / wtests # plotted are: # - normalized observations (offsets) # - optionally background of magnitude image # - correlation as circles (legenda... o=1), thickness arrow? ###################################################################### echo "Setting GMT defaults" # PAPER_MEDIA a4+ \ gmtset MEASURE_UNIT cm \ PAPER_MEDIA a4 \ PAGE_ORIENTATION portrait \ ANOT_FONT Helvetica \ ANOT_FONT_SIZE 10p \ ANOT_OFFSET 0.2 \ BASEMAP_AXES WeSn \ LABEL_FONT Helvetica \ LABEL_FONT_SIZE 10 \ UNIX_TIME_POS -2/-2 \ D_FORMAT %lg ###################################################################### ### Labeling of axis. echo " +++ Plotting the observed offset vectors (normalized) +++" set TITLE = "Offset_vectors_(Corr_>_$THRESHOLD)" set XLABEL = "Azimuth" set YLABEL = "Range" # height=y=azimuth, assume 5*stretched @ WIDTH = ( ( $PN - $P0 ) + 1) @ HEIGHT = ( ( $LN - $L0 ) + 1) set SLCFORMAT = "cr4" if ( $DOBG ) then # filewidth should be used, but is equal... #@ SIZECI2 = $WIDTH * $HEIGHT * 4 #@ SIZECR4 = $WIDTH * $HEIGHT * 8 set SIZECI2 = `awk 'BEGIN{print '$WIDTH' * '$HEIGHT' * 4 }'` # MA avoid integer overflow set SIZECR4 = `awk 'BEGIN{print '$WIDTH' * '$HEIGHT' * 8 }'` set FSIZE = `ls -l $SLCFILE | $AWK '{print $5}'` if ( $FSIZE == $SIZECI2 ) then echo " *** File format ${SLCFILE}: complex short." set SLCFORMAT = ci2 else if ( $FSIZE == $SIZECR4 ) then echo " *** File format ${SLCFILE}: complex float." set SLCFORMAT = cr4 else echo " *** Sorry, no background, file format could not be determined." set DOBG = "0" endif endif ###################################################################### # GMT options @ TICKSL = $HEIGHT / 7 @ TICKSP = $WIDTH / 7 set RANGE = "-R$P0/$PN/$L0/$LN" set GENOPT = "-P -: " set FRAME = "-B"$TICKSP":"$YLABEL":/"$TICKSL":"$XLABEL"::."$TITLE":" set XSIZE = "16" set YSIZE = "0" @ NUMPIXS = ( $WIDTH * $HEIGHT ) # size paper, largest size $XSIZE # actually should go to landscape in that case... # strict stretching ERS1/2 only... set RATIO = "5" @ HEIGHT = $HEIGHT / $RATIO if ( $HEIGHT > $WIDTH ) then set YSIZE = $XSIZE #%// Bert Kampes, 31-Mar-2005: changed to awk from bc #set XSIZE = `echo "scale=3; $WIDTH/$HEIGHT*$YSIZE" | bc -l` set XSIZE = `echo "$WIDTH $HEIGHT $YSIZE" | $AWK '{printf "%f", $1 / $2 * $3}'` else #%// Bert Kampes, 31-Mar-2005: changed to awk from bc #set YSIZE = `echo "scale=3; $HEIGHT/$WIDTH*$XSIZE" | bc -l` set YSIZE = `echo "$HEIGHT $WIDTH $XSIZE" | $AWK '{printf "%f", $1 / $2 * $3}'` endif echo " *** Size plot (x,y): $XSIZE $YSIZE" set SIZE = "-JX$XSIZE/$YSIZE" ###################################################################### ### First plot background if requested. # for now, otherwize error set GRDFILE = $$.grd set CPTFILE = $$.cpt if ( $DOBG ) then echo " *** Making background plot..." set SUBX = "1" set SUBY = "1" # try to limit tmp GRDFILE to 10MB (2.500.000 binary float pixels) if ( $NUMPIXS > 10000000 ) then # eg. 25.000 * 5.000 set SUBY = "15" # else > 10MB tmpfile set SUBX = "3" # else > 10MB tmpfile else if ( $NUMPIXS > 5000000 ) then # eg. 10.000 * 5000 set SUBY = "10" # else > 10MB tmpfile set SUBX = "2" # else > 10MB tmpfile else if ( $NUMPIXS > 1250000 ) then # eg. 1500 * 5000 set SUBY = "5" endif echo " *** Subsampling data with factors (x,y): $SUBX $SUBY" # # assume total file has to be plotted (call from Doris...) #echo \\n" Mirroring in horiz, rather do it with GMT, but how?" : -Jx/-y ! set PROG = "cpxfiddle -w$WIDTH -f$SLCFORMAT -qmag -e0.2 -ofloat -M$SUBX/$SUBY -- $SLCFILE" # correct for GMT, subsampling output = ceil ((P-p+1)/sub) # outputlines after subsampling = ceil((P-p+1)/sub) #subsampling #set NUMX = `echo "$P0 $PN $SUBX" | $AWK '{printf "%i", ($2-$1)/$3+1}'` #set NUMY = `echo "$L0 $LN $SUBY" | $AWK '{printf "%i", ($2-$1)/$3+1}'` #multilooking set NUMX = `echo "$P0 $PN $SUBX" | $AWK '{print int(($2-$1+1)/$3)}'` set NUMY = `echo "$L0 $LN $SUBY" | $AWK '{print int(($2-$1+1)/$3)}'` echo " *** Number of output pixels (x,y): $NUMX $NUMY" #set EAST = `echo "$P0+($NUMX-1)*$SUBX" | bc -l` #set NORTH = `echo "$L0+($NUMY-1)*$SUBY" | bc -l` #%// Bert Kampes, 31-Mar-2005: changed to awk from bc set EAST = `echo "$P0 $NUMX $SUBX" | $AWK '{printf "%f", $1 + ( $2 - 1 ) * $3}'` set NORTH = `echo "$L0 $NUMY $SUBY" | $AWK '{printf "%f", $1 + ( $2 - 1 ) * $3}'` set BKRANGE = "-R$P0/$EAST/$L0/$NORTH" echo " *** GMT range: $BKRANGE" set GRDFILE = $$.grd set INC = "-I$SUBX/$SUBY" set IFORMAT = "-Zf" # binary float values echo " Calling: $PROG | xyz2grd -G$GRDFILE $BKRANGE $INC $IFORMAT" $PROG | xyz2grd -G$GRDFILE $BKRANGE $INC $IFORMAT # set CPTFILE = $$.cpt set CPTNAME = gray echo " Calling: grd2cpt $GRDFILE -C$CPTNAME -Z >! $CPTFILE" grd2cpt $GRDFILE -C$CPTNAME -Z >! $CPTFILE # # lower left is O of coord. system, while upperleft for grd file -> mirror horiz. #OK.. grdimage $GRDFILE $SIZE -C$CPTFILE -P -K -T >! $PSFILE # T slow, large: grdimage $GRDFILE $SIZE -C$CPTFILE -P -K -T >! $PSFILE set BKSIZE = "-JX$XSIZE/-$YSIZE" echo " Calling: grdimage $GRDFILE $BKSIZE -C$CPTFILE -P -K >! $PSFILE" grdimage $GRDFILE $BKSIZE -C$CPTFILE -P -K >! $PSFILE # Tidy tidy tidy echo " removing grdfile, cptfile: $GRDFILE $CPTFILE" rm -f $GRDFILE rm -f $CPTFILE # Set Overlay for next if this was first, else initialize new plot system set GMTFLAGS = "-K -O -N $GENOPT $RANGE $FRAME $SIZE -U -Sc -W6/255/0/0" else set GMTFLAGS = "-K -N $GENOPT $RANGE $FRAME $SIZE -U -Sc -W6/255/0/0" endif ###################################################################### ### Plot the location circles, where correl=size. echo " +++ Plotting location circles, size (cm) is correlation +++" $AWK '{print $2, $3, $6}' $TMPFILE | psxy $GMTFLAGS >> $PSFILE # set GMTFLAGS = "-K -O -N $GENOPT $RANGE $SIZE -Sc -W6/255/0/0" echo " +++ Plotting legenda circle +++" echo "$L0 $P0 1.0" | psxy -X-1.0 -Y-1.0 $GMTFLAGS >> $PSFILE echo "$L0 $P0 0.5" | psxy -Y-0.25 $GMTFLAGS >> $PSFILE #pstext:(x, y, size, angle, fontno, justify, text) set GMTFLAGS = "-K -O -N $GENOPT $RANGE $SIZE" echo "$L0 $P0 12 0 0 CM correlation" | pstext -Y1.0 $GMTFLAGS >> $PSFILE echo "$L0 $P0 12 0 0 LM 1.0" | pstext -X0.5 -Y-0.5 $GMTFLAGS >> $PSFILE echo "$L0 $P0 12 0 0 LM 0.5" | pstext -Y-0.5 $GMTFLAGS >> $PSFILE ###################################################################### ### Plot normalized offset vectors. # -G fill # -Sv arrowwidth/headlength/headwidth [0.075c/0.3c/0.25c] set GMTFLAGS = "-N -O -K -X0.5 -Y1.25 $GENOPT $RANGE $SIZE -Sv0.04/0.25/0.125 -G0/0/255 -W2/0/0/255" # echo "START STDL computation" set MINL = `$AWK 'NR==1{m=$4}$4m{m=$4}END{print m}'<$TMPFILE` set MEANL = `$AWK '{s += $4}END{printf "%f", s/NR}'<$TMPFILE` # set MEANL = $MINL # Lennert set STDL = `$AWK '{sq += ( $4 - '$MEANL' ) * ( $4 - '$MEANL' )};END{printf "%f", sq / ( NR - 1 )}'<$TMPFILE` #set STDL = `$AWK -v m=$MEANL '{sq+=($4-m)*($4-m)};END{print sq/(NR-1)}'<$TMPFILE` # echo "START STDP computation" set MINP = `$AWK 'NR==1{m=$5}$5m{m=$5}END{print m}'<$TMPFILE` set MEANP = `$AWK '{s += $5}END{printf "%f", s / NR}'<$TMPFILE` # set MEANP = $MINP # Lennert set STDP = `$AWK '{sq += ( $5 - '$MEANP' ) * ( $5 - '$MEANP' )};END{printf "%f", sq / ( NR - 1 )}'<$TMPFILE` #set STDP = `$AWK -v m=$MEANP '{sq+=($5-m)*($5-m)};END{print sq/(NR-1)}'<$TMPFILE` echo " *** min, max, mean, std (line): $MINL $MAXL $MEANL $STDL" echo " *** min, max, mean, std (pixel): $MINP $MAXP $MEANP $STDP" ###################################################################### ### Normalize vectors by subtracting mean-2: ### plot arrows as they are, normalized by max length ? (always longest==3cm?) #no cause then offset 1000 <> 1001 is no difference while it is the same as 10<>11 # thus scale length by l-max echo " *** Normalizing offset line by subtracting: $MEANL - 1" echo " *** Normalizing offset pixel by subtracting: $MEANP - 1" # #$AWK -v wl=$MEANL -v wp=$MEANP \ # '{ \ # {l=$4-wl-1.} \ # {p=$5-wp-1.} \ echo "start psxy vector drawing" # {dir=57.3*atan2(l,p)} \ # possibly gawk or nawk define atan2, not standard awk... $AWK '{{l = $4 - '$MEANL' - 1.0 }{p = $5 - '$MEANP' - 1.0 } \ {l = l + 0.0000001} {p = p + 0.0000001} \ {dir = 57.3 * atan2(l,p)} \ {scale = 1.5} \ {len = scale * sqrt ( l * l + p * p )} \ {printf "%.1f %.1f %.1f %.1f\n", $2, $3, dir, len} \ }' \ $TMPFILE | \ psxy $GMTFLAGS >> $PSFILE echo "...finished psxy vector drawing" ### Print info on points as text (# offl offp). set GMTFLAGS = "-M -Wo -D0/2.5 -O -N -K $GENOPT $RANGE $SIZE" echo "> $LN $P0 8 0 0 LB 0.4 15 l" >! $TMPFILE.2 $AWK '{printf "@;255/0/0; @:10: %4.0i @;0/0/0; @:8: (%4.2f;%4.2f) - \n", $1,$4,$5}' $TMPFILE >> $TMPFILE.2 # Avoid overflow with head. head -n 60 $TMPFILE.2 | pstext $GMTFLAGS >> $PSFILE rm -f $TMPFILE.2 ### Add the window numbers (last overlay, no -K (close plot system)). #pstext: (x, y, size(pts), angle(ccw), fontno, justify, text) set GMTFLAGS = "-O -N -G0/0/0 $GENOPT $RANGE $SIZE" echo " Calling: pstext $GMTFLAGS >> $PSFILE" #green, 14pts, RightTop BottomLeft $AWK '{printf "%.1f %.1f 10 0 0 RT %s\n", $2, $3, $1}' $TMPFILE | pstext $GMTFLAGS >> $PSFILE # calls from Doris, cannot interactive... #%// BK 19-Jul-2000 echo " Calling: viewanddel" rm -f $TMPFILE $GRDFILE $CPTFILE viewanddel $PSFILE ### EOF Doris-5.0.3Beta/bin/plotoffsets.bruno000077500000000000000000000415471312547014700176040ustar00rootroot00000000000000#!/bin/csh -f # Changed this to csh -f. The -f option has been added after a # report that this script failed for a tcsh user who had a .cshrc file. # For Cygwin users, link your tcsh to csh, i.e., ln -s /bin/tcsh /bin/csh, # or obtain a regular csh from somewhere. #%// BK 27-Apr-2002 # # plotoffsets for gmt3-3 # used by Doris software for plotting of offset vectors after fine. # plotting magnitude background may require some diskspace # (subx, suby..) # bg assumed to be in one file, size=(width*height); width=pN-p0+1 # BK 16-May-2000 # sleeps & calls viewanddel instead of gv, for Doris software. #%// BK 19-Jul-2000 ### RCS info ##### #%// BK 17-May-2000 #%// $Revision: 3.12 $ $Date: 2003/09/01 11:38:00 $ ################ ################ # TODO: # -plot unit offset vectors # (this is pretty difficult, since normalized, what to plot, added it # in plotcpm for error vectors, bk 15 mar01) #%// BK 19-Jul-2000 ### Handle input. # give doris time to write result file sleep 1 set PRG = `basename "$0"` set VER = "v1.0, FMR software" set AUT = "Bert Kampes, (c)1999-2001" echo "$PRG $VER, $AUT" echo " " ### set USAGE = "0" #synopsis set HELP = "0" #exit afterwards set IFILE = "interferogram.out" # arg 1 default # args 2:5 (default) file dimension (plot dim.) @ L0 = 1 @ LN = 25000 @ P0 = 1 @ PN = 4900 set THRESHOLD = "0.4" # arg6 default set SLCFILE = "" # arg7 optional set SLCFORMAT = "" set DOBG = "0" # default (not possible w/o l0,lN,p0,pN switch ( $#argv ) case '7': set DOBG = "1" set SLCFILE = "$7" # ||| fall through ||| # case '6': set THRESHOLD = "$6" # ||| fall through ||| # case '5': @ L0 = $2 @ LN = $3 @ P0 = $4 @ PN = $5 # ||| fall through ||| # case '2': case '1': set IFILE = $1 breaksw # --- no fall through --- # default: set HELP = "1" endsw if ( $#argv == 2) set THRESHOLD = "$2" # Check input if ( ! -r "$IFILE" ) then echo " input file: $IFILE cannot be read." set HELP = "1" endif # Check if something went wrong set MORE = more; less >& /dev/null if ( $status == 0 ) set MORE = 'less -de' echo "Using as pager program: $MORE" if ( $HELP ) set USAGE = "1" if ( $USAGE ) then #cat << __EOF_USAGE | more -d cat << __EOF_USAGE | $MORE ----------------------------------------------------------------------- $PRG -- Program to plot offset vectors from Doris Position, correlation, and background image can be plotted. SYNOPSIS: $PRG ifile [linelo hi pixlo hi [threshold [slcfile]]] ifile: Resultfile from Doris [mandatory arg] linelo: First azimuth line. [default: 1] linehi: Last azimuth line. [default: 25000] pixlo: First range pixel. [default: 1] pixhi: Last range pixel. [default: 4900] threshold: Only plot estimated with correlation above threshold. [default: 0.4] slcfile: Complex raw file. Magnitude is used as background image. (format can be complex real4 or short int.) EXAMPLE: $PRG interferogram.out 1 25000 1 4900 0.4 slcfile.raw PROG may depend on gawk or nawk and not work with std awk... ----------------------------------------------------------------------- __EOF_USAGE endif if ( $HELP ) then #cat << __EOF_HELP | more -de cat << __EOF_HELP | $MORE ifile is the interferogram result file from the Doris software, see this script for details. Somewhere the fine output section should be present, containing lines such as: ******************************************************************* *_Start_fine_coreg ******************************************************************* Oversampling factor: 16 Number_of_correlation_windows: 100 Number posL posP offsetL offsetP correlation 0 27 27 241.06 3.19 0.42 1 27 127 241.36 3.29 0.72 ... 99 4733 971 241.86 3.50 0.48 ******************************************************************* * End_fine_coreg:_NORMAL ******************************************************************* See also: cpxfiddle, GMT. __EOF_HELP exit -1 endif ### Initialize variables set TMPDIR = "." if ( ! -w "$TMPDIR" ) then set TMPDIR = "/tmp" endif if ( ! -w "$TMPDIR" ) then echo "Sorry, directory $TMPDIR seems not writable, exiting." exit -2 endif set PSFILE = $TMPDIR/tmpplot.ps set TMPFILE = $TMPDIR/tmpdata.plot rm -f $PSFILE $TMPFILE ### ifile is transformed to tmpfile with columns: # 1: window number # 2: location x # 3: location y # 4: offset x # 5: offset y # 6: correlation ### Create tmpfile with only data: grep fine section with awk and ### remove trailing comment lines (5) and tailing comment (2) ### ###1: *_Start_fine_coreg ###2: ******************************************************************* ###3: Oversampling factor: 16 ###4: Number_of_correlation_windows: 100 ###5: Number posL posP offsetL offsetP correlation ###6: 0 27 27 241.06 3.19 0.42 ### ... ###x: 99 4733 971 241.06 3.50 0.41 ###x+1: ###x+2: ******************************************************************* ###x+3: * End_fine_coreg:_NORMAL ###x+4: ******************************************************************* ### # ###################################################################### ### find out if nawk is available, since awk seems not to know atan2? set AWK = awk; echo 1 | /usr/xpg4/bin/awk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = '/usr/xpg4/bin/awk' echo 1 | gawk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = 'gawk' echo 1 | nawk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = 'nawk' echo "Using as awk program: $AWK" ###################################################################### ### 1. Grep between start stop pair: echo "TMPFILE BEING GENERATED: step1" $AWK '/Start_fine/, /End_fine/' $IFILE >! $TMPFILE.$$ ### 2. Get number of points (starting at window 0): @ NUMPOINTS = `$AWK '/Number_of/ {print $2}' $TMPFILE.$$` #### 3. Reduce file only to data: #tail -n +6 $TMPFILE.$$ | head -n $NUMPOINTS >! $TMPFILE #### 4. Remove above threshold (here is most easy...) #$AWK -v t=$THRESHOLD '$6>=t' $TMPFILE >! $TMPFILE.$$ #mv -f $TMPFILE.$$ $TMPFILE # #%// BK 25-Sep-2001: following bug report by Irek Baran. echo "TMPFILE BEING GENERATED: step2" #$AWK -v n=$NUMPOINTS -v t=$THRESHOLD '{if(NR>5&&NRt){print $0}}}' $TMPFILE.$$ > $TMPFILE #rm -f $TMPFILE.$$ #test how to pass arguments. failsave seems to be: #echo 111 | $AWK '{print '$t'}' #%// BK 16-Jun-2003 $AWK '{if(NR>5&&NR<'$NUMPOINTS'+6){if ($6>'$THRESHOLD'){print $0}}}' $TMPFILE.$$ > $TMPFILE rm -f $TMPFILE.$$ echo "TMPFILE GENERATED" ### Check if we have points ########################################## @ NP = `$AWK '{l=NR};END{print l}' $TMPFILE` echo "$NP points above coherence threshold $THRESHOLD found." if ( $NP < 1 ) then echo "exiting..." rm -f $TMPFILE exit endif ###################################################################### ### Plot: location of windows / wtests # plotted are: # - normalized observations (offsets) # - optionally background of magnitude image # - correlation as circles (legenda... o=1), thickness arrow? ###################################################################### echo "Setting GMT defaults" # PAPER_MEDIA a4+ \ gmtset MEASURE_UNIT cm \ PAPER_MEDIA a4 \ PAGE_ORIENTATION portrait \ ANOT_FONT Helvetica \ ANOT_FONT_SIZE 10p \ ANOT_OFFSET 0.2 \ BASEMAP_AXES WeSn \ LABEL_FONT Helvetica \ LABEL_FONT_SIZE 10 \ UNIX_TIME_POS -2/-2 \ D_FORMAT %lg ###################################################################### ### Labeling of axis. echo " +++ Plotting the observed offset vectors (normalized) +++" set TITLE = "Offset_vectors_(Corr_>_$THRESHOLD)" set XLABEL = "Azimuth" set YLABEL = "Range" # height=y=azimuth, assume 5*stretched @ WIDTH = ( ( $PN - $P0 ) + 1) @ HEIGHT = ( ( $LN - $L0 ) + 1) set SLCFORMAT = "cr4" if ( $DOBG ) then # filewidth should be used, but is equal... @ SIZECI2 = $WIDTH * $HEIGHT * 4 @ SIZECR4 = $WIDTH * $HEIGHT * 8 set FSIZE = `ls -l $SLCFILE | $AWK '{print $5}'` if ( $FSIZE == $SIZECI2 ) then echo " *** File format ${SLCFILE}: complex short." set SLCFORMAT = ci2 else if ( $FSIZE == $SIZECR4 ) then echo " *** File format ${SLCFILE}: complex float." set SLCFORMAT = cr4 else echo " *** Sorry, no background, file format could not be determined." set DOBG = "0" endif endif ###################################################################### # GMT options @ TICKSL = $HEIGHT / 7 @ TICKSP = $WIDTH / 7 set RANGE = "-R$P0/$PN/$L0/$LN" set GENOPT = "-P -: " set FRAME = "-B"$TICKSP":"$YLABEL":/"$TICKSL":"$XLABEL"::."$TITLE":" set XSIZE = "16" set YSIZE = "0" @ NUMPIXS = ( $WIDTH * $HEIGHT ) # size paper, largest size $XSIZE # actually should go to landscape in that case... # strict stretching ERS1/2 only... set RATIO = "5" @ HEIGHT = $HEIGHT / $RATIO if ( $HEIGHT > $WIDTH ) then set YSIZE = $XSIZE set XSIZE = `echo "scale=3; $WIDTH/$HEIGHT*$YSIZE" | bc -l` else set YSIZE = `echo "scale=3; $HEIGHT/$WIDTH*$XSIZE" | bc -l` endif echo " *** Size plot (x,y): $XSIZE $YSIZE" set SIZE = "-JX$XSIZE/$YSIZE" ###################################################################### ### First plot background if requested. # for now, otherwize error set GRDFILE = $$.grd set CPTFILE = $$.cpt if ( $DOBG ) then echo " *** Making background plot..." set SUBX = "1" set SUBY = "1" # try to limit tmp GRDFILE to 10MB (2.500.000 binary float pixels) if ( $NUMPIXS > 10000000 ) then # eg. 25.000 * 5.000 set SUBY = "15" # else > 10MB tmpfile set SUBX = "3" # else > 10MB tmpfile else if ( $NUMPIXS > 5000000 ) then # eg. 10.000 * 5000 set SUBY = "10" # else > 10MB tmpfile set SUBX = "2" # else > 10MB tmpfile else if ( $NUMPIXS > 1250000 ) then # eg. 1500 * 5000 set SUBY = "5" endif echo " *** Subsampling data with factors (x,y): $SUBX $SUBY" # # assume total file has to be plotted (call from Doris...) #echo \\n" Mirroring in horiz, rather do it with GMT, but how?" : -Jx/-y ! set PROG = "cpxfiddle -w$WIDTH -f$SLCFORMAT -qmag -e0.2 -ofloat -M$SUBX/$SUBY -- $SLCFILE" # correct for GMT, subsampling output = ceil ((P-p+1)/sub) # outputlines after subsampling = ceil((P-p+1)/sub) #subsampling #set NUMX = `echo "$P0 $PN $SUBX" | $AWK '{printf "%i", ($2-$1)/$3+1}'` #set NUMY = `echo "$L0 $LN $SUBY" | $AWK '{printf "%i", ($2-$1)/$3+1}'` #multilooking set NUMX = `echo "$P0 $PN $SUBX" | $AWK '{print int(($2-$1+1)/$3)}'` set NUMY = `echo "$L0 $LN $SUBY" | $AWK '{print int(($2-$1+1)/$3)}'` echo " *** Number of output pixels (x,y): $NUMX $NUMY" set EAST = `echo "$P0+($NUMX-1)*$SUBX" | bc -l` set NORTH = `echo "$L0+($NUMY-1)*$SUBY" | bc -l` set BKRANGE = "-R$P0/$EAST/$L0/$NORTH" echo " *** GMT range: $BKRANGE" set GRDFILE = $$.grd set INC = "-I$SUBX/$SUBY" set IFORMAT = "-Zf" # binary float values echo " Calling: $PROG | xyz2grd -G$GRDFILE $BKRANGE $INC $IFORMAT" $PROG | xyz2grd -G$GRDFILE $BKRANGE $INC $IFORMAT # set CPTFILE = $$.cpt set CPTNAME = gray echo " Calling: grd2cpt $GRDFILE -C$CPTNAME -Z >! $CPTFILE" grd2cpt $GRDFILE -C$CPTNAME -Z >! $CPTFILE # # lower left is O of coord. system, while upperleft for grd file -> mirror horiz. #OK.. grdimage $GRDFILE $SIZE -C$CPTFILE -P -K -T >! $PSFILE # T slow, large: grdimage $GRDFILE $SIZE -C$CPTFILE -P -K -T >! $PSFILE set BKSIZE = "-JX$XSIZE/-$YSIZE" echo " Calling: grdimage $GRDFILE $BKSIZE -C$CPTFILE -P -K >! $PSFILE" grdimage $GRDFILE $BKSIZE -C$CPTFILE -P -K >! $PSFILE # Tidy tidy tidy echo " removing grdfile, cptfile: $GRDFILE $CPTFILE" rm -f $GRDFILE rm -f $CPTFILE # Set Overlay for next if this was first, else initialize new plot system set GMTFLAGS = "-K -O -N $GENOPT $RANGE $FRAME $SIZE -U -Sc -W6/255/0/0" else set GMTFLAGS = "-K -N $GENOPT $RANGE $FRAME $SIZE -U -Sc -W6/255/0/0" endif ###################################################################### ### Plot the location circles, where correl=size. echo " +++ Plotting location circles, size (cm) is correlation +++" $AWK '{print $2, $3, $6}' $TMPFILE | psxy $GMTFLAGS >> $PSFILE # set GMTFLAGS = "-K -O -N $GENOPT $RANGE $SIZE -Sc -W6/255/0/0" echo " +++ Plotting legenda circle +++" echo "$L0 $P0 1.0" | psxy -X-1.0 -Y-1.0 $GMTFLAGS >> $PSFILE echo "$L0 $P0 0.5" | psxy -Y-0.25 $GMTFLAGS >> $PSFILE #pstext:(x, y, size, angle, fontno, justify, text) set GMTFLAGS = "-K -O -N $GENOPT $RANGE $SIZE" echo "$L0 $P0 12 0 0 CM correlation" | pstext -Y1.0 $GMTFLAGS >> $PSFILE echo "$L0 $P0 12 0 0 LM 1.0" | pstext -X0.5 -Y-0.5 $GMTFLAGS >> $PSFILE echo "$L0 $P0 12 0 0 LM 0.5" | pstext -Y-0.5 $GMTFLAGS >> $PSFILE ###################################################################### ### Plot normalized offset vectors. # -G fill # -Sv arrowwidth/headlength/headwidth [0.075c/0.3c/0.25c] set GMTFLAGS = "-N -O -K -X0.5 -Y1.25 $GENOPT $RANGE $SIZE -Sv0.04/0.25/0.125 -G0/0/255 -W2/0/0/255" # echo "START STDL computation" set MINL = `$AWK 'NR==1{m=$4}$4m{m=$4}END{print m}'<$TMPFILE` set MEANL = `$AWK '{s += $4}END{printf "%f", s/NR}'<$TMPFILE` set STDL = `$AWK '{sq += ( $4 - '$MEANL' ) * ( $4 - '$MEANL' )};END{printf "%f", sq / ( NR - 1 )}'<$TMPFILE` #set STDL = `$AWK -v m=$MEANL '{sq+=($4-m)*($4-m)};END{print sq/(NR-1)}'<$TMPFILE` # echo "START STDP computation" set MINP = `$AWK 'NR==1{m=$5}$5m{m=$5}END{print m}'<$TMPFILE` set MEANP = `$AWK '{s += $5}END{printf "%f", s / NR}'<$TMPFILE` set STDP = `$AWK '{sq += ( $5 - '$MEANP' ) * ( $5 - '$MEANP' )};END{printf "%f", sq / ( NR - 1 )}'<$TMPFILE` #set STDP = `$AWK -v m=$MEANP '{sq+=($5-m)*($5-m)};END{print sq/(NR-1)}'<$TMPFILE` echo " *** min, max, mean, std (line): $MINL $MAXL $MEANL $STDL" echo " *** min, max, mean, std (pixel): $MINP $MAXP $MEANP $STDP" set MIND = `$AWK 'NR==1{m=sqrt( $4 * $4 + $5 * $5 )}sqrt( $4 * $4 + $5 * $5 ) 1001 is no difference while it is the same as 10<>11 # thus scale length by l-max echo " *** Normalizing offset line by subtracting: $MEANL - 1" echo " *** Normalizing offset pixel by subtracting: $MEANP - 1" # #$AWK -v wl=$MEANL -v wp=$MEANP \ # '{ \ # {l=$4-wl-1.} \ # {p=$5-wp-1.} \ echo "start psxy vector drawing" # {dir=57.3*atan2(l,p)} \ # possibly gawk or nawk define atan2, not standard awk... #$AWK '{{l = $4 - '$MEANL' - 1.0 }{p = $5 - '$MEANP' - 1.0 } \ # {l = l + 0.0000001} {p = p + 0.0000001} \ # {dir = 57.3 * atan2(l,p)} \ #$AWK '{{l = $4 - '$MEANL' - 1.0 }{p = $5 - '$MEANP' - 1.0 } \ # {l = l + 0.0000001} {p = p + 0.0000001} \ # {dir = 57.3 * atan2($4,$5)} \ # {scale = 1.5} \ # {len = scale * sqrt ( l * l + p * p )} \ # {printf "%.1f %.1f %.1f %.1f\n", $2, $3, dir, len} \ # }' \ # $TMPFILE | \ # psxy $GMTFLAGS >> $PSFILE $AWK '{{dir = 57.3 * atan2($4,$5)} \ {len = sqrt ( $4 * $4 + $5 * $5 )} \ {len = len + 1 - '$MIND'} \ {printf "%.1f %.1f %.1f %.1f\n", $2, $3, dir, len} \ }' \ $TMPFILE | \ psxy $GMTFLAGS >> $PSFILE echo "...finished psxy vector drawing" ### Print info on points as text (# offl offp). set GMTFLAGS = "-M -Wo -D0/2.5 -O -N -K $GENOPT $RANGE $SIZE" echo "> $LN $P0 8 0 0 LB 0.4 15 l" >! $TMPFILE.2 $AWK '{printf "@;255/0/0; @:10: %4.0i @;0/0/0; @:8: (%4.2f;%4.2f) - \n", $1,$4,$5}' $TMPFILE >> $TMPFILE.2 # Avoid overflow with head. head -n 60 $TMPFILE.2 | pstext $GMTFLAGS >> $PSFILE rm -f $TMPFILE.2 ### Add the window numbers (last overlay, no -K (close plot system)). #pstext: (x, y, size(pts), angle(ccw), fontno, justify, text) set GMTFLAGS = "-O -N -G0/0/0 $GENOPT $RANGE $SIZE" echo " Calling: pstext $GMTFLAGS >> $PSFILE" #green, 14pts, RightTop BottomLeft $AWK '{printf "%.1f %.1f 10 0 0 RT %s\n", $2, $3, $1}' $TMPFILE | pstext $GMTFLAGS >> $PSFILE # calls from Doris, cannot interactive... #%// BK 19-Jul-2000 echo " Calling: viewanddel" #rm -f $TMPFILE $GRDFILE $CPTFILE viewanddel $PSFILE ### EOF Doris-5.0.3Beta/bin/plotoffsets_cc000077500000000000000000000407661312547014700171270ustar00rootroot00000000000000#!/bin/csh -f # plotoffsets_cc for gmt3-3 # used by Doris software for plotting of offset vectors after coarse coregistration. # plotting magnitude background may require some diskspace # (subx, suby..) # bg assumed to be in one file, size=(width*height); width=pN-p0+1 # # AO: Adapted for coarse correlation step # # Developers: # Bert Kampes # Anneleen Oyen ################ ################ ### Handle input. # give doris time to write result file sleep 1 set PRG = `basename "$0"` set VER = "v1.0, FMR software" set AUT = "TUDelft, (c) 1999-2010" echo "$PRG $VER, $AUT" echo " " ### set USAGE = "0" #synopsis set HELP = "0" #exit afterwards set IFILE = "interferogram.out" # arg 1 default # args 2:5 (default) file dimension (plot dim.) @ L0 = 1 @ LN = 25000 @ P0 = 1 @ PN = 4900 set THRESHOLD = "0.4" # arg6 default set SLCFILE = "" # arg7 optional set SLCFORMAT = "" set DOBG = "0" # default (not possible w/o l0,lN,p0,pN switch ( $#argv ) case '7': set DOBG = "1" set SLCFILE = "$7" # ||| fall through ||| # case '6': set THRESHOLD = "$6" # ||| fall through ||| # case '5': @ L0 = $2 @ LN = $3 @ P0 = $4 @ PN = $5 # ||| fall through ||| # case '2': case '1': set IFILE = $1 breaksw # --- no fall through --- # default: set HELP = "1" endsw if ( $#argv == 2) set THRESHOLD = "$2" # Check input if ( ! -r "$IFILE" ) then echo " input file: $IFILE cannot be read." set HELP = "1" endif # Check if something went wrong set MORE = more; less >& /dev/null if ( $status == 0 ) set MORE = 'less -de' echo "Using as pager program: $MORE" if ( $HELP ) set USAGE = "1" if ( $USAGE ) then #cat << __EOF_USAGE | more -d cat << __EOF_USAGE | $MORE ----------------------------------------------------------------------- $PRG -- Program to plot offset vectors from Doris Position, correlation, and background image can be plotted. SYNOPSIS: $PRG ifile [linelo hi pixlo hi [threshold [slcfile]]] ifile: Resultfile from Doris [mandatory arg] linelo: First azimuth line. [default: 1] linehi: Last azimuth line. [default: 25000] pixlo: First range pixel. [default: 1] pixhi: Last range pixel. [default: 4900] threshold: Only plot estimated with correlation above threshold. [default: 0.4] slcfile: Complex raw file. Magnitude is used as background image. (format can be complex real4 or short int.) EXAMPLE: $PRG interferogram.out 1 25000 1 4900 0.4 slcfile.raw PROG may depend on gawk or nawk and not work with std awk... ----------------------------------------------------------------------- __EOF_USAGE endif if ( $HELP ) then #cat << __EOF_HELP | more -de cat << __EOF_HELP | $MORE ifile is the interferogram result file from the Doris software, see this script for details. Somewhere the coarse coregistration output section should be present, containing lines such as: ******************************************************************* *_Start_coarse_correl: ******************************************************************* Estimated translation slave w.r.t. master: Coarse_correlation_translation_lines: -2 Coarse_correlation_translation_pixels: -4 Number of correlation windows: 21 of 21 center(l,p) coherence offsetL offsetP 0 1532 248 0.391786 -2 -3 1 1532 2805 0.381579 -2 -4 ... 20 25217 5361 0.581629 -2 -4 ******************************************************************* * End_coarse_correl:_NORMAL ******************************************************************* See also: cpxfiddle, GMT. __EOF_HELP exit -1 endif ### Initialize variables set TMPDIR = "." if ( ! -w "$TMPDIR" ) then set TMPDIR = "/tmp" endif if ( ! -w "$TMPDIR" ) then echo "Sorry, directory $TMPDIR seems not writable, exiting." exit -2 endif set PSFILE = $TMPDIR/tmpplot.ps set TMPFILE = $TMPDIR/tmpdata.plot rm -f $PSFILE $TMPFILE ### ifile is transformed to tmpfile with columns: # 1: window number # 2: location x # 3: location y # 4: offset x # 5: offset y # 6: correlation ### Create tmpfile with only data: grep fine section with awk and ### remove trailing comment lines (5) and tailing comment (2) ### ###1: *_Start_fine_coreg ###2: ******************************************************************* ###3: Oversampling factor: 16 ###4: Number_of_correlation_windows: 100 ###5: Number posL posP offsetL offsetP correlation ###6: 0 27 27 241.06 3.19 0.42 ### ... ###x: 99 4733 971 241.06 3.50 0.41 ###x+1: ###x+2: ******************************************************************* ###x+3: * End_fine_coreg:_NORMAL ###x+4: ******************************************************************* ### # ###################################################################### ### find out if nawk is available, since awk seems not to know atan2? set AWK = awk; echo 1 | /usr/xpg4/bin/awk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = '/usr/xpg4/bin/awk' echo 1 | gawk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = 'gawk' echo 1 | nawk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = 'nawk' echo "Using as awk program: $AWK" ###################################################################### ### 1. Grep between start stop pair: echo "TMPFILE BEING GENERATED: step1" $AWK '/Start_coarse_correl/, /End_coarse_correl/' $IFILE >! $TMPFILE.$$ #echo $AWK ### 2. Get number of points (starting at window 0): @ NUMPOINTS = `$AWK '/Number of correlation windows/ {print $5}' $TMPFILE.$$` #echo NUMPOINTS=$NUMPOINTS #### 3. Reduce file only to data: #tail -n +6 $TMPFILE.$$ | head -n $NUMPOINTS >! $TMPFILE #### 4. Remove above threshold (here is most easy...) #$AWK -v t=$THRESHOLD '$6>=t' $TMPFILE >! $TMPFILE.$$ #mv -f $TMPFILE.$$ $TMPFILE # #%// BK 25-Sep-2001: following bug report by Irek Baran. echo "TMPFILE BEING GENERATED: step2" #$AWK -v n=$NUMPOINTS -v t=$THRESHOLD '{if(NR>5&&NRt){print $0}}}' $TMPFILE.$$ > $TMPFILE #rm -f $TMPFILE.$$ #test how to pass arguments. failsave seems to be: #echo 111 | $AWK '{print '$t'}' #%// BK 16-Jun-2003 #$AWK '{if(NR>5&&NR<'$NUMPOINTS'+6){if ($6>'$THRESHOLD'){print $0}}}' $TMPFILE.$$ > $TMPFILE # v3.16: more info lines in resfile, skip more. $AWK '{if(NR>8&&NR<'$NUMPOINTS'+9){if ($4>'$THRESHOLD'){print $0}}}' $TMPFILE.$$ > $TMPFILE #rm -f $TMPFILE.$$ echo "TMPFILE GENERATED" ### Check if we have points ########################################## @ NP = `$AWK '{l=NR};END{print l}' $TMPFILE` echo "$NP points above coherence threshold $THRESHOLD found." if ( $NP < 1 ) then echo "exiting..." rm -f $TMPFILE exit endif ###################################################################### ### Plot: location of windows / wtests # plotted are: # - normalized observations (offsets) # - optionally background of magnitude image # - correlation as circles (legenda... o=1), thickness arrow? ###################################################################### echo "Setting GMT defaults" # PAPER_MEDIA a4+ \ gmtset MEASURE_UNIT cm \ PAPER_MEDIA a4 \ PAGE_ORIENTATION portrait \ ANOT_FONT Helvetica \ ANOT_FONT_SIZE 10p \ ANOT_OFFSET 0.2 \ BASEMAP_AXES WeSn \ LABEL_FONT Helvetica \ LABEL_FONT_SIZE 10 \ UNIX_TIME_POS -2/-2 \ D_FORMAT %lg ###################################################################### ### Labeling of axis. echo " +++ Plotting the observed offset vectors (normalized) +++" set TITLE = "Offset_vectors_(Corr_>_$THRESHOLD)" set XLABEL = "Azimuth" set YLABEL = "Range" # height=y=azimuth, assume 5*stretched @ WIDTH = ( ( $PN - $P0 ) + 1) @ HEIGHT = ( ( $LN - $L0 ) + 1) set SLCFORMAT = "cr4" if ( $DOBG ) then # filewidth should be used, but is equal... @ SIZECI2 = $WIDTH * $HEIGHT * 4 @ SIZECR4 = $WIDTH * $HEIGHT * 8 set FSIZE = `ls -l $SLCFILE | $AWK '{print $5}'` if ( $FSIZE == $SIZECI2 ) then echo " *** File format ${SLCFILE}: complex short." set SLCFORMAT = ci2 else if ( $FSIZE == $SIZECR4 ) then echo " *** File format ${SLCFILE}: complex float." set SLCFORMAT = cr4 else echo " *** Sorry, no background, file format could not be determined." set DOBG = "0" endif endif ###################################################################### # GMT options @ TICKSL = $HEIGHT / 7 @ TICKSP = $WIDTH / 7 set RANGE = "-R$P0/$PN/$L0/$LN" set GENOPT = "-P -: " set FRAME = "-B"$TICKSP":"$YLABEL":/"$TICKSL":"$XLABEL"::."$TITLE":" set XSIZE = "16" set YSIZE = "0" @ NUMPIXS = ( $WIDTH * $HEIGHT ) # size paper, largest size $XSIZE # actually should go to landscape in that case... # strict stretching ERS1/2 only... set RATIO = "5" @ HEIGHT = $HEIGHT / $RATIO if ( $HEIGHT > $WIDTH ) then set YSIZE = $XSIZE #%// Bert Kampes, 31-Mar-2005: changed to awk from bc #set XSIZE = `echo "scale=3; $WIDTH/$HEIGHT*$YSIZE" | bc -l` set XSIZE = `echo "$WIDTH $HEIGHT $YSIZE" | $AWK '{printf "%f", $1 / $2 * $3}'` else #%// Bert Kampes, 31-Mar-2005: changed to awk from bc #set YSIZE = `echo "scale=3; $HEIGHT/$WIDTH*$XSIZE" | bc -l` set YSIZE = `echo "$HEIGHT $WIDTH $XSIZE" | $AWK '{printf "%f", $1 / $2 * $3}'` endif echo " *** Size plot (x,y): $XSIZE $YSIZE" set SIZE = "-JX$XSIZE/$YSIZE" ###################################################################### ### First plot background if requested. # for now, otherwize error set GRDFILE = $$.grd set CPTFILE = $$.cpt if ( $DOBG ) then echo " *** Making background plot..." set SUBX = "1" set SUBY = "1" # try to limit tmp GRDFILE to 10MB (2.500.000 binary float pixels) if ( $NUMPIXS > 10000000 ) then # eg. 25.000 * 5.000 set SUBY = "15" # else > 10MB tmpfile set SUBX = "3" # else > 10MB tmpfile else if ( $NUMPIXS > 5000000 ) then # eg. 10.000 * 5000 set SUBY = "10" # else > 10MB tmpfile set SUBX = "2" # else > 10MB tmpfile else if ( $NUMPIXS > 1250000 ) then # eg. 1500 * 5000 set SUBY = "5" endif echo " *** Subsampling data with factors (x,y): $SUBX $SUBY" # # assume total file has to be plotted (call from Doris...) #echo \\n" Mirroring in horiz, rather do it with GMT, but how?" : -Jx/-y ! set PROG = "cpxfiddle -w$WIDTH -f$SLCFORMAT -qmag -e0.2 -ofloat -M$SUBX/$SUBY -- $SLCFILE" # correct for GMT, subsampling output = ceil ((P-p+1)/sub) # outputlines after subsampling = ceil((P-p+1)/sub) #subsampling #set NUMX = `echo "$P0 $PN $SUBX" | $AWK '{printf "%i", ($2-$1)/$3+1}'` #set NUMY = `echo "$L0 $LN $SUBY" | $AWK '{printf "%i", ($2-$1)/$3+1}'` #multilooking set NUMX = `echo "$P0 $PN $SUBX" | $AWK '{print int(($2-$1+1)/$3)}'` set NUMY = `echo "$L0 $LN $SUBY" | $AWK '{print int(($2-$1+1)/$3)}'` echo " *** Number of output pixels (x,y): $NUMX $NUMY" #set EAST = `echo "$P0+($NUMX-1)*$SUBX" | bc -l` #set NORTH = `echo "$L0+($NUMY-1)*$SUBY" | bc -l` #%// Bert Kampes, 31-Mar-2005: changed to awk from bc set EAST = `echo "$P0 $NUMX $SUBX" | $AWK '{printf "%f", $1 + ( $2 - 1 ) * $3}'` set NORTH = `echo "$L0 $NUMY $SUBY" | $AWK '{printf "%f", $1 + ( $2 - 1 ) * $3}'` set BKRANGE = "-R$P0/$EAST/$L0/$NORTH" echo " *** GMT range: $BKRANGE" set GRDFILE = $$.grd set INC = "-I$SUBX/$SUBY" set IFORMAT = "-Zf" # binary float values echo " Calling: $PROG | xyz2grd -G$GRDFILE $BKRANGE $INC $IFORMAT" $PROG | xyz2grd -G$GRDFILE $BKRANGE $INC $IFORMAT # set CPTFILE = $$.cpt set CPTNAME = gray echo " Calling: grd2cpt $GRDFILE -C$CPTNAME -Z >! $CPTFILE" grd2cpt $GRDFILE -C$CPTNAME -Z >! $CPTFILE # # lower left is O of coord. system, while upperleft for grd file -> mirror horiz. #OK.. grdimage $GRDFILE $SIZE -C$CPTFILE -P -K -T >! $PSFILE # T slow, large: grdimage $GRDFILE $SIZE -C$CPTFILE -P -K -T >! $PSFILE set BKSIZE = "-JX$XSIZE/-$YSIZE" echo " Calling: grdimage $GRDFILE $BKSIZE -C$CPTFILE -P -K >! $PSFILE" grdimage $GRDFILE $BKSIZE -C$CPTFILE -P -K >! $PSFILE # Tidy tidy tidy echo " removing grdfile, cptfile: $GRDFILE $CPTFILE" rm -f $GRDFILE rm -f $CPTFILE # Set Overlay for next if this was first, else initialize new plot system set GMTFLAGS = "-K -O -N $GENOPT $RANGE $FRAME $SIZE -U -Sc -W6/255/0/0" else set GMTFLAGS = "-K -N $GENOPT $RANGE $FRAME $SIZE -U -Sc -W6/255/0/0" endif ###################################################################### ### Plot the location circles, where correl=size. echo " +++ Plotting location circles, size (cm) is correlation +++" $AWK '{print $2, $3, $6}' $TMPFILE | psxy $GMTFLAGS >> $PSFILE # set GMTFLAGS = "-K -O -N $GENOPT $RANGE $SIZE -Sc -W6/255/0/0" echo " +++ Plotting legenda circle +++" echo "$L0 $P0 1.0" | psxy -X-1.0 -Y-1.0 $GMTFLAGS >> $PSFILE echo "$L0 $P0 0.5" | psxy -Y-0.25 $GMTFLAGS >> $PSFILE #pstext:(x, y, size, angle, fontno, justify, text) set GMTFLAGS = "-K -O -N $GENOPT $RANGE $SIZE" echo "$L0 $P0 12 0 0 CM correlation" | pstext -Y1.0 $GMTFLAGS >> $PSFILE echo "$L0 $P0 12 0 0 LM 1.0" | pstext -X0.5 -Y-0.5 $GMTFLAGS >> $PSFILE echo "$L0 $P0 12 0 0 LM 0.5" | pstext -Y-0.5 $GMTFLAGS >> $PSFILE ###################################################################### ### Plot normalized offset vectors. # -G fill # -Sv arrowwidth/headlength/headwidth [0.075c/0.3c/0.25c] set GMTFLAGS = "-N -O -K -X0.5 -Y1.25 $GENOPT $RANGE $SIZE -Sv0.04/0.25/0.125 -G0/0/255 -W2/0/0/255" # echo "START STDL computation" set MINL = `$AWK 'NR==1{m=$5}$5m{m=$5}END{print m}'<$TMPFILE` set MEANL = `$AWK '{s += $5}END{printf "%f", s/NR}'<$TMPFILE` set STDL = `$AWK '{sq += ( $5 - '$MEANL' ) * ( $5 - '$MEANL' )};END{printf "%f", sq / ( NR - 1 )}'<$TMPFILE` #set STDL = `$AWK -v m=$MEANL '{sq+=($5-m)*($5-m)};END{print sq/(NR-1)}'<$TMPFILE` # echo "START STDP computation" set MINP = `$AWK 'NR==1{m=$6}$6m{m=$6}END{print m}'<$TMPFILE` set MEANP = `$AWK '{s += $6}END{printf "%f", s / NR}'<$TMPFILE` set STDP = `$AWK '{sq += ( $6 - '$MEANP' ) * ( $6 - '$MEANP' )};END{printf "%f", sq / ( NR - 1 )}'<$TMPFILE` #set STDP = `$AWK -v m=$MEANP '{sq+=($6-m)*($6-m)};END{print sq/(NR-1)}'<$TMPFILE` echo " *** min, max, mean, std (line): $MINL $MAXL $MEANL $STDL" echo " *** min, max, mean, std (pixel): $MINP $MAXP $MEANP $STDP" ###################################################################### ### Normalize vectors by subtracting mean-2: ### plot arrows as they are, normalized by max length ? (always longest==3cm?) #no cause then offset 1000 <> 1001 is no difference while it is the same as 10<>11 # thus scale length by l-max echo " *** Normalizing offset line by subtracting: $MEANL - 1" echo " *** Normalizing offset pixel by subtracting: $MEANP - 1" # #$AWK -v wl=$MEANL -v wp=$MEANP \ # '{ \ # {l=$5-wl-1.} \ # {p=$6-wp-1.} \ echo "start psxy vector drawing" # {dir=57.3*atan2(l,p)} \ # possibly gawk or nawk define atan2, not standard awk... $AWK '{{l = $5 - '$MEANL' - 1.0 }{p = $6 - '$MEANP' - 1.0 } \ {l = l + 0.0000001} {p = p + 0.0000001} \ {dir = 57.3 * atan2(l,p)} \ {scale = 1.5} \ {len = scale * sqrt ( l * l + p * p )} \ {printf "%.1f %.1f %.1f %.1f\n", $2, $3, dir, len} \ }' \ $TMPFILE | \ psxy $GMTFLAGS >> $PSFILE echo "...finished psxy vector drawing" ### Print info on points as text (# offl offp). set GMTFLAGS = "-M -Wo -D0/2.5 -O -N -K $GENOPT $RANGE $SIZE" echo "> $LN $P0 8 0 0 LB 0.4 15 l" >! $TMPFILE.2 $AWK '{printf "@;255/0/0; @:10: %4.0i @;0/0/0; @:8: (%4.2f;%4.2f) - \n", $1,$5,$6}' $TMPFILE >> $TMPFILE.2 # Avoid overflow with head. head -n 60 $TMPFILE.2 | pstext $GMTFLAGS >> $PSFILE rm -f $TMPFILE.2 ### Add the window numbers (last overlay, no -K (close plot system)). #pstext: (x, y, size(pts), angle(ccw), fontno, justify, text) set GMTFLAGS = "-O -N -G0/0/0 $GENOPT $RANGE $SIZE" echo " Calling: pstext $GMTFLAGS >> $PSFILE" #green, 14pts, RightTop BottomLeft $AWK '{printf "%.1f %.1f 10 0 0 RT %s\n", $2, $3, $1}' $TMPFILE | pstext $GMTFLAGS >> $PSFILE # calls from Doris, cannot interactive... #%// BK 19-Jul-2000 echo " Calling: viewanddel" rm -f $TMPFILE $GRDFILE $CPTFILE viewanddel $PSFILE ### EOF Doris-5.0.3Beta/bin/rs2_dump_data.py000077500000000000000000000212141312547014700172500ustar00rootroot00000000000000#!/usr/bin/env python #-----------------------------------------------------------------# # A python code for extracting image matrix from RS2 geotiff file # using gdal_translate # # Author: TUDelft - 2010 # Maintainer: Mahmut Arikan # # Developed based on tsx_dump_data.py code. # #-----------------------------------------------------------------# import os,sys,time from os import path import xml.etree.ElementTree as etree # parameters required for cropping and flipping codeRevision=1.1 # this code revision number def usage(): print 'INFO : @(#)Doris InSAR software, $Revision: %s $, $Author: TUDelft $' % codeRevision print print 'Usage : rs2_dump_data.py [l0 lN p0 pN] [-res RESFILE]' print print ' inputfile is the input Radarsat-2 geotiff filename : master.tif' print ' outputfile is the output filename : master.slc' print ' l0 is the first azimuth line (starting at 1)' print ' lN is the last azimuth line' print ' p0 is the first range pixel (starting at 1)' print ' pN is the last range pixel' print ' RESFILE DORIS result file that is to be updated for crop metadata (optional)' print print ' This software is part of Doris InSAR software package.\n' print '(c) 1999-2010 Delft University of Technology, the Netherlands.\n' try: inputFileName = sys.argv[1] outputFileName = sys.argv[2] except: print '\nError : Unrecognized input or missing arguments\n\n' usage() sys.exit(1) inputFileName = sys.argv[1] outputFileName = sys.argv[2] resFile = None for element in range(len(sys.argv)): option = sys.argv[element]; if option == '-res': resFile = str(sys.argv[element+1]) # print resFile del sys.argv[element+1] del sys.argv[element] break if len(sys.argv) == 3: outputWinFirstLine = None outputWinLastLine = None outputWinFirstPix = None outputWinLastPix = None elif len(sys.argv) > 3 and len(sys.argv) < 9: outputWinFirstLine = int(sys.argv[3]) # Firstline outputWinLastLine = int(sys.argv[4]) # Lastline outputWinFirstPix = int(sys.argv[5]) # Firstpix outputWinLastPix = int(sys.argv[6]) # Lastpix elif len(sys.argv) > 3 and len(sys.argv) < 7: print '\nError : Unrecognized input or missing arguments\n\n' usage() sys.exit(1) else: outputWinFirstLine = None outputWinLastLine = None outputWinFirstPix = None outputWinLastPix = None # Extract some important parameters for coordinate manipulation productfile = path.join(path.dirname(inputFileName), 'product.xml') tree = etree.parse(productfile) # NS = 'http://www.rsi.ca/rs2/prod/xml/schemas' PASS = tree.find('.//{%s}passDirection' % NS).text # Ascending or Descending line_order = tree.find('.//{%s}lineTimeOrdering' % NS).text pixl_order = tree.find('.//{%s}pixelTimeOrdering' % NS).text # Increasing or Decreasing Nlines = int(tree.find('.//{%s}numberOfLines' % NS).text) Npixls = int(tree.find('.//{%s}numberOfSamplesPerLine' % NS).text) in_FirstLine = outputWinFirstLine in_LastLine = outputWinLastLine in_FirstPix = outputWinFirstPix in_LastPix = outputWinLastPix if line_order == 'Increasing': print('INFO : Detected a imagery %s line time order' % line_order) else: print('INFO : Detected a imagery %s line time order' % line_order) print('INFO : Adjusting first line and last line ') outputWinFirstLine = Nlines-in_LastLine+1 outputWinLastLine = Nlines-in_FirstLine+1 print Nlines, Npixls print outputWinFirstLine,outputWinLastLine,outputWinFirstPix,outputWinLastPix if pixl_order == 'Increasing': print('INFO : Detected a imagery %s pixel time order' % pixl_order) else: print('INFO : Detected a imagery %s pixel time order' % pixl_order) print('INFO : Adjusting first pixel and last pixel ') outputWinFirstPix = Npixls-in_LastPix+1 outputWinLastPix = Npixls-in_FirstPix+1 print Nlines, Npixls print outputWinFirstLine,outputWinLastLine,outputWinFirstPix,outputWinLastPix # GDAL Extract image matrix using gdal_translate # Ex: gdal_translate -of ENVI -ot Int16 -co INTERLEAVE=BIP imagery_HH.tif rs2_slc.raw gdalCall = 'gdal_translate' # GDAL parameters outputDataFormat = 'ENVI' #outputDataType = 'CInt16' outputDataType = 'Int16' outputDataType2 = 'ci2' # for cpxfiddle outputInterleave = 'INTERLEAVE=BIP' cmd = '%s %s -ot %s -of %s -co %s %s' % (gdalCall,inputFileName,outputDataType,outputDataFormat,outputInterleave,outputFileName+'.noflip') if outputWinFirstPix is not None: # xoff yoff xsize = width ysize= height # 1 --> 0 1 --> 0 cmd = cmd + (' -srcwin %s %s %s %s' % (outputWinFirstPix-1,outputWinFirstLine-1,outputWinLastPix-outputWinFirstPix+1,outputWinLastLine-outputWinFirstLine+1)) print cmd failure = os.system(cmd) if failure: print '%s: running %s failed' % (sys.argv[0],cmd) sys.exit(1) #else: # os.rename(os.path.splitext(outputFileName)[0]+'.j00',outputFileName) print('\nINFO : Start flipping image to radar coordinate for a %s orbit.' % PASS) # Flip using cpxfiddle # get keyword asc or desc from .res # if resFile is not None: # inStream = open(resFile,'r') # find ascending tag then # -m Y for ascending # -m X for descending orbit cpxfcall='cpxfiddle -q normal -o short ' # cpxfiddle -w 3788 -f ci2 -q normal -o short -m Y rs2_slc.raw.noflip > rs2_slc.raw if PASS == 'Ascending': cmd = cpxfcall + ( '-w %s -f %s -m %s %s > %s ' % (outputWinLastPix-outputWinFirstPix+1,outputDataType2,'Y',outputFileName+'.noflip',outputFileName)) print('INFO : %s ' % cmd) else: cmd = cpxfcall + ( '-w %s -f %s -m %s %s > %s ' % (outputWinLastPix-outputWinFirstPix+1,outputDataType2,'X',outputFileName+'.noflip',outputFileName)) print('INFO : %s ' % cmd) failure = os.system(cmd) if failure: print '%s: running %s failed' % (sys.argv[0],cmd) sys.exit(1) else: os.remove(outputFileName+'.noflip') # Manual call to update Doris res file # check whether the file exist!!! if resFile is not None: print resFile # load header #headerFileStream = open(os.path.splitext(outputFileName)[0]+'.hdr','r') headerFileStream = open(outputFileName+'.hdr','r') for line in headerFileStream: pair = line.split() if len(pair) > 1: vars()[pair[0]] = pair[2] # set IMAGE_LINES and LINE_SAMPLES # print vars()[pair[0]] # check whether the file exist outStream = open(resFile,'a') outStream.write('\n') outStream.write('*******************************************************************\n') outStream.write('*_Start_crop: geotiff\n') outStream.write('*******************************************************************\n') outStream.write('Data_output_file: %s\n' % outputFileName) outStream.write('Data_output_format: complex_short\n') # HARDCODED if outputWinFirstPix is not None: outStream.write('First_line (w.r.t. original_image): %s\n' % in_FirstLine) outStream.write('Last_line (w.r.t. original_image): %s\n' % in_LastLine) outStream.write('First_pixel (w.r.t. original_image): %s\n' % in_FirstPix) outStream.write('Last_pixel (w.r.t. original_image): %s\n' % in_LastPix) elif outputWinFirstPix is None: outStream.write('First_line (w.r.t. original_image): 1\n') outStream.write('Last_line (w.r.t. original_image): %s\n' % lines ) outStream.write('First_pixel (w.r.t. original_image): 1\n') outStream.write('Last_pixel (w.r.t. original_image): %s\n' % samples ) outStream.write('*******************************************************************\n') outStream.write('* End_crop:_NORMAL\n') outStream.write('*******************************************************************\n') outStream.write('\n') outStream.write(' Current time: %s\n' % time.asctime()) outStream.write('\n') # close output file outStream.close() # replace crop tag in result file sourceText = "crop: 0" replaceText = "crop: 1" inputStream = open(resFile,'r') textStream = inputStream.read() inputStream.close() outputStream = open(resFile, "w") outputStream.write(textStream.replace(sourceText, replaceText)) outputStream.close() #EOF Doris-5.0.3Beta/bin/rs2_dump_header2doris.py000077500000000000000000000342311312547014700207150ustar00rootroot00000000000000#!/usr/bin/python #-----------------------------------------------------------------# # A python code for parsing RS2 XML file into python data structures # and from there into DORIS res file structure # # Author: TUDelft - 2010 # Maintainer: Mahmut Arikan # # Developed based on tsx_dump_header2doris.py. # # this is rather fair implementation and should be used as a structure # for the future implementation of XML/GeoTIFF data readers # NO XPATH version # 2012.Nov Fix for ascending mode time parameters Samie Esfahany and Mahmut # 2013.Sep Fix for UF and MF acquisition modes and cleanup, Piers van der TOrren #-----------------------------------------------------------------# from lxml import etree import sys from datetime import datetime #try: # from lxml import etree #except ImportError: # import xml.etree.ElementTree as etree codeRevision=1.2 # this code revision number def usage(): print 'INFO : @(#)Doris InSAR software, $Revision: %s $, $Author: TUDelft $' % codeRevision print print 'Usage : python rs2_dump_header2doris.py rs2_XML_product > outputfile' print ' where rs2_XML_product is the input filename' print print ' This software is part of Doris InSAR software package.\n' print '(c) 1999-2010 Delft University of Technology, the Netherlands.\n' try: inputFileName = sys.argv[1] # outputFileName = sys.argv[2] # outStream = open(outputFileName,'w') except: print '\nError : Unrecognized input or missing arguments\n\n' usage() sys.exit(1) # Helper functions def nsmap_none(path, ns='None:'): """ Add a namespace to each tag in the given path which doesn't have one. """ def add_ns_if_none(tag): if tag in ('', '.', '*') or ':' in tag: return tag else: return ''.join((ns, tag)) return '/'.join(add_ns_if_none(tag) for tag in path.split('/')) def hms2sec(hmsString): """ input hmsString syntax: XX:XX:XX.xxxxxx """ return int(hmsString[0:2])*3600 + \ int(hmsString[3:5])*60 + \ float(hmsString[6:]) # constants SOL = 299792458.0 # speed of light dateformat = '%Y-%m-%dT%H:%M:%S.%fZ' # default namespace nsmap = {None:"http://www.rsi.ca/rs2/prod/xml/schemas"} ns = '{' + nsmap[None] + '}' inTree = etree.parse(inputFileName) # query syntax for every field queryList = { # mission info 'mission' : 'sourceAttributes/satellite', # imageFile file # fullResolutionImageData pole="HH" # inTree.findall('imageAttributes/fullResolutionImageData')[0].text, and more [1] .. [3] 'imageFile' : 'imageAttributes/fullResolutionImageData', #'imageLines' : 'imageAttributes/rasterAttributes/numberOfLines', 'imageLines' : 'imageAttributes//numberOfLines', 'imagePixels' : 'imageAttributes//numberOfSamplesPerLine', 'imageLineSpacing' : 'imageAttributes//sampledLineSpacing', 'imagePixelSpacing' : 'imageAttributes//sampledPixelSpacing', # volume info #'volFile' : 'productComponents/annotation/file/location/filename', # HARDCODED!!! for radarsat-2 # following smt like Level 1B Product, check manual 'volID' : 'productId', 'volRef' : 'documentIdentifier', # product info #productSpec' : 'generalHeader/referenceDocument', # TSX 'productSpec' : 'documentIdentifier', 'productVolDate' : 'imageGenerationParameters//processingTime', 'productSoftVer' : 'imageGenerationParameters//softwareVersion', 'productDate' : 'sourceAttributes/rawDataStartTime', 'productFacility' : 'imageGenerationParameters//processingFacility', # scene info #'scenePol' : 'sourceAttributes/radarParameters/acquisitionType', # Fine Quad Polarization 'scenePol' : 'sourceAttributes//polarizations', 'sceneBeam' : 'sourceAttributes//beams', 'sceneBeamMode' : 'sourceAttributes/beamModeMnemonic', 'list_sceneLat' : 'imageAttributes/geographicInformation/geolocationGrid/imageTiePoint/geodeticCoordinate/latitude', 'list_sceneLon' : 'imageAttributes/geographicInformation/geolocationGrid/imageTiePoint/geodeticCoordinate/longitude', 'sceneRecords' : 'imageGenerationParameters/sarProcessingInformation/numberOfLinesProcessed', 'antennaLookDir' : 'sourceAttributes//antennaPointing', 'missinglines' : 'sourceAttributes//numberOfMissingLines', # orbit info 'orbitABS' : 'sourceAttributes/orbitAndAttitude//orbitDataFile', 'orbitDir' : 'sourceAttributes//passDirection', 'list_orbitTime' : 'sourceAttributes//stateVector/timeStamp', 'list_orbitX' : 'sourceAttributes//stateVector/xPosition', 'list_orbitY' : 'sourceAttributes//stateVector/yPosition', 'list_orbitZ' : 'sourceAttributes//stateVector/zPosition', 'list_orbitXV' : 'sourceAttributes//stateVector/xVelocity', 'list_orbitYV' : 'sourceAttributes//stateVector/yVelocity', 'list_orbitZV' : 'sourceAttributes//stateVector/zVelocity', # range 'list_rangeRSR' : 'sourceAttributes//adcSamplingRate', # for UF mode there are two subpulses which have to be added together 'rangeBW' : 'imageGenerationParameters//rangeLookBandwidth', 'rangeWind' : 'imageGenerationParameters//rangeWindow/windowName', 'rangeWindCoeff' : 'imageGenerationParameters//rangeWindow/windowCoefficient', 'rangeTimePix' : 'imageGenerationParameters//slantRangeTimeToFirstRangeSample', # azimuth 'azimuthPRF' : 'sourceAttributes//pulseRepetitionFrequency', # for some modes (MF, UF) this value is changed in processing, calculate from other values 'azimuthBW' : 'imageGenerationParameters//azimuthLookBandwidth', 'azimuthWind' : 'imageGenerationParameters//azimuthWindow/windowName', 'azimuthWindCoeff' : 'imageGenerationParameters//azimuthWindow/windowCoefficient', 'azimuthTimeFirstLine': 'imageGenerationParameters//zeroDopplerTimeFirstLine', 'azimuthTimeLastLine' : 'imageGenerationParameters//zeroDopplerTimeLastLine', # doppler 'dopplerTime' : 'imageGenerationParameters//timeOfDopplerCentroidEstimate', 'dopplerCoeff' : 'imageGenerationParameters//dopplerCentroidCoefficients', # for wavelength computation 'radarfreq' : 'sourceAttributes//radarCenterFrequency', # wavelength_computed = (0.000000001*SOL/atof(c8freq)) seems more reliable, BK 03/04 } # get variables and parameters from xml container = {} for key, value in queryList.iteritems(): if key.startswith('list_'): container[key] = [tag.text for tag in inTree.findall(nsmap_none(value, ns))] else: container[key] = inTree.findtext(nsmap_none(value, ns)) if container[key] == None: raise Exception('Path {0} not found in XML'.format(value)) container['dopplerCoeff'] = container['dopplerCoeff'].split() def mean(l): return sum(l)/len(l) container['sceneCenLat'] = mean([float(val) for val in container['list_sceneLat']]) container['sceneCenLon'] = mean([float(val) for val in container['list_sceneLon']]) # sum subpulses for UF like modes RSR1 = sum(float(val) for val in container['list_rangeRSR']) # alternative: calculate RSR from given pixel spacing, former way doesn't work correctly for reduced resolution XF images. Difference is a factor 1.0000001 container['rangeRSR'] = SOL/float(container['imagePixelSpacing'])/2 # for backwards compatibility use first method when values are very close to each other if 0.9999 < RSR1/container['rangeRSR'] < 1.0001: container['rangeRSR'] = RSR1 # Calculate PRF azimuthTimeFirstLine = datetime.strptime(container['azimuthTimeFirstLine'], dateformat) azimuthTimeLastLine = datetime.strptime(container['azimuthTimeLastLine'], dateformat) obs_time = (azimuthTimeLastLine - azimuthTimeFirstLine).total_seconds() # set start time to the first observed line (for ascending the image is flipped) if obs_time > 0: azimuthTimeStart = azimuthTimeFirstLine else: azimuthTimeStart = azimuthTimeLastLine obs_time = -obs_time if container['sceneBeam'] != 'S3': # Hacky fix for S3 merged images container['azimuthPRF'] = (float(container['imageLines']) - 1)/obs_time # --------------------------------------------------------------------------------------------------------- #print container['mission'] #exit() dummyVar = 'DUMMY' print('\nrs2_dump_header2doris.py v%s, doris software, 2013\n' % codeRevision) print('*******************************************************************') print('*_Start_readfiles:') print('*******************************************************************') print('Volume file: %s' % 'product.xml') # container['volFile']) # HARDCODED!!! for Radarsat-2 print('Volume_ID: %s' % container['volID']) print('Volume_identifier: %s' % container['volRef']) print('Volume_set_identifier: %s' % dummyVar) print('(Check)Number of records in ref. file: %s' % container['sceneRecords']) print('SAR_PROCESSOR: %s %s' % (str.split(container['productSpec'])[0][:2],container['productSoftVer'])) print('SWATH: %s' % container['sceneBeam']) print('PASS: %s' % container['orbitDir']) print('IMAGING_MODE: %s %s' % (container['sceneBeamMode'],container['scenePol'])) print('RADAR_FREQUENCY (Hz): %s' % container['radarfreq']) print('') print('Product type specifier: %s' % container['mission']) print('Logical volume generating facility: %s' % container['productFacility']) print('Logical volume creation date: %s' % container['productVolDate']) print('Location and date/time of product creation: %s' % container['productDate']) #print('Scene identification: Orbit: %s %s Mode: %s' % (container['orbitABS'].split('_')[0],container['orbitDir'],container['sceneBeamMode'])) print('Scene identification: Orbit: %s %s' % (container['orbitABS'].split('_')[0], azimuthTimeStart.strftime(dateformat))) print('Scene location: lat: %.4f lon: %.4f' % (float(container['sceneCenLat']),float(container['sceneCenLon']))) print('') print('Leader file: %s' % 'product.xml') # container['volFile']) # HARDCODED!!! for Radarsat-2 print('Sensor platform mission identifer: %s' % container['mission']) print('Scene_centre_latitude: %s' % container['sceneCenLat']) print('Scene_centre_longitude: %s' % container['sceneCenLon']) print('Scene_centre_heading: %s' % 'Null') # needs to be computed from geoinfo print('Radar_wavelength (m): %s' % str(SOL/float(container['radarfreq']))) print('First_pixel_azimuth_time (UTC): %s' % azimuthTimeStart.strftime('%d-%b-%Y %H:%M:%S.%f')) print('Pulse_Repetition_Frequency (computed, Hz): %s' % container['azimuthPRF']) print('Total_azimuth_band_width (Hz): %s' % float(container['azimuthBW'])) print('Weighting_azimuth: %s %f' % (str.upper(container['azimuthWind']), float(container['azimuthWindCoeff']))) print('Xtrack_f_DC_constant (Hz, early edge): %s' % container['dopplerCoeff'][0]) print('Xtrack_f_DC_linear (Hz/s, early edge): %s' % container['dopplerCoeff'][1]) print('Xtrack_f_DC_quadratic (Hz/s/s, early edge): %s' % container['dopplerCoeff'][2]) print('Range_time_to_first_pixel (2way) (ms): %0.15f' % (float(container['rangeTimePix'])*1000)) print('Range_sampling_rate (computed, MHz): %0.6f' % (float(container['rangeRSR'])/1000000)) print('Total_range_band_width (MHz): %s' % (float(container['rangeBW'])/1000000)) print('Weighting_range: %s %f' % (str.upper(container['rangeWind']), float(container['rangeWindCoeff']))) print('') print('*******************************************************************') print('Datafile: %s' % container['imageFile']) print('Dataformat: %s' % 'GeoTIFF') # hardcoded!!! print('Number_of_lines_original: %s' % container['imageLines']) print('Number_of_pixels_original: %s' % container['imagePixels']) print('*******************************************************************') print('* End_readfiles:_NORMAL') print('*******************************************************************') print('') print('') print('*******************************************************************') print('*_Start_leader_datapoints: %s ' % container['orbitABS'].split('_')[1]) print('*******************************************************************') print(' t(s) X(m) Y(m) Z(m) X_V(m/s) Y_V(m/s) Z_V(m/s)') print('NUMBER_OF_DATAPOINTS: %s' % len(container['list_orbitTime'])) # MA : positions and velocities for i in range(len(container['list_orbitTime'])): print(' %.6f %s %s %s %s %s %s' % (hms2sec(container['list_orbitTime'][i].split('T')[1].strip('Z')), container['list_orbitX'][i], container['list_orbitY'][i], container['list_orbitZ'][i], container['list_orbitXV'][i], container['list_orbitYV'][i], container['list_orbitZV'][i])) print('') print('*******************************************************************') print('* End_leader_datapoints:_NORMAL') print('*******************************************************************') # print('\n') # print(' Current time: %s\n' % time.asctime()) # print('\n') #EOF Doris-5.0.3Beta/bin/run000077500000000000000000002022051312547014700147020ustar00rootroot00000000000000#!/bin/sh ########################################################## # Script that: # - Runs SAR software: Doris # - (Delft Object-oriented Radar Interferometric Software) # - Prints out helpdoris script # - NOTE: uses environment variables EDITOR, PAGER (if exist) # # Version history: # v1.0 22/03/99 bert initial version. # v1.1 28/04/99 bert added -g(enerate) option. # v1.2 12/05/99 bert added info variables (AUTHOR etc.). # v1.3 02/06/99 bert added steps 8. slant2h and 9. geocode. # v1.4 02/06/99 bert added checks for savety + renaming # v2.0 02/12/99 bert new setup of steps, general improvements # v2.1 22/05/00 bert environment variables # v2.2 06/03/01 bert file name conventions (extensions) # masterorb_slaveorb.cint .srp .srd .uint .coh .dcint # v3.0 02/02/02 bert changed from ksh to sh since cygwin didn't have one. # v3.1 12-Sep-2003 bert added quick look processing # v4.01 12-Dec-2008 FvL updates for Doris 4.01 # v4.01 23-Dec-2008 MA minor revisions for Doris 4.01 # v4.01 13-Apr-2009 MA TSX update # v4.02 29-May-2009 MA Ellipsoid card generated # v4.0x 23-Jun-2010 MA,PD RS2 and CSK read/crop parameters updated # # Future plans: # Print out: checklist.tex , shortmanual.tex, (see helpdoris) # If existed output, interactive solution for rename, don't auto # add check if input exists before vi # We had some problems with the which command, so changd it to running programs # looking for exit status... # # Disclaimer: # This run file comes without warranty, # You are allowed to change/add whatever you like. # If you are using this script for running the Doris software, # please keep the version history and disclaimer. # Mail comments/bugs to doris_users@tudelft.nl ########################################################## ########################################################## PROG="doris" # executable name in path PROGDEBUG="doris.debug" # executable name in path PROGINCWD="./processor" # executable name in working dir ########################################################## ### Default values for -g option; not used in processing. ### AUTHOR="TUDelft - MGP Radar Group" # Bert Kampes is the main author MASTER="master" SLAVE="slave" REMARKS="No remarks" BASELINE="Unknown" DATE=`date "+%b %d, %Y (%A)"` # cannot be changed by input option ### Default directories for input/output ### INPUTDIR="Inputfiles" # directory for input OUTPUTDIR="Outinfo" # directory for output standard out DATAOUTDIR="Outdata" # directory for output matrices WORKDIR="." # don't change? ### Default parameter files/logfile ### LOGFILE="doris.log" # BK 19-Jan-2001: defaults to -M -S if specified #MASTERRES="master.res" #SLAVERES="slave.res" #INTERFRES="products.res" ########################################################## # No need to change anything below this line (i hope) # # But feel free to change default input generation to # # Save you some editing work later. # ######################################################### ########################################################## # To run Doris software: # 1) make sure your path is ok. # 2) create work directory, # 3) run -g etc. creates the input etc. # 4) run -s runs the software. -h(elp) ######################################################### ######################################################### ######################################################### # Script variables. bn=`basename $0` EDIT=999 STEP=999 VIEW=999 RESULT=999 INPUT= INPUT_1=input.m_initial INPUT_2=input.s_initial INPUT_3=input.coregistration INPUT_4=input.resample INPUT_5=input.products INPUT_6=input.filter_unwrap INPUT_7=input.s2h_geocode #INPUT_8=input. INPUT_9=input.quicklook DOGENERATE="0" # no default -g ... # ------------------------------- # Functions for convenience. NAME() { echo " $bn -- Utility for running the Delft insar processor." } SYNOPSIS() { echo " $bn -s/-e/-v step -ql [-f inputfile -r file-id -d]" echo " /-g [-M master -S slave -B baseline -R remark -A author]" echo " /-h" echo " ($bn -h gives more help)" } USAGE() { echo "Usage:" SYNOPSIS exit 1 } MANPG() { cat << __MANEOF PROGRAM: $name SYNOPSIS: $synopsis DESCRIPTION: This script is convenient for running the Doris InSAR software. It generates template input files, and serves as a shell. It allows you to edit the generated input, and to run Doris. Of course the results can also be viewed. The environment variables PAGER and EDITOR are used (if set) for viewing and editing. In your current setup, the programs "$PAGER" and "$EDITOR" are used respectively. __MANEOF if [ -x $PROGINCWD ]; then echo " "The executable: \"$PROGINCWD\" "is used (run -s step)." else echo " "The executable: \"$PROG\" "is used (run -s step)." fi cat << __MANEOF OPTIONS: ========================== === GENERATING OPTIONS === ========================== -g Generate directories, template input files. Use -M -S -A -B -R to specify comments in template input files. It makes the following directories: for the input files: "$INPUTDIR/" for the redirected stdout: "$OUTPUTDIR/" for data output: "$DATAOUTDIR/" Either the program: "$PROG" (default in your path), "$PROGDEBUG" (-d option), or "$PROGINCWD" (if it exists). is called. -M master Only in combination with -g option. Specify name for master image (e.g., orbit number). This variable is used to name the output data files and as a comment at the top of the input files. The M_RESFILE is assigned to 'master'.res The I_RESFILE is assigned to 'master_slave'.res -S slave Only in combination with -g option. Specify name for slave image (e.g., orbit number). This variable is used to name the output data files and as a comment at the top of the input files. The S_RESFILE is assigned to 'slave'.res The I_RESFILE is assigned to 'master_slave'.res -A author Only in combination with -g option. Specify name of author/ person who is processing. Used only as a comment at the top of the input files. -B baseline Only in combination with -g option. Specify baseline (e.g., 100). Used only as a comment at the top of the input files. -R remarks Only in combination with -g option. Specify any remarks on the processing. Used only as a comment at the top of the input files. ========================== === PROCESSING OPTIONS === ========================== -e step edit the inputfiles. then exit (no processing). -ql Quicklook processing. (Edit input: run -e1; run -e2; run -e9). If run -s1 has not been done yet, it perform it. If run -s2 has not been done yet, it perform it. Then it copies the $MASTERRES to master_QL.res and $SLAVERES to slave_QL.res Finally it runs doris with options in run -e9 (all steps for interferogram). -s step proces the input file for this step. 1: initial steps for master (readfiles, crop, porbits) 2: initial steps for slave (readfiles, crop, porbits) 3: coregistration (coarse, fine) 4: compute coregistration parameters and perform resampling 5: interferometric product generation and reference phase 6: phase filtering (and phase unwrapping) 7: slant to height conversion and geocoding 8: n/a 9: quicklook processing. This step first performs a run -s1 and a run -s2 to read master and slave. Make sure that you have edited the input files with run -e1 and run -e2. Then, all steps to quickly create an interferogram are performed. You can edit that with run -e9, but there should be no need for that. -v step view output file of step. -r file-ID view/edit result output file. 1: "$MASTERRES" (master result file) 2: "$SLAVERES" (slave result file) 3: "$INTERFRES" (interferogram result file) 4: "$LOGFILE" (logfile) ========================== === FURTHER OPTIONS === ========================== -f infile Specify an input file to process. Useage of this option is discouraged, use option -s step. (or use command line syntax if you like that better.) -d Use debugger version: $PROGDEBUG instead of regular: $PROG These executables have to be in your path. This option can be used if normal processing goes wrong. The redirected stdout can get very large (2GB) with this option. ========================== === EXAMPLES === ========================== Normally, the processing starts by generating input files: run -g Then, check/edit the input for the first step: run -e1 Next the executable $PROG is called by: run -s1 The output can be viewed with: run -v1 for the stdout and with: run -r[1/2/3/4] The processing continues with the next step: run -e2 etc. To generate the input files for master 21066, slave 01393, with a baseline of about 100m for testing purposes: run -g -M 21066 -S 01393 -R "Testing generate option" -B 100 To edit the input file for step one: run -e 1 To run first step, and put ouput file (redirected stout) in dir: run -s 1 To view the output file for step one: run -v 1 To run an input file named inputA in the current directory (discouraged with -f): run -f inputA doris inputA > outputA ========================== === AUTHOR === ========================== Author: $bn is written by Bert Kampes, Delft University, (c)1999-2003, b.m.kampes@lr.tudelft.nl. Known bugs: It is not possible to edit more then one file with the -e option. See also: helpdoris plotoffsets plotcpm Note: You can edit this script if you want other options, etc. Please notify b.m.kampes@lr.tudelft.nl in that case. __MANEOF } # generate input files------------------ GENERAL() { cat << __GENERALEOF # ********************************************************************** # *** Doris inputfile generated by: $bn at: $DATE ***** # ********************************************************************** # *** # *** Filename: $INPUTDIR/$fn # *** Author: $AUTHOR # *** Master: $MASTER # *** Slave : $SLAVE # *** Baseline: $BASELINE # *** Remarks: $REMARKS # *** # *** Intended to be used with shell script: $bn # ********************************************************************** ######################################################################## # NOTE: BK 16-JUN-2003 # # It seems when compiled with g++ 3.2, there cannot be an empty # # optional argument, since instead the first (key) of the next line # # is read. Therefore, it seems wise to always use arguments, or to # # always have a comment with "//" behind the last argument. # # Of course there must be a way to prevent this, but I don't know how# ######################################################################## # ------------------------------------------ # The general options # ------------------------------------------ SCREEN info // level of output to standard out c SCREEN debug // [trace, debug, info, progress, warning, error] c SCREEN trace // [trace, debug, info, progress, warning, error] BEEP warning // level of beeping c PREVIEW xv // SUNraster files with cpxfiddle PREVIEW on // SUNraster files with cpxfiddle MEMORY 500 // [MB] RAM available to Doris OVERWRITE ON // do overwrite existing files BATCH ON // do process non-interactive LISTINPUT ON // do copy this file to log HEIGHT 0.0 // average WGS84 terrain height TIEPOINT 0.0 0.0 0.0 // lat/lon/hei of a tiepoint ORB_INTERP POLYFIT 4 // 5th degree polynomial c ORB_INTERP SPLINE // natural cubic spline c ORB_INTERP POLYFIT // orbit interpolation method c ELLIPSOID WGS84 // WGS84 (default), GRS80, BESSEL or define a,b (major radius, minor radius) c DUMPBASELINE 15 10 // eval baseline on grid c M_RG_T_ERROR 0.0 // one-way [sec] timing error c M_AZ_T_ERROR 0.0 // azimuth timing error c S_RG_T_ERROR 0.0 // one-way [sec]; d_rg=err*rsr*2 c S_AZ_T_ERROR 0.0 // [sec]; d_az=err*prf [m] __GENERALEOF } FILES() { cat << __FILESEOF # ------------------------------------------ # The general io files # ------------------------------------------ LOGFILE $LOGFILE // log file M_RESFILE $MASTERRES // parameter file master S_RESFILE $SLAVERES // parameter file slave I_RESFILE $INTERFRES // parameter file interferogram __FILESEOF } GEN_1() { fn=$INPUT_1 GENERAL FILES cat << __GENEOF_1a PROCESS m_readfiles // reading of slc files PROCESS m_porbits // get precise orbits PROCESS m_crop // convert data to internal format PROCESS m_simamp // simulate amplitude PROCESS m_timing // estimate timing error c PROCESS m_ovs // optionally oversample data __GENEOF_1a cat << __GENEOF_1b # ------------------------------------------ # READFILES (master) # ------------------------------------------ c M_IN_METHOD JERS // uses ERS ceos reader c M_IN_METHOD RSAT // uses RSAT ceos reader c M_IN_METHOD ATLANTIS // uses RSAT ceos reader c M_IN_METHOD ALOS // uses ALOS ceos reader # -- select following 5 for ERS ceos reader -- M_IN_METHOD ERS // default M_IN_VOL /CDROM/SCENE1/VDF_DAT.001 // slc volume file M_IN_LEA /CDROM/SCENE1/LEA_01.001 // slc leaderfile M_IN_DAT /CDROM/SCENE1/DAT_01.001 // slc data file M_IN_NULL dummy // # # # --or select following 2 for ERS-- c M_IN_METHOD ERS_N1 // ERS1/2 in Envisat format c M_IN_DAT SAR_IMS_1PXDLR19951008_144123_00000017G150_00096_22128_3605.E1 // please link the actual input file with "ln -s" to avoid long pathnames # # --or select following 2 for ENVISAT-- c M_IN_METHOD ASAR // ENVISAT c M_IN_DAT ASA_IMS_1PXPDE19911013_214038_00000015X000_00000_04784_0002.N1 // please link the actual input file with "ln -s" to avoid long pathnames # # c M_IN_METHOD TSX // TERRASAR-X c M_IN_DAT IMAGE_HH_SRA_strip_007.cos // please link the actual input file with "ln -s" c M_IN_LEA TSX1_metadata.xml # # c M_IN_METHOD RADARSAT-2 // RADARSAT-2 c M_IN_DAT imagery_HH.tif // please link the actual input file with "ln -s" c M_IN_LEA product.xml # # c M_IN_METHOD CSK // Cosmo-skymed c M_IN_DAT master.h5 // please link the actual (CSKS1_SCS_B_HI_05_HH_RA_SF_date.h5) // input file with "ln -s" # ------------------------------------------ # PORBITS (master) # ------------------------------------------ M_ORBDIR /data/delftorbits/ers? c M_ORBDIR /data/delftorbits/ers1/dgm-e04 // dgm gravity model c M_ORBDIR /data/delftorbits/ers2/eigen-grace01s // grace gravity model c M_ORBDIR /data/delftorbits/envisat/eigen-grace01s // grace gravity model c --for spline-- c M_ORB_EXTRATIME 300 // Time before first line c M_ORB_INTERVAL 30 // Time between data c M_ORB_DUMP 0.05 // dump to ascii file c --for polyfit(3)-- M_ORB_EXTRATIME 5 // Time before first line M_ORB_INTERVAL 4 // Time between data # ------------------------------------------ # CROP (master) # ------------------------------------------ c --for CEOS reader: ERS JERS RADARSAT-1 ALOS-- M_CROP_IN /CDROM/SCENE1/DAT_01.001 // slc data file c c --or for ENVISAT-- c M_CROP_IN /cdrom/ASA_IMS_1PXPDE19911013_214038_00000015X000_00000_04784_0002.N1 // please link the actual input file with "ln -s" to avoid long pathnames c c --or for TERRASAR-X c M_CROP_IN IMAGE_HH_SRA_strip_007.cos // please link the actual input file with "ln -s" c c --or for Radarsat-2 c M_CROP_IN FQ9HV_20090515.tif // please link the actual input file with "ln -s" c c --or for Cosmo-skymed c M_CROP_IN master.h5 // please link the actual (CSKS1_SCS_B_HI_05_HH_RA_SF_date.h5) // input file with "ln -s" c c --and the rest of parameters M_CROP_OUT $DATAOUTDIR/$MASTER.raw // output filename M_DBOW 1 5000 1 1000 // database output window in the radar cordinates c M_DBOW_GEO 41.1 12.0 5000 1000 // lat_0[deg], lon_0, height, width[pix] # ------------------------------------------ # SIMULATE AMPLITUDE (master) # ------------------------------------------ SAM_IN_DEM final_netherlands.dem SAM_IN_FORMAT r4 // default is short integer SAM_IN_SIZE 4801 6001 SAM_IN_DELTA 0.000833333 0.000833333 SAM_IN_UL 54 3 SAM_IN_NODATA -32768 SAM_OUT_FILE master_sam.raw SAM_OUT_DEM master_demcrop.dem c SAM_OUT_DEM_LP master_demhei_lp.raw c SAM_OUT_THETA_LP master_theta_lp.raw # ------------------------------------------ # TIMING (master) # ------------------------------------------ MTE_METHOD magspace c MTE_IN_POS window_locations.txt MTE_NWIN 16 MTE_WINSIZE 256 128 MTE_ACC 32 32 MTE_INITOFF 0 0 # ------------------------------------------ # OVERSAMPLE (master) # ------------------------------------------ M_OVS_OUT $DATAOUTDIR/${MASTER}_ovs.raw // output filename M_OVS_OUT_FORMAT ci2 // output format for the oversampled image ci2 | cr4. M_OVS_FACT_RNG 2 // range oversampling ratio M_OVS_FACT_AZI 1 // azimuth oversampling ratio (>2 not implemented yet!) M_OVS_KERNELSIZE 16 // interpolation kernel length c // c // STOP // mandatory # vim: syntax=doris __GENEOF_1b } # # GEN_2() { fn=$INPUT_2 GENERAL FILES cat << __GENEOF_2a PROCESS s_readfiles // reading of slc files PROCESS s_porbits // get precise orbits PROCESS s_crop // convert data to internal format c PROCESS s_ovs // optionally oversample data __GENEOF_2a cat << __GENEOF_2b # ------------------------------------------ # READFILES (slave) # ------------------------------------------ c S_IN_METHOD JERS // uses ERS ceos reader c S_IN_METHOD RSAT // uses RSAT ceos reader c S_IN_METHOD ATLANTIS // uses RSAT ceos reader c S_IN_METHOD ALOS // uses ALOS ceos reader # -- select following 5 for ERS ceos reader -- S_IN_METHOD ERS // default S_IN_VOL /CDROM/SCENE1/VDF_DAT.001 // slc volume file S_IN_LEA /CDROM/SCENE1/LEA_01.001 // slc leaderfile S_IN_DAT /CDROM/SCENE1/DAT_01.001 // slc data file S_IN_NULL dummy // # # # --or select following 2 for ENVISAT-- // c S_IN_METHOD ASAR // ENVISAT c S_IN_DAT ASA_IMS_1PXPDE19911013_214038_00000015X000_00000_04784_0002.N1 // please link the actual input file with "ln -s" to avoid long pathnames # # c S_IN_METHOD TSX // TERRASAR-X c S_IN_DAT IMAGE_HH_SRA_strip_007.cos // please link the actual input file with "ln -s" c S_IN_LEA TSX1_metadata.xml # # c S_IN_METHOD RADARSAT-2 c S_IN_DAT FQ9HV_20090515.tif // please link the actual input file with "ln -s" c S_IN_LEA FQ9_20090515.xml # # c S_IN_METHOD CSK // Cosmo-skymed c S_IN_DAT slave.h5 // please link the actual (CSKS1_SCS_B_HI_05_HH_RA_SF_date.h5) // input file with "ln -s" # ------------------------------------------ # PORBITS (slave) # ------------------------------------------ S_ORBDIR /data/delftorbits/ers? c S_ORBDIR /data/delftorbits/ers1/dgm-e04 // dgm gravity model c S_ORBDIR /data/delftorbits/ers2/eigen-grace01s // grace gravity model c S_ORBDIR /data/delftorbits/envisat/eigen-grace01s // grace gravity model c --for spline-- c S_ORB_EXTRATIME 300 // Time before first line c S_ORB_INTERVAL 30 // Time between data c S_ORB_DUMP 0.05 // dump to ascii file c --for polyfit(3)-- S_ORB_EXTRATIME 5 // Time before first line S_ORB_INTERVAL 4 // Time between data # ------------------------------------------ # CROP (slave) # ------------------------------------------ c --for CEOS reader: ERS JERS RADARSAT-1 ALOS-- S_CROP_IN /CDROM/SCENE1/DAT_01.001 // slc data file c c --or for ENVISAT-- c S_CROP_IN /cdrom/ASA_IMS_1PXPDE19911013_214038_00000015X000_00000_04784_0002.N1 // please link the actual input file with "ln -s" to avoid long pathnames c c --or for TERRASAR-X c S_CROP_IN IMAGE_HH_SRA_strip_007.cos // please link the actual input file with "ln -s" c c --or for Radarsat-2 c S_CROP_IN FQ9HV_20090515.tif // please link the actual input file with "ln -s" c c --or for Cosmo-skymed c S_CROP_IN slave.h5 // please link the actual (CSKS1_SCS_B_HI_05_HH_RA_SF_date.h5) // input file with "ln -s" c c --and the rest of parameters S_CROP_OUT $DATAOUTDIR/$SLAVE.raw // output file S_DBOW 101 6100 11 1010 // database output window in the radar coordinates c S_DBOW_GEO 41.1 12.0 5000 1000 // lat_0[deg], lon_0, height, width[pix] # ------------------------------------------ # OVERSAMPLE (slave) # ------------------------------------------ S_OVS_OUT $DATAOUTDIR/${SLAVE}_ovs.raw // output filename S_OVS_OUT_FORMAT ci2 // output format for the oversampled image ci2 | cr4. S_OVS_FACT_RNG 2 // range oversampling ratio S_OVS_FACT_AZI 1 // azimuth oversampling ratio (>1 not implemented yet!) S_OVS_KERNELSIZE 16 // interpolation kernel length c c STOP // mandatory # vim: syntax=doris __GENEOF_2b } # GEN_3() { fn=$INPUT_3 GENERAL FILES cat << __GENEOF_3a PROCESS coarseorb // no cards later PROCESS coarsecorr // based on correlation PROCESS m_filtazi // azimuth filter PROCESS s_filtazi // azimuth filter c PROCESS filtrange // range filter (orbits) c -- note that fine requires good initial offset by coarsecorr -- c -- ..and/or coarseorb. See the logfile if the coarse offset -- c -- ..is computed correctly if you have low coherence after fine -- PROCESS fine // fine coregistration PROCESS reltiming // relative timing error master-slave PROCESS demassist // DEM assisted coregistration __GENEOF_3a cat << __GENEOF_3b # ------------------------------------------ # COARSE COREGISTRATION # ------------------------------------------ CC_METHOD magfft // default c CC_METHOD magspace // CC_NWIN 21 // number of large windows CC_WINSIZE 256 256 // size of windows (square better?) c CC_INITOFF 0 0 // initial offset CC_INITOFF orbit // use result of orbits # ------------------------------------------ # AZIMUTH FILTERING # ------------------------------------------ c AF_METHOD // AF_BLOCKSIZE 1024 // fftlength each column AF_OVERLAP 64 // hbs AF_HAMMING 0.75 // alpha of hamming, see logfile AF_OUT_MASTER $DATAOUTDIR/$MASTER.af AF_OUT_SLAVE $DATAOUTDIR/$SLAVE.af AF_OUT_FORMAT cr4 // # ------------------------------------------ # RANGE FILTERING (master&slave) # ------------------------------------------ RF_METHOD porbits // based on orbit geometry RF_SLOPE 0.0 // [deg] and terrain slope RF_FFTLENGTH 1024 // power of 2 RF_HAMMING 0.75 // 'alpha' RF_OUT_MASTER $DATAOUTDIR/$MASTER.rf_orb RF_OUT_SLAVE $DATAOUTDIR/$SLAVE.rf_orb RF_OUT_FORMAT cr4 // # ------------------------------------------ # FINE COREGISTRATION # ------------------------------------------ c FC_METHOD magfft // fast FC_METHOD oversample // best: oversample complex data c FC_METHOD magspace // same as magfft FC_NWIN 601 // number of smaller windows c FC_IN_POS highcorr.pos // filename with window positions FC_WINSIZE 64 64 // size of windows FC_ACC 8 8 // search window, 2^n FC_INITOFF coarsecorr // use result of coarse FC_OSFACTOR 32 // oversampling factor FC_PLOT 0.2 NOBG // GMT plot with magnitude background # ------------------------------------------ # RELATIVE TIMING ERROR # ------------------------------------------ RTE_THRESHOLD 0.4 RTE_MAXITER 10000 RTE_K_ALPHA 1.97 # ------------------------------------------ # DEM ASSISTED COREGISTRATION # ------------------------------------------ DAC_IN_DEM final_netherlands.dem DAC_IN_FORMAT r4 // default is short integer DAC_IN_SIZE 4801 6001 DAC_IN_DELTA 0.000833333 0.000833333 DAC_IN_UL 54 3 DAC_IN_NODATA -32768 c DAC_OUT_DEM demassist.dem c DAC_OUT_DEMI demassist_int.dem c DAC_OUT_DEM_LP demheight_lp.raw c // c // STOP // mandatory # vim: syntax=doris __GENEOF_3b } # # GEN_4() { fn=$INPUT_4 GENERAL FILES cat << __GENEOF_4a c -- note that coregpm requires a threshold, and you may need -- c -- ..to run step coregpm again. I put it here as process -- c -- ..to obtain an automatic processing for my test data. -- c -- ..but normally you have to remove some points interactively -- c -- ..in an iterative way (i.e., before running "resample). -- PROCESS coregpm // estimate coregistration param. PROCESS resample // slave c -- note that filtrange adaptive is recommended to run. -- c PROCESS filtrange // master&slave __GENEOF_4a cat << __GENEOF_4b # ------------------------------------------ # COREGISTRATION PARAMETERS MODELING # ------------------------------------------ CPM_THRESHOLD 0.2 // higher threshold->less windows c CPM_DEGREE 2 // 2d-polynomial CPM_DEGREE 1 // 1d-polynomial (if demassist coregistration) c CPM_WEIGHT linear // or [none] c CPM_WEIGHT quadratic // or [none] CPM_WEIGHT bamler // paper R.Bamler, IGARSS 2000/2004 CPM_MAXITER 10000 // automated removal, max 10000 iterations c CPM_K_ALPHA 1.97 // automated removal crit. value CPM_PLOT NOBG // plot w/o magnitude background c CPM_DUMP OFF // no creation of files # ------------------------------------------ # RESAMPLING SLAVE # ------------------------------------------ c --- Interpolation Kernel --- c RS_METHOD tri // linear c RS_METHOD nearest // nearest neighbour c RS_METHOD cc4p // cubic convolution c RS_METHOD cc6p // good choice; tested c RS_METHOD ts6p // truncated sinc c RS_METHOD ts8p // truncated sinc c RS_METHOD ts16p // slower but better c RS_METHOD knab6p // better than cc6 (theory) c RS_METHOD knab8p // KNAB window c RS_METHOD knab10p // KNAB window c RS_METHOD knab16p // KNAB window c RS_METHOD knab4p // KNAB window RS_METHOD rc6p // best choice (theory 0.9999) c RS_METHOD rc12p // best choice (theory 0.9999) c c --- Output file --- RS_OUT_FILE $DATAOUTDIR/$SLAVE.resampled RS_OUT_FORMAT cr4 // c RS_DBOW 2000 3000 1 5000 // database output window c RS_DBOW_GEO 52.6743 5.3434 10000 2000 // lat_0[deg], lon_0, height, width[pix] RS_SHIFTAZI on // keep this on # ------------------------------------------ # RANGE FILTERING (master&slave) # ------------------------------------------ RF_METHOD adaptive // estimate local fringe freq. c RF_FFTLENGTH 8 // 8 pixels ~ 160m ground range c RF_FFTLENGTH 32 // 32 pixels ~ 640m ground range RF_FFTLENGTH 128 // 128 pixels ~ 2500m ground range RF_OVERLAP 50 // half overlap RF_OVERSAMPLE 2 // master/slave before ifg generation RF_NLMEAN 9 // must be odd (15 pixels ~ 60m) RF_THRESHOLD 2 // SNR spectral peak detection RF_HAMMING 0.75 // alpha of Hamming window RF_WEIGHTCORR OFF RF_OUT_MASTER $DATAOUTDIR/$MASTER.rf_adapt RF_OUT_SLAVE $DATAOUTDIR/$SLAVE.rf_adapt c RF_OUT_FORMAT ci2 // reduce output file size c // c // STOP // mandatory # vim: syntax=doris __GENEOF_4b } # # GEN_5() { fn=$INPUT_5 GENERAL FILES cat << __GENEOF_5a PROCESS interfero // // -- note: compute reference phase after interfero, -- // -- ..otherwise it is subtracted in INT_METHOD old -- PROCESS comprefpha // estimate flatearth param. PROCESS subtrrefpha // PROCESS comprefdem // synthetic phase from DEM PROCESS subtrrefdem // PROCESS coherence // __GENEOF_5a cat << __GENEOF_5b # ------------------------------------------ # INTERFEROGRAM # ------------------------------------------ INT_METHOD old // c INT_METHOD oversample // INT_OUT_CINT $DATAOUTDIR/${MASTER}_${SLAVE}.cint // optional complex int. c INT_OUT_INT $DATAOUTDIR/${MASTER}_${SLAVE}.int // optional real int. INT_MULTILOOK 5 1 // line, pixel factors # ------------------------------------------ # REFERENCE PHASE COMPUTATION # ------------------------------------------ FE_METHOD porbits // c FE_METHOD method2 // not implemented? FE_DEGREE 5 // FE_NPOINTS 501 // # ------------------------------------------ # SUBTRACT REFERENCE PHASE # ------------------------------------------ c SRP_METHOD exact // compute foreach pixel c SRP_METHOD polynomial // evaluate comprefpha poly SRP_OUT_CINT $DATAOUTDIR/${MASTER}_${SLAVE}.srp // SRP_MULTILOOK 2 2 c SRP_DUMPREFPHA ON c SRP_OUT_REFPHA $DATAOUTDIR/refphase.cr4 // only output for debug # ------------------------------------------ # REFERENCE DEM # ------------------------------------------ CRD_IN_DEM /home/fmr/d4/dem/gtopo30/w020n90/W020N90.DEM c CRD_IN_FORMAT r4 // default is short integer CRD_IN_UL 89.995833333333333 -19.995833333333333333333 // w020n90.HDR CRD_IN_SIZE 6000 4800 // number of rows columns CRD_IN_DELTA 0.00833333333333333333 0.00833333333333333333 // latitude, longitude dec degrees CRD_IN_NODATA -9999 // DEM invalid sample indicator CRD_INCLUDE_FE OFF // phase w.r.t. ellips c CRD_OUT_DEM $DATAOUTDIR/DEM_crop.raw // debug cropped dem c CRD_OUT_DEMI $DATAOUTDIR/DEM_crop_interp.raw // debug cropped dem interpolated c CRD_OUT_DEM_LP $DATAOUTDIR/refdem_hei.raw // DEM [m] in radar geometry CRD_OUT_FILE $DATAOUTDIR/refdem_pha.raw // phase of DEM # ------------------------------------------ # SUBTRREF DEM # ------------------------------------------ SRD_OUT_CINT $DATAOUTDIR/${MASTER}_${SLAVE}.srd // c // c // # ------------------------------------------ # COHERENCE # ------------------------------------------ c COH_METHOD refphase_only // COH_METHOD include_refdem // remove topographic phase also. c COH_OUT_CCOH $DATAOUTDIR/${MASTER}_${SLAVE}.ccoh // optional complex image COH_OUT_COH $DATAOUTDIR/${MASTER}_${SLAVE}.coh // optional real COH_MULTILOOK 10 2 // same as interferogram COH_WINSIZE 20 4 // estimator window size c // c // STOP // mandatory # vim: syntax=doris __GENEOF_5b } # # GEN_6() { fn=$INPUT_6 GENERAL FILES cat << __GENEOF_6a c -- note to set filtparameters correctly, or not to filter. -- c -- ..also set unwrap snaphu to correct model. -- c -- ..unwrap relies on snaphu to be installed! -- PROCESS filtphase // filter interferogram PROCESS unwrap // unwrap interferogram c PROCESS dinsar // differential interferogram __GENEOF_6a cat << __GENEOF_6b # ------------------------------------------ # PHASE FILTERING # ------------------------------------------ c PF_IN_FILE $DATAOUTDIR/${MASTER}_${SLAVE}.srp 323 // only for standalone usage PF_OUT_FILE $DATAOUTDIR/${MASTER}_${SLAVE}.cint.filtered PF_METHOD spatialconv PF_KERNEL 5 1 1 1 1 1 c c PF_KERNEL 5 1 4 9 4 1 c c PF_KERNEL 5 1 2 3 2 1 c c PF_KERNEL 3 -1 1 0 c c PF_IN_KERNEL2D myfilt.asc c c PF_METHOD goldstein c PF_ALPHA 1.8 c PF_BLOCKSIZE 32 c PF_OVERLAP 12 c PF_KERNEL 5 1 1 1 1 1 # ------------------------------------------ # PHASE UNWRAPPING # ------------------------------------------ c UW_METHOD RAMON // (delft only) c UW_SEEDS 100 // delta seedL = seedP c UW_SEEDS 100 200 // c UW_SEEDS seedfilename // put EOL after last UW_OUT_FILE $DATAOUTDIR/${MASTER}_${SLAVE}.uint // unwrapped interferogram c UW_OUT_REGIONS $DATAOUTDIR/${MASTER}_${SLAVE}.regions // 2b used with manuw.m UW_METHOD SNAPHU UW_OUT_FORMAT HGT UW_SNAPHU_LOG snaphu.log UW_SNAPHU_coh $DATAOUTDIR/${MASTER}_${SLAVE}.coh UW_SNAPHU_MODE TOPO UW_SNAPHU_INIT MST UW_SNAPHU_VERBOSE ON # ------------------------------------------ # DIFFERENTIAL INSAR # ------------------------------------------ DI_OUT_FILE $DATAOUTDIR/${MASTER}_${SLAVE}.dcint // differential DI_IN_TOPOSLAVE topodir/slave.res DI_IN_TOPOINT topodir/products.res c DI_IN_TOPOMASTER topodir/master.res // 4 pass c DI_OUT_SCALED debug.raw c // c // STOP // mandatory # vim: syntax=doris __GENEOF_6b } # # GEN_7() { fn=$INPUT_7 GENERAL FILES cat << __GENEOF_7a PROCESS slant2h // PROCESS geocode // __GENEOF_7a cat << __GENEOF_7b # ------------------------------------------ # SLANT TO HEIGHT CONVERSION # ------------------------------------------ c c S2H_METHOD ambiguity // c S2H_METHOD rodriguez // S2H_METHOD schwabisch // adviced! S2H_NPOINTS 200 // S2H_DEGREE1D 2 // S2H_NHEIGHTS 3 // S2H_DEGREE2D 5 // S2H_OUT_HEI $DATAOUTDIR/heights.raw // C S2H_OUT_HEI $DATAOUTDIR/s2h_heights.raw // C S2H_OUT_LAM $DATAOUTDIR/s2h_lambda.raw // C S2H_OUT_PHI $DATAOUTDIR/s2h_phi.raw // # ------------------------------------------ # GEOCODING # ------------------------------------------ GEO_OUT_PHI $DATAOUTDIR/phi.raw // GEO_OUT_LAM $DATAOUTDIR/lambda.raw // c // c // STOP // mandatory # vim: syntax=doris __GENEOF_7b } # # GEN_8() { fn=$INPUT_8 GENERAL FILES cat << __GENEOF_8a PROCESS ??? __GENEOF_8a cat << __GENEOF_8b # ------------------------------------------ # ?? # ------------------------------------------ c CARDS GO HERE c CARDS GO HERE c CARDS GO HERE c // c // STOP // mandatory __GENEOF_8b } # # GEN_9() { fn=$INPUT_9 cat << __GENEOF_9a ###################################################################################### ### This is a (full scene) quicklook processing. To quickly see the ifg etc, ### ### use "run -ql (or equivalently run -s9)". ### ### this will run -s1; run -s2; run -s9 (i.e, read files, process them ### ### Therefore, also edit step1,2 input (run -e1; run -e2) to set input filenames. ### ### You can set the DBOW crop there. If master.res or slave.res already exist ### ### then these steps are skipped. ### ### ### ### Basically we read the data, then automated coregistration with lower quality, ### ### fast resampling to short output format, and form the interferogram, flatten it ### ### and compute the coherence image, all heavily multilooked. ### ### NO spektral filtering. Experimental... ### ### ### ### This takes about 6 minutes for a quarter scene. ### ### ### ###%// BK 15-Sep-2003 ### ###################################################################################### SCREEN info // level of output to standard out BEEP warning // level of beeping PREVIEW on // SUNraster files with cpxfiddle MEMORY 200 // MB OVERWRITE ON // overwrite existing files BATCH ON // non-interactive LISTINPUT ON // copy this file to log ORB_INTERP POLYFIT 3 // orbit interpolation method LOGFILE quicklook.log // M_RESFILE master_QL.res // after run -s1, run -s2 the files are S_RESFILE slave_QL.res // copied to these I_RESFILE ifg_QL.res // names ### ### PROCESS coarseorb // no cards later PROCESS coarsecorr // based on correlation PROCESS fine // fine coregistration PROCESS coregpm // estimate coregistration param. PROCESS resample // slave PROCESS interfero // PROCESS comprefpha // estimate flatearth param. PROCESS subtrrefpha // PROCESS coherence // ### ### CC_METHOD magfft // default CC_NWIN 21 // number of windows CC_WINSIZE 256 256 // size of large windows CC_INITOFF orbit // use result of orbits ### ### FC_METHOD magfft // FC_NWIN 501 // number of windows FC_WINSIZE 64 64 // size of small windows FC_ACC 8 8 // search window, 2^n FC_INITOFF coarsecorr // use result of coarse FC_OSFACTOR 8 // oversampling factor ### ### CPM_THRESHOLD 0.2 // CPM_DEGREE 2 // CPM_WEIGHT quadratic // none | linear | quadratic CPM_MAXITER 350 // automated removal, max 20 iterations CPM_K_ALPHA 5.00 // automated removal crit. value ### ### RS_METHOD tri // linear interpolation RS_OUT_FILE $DATAOUTDIR/$SLAVE.resampled_QL RS_OUT_FORMAT ci2 // RS_SHIFTAZI off // doppler ### ### INT_METHOD old // INT_OUT_CINT $DATAOUTDIR/${MASTER}_${SLAVE}.cint_QL // optional complex int. INT_MULTILOOK 10 2 // 20 x 20 m ### ### FE_METHOD porbits // FE_DEGREE 5 // FE_NPOINTS 301 // ### ### SRP_OUT_CINT $DATAOUTDIR/${MASTER}_${SLAVE}.srp_QL // SRP_MULTILOOK 3 3 // total 60x60 m ### ### COH_METHOD refphase_only // options: refphase_only or include_refdem COH_OUT_COH $DATAOUTDIR/${MASTER}_${SLAVE}.coh_QL // optional real COH_MULTILOOK 30 6 // COH_WINSIZE 30 6 // ### STOP // mandatory # vim: syntax=doris __GENEOF_9a } GENERATE() { #BK 19-Jan-2001: set resultfiles -M -S option MASTERRES="$MASTER.res" SLAVERES="$SLAVE.res" INTERFRES="${MASTER}_${SLAVE}.res" # Workdir if [ ! -d $WORKDIR ]; then mkdir $WORKDIR echo "${bn}: ***INFO*** workdir: $WORKDIR created." fi # Directory where input prototypes are stored. if [ -d $INPUTDIR ]; then echo "${bn}: ***WARNING*** inputdir: $INPUTDIR existed, I renamed it to $INPUTDIR.$$." mv -f $INPUTDIR $INPUTDIR.$$ fi mkdir $INPUTDIR # Output directory for redirected standard output. if [ -d $OUTPUTDIR ]; then echo "${bn}: ***WARNING*** outputdir: $OUTPUTDIR existed, I renamed it to $OUTPUTDIR.$$" mv -f $OUTPUTDIR $OUTPUTDIR.$$ fi mkdir $OUTPUTDIR # Output directory for matrices. if [ ! -d $DATAOUTDIR ]; then mkdir $DATAOUTDIR fi # Test if executable is present. #if [ ! -x $SWDIR/$PROG ]; then # echo "executable: $SWDIR/$PROG not present." # if [ ! -x $WORKDIR/$PROG ]; then # echo "also not in workdir: $WORKDIR, exiting." # exit 4 # fi # echo "Continuing" #fi #if [ -x $WORKDIR/$PROG ]; then # echo "executable already present in: $WORKDIR/$PROG, I renamed it to $WORKDIR/$PROG.$$" # mv -f $WORKDIR/$PROG $WORKDIR/$PROG.$$ #fi # cp $SWDIR/$PROG $WORKDIR/$PROG GEN_1 > $INPUTDIR/$INPUT_1 GEN_2 > $INPUTDIR/$INPUT_2 GEN_3 > $INPUTDIR/$INPUT_3 GEN_4 > $INPUTDIR/$INPUT_4 GEN_5 > $INPUTDIR/$INPUT_5 GEN_6 > $INPUTDIR/$INPUT_6 GEN_7 > $INPUTDIR/$INPUT_7 # GEN_8 > $INPUTDIR/$INPUT_8 GEN_9 > $INPUTDIR/$INPUT_9 echo "${bn}: ***INFO*** generation of inputfiles finished." echo "${bn}: ***INFO*** inputdir: $INPUTDIR" echo "${bn}: ***INFO*** outputdir (stout): $OUTPUTDIR" echo "${bn}: ***INFO*** outputdir (matrices): $DATAOUTDIR" # # BK 25-feb-2000 # 2nd check is not ok, should check with whence? # if [ -x $PROGINCWD ]; then echo "${bn}: ***INFO*** Using executable in cwd: $PROGINCWD" else echo "${bn}: ***INFO*** Using executable in path: $PROG" echo "${bn}: ***INFO*** or (if -d option present): $PROGDEBUG" fi echo "${bn}: ***TIP*** run -e1; run -s1" exit 0 } ################################################## # START SCRIPT --------------- # Set viewer (if no default environment variables: PAGER and EDITOR) ### # Set PAGER (VIEWER) and EDITOR if not default (prefer less and nedit) if [ "X$PAGER" = "X" ]; then #default should be specified in your login resource file. echo "environment variable PAGER not set, please set this variable" echo "to specify your prefered viewer. For example in csh shell type:" echo " setenv PAGER more" echo " setenv PAGER less (adviced)" #PAGER="more" PAGER="less" $PAGER 2>&1 if [ "$status" = "0" ]; then echo "PAGER: $PAGER found in path..." else PAGER="more" echo "using PAGER $PAGER" fi fi VIEWER="$PAGER" if [ "X$EDITOR" = "X" ]; then #default should be specified in your login resource file. echo "environment variable EDITOR not set, please set this variable" echo "to specify your prefered editor. For example in csh shell type:" echo " setenv EDITOR vi" echo " setenv EDITOR nedit" echo " setenv EDITOR xemacs" EDITOR="nedit" $EDITOR 2>&1 if [ "$status" = "0" ]; then echo "EDITOR: $EDITOR found in path..." else EDITOR="vi" echo "using EDITOR $EDITOR" fi fi # Assume template inputfile are generated, obtain name of files... # only for view? if [ "$DOGENERATE" = "0" ]; then if [ -r $INPUTDIR/$INPUT_1 ]; then MASTERRES=`awk '/M_RESFILE/ {print $2}' $INPUTDIR/$INPUT_1` SLAVERES=`awk '/S_RESFILE/ {print $2}' $INPUTDIR/$INPUT_1` INTERFRES=`awk '/I_RESFILE/ {print $2}' $INPUTDIR/$INPUT_1` fi fi # Help wanted? #if [ $# -eq 1 -a "$1" = "-h" ]; then if [ "$1" = "-h" ]; then name=`NAME` synopsis=`SYNOPSIS` MANPG | $PAGER exit fi ### Simple options parsing by bert... since getopts not known on my cygwin sh shell (?) ### This is slower and not tested properly like lib function, but seems to work. ### Also it doesn't incorporate numargs exceptions checks. ### Bert Kampes, 03-Feb-2002. #1) delete all spaces from input option string, delimiters are - signs #2) insert spaces before - signs (use QQQ to keep spaces in OPTARG) #3) for each word, obtain option and argument #INPUTARGS=`echo "$*" | sed 's/ /QQQ/g' | sed 's/-/ -/g'` INPUTARGS=`echo "$*" | sed 's/ //g' | sed 's/-/ -/g'` for OPTION in $INPUTARGS; do OPTKEY=`echo $OPTION | awk '{print substr($1,1,2)}'` OPTARG=`echo $OPTION | awk '{print substr($1,3)}'` # OPTARG=`echo $OPTION | awk '{print substr($1,3)}' | sed 's/QQQ/ /g'` # echo "OPTKEY: "XXX${OPTKEY}XXX # echo "OPTARG: "XXX${OPTARG}XXX # if test "$OPTKEY"="-f"; then # INPUT="$OPTARG" # fi ### quicklook run step 9 case $OPTKEY in -f) INPUT=$OPTARG ;; -d) PROG=$PROGDEBUG ;; -s) STEP=$OPTARG ;; -q) STEP=9 ;; -e) EDIT=$OPTARG ;; -v) VIEW=$OPTARG ;; -r) RESULT=$OPTARG ;; -g) DOGENERATE="1" ;; -M) MASTER=$OPTARG ;; -S) SLAVE=$OPTARG ;; -A) AUTHOR=$OPTARG ;; -B) BASELINE=$OPTARG ;; -R) REMARKS=$OPTARG ;; -h) USAGE ;; \?) USAGE ;; *) echo "wrong input argument"; USAGE ;; esac done ### OLD KSH getopts... ### Get other options. ###OPTIONS="f:s:e:v:r:M:S:A:B:R:gd" ###while getopts $OPTIONS OPT; do ### case $OPT in ### f) INPUT=$OPTARG ;; ### d) PROG=$PROGDEBUG ;; ### s) STEP=$OPTARG ;; ### e) EDIT=$OPTARG ;; ### v) VIEW=$OPTARG ;; ### r) RESULT=$OPTARG ;; ### g) DOGENERATE="1" ;; ### M) MASTER=$OPTARG ;; ### S) SLAVE=$OPTARG ;; ### A) AUTHOR=$OPTARG ;; ### B) BASELINE=$OPTARG ;; ### R) REMARKS=$OPTARG ;; ### \?) USAGE ;; ### esac ###done # Check any input. if [ "$1" = "" ]; then USAGE fi # -g option. if [ "$DOGENERATE" = "1" ]; then GENERATE fi # -e option. case $EDIT in 1) if [ -r $INPUTDIR/$INPUT_1 ]; then $EDITOR $INPUTDIR/$INPUT_1 #echo "don't forget to mountcd"; echo "to run, use: $bn -s$EDIT" else echo "${bn}: ***ERROR*** file $INPUTDIR/$INPUT_1 not found." fi;; 2) if [ -r $INPUTDIR/$INPUT_2 ]; then $EDITOR $INPUTDIR/$INPUT_2 #echo "don't forget to mountcd" echo "to run, use: $bn -s$EDIT" else echo "${bn}: ***ERROR*** file $INPUTDIR/$INPUT_2 not found." fi;; 3) if [ -r $INPUTDIR/$INPUT_3 ]; then $EDITOR $INPUTDIR/$INPUT_3 echo "to run, use: $bn -s$EDIT" else echo "${bn}: ***ERROR*** file $INPUTDIR/$INPUT_3 not found." fi;; 4) if [ -r $INPUTDIR/$INPUT_4 ]; then $EDITOR $INPUTDIR/$INPUT_4 echo "to run, use: $bn -s$EDIT" else echo "${bn}: ***ERROR*** file $INPUTDIR/$INPUT_4 not found." fi;; 5) if [ -r $INPUTDIR/$INPUT_5 ]; then $EDITOR $INPUTDIR/$INPUT_5 echo "to run, use: $bn -s$EDIT" else echo "${bn}: ***ERROR*** file $INPUTDIR/$INPUT_5 not found." fi;; 6) if [ -r $INPUTDIR/$INPUT_6 ]; then $EDITOR $INPUTDIR/$INPUT_6 echo "to run, use: $bn -s$EDIT" else echo "${bn}: ***ERROR*** file $INPUTDIR/$INPUT_6 not found." fi;; 7) if [ -r $INPUTDIR/$INPUT_7 ]; then $EDITOR $INPUTDIR/$INPUT_7 echo "to run, use: $bn -s$EDIT" else echo "${bn}: ***ERROR*** file $INPUTDIR/$INPUT_7 not found." fi;; 8) if [ -r $INPUTDIR/$INPUT_8 ]; then $EDITOR $INPUTDIR/$INPUT_8 echo "to run, use: $bn -s$EDIT" else echo "${bn}: ***ERROR*** file $INPUTDIR/$INPUT_8 not found." fi;; 9) if [ -r $INPUTDIR/$INPUT_9 ]; then $EDITOR $INPUTDIR/$INPUT_9 echo "to run, use: $bn -s$EDIT" else echo "${bn}: ***ERROR*** file $INPUTDIR/$INPUT_9 not found." fi;; 999) ;; *) echo "wrong -e(dit) argument"; USAGE ;; esac # -s option. if [ "$STEP" != "999" ]; then case $STEP in 1) INPUT=$INPUT_1 ;; 2) INPUT=$INPUT_2 ;; 3) INPUT=$INPUT_3 ;; 4) INPUT=$INPUT_4 ;; 5) INPUT=$INPUT_5 ;; 6) INPUT=$INPUT_6 ;; 7) INPUT=$INPUT_7 ;; 8) INPUT=$INPUT_8 ;; 9) INPUT=$INPUT_9 ;; # 999) ;; *) echo "wrong -s argument"; USAGE ;; esac #substitution problem on capone with sh? (simple solution change name...) #%// BK 16-Jun-2003 #OUTFILE=$OUTPUTDIR/out.${INPUT#input.} OUTFILE=$OUTPUTDIR/stdout.$INPUT INPUT=$INPUTDIR/$INPUT ### Check if there is an inputfile. if [ ! -r $INPUT ]; then echo "${bn}: ***ERROR*** Inputfile: $INPUT not readable, exiting" exit fi; ### Check if output allready exists. if [ -f $OUTFILE ]; then echo "${bn}: ***WARNING*** (redirected) outputfile: $OUTFILE existed, I renamed it to $OUTFILE.$$" mv -f $OUTFILE $OUTFILE.$$ fi; ### if no -d option and prog "doris" is present in cwd, use it. if [ -x $PROGINCWD ] && [ $PROG != $PROGDEBUG ]; then PROG=$PROGINCWD fi; ### If quicklook processing, first run step1 and step2 to read the data ### this means step=9, and run that after that! touch $OUTFILE if [ "$STEP" = "9" ]; then touch $LOGFILE mv $LOGFILE $LOGFILE.tmp echo " " echo " - - PERFORMING QUICKLOOK PROCESSING - -" echo " " echo " First I will do: run -s1, then run -s2 (readfiles and crop)" echo " Then I will copy the resultfiles to new QL names" echo " Then I will do: run -s9 (the steps to get the interferogram)" echo " " echo " I will pause after the master has been read, so you can change the CDROM" echo " " echo " ---------------------------------------------------------------" >> $OUTFILE echo " --- START STEP 1 for QUICKLOOK --------------------------------" >> $OUTFILE echo " ---------------------------------------------------------------" >> $OUTFILE if [ -f master_QL.res ]; then echo " SKIPPING run -s1 since file master_QL.res exists (master has been read)" else $PROG $INPUTDIR/$INPUT_1 >> $OUTFILE if [ ! -f $MASTERRES ]; then echo "file $MASTERRES does not exist. Exiting." mv $LOGFILE.tmp $LOGFILE exit 1 fi; cp $MASTERRES master_QL.res fi; echo " " echo " *************************************************************" echo " *** Pausing after reading master so you can change cdrom. ***" echo " *** Press when ready to proceed. ***" echo " *************************************************************" echo " " read key echo " " echo " ---------------------------------------------------------------" >> $OUTFILE echo " --- START STEP 2 for QUICKLOOK --------------------------------" >> $OUTFILE echo " ---------------------------------------------------------------" >> $OUTFILE if [ -f slave_QL.res ]; then echo " SKIPPING run -s1 since file slave_QL.res exists (slave has been read)" else $PROG $INPUTDIR/$INPUT_2 >> $OUTFILE if [ ! -f $SLAVERES ]; then echo "file $SLAVERES does not exist. Exiting." mv $LOGFILE.tmp $LOGFILE exit 1 fi; cp $SLAVERES slave_QL.res fi; echo " " echo " Done with reading slave (and master). Proceeding with quicklook" echo " First copying master and slave result file to master_QL.res, slave_QL.res" echo " " echo " ---------------------------------------------------------------" >> $OUTFILE echo " --- START STEP 9 for QUICKLOOK --------------------------------" >> $OUTFILE echo " --- (first moving the output files of run -s1 and run -s2 -----" >> $OUTFILE echo " ---------------------------------------------------------------" >> $OUTFILE mv $LOGFILE quicklook.log mv $LOGFILE.tmp $LOGFILE if [ -f ifg_QL.res ]; then echo "file ifg_QL.res already exists??? continuing..." fi; fi; ### Execute program (use >> for quicklook, is an empty touched file anyway) echo " $PROG $INPUT >> $OUTFILE " echo " " $PROG $INPUT >> $OUTFILE echo " " echo " Redirected output in file: $OUTFILE" echo " view with: run -v$STEP" ### Save some work for user / tips ### if [ "$STEP" = "1" ]; then # echo " don't forget to umountcd" echo " NOTE: before run -s1, you can do run -ql to get a quicklook processing." echo " which will run step 1 and 2 if not done already." fi; if [ "$STEP" = "9" ]; then echo " " echo " Moving quicklook output to QL sub directory." echo " " mkdir QL mv *ras *ras.sh *_QL* *quicklook* ./QL fi; fi; ### -v option. case $VIEW in 1) if [ -r $OUTPUTDIR/stdout.$INPUT_1 ]; then $VIEWER $OUTPUTDIR/stdout.$INPUT_1 else echo "${bn}: ***ERROR*** file $OUTPUTDIR/stdout.$INPUT_1 not found." fi;; 2) if [ -r $OUTPUTDIR/stdout.$INPUT_2 ]; then $VIEWER $OUTPUTDIR/stdout.$INPUT_2 else echo "${bn}: ***ERROR*** file $OUTPUTDIR/stdout.$INPUT_2 not found." fi;; 3) if [ -r $OUTPUTDIR/stdout.$INPUT_3 ]; then $VIEWER $OUTPUTDIR/stdout.$INPUT_3 else echo "${bn}: ***ERROR*** file $OUTPUTDIR/stdout.$INPUT_3 not found." fi;; 4) if [ -r $OUTPUTDIR/stdout.$INPUT_4 ]; then $VIEWER $OUTPUTDIR/stdout.$INPUT_4 else echo "${bn}: ***ERROR*** file $OUTPUTDIR/stdout.$INPUT_4 not found." fi;; 5) if [ -r $OUTPUTDIR/stdout.$INPUT_5 ]; then $VIEWER $OUTPUTDIR/stdout.$INPUT_5 else echo "${bn}: ***ERROR*** file $OUTPUTDIR/stdout.$INPUT_5 not found." fi;; 6) if [ -r $OUTPUTDIR/stdout.$INPUT_6 ]; then $VIEWER $OUTPUTDIR/stdout.$INPUT_6 else echo "${bn}: ***ERROR*** file $OUTPUTDIR/stdout.$INPUT_6 not found." fi;; 7) if [ -r $OUTPUTDIR/stdout.$INPUT_7 ]; then $VIEWER $OUTPUTDIR/stdout.$INPUT_7 else echo "${bn}: ***ERROR*** file $OUTPUTDIR/stdout.$INPUT_7 not found." fi;; 8) if [ -r $OUTPUTDIR/stdout.$INPUT_8 ]; then $VIEWER $OUTPUTDIR/stdout.$INPUT_8 else echo "${bn}: ***ERROR*** file $OUTPUTDIR/stdout.$INPUT_8 not found." fi;; 9) if [ -r $OUTPUTDIR/stdout.$INPUT_9 ]; then $VIEWER $OUTPUTDIR/stdout.$INPUT_9 else echo "${bn}: ***ERROR*** file $OUTPUTDIR/stdout.$INPUT_9 not found." fi;; 999) ;; *) echo "wrong -v argument"; USAGE ;; esac cd $WORKDIR # -r option. case $RESULT in 1) if [ -r $MASTERRES ]; then $EDIT $MASTERRES else echo "${bn}: ***ERROR*** file $MASTERRES not found." fi;; 2) if [ -r $SLAVERES ]; then $EDIT $SLAVERES else echo "${bn}: ***ERROR*** file $SLAVERES not found." fi;; 3) if [ -r $INTERFRES ]; then $EDIT $INTERFRES else echo "${bn}: ***ERROR*** file $INTERFRES not found." fi;; 4) if [ -r $LOGFILE ]; then $EDIT $LOGFILE else echo "${bn}: ***ERROR*** file $LOGFILE not found." fi;; 999) ;; *) echo "wrong -v argument"; USAGE ;; esac exit 0 ### RCS ##### # $Source: /users/kampes/DEVELOP/DORIS/doris/bin/RCS/run,v $ # $Revision: 4.01 $ # $Author: FvL $ # $Date: 2008/12/17 12:02:06 $ # $Log: run,v $ # Revision 4.01 2008/12/17 12:02:06 FvL # Update to doris v4.01 # # Revision 3.47 2005/09/20 12:02:06 kampes # *** empty log message *** # # Revision 3.46 2005/09/20 11:02:16 kampes # ERR changed to ERROR # # Revision 3.45 2005/08/25 13:38:01 kampes # *** empty log message *** # # Revision 3.44 2005/08/25 07:37:50 kampes # *** empty log message *** # # Revision 3.43 2005/08/24 15:12:40 kampes # *** empty log message *** # # Revision 3.42 2005/08/24 11:35:32 kampes # *** empty log message *** # # Revision 3.41 2005/08/16 11:46:26 kampes # update for v3.16 # # Revision 3.40 2005/07/28 09:28:48 kampes # *** empty log message *** # # Revision 3.39 2005/04/16 10:08:05 kampes # *** empty log message *** # # Revision 3.38 2005/04/16 10:00:37 kampes # added CRD_OUT_DEM_LP # # Revision 3.37 2005/04/08 14:09:53 kampes # *** empty log message *** # # Revision 3.36 2005/03/08 14:04:55 kampes # *** empty log message *** # # Revision 3.35 2004/09/20 08:05:59 kampes # *** empty log message *** # # Revision 3.34 2004/09/15 10:49:03 kampes # *** empty log message *** # # Revision 3.33 2004/09/13 08:20:57 kampes # *** empty log message *** # # Revision 3.32 2004/08/24 15:33:15 kampes # *** empty log message *** # # Revision 3.31 2004/08/09 09:46:53 kampes # *** empty log message *** # # Revision 3.30 2004/08/03 13:22:56 kampes # increased default memory usage # # Revision 3.29 2004/06/17 09:38:54 kampes # *** empty log message *** # # Revision 3.28 2004/06/03 06:19:52 kampes # *** empty log message *** # # Revision 3.27 2004/05/13 18:28:58 kampes # *** empty log message *** # # Revision 3.26 2004/01/20 15:08:03 kampes # added oversampling # # Revision 3.25 2003/12/22 06:50:51 kampes # added knab windows card # # Revision 3.24 2003/12/15 07:56:41 kampes # added DBOW_GEO card # # Revision 3.23 2003/11/27 16:14:54 kampes # *** empty log message *** # # Revision 3.22 2003/11/27 16:01:11 kampes # *** empty log message *** # # Revision 3.21 2003/11/27 15:39:42 kampes # *** empty log message *** # # Revision 3.20 2003/09/15 13:27:54 kampes # *** empty log message *** # # Revision 3.19 2003/09/15 13:11:26 kampes # *** empty log message *** # # Revision 3.18 2003/09/15 12:24:12 kampes # *** empty log message *** # # Revision 3.17 2003/09/15 10:14:08 kampes # added quicklook # # Revision 3.16 2003/09/12 15:12:46 kampes # added quicklook as s9 # # Revision 3.15 2003/09/01 15:33:33 kampes # *** empty log message *** # # Revision 3.14 2003/09/01 06:42:56 kampes # *** empty log message *** # # Revision 3.13 2003/08/28 17:12:36 kampes # added coregpm maxioter # # Revision 3.12 2003/08/14 08:45:58 kampes # added jers info # # Revision 3.11 2003/06/24 08:32:38 kampes # release version # # Revision 3.10 2003/06/17 13:24:00 kampes # *** empty log message *** # # Revision 3.9 2003/06/16 14:59:10 kampes # increased default numwindows fine coreg. # # Revision 3.8 2003/06/16 11:44:33 kampes # seemed to be a problem with run file variable name substitution. # # Revision 3.7 2003/06/16 07:05:11 kampes # new version # # Revision 3.6 2003/04/15 06:31:58 kampes # *** empty log message *** # # Revision 3.5 2003/04/14 06:35:15 kampes # doris release 3.5 # # Revision 1.60 2001/09/28 14:09:57 14:09:57 kampes (B.M.Kampes) # release doris 3.2 # # Revision 1.57 2000/12/07 13:53:44 13:53:44 kampes (B.M.Kampes) # release 3 # # Revision 1.56 2000/10/24 13:46:20 13:46:20 kampes (B.M.Kampes) # doris2.6 # # Revision 1.42 2000/04/05 11:37:13 11:37:13 kampes (B.M.Kampes) # range filtering # # Revision 1.41 2000/02/25 15:36:20 15:36:20 kampes (B.M.Kampes) # cohwinsize added. # # Revision 1.40 2000/02/25 09:45:26 09:45:26 kampes (B.M.Kampes) # check whence # # Revision 1.39 2000/02/16 17:44:49 17:44:49 kampes (B.M.Kampes) # new cards, refdem, check release 2.2 # # Revision 1.37 2000/02/09 11:22:35 11:22:35 kampes (B.M.Kampes) # new cards # # Revision 1.32 2000/01/06 09:55:04 09:55:04 kampes (B.M.Kampes) # use exe in cwd # # Revision 1.31 2000/01/06 09:25:06 09:25:06 kampes (B.M.Kampes) # author added # # Revision 1.29 99/12/20 14:35:45 14:35:45 kampes (B.M.Kampes) # synopsis updated # # Revision 1.28 99/12/16 13:53:03 13:53:03 kampes (B.M.Kampes) # some new options -d for use with 1 script # # Revision 1.27 99/12/13 16:50:42 16:50:42 kampes (B.M.Kampes) # *** empty log message *** # # Revision 1.26 99/12/09 16:06:48 16:06:48 kampes (B.M.Kampes) # mountcds # # Revision 1.25 99/12/09 15:11:44 15:11:44 kampes (B.M.Kampes) # bugfixed # # Revision 1.24 99/12/03 09:39:31 09:39:31 kampes (B.M.Kampes) # new setup steps, reviewed ok version. # # # Revision 1.16 99/11/02 11:34:53 11:34:53 kampes (B.M.Kampes) # doris v1.2 s2h geocoding # # Revision 1.1 99/09/13 15:57:22 15:57:22 kampes (B.M.Kampes) # initial version # ############# Doris-5.0.3Beta/bin/sec2hhmmss.py000077500000000000000000000007771312547014700166130ustar00rootroot00000000000000#!/usr/bin/env python import os,sys,time def usage(): print '\nUsage: python sec2hhmmss.py time' print ' where time is the time of day in seconds.' print ' ' print ' Example ' print ' sec2hhmmss.py 59800.445398' print ' 16:36:40.393' try: timeOfDay = sys.argv[1] except: print 'Unrecognized input' usage() sys.exit(1) timeOfDay = float(sys.argv[1]) hh = timeOfDay//3600 timeOfDay = timeOfDay%3600 mm = timeOfDay//60 ss = timeOfDay%60 print "%d:%d:%f" %(hh,mm,ss) Doris-5.0.3Beta/bin/tsx_dump_data.py000077500000000000000000000113511312547014700173610ustar00rootroot00000000000000#!/usr/bin/env python import os,sys,time def usage(): print '\nUsage: python tsx_dump_data.py tsx_COSAR_product outputfile [l0 lN p0 pN] -res RESFILE' print ' where tsx_COSAR_product is the input filename' print ' outputfile is the output filename' print ' l0 is the first azimuth line (starting at 1)' print ' lN is the last azimuth line' print ' p0 is the first range pixel (starting at 1)' print ' pN is the last range pixel' print ' RESFILE DORIS result file that is to be updated for crop metadata' try: inputFileName = sys.argv[1]; outputFileName = sys.argv[2] except: print 'Unrecognized input' usage() sys.exit(1) inputFileName = sys.argv[1] outputFileName = sys.argv[2] resFile = None for element in range(len(sys.argv)): option = sys.argv[element]; if option == '-res': resFile = str(sys.argv[element+1]) # print resFile del sys.argv[element+1] del sys.argv[element] break if len(sys.argv) == 3: outputWinFirstLine = None outputWinLastLine = None outputWinFirstPix = None outputWinLastPix = None elif len(sys.argv) > 3 and len(sys.argv) < 9: outputWinFirstLine = int(sys.argv[3])-1 # gdal srcwin starting at 0 outputWinLastLine = int(sys.argv[4]) # Lastline --> yoff (later) outputWinFirstPix = int(sys.argv[5])-1 # gdal srcwin starting at 0 outputWinLastPix = int(sys.argv[6]) # Lastpix --> yoff (later) elif len(sys.argv) > 3 and len(sys.argv) < 7: print 'Unrecognized input' usage() sys.exit(1) else: outputWinFirstLine = None outputWinLastLine = None outputWinFirstPix = None outputWinLastPix = None # system parameters :: check whether its there gdalCall = 'gdal_translate' # Output data parameters outputDataFormat = 'MFF' outputDataType = 'CInt16' cmd = '%s %s -ot %s -of %s %s' % (gdalCall,inputFileName,outputDataType,outputDataFormat,outputFileName) if outputWinFirstPix is not None: cmd = cmd + (' -srcwin %s %s %s %s' % (outputWinFirstPix,outputWinFirstLine,outputWinLastPix-outputWinFirstPix,outputWinLastLine-outputWinFirstLine)) #print cmd failure = os.system(cmd) if failure: print '%s: running %s failed' % (sys.argv[0],cmd) sys.exit(1) else: os.rename(os.path.splitext(outputFileName)[0]+'.j00',outputFileName) # call to cpxfiddle # check whether the file exist!!! if resFile is not None: print resFile # load header headerFileStream = open(os.path.splitext(outputFileName)[0]+'.hdr','r') for line in headerFileStream: pair = line.split() if len(pair) > 1: vars()[pair[0]] = pair[2] # set IMAGE_LINES and LINE_SAMPLES # print vars()[pair[0]] # check whether the file exist outStream = open(resFile,'a') outStream.write('\n') outStream.write('*******************************************************************\n') outStream.write('*_Start_crop: cosar\n') outStream.write('*******************************************************************\n') outStream.write('Data_output_file: %s\n' % outputFileName) outStream.write('Data_output_format: complex_short\n') # hardcoded if outputWinFirstPix is not None: outStream.write('First_line (w.r.t. original_image): %s\n' % (outputWinFirstLine+1)) # back to Doris convention outStream.write('Last_line (w.r.t. original_image): %s\n' % outputWinLastLine) outStream.write('First_pixel (w.r.t. original_image): %s\n' % (outputWinFirstPix+1)) outStream.write('Last_pixel (w.r.t. original_image): %s\n' % outputWinLastPix) elif outputWinFirstPix is None: outStream.write('First_line (w.r.t. original_image): 1\n') outStream.write('Last_line (w.r.t. original_image): %s\n' % IMAGE_LINES) outStream.write('First_pixel (w.r.t. original_image): 1\n') outStream.write('Last_pixel (w.r.t. original_image): %s\n' % LINE_SAMPLES) outStream.write('*******************************************************************\n') outStream.write('* End_crop:_NORMAL\n') outStream.write('*******************************************************************\n') outStream.write('\n') outStream.write(' Current time: %s\n' % time.asctime()) outStream.write('\n') # close output file outStream.close() # replace crop tag in result file sourceText = "crop: 0" replaceText = "crop: 1" inputStream = open(resFile,'r') textStream = inputStream.read() inputStream.close() outputStream = open(resFile, "w") outputStream.write(textStream.replace(sourceText, replaceText)) outputStream.close() Doris-5.0.3Beta/bin/tsx_dump_header2doris.py000077500000000000000000000230441312547014700210250ustar00rootroot00000000000000#!/usr/bin/python # live code for parsing of XML TSX file into python data structures # and from there into DORIS res file structure # this is rather fair implementation and should be used as a structure # for the future implementation of XML/GeoTIFF data readers from lxml import etree import string, time, sys #import xml.etree.ElementTree as ElementTree #import types def usage(): print '\nUsage: python tsx_dump_header2doris.py tsx_XML_product > outputfile' print ' where tsx_XML_product is the input filename' # print ' outputfile is the output DORIS resultfile' try: inputFileName = sys.argv[1] # outputFileName = sys.argv[2] # outStream = open(outputFileName,'w') except: print 'Unrecognized input' usage() sys.exit(1) # input file #inputFileName = '04091/04091.xml' # #outputFileName = 'inputFileName' inTree = etree.parse(inputFileName) # query syntax for every field queryList = {\ # mission info 'mission' : './/generalHeader/mission',\ # imageData file 'imageData' : './/productComponents/imageData/file/location/filename',\ 'imageLines' : './/imageDataInfo/imageRaster/numberOfRows',\ 'imagePixels': './/imageDataInfo/imageRaster/numberOfColumns',\ # volume info 'volFile' : './/productComponents/annotation/file/location/filename',\ 'volID' : './/generalHeader/itemName',\ 'volRef' : './/generalHeader/referenceDocument',\ # product info 'productSpec' : './/generalHeader/referenceDocument',\ 'productVolDate' : './/setup//IOCSAuxProductGenerationTimeUTC',\ 'productDate' : './/generalHeader/generationTime',\ 'productFacility': './/productInfo/generationInfo/level1ProcessingFacility',\ # scene info 'scenePol' : './/productInfo/acquisitionInfo//polLayer',\ 'sceneMode' : './/setup/orderInfo/imagingMode',\ 'sceneCenLat' : './/sceneInfo/sceneCenterCoord/lat',\ 'sceneCenLon' : './/sceneInfo/sceneCenterCoord/lon',\ 'sceneRecords' : './/imageDataInfo/imageRaster/numberOfRows',\ # orbit info 'orbitABS' : './/productInfo/missionInfo/absOrbit',\ 'orbitDir' : './/productInfo/missionInfo/orbitDirection',\ 'orbitTime': './/stateVec/timeUTC',\ 'orbitX' : './/stateVec/posX',\ 'orbitY' : './/stateVec/posY',\ 'orbitZ' : './/stateVec/posZ',\ # range 'rangeRSR' :'.//productSpecific/complexImageInfo/commonRSF',\ 'rangeBW' :'.//processingParameter/rangeLookBandwidth',\ 'rangeWind' :'.//processingParameter/rangeWindowID',\ 'rangeTimePix' :'.//sceneInfo/rangeTime/firstPixel',\ # azimuth 'azimuthPRF' :'.//productSpecific/complexImageInfo/commonPRF',\ 'azimuthBW' :'.//processingParameter/azimuthLookBandwidth',\ 'azimuthWind' :'.//processingParameter/azimuthWindowID',\ 'azimuthTimeStart' : './/sceneInfo/start/timeUTC',\ # doppler 'dopplerTime' :'.//dopplerEstimate/timeUTC',\ 'dopplerCoeff0':'.//combinedDoppler/coefficient[@exponent="0"]',\ 'dopplerCoeff1':'.//combinedDoppler/coefficient[@exponent="1"]',\ 'dopplerCoeff2':'.//combinedDoppler/coefficient[@exponent="2"]',\ } # temp variables and parameters container = {} # containerTemp = {} events = ('end',) # functions : not sure if needed def fast_iter_string(context): for event,elem in context: return elem.text # works with lists def fast_iter_list(context,tag=''): for event,elem in context: return elem.iterchildren(tag=tag).next().text def hms2sec(hmsString,convertFlag='int'): # input hmsString syntax: XX:XX:XX.xxxxxx secString = int(hmsString[0:2])*3600 + \ int(hmsString[3:5])*60 + \ float(hmsString[6:]) if convertFlag == 'int' : return int(secString) elif convertFlag == 'float' : return float(secString) else: return int(secString) for key in queryList.keys(): try: vars()[key]; except KeyError or NameError: vars()[key] = []; queryListKey = queryList[key] for nodes in inTree.findall(queryListKey): # for nodes in inTree.findall(queryList[key]): vars()[key].append(nodes.text) container[key] = vars()[key] # --------------------------------------------------------------------------------------------------------- dummyVar = 'DUMMY' # outStream.write('MASTER RESULTFILE: %s\n' % outputFileName) # outStream.write('\n') # outStream.write('\n') # outStream.write('Start_process_control\n') # outStream.write('readfiles: 1\n') # outStream.write('precise_orbits: 0\n') # outStream.write('crop: 0\n') # outStream.write('sim_amplitude: 0\n') # outStream.write('master_timing: 0\n') # outStream.write('oversample: 0\n') # outStream.write('resample: 0\n') # outStream.write('filt_azi: 0\n') # outStream.write('filt_range: 0\n') # outStream.write('NOT_USED: 0\n') # outStream.write('End_process_control\n') # outStream.write('\n') print('\ntsx_dump_header2doris.py v1.0, doris software, 2009\n') print('*******************************************************************') print('*_Start_readfiles:') print('*******************************************************************') print('Volume file: %s' % container['volFile'][0]) print('Volume_ID: %s' % container['volID'][0]) print('Volume_identifier: %s' % container['volRef'][0]) print('Volume_set_identifier: %s' % dummyVar) print('(Check)Number of records in ref. file: %s' % container['sceneRecords'][0]) print('SAR_PROCESSOR: %s' % str.split(container['productSpec'][0])[0]) print('Product type specifier: %s' % container['mission'][0]) print('Logical volume generating facility: %s' % container['productFacility'][0]) print('Logical volume creation date: %s' % container['productVolDate'][0]) print('Location and date/time of product creation: %s' % container['productDate'][0]) print('Scene identification: Orbit: %s %s Mode: %s' % (container['orbitABS'][0],container['orbitDir'][0],container['sceneMode'][0])) print('Scene location: lat: %.4f lon: %.4f' % (float(container['sceneCenLat'][0]),float(container['sceneCenLon'][0]))) print('Leader file: %s' % container['volFile'][0]) print('Sensor platform mission identifer: %s' % container['mission'][0]) print('Scene_centre_latitude: %s' % container['sceneCenLat'][0]) print('Scene_centre_longitude: %s' % container['sceneCenLon'][0]) print('Radar_wavelength (m): 0.031') #HARDCODED!!! print('First_pixel_azimuth_time (UTC): %s %s' % (time.strftime("%d-%b-%Y",time.strptime(container['azimuthTimeStart'][0].split('T')[0],"%Y-%m-%d")),container['azimuthTimeStart'][0].split('T')[1][:-1])) print('Pulse_Repetition_Frequency (computed, Hz): %s' % container['azimuthPRF'][0]) print('Total_azimuth_band_width (Hz): %s' % container['azimuthBW'][0]) print('Weighting_azimuth: %s' % str.upper(container['azimuthWind'][0])) print('Xtrack_f_DC_constant (Hz, early edge): %s' % container['dopplerCoeff0'][0]) print('Xtrack_f_DC_linear (Hz/s, early edge): %s' % container['dopplerCoeff1'][0]) try: print('Xtrack_f_DC_quadratic (Hz/s/s, early edge): %s' % container['dopplerCoeff2'][0]) except: print('Xtrack_f_DC_quadratic (Hz/s/s, early edge): %s' % [0][0]) print('Range_time_to_first_pixel (2way) (ms): %0.15f' % (float(container['rangeTimePix'][0])*1000)) print('Range_sampling_rate (computed, MHz): %0.6f' % (float(container['rangeRSR'][0])/1000000)) print('Total_range_band_width (MHz): %s' % (float(container['rangeBW'][0])/1000000)) print('Weighting_range: %s' % str.upper(container['rangeWind'][0])) print('') print('*******************************************************************') print('Datafile: %s' % container['imageData'][0]) print('Dataformat: %s' % 'TSX_COSAR') # hardcoded!!! print('Number_of_lines_original: %s' % container['imageLines'][0]) print('Number_of_pixels_original: %s' % container['imagePixels'][0]) print('*******************************************************************') print('* End_readfiles:_NORMAL') print('*******************************************************************') print('') print('') print('*******************************************************************') print('*_Start_leader_datapoints') print('*******************************************************************') print(' t(s) X(m) Y(m) Z(m)') print('NUMBER_OF_DATAPOINTS: %s' % len(container['orbitTime'])) print('') for i in range(len(container['orbitTime'])): print(' %s %s %s %s' % (hms2sec(container['orbitTime'][i].split('T')[1]),\ container['orbitX'][i],\ container['orbitY'][i],\ container['orbitZ'][i])) print('') print('*******************************************************************') print('* End_leader_datapoints:_NORMAL') print('*******************************************************************') # print('\n') # print(' Current time: %s\n' % time.asctime()) # print('\n') # close output file #outStream.close() Doris-5.0.3Beta/bin/tsx_dump_header2doris_noxpath.py000077500000000000000000000246201312547014700225670ustar00rootroot00000000000000#!/usr/bin/python # live code for parsing of XML TSX file into python data structures # and from there into DORIS res file structure # this is rather fair implementation and should be used as a structure # for the future implementation of XML/GeoTIFF data readers from lxml import etree import string, time, sys #import xml.etree.ElementTree as ElementTree #import types def usage(): print '\nUsage: python tsx_dump_header2doris.py tsx_XML_product > outputfile' print ' where tsx_XML_product is the input filename' # print ' outputfile is the output DORIS resultfile' try: inputFileName = sys.argv[1] # outputFileName = sys.argv[2] # outStream = open(outputFileName,'w') except: print 'Unrecognized input' usage() sys.exit(1) # input file #inputFileName = '04091/04091.xml' # #outputFileName = 'inputFileName' inTree = etree.parse(inputFileName) # query syntax for every field queryList = {\ # mission info 'mission' : './/generalHeader/mission',\ # imageData file 'imageData' : './/productComponents/imageData/file/location/filename',\ 'imageLines' : './/imageDataInfo/imageRaster/numberOfRows',\ 'imagePixels': './/imageDataInfo/imageRaster/numberOfColumns',\ # volume info 'volFile' : './/productComponents/annotation/file/location/filename',\ 'volID' : './/generalHeader/itemName',\ 'volRef' : './/generalHeader/referenceDocument',\ # product info 'productSpec' : './/generalHeader/referenceDocument',\ 'productVolDate' : './/setup//IOCSAuxProductGenerationTimeUTC',\ 'productDate' : './/generalHeader/generationTime',\ 'productFacility': './/productInfo/generationInfo/level1ProcessingFacility',\ # scene info 'scenePol' : './/productInfo/acquisitionInfo//polLayer',\ 'sceneMode' : './/setup/orderInfo/imagingMode',\ 'sceneCenLat' : './/sceneInfo/sceneCenterCoord/lat',\ 'sceneCenLon' : './/sceneInfo/sceneCenterCoord/lon',\ 'sceneRecords' : './/imageDataInfo/imageRaster/numberOfRows',\ # orbit info 'orbitABS' : './/productInfo/missionInfo/absOrbit',\ 'orbitDir' : './/productInfo/missionInfo/orbitDirection',\ 'orbitTime': './/stateVec/timeUTC',\ 'orbitX' : './/stateVec/posX',\ 'orbitY' : './/stateVec/posY',\ 'orbitZ' : './/stateVec/posZ',\ # range 'rangeRSR' :'.//productSpecific/complexImageInfo/commonRSF',\ 'rangeBW' :'.//processingParameter/rangeLookBandwidth',\ 'rangeWind' :'.//processingParameter/rangeWindowID',\ 'rangeTimePix' :'.//sceneInfo/rangeTime/firstPixel',\ # azimuth 'azimuthPRF' :'.//productSpecific/complexImageInfo/commonPRF',\ 'azimuthBW' :'.//processingParameter/azimuthLookBandwidth',\ 'azimuthWind' :'.//processingParameter/azimuthWindowID',\ 'azimuthTimeStart' : './/sceneInfo/start/timeUTC',\ 'heading' : './/sceneInfo/headingAngle',\ # doppler 'dopplerTime' :'.//dopplerEstimate/timeUTC',\ 'dopplerCoeff':'.//combinedDoppler/coefficient',\ # 'dopplerCoeff0':'.//combinedDoppler/coefficient[@exponent="0"]',\ # 'dopplerCoeff1':'.//combinedDoppler/coefficient[@exponent="1"]',\ # 'dopplerCoeff2':'.//combinedDoppler/coefficient[@exponent="2"]',\ } # temp variables and parameters container = {} # containerTemp = {} events = ('end',) # functions : not sure if needed def fast_iter_string(context): for event,elem in context: return elem.text # works with lists def fast_iter_list(context,tag=''): for event,elem in context: return elem.iterchildren(tag=tag).next().text def hms2sec(hmsString,convertFlag='int'): # input hmsString syntax: XX:XX:XX.xxxxxx secString = int(hmsString[0:2])*3600 + \ int(hmsString[3:5])*60 + \ float(hmsString[6:]) if convertFlag == 'int' : return int(secString) elif convertFlag == 'float' : return float(secString) else: return int(secString) for key in queryList.keys(): try: vars()[key]; except KeyError or NameError: vars()[key] = []; for nodes in inTree.findall(queryList[key]): if key == 'dopplerCoeff': vars()[key].append(nodes.text) if nodes.attrib.values()[0] == '0': keyTemp = 'dopplerCoeff0' # reset key try: vars()[keyTemp]; except KeyError or NameError: vars()[keyTemp] = []; vars()[keyTemp].append(nodes.text) elif nodes.attrib.values()[0] == '1': keyTemp = 'dopplerCoeff1' # reset key try: vars()[keyTemp]; except KeyError or NameError: vars()[keyTemp] = []; vars()[keyTemp].append(nodes.text) elif nodes.attrib.values()[0] == '2': keyTemp = 'dopplerCoeff2' # reset key try: vars()[keyTemp]; except KeyError or NameError: vars()[keyTemp] = []; vars()[keyTemp].append(nodes.text) container[keyTemp] = vars()[keyTemp] else: vars()[key].append(nodes.text) container[key] = vars()[key] # --------------------------------------------------------------------------------------------------------- dummyVar = 'DUMMY' # print('MASTER RESULTFILE: %s\n' % outputFileName) # print('\n') # print('\n') # print('Start_process_control\n') # print('readfiles: 1') # print('precise_orbits: 0') # print('crop: 0') # print('sim_amplitude: 0') # print('master_timing: 0') # print('oversample: 0') # print('resample: 0') # print('filt_azi: 0') # print('filt_range: 0') # print('NOT_USED: 0') # print('End_process_control\n') # print('\n') print('\ntsx_dump_header2doris.py v1.0, doris software, 2009\n') print('*******************************************************************') print('*_Start_readfiles:') print('*******************************************************************') print('Volume file: %s' % container['volFile'][0]) print('Volume_ID: %s' % container['volID'][0]) print('Volume_identifier: %s' % container['volRef'][0]) print('Volume_set_identifier: %s' % dummyVar) print('(Check)Number of records in ref. file: %s' % container['sceneRecords'][0]) print('SAR_PROCESSOR: %s' % str.split(container['productSpec'][0])[0]) print('Product type specifier: %s' % container['mission'][0]) print('Logical volume generating facility: %s' % container['productFacility'][0]) print('Logical volume creation date: %s' % container['productVolDate'][0]) print('Location and date/time of product creation: %s' % container['productDate'][0]) print('Scene identification: Orbit: %s %s Mode: %s' % (container['orbitABS'][0],container['orbitDir'][0],container['sceneMode'][0])) print('Scene location: lat: %.4f lon: %.4f' % (float(container['sceneCenLat'][0]),float(container['sceneCenLon'][0]))) print('Leader file: %s' % container['volFile'][0]) print('Sensor platform mission identifer: %s' % container['mission'][0]) print('Scene_centre_latitude: %s' % container['sceneCenLat'][0]) print('Scene_centre_longitude: %s' % container['sceneCenLon'][0]) print('Scene_center_heading: %2.0f' % (float(container['heading'][0]))) print('Radar_wavelength (m): 0.031') #HARDCODED!!! print('First_pixel_azimuth_time (UTC): %s %s' % (time.strftime("%d-%b-%Y",time.strptime(container['azimuthTimeStart'][0].split('T')[0],"%Y-%m-%d")),container['azimuthTimeStart'][0].split('T')[1][:-1])) print('Pulse_Repetition_Frequency (computed, Hz): %s' % container['azimuthPRF'][0]) print('Total_azimuth_band_width (Hz): %s' % container['azimuthBW'][0]) print('Weighting_azimuth: %s' % str.upper(container['azimuthWind'][0])) print('Xtrack_f_DC_constant (Hz, early edge): %s' % container['dopplerCoeff0'][0]) print('Xtrack_f_DC_linear (Hz/s, early edge): %s' % container['dopplerCoeff1'][0]) print('Xtrack_f_DC_quadratic (Hz/s/s, early edge): %s' % container['dopplerCoeff2'][0]) print('Range_time_to_first_pixel (2way) (ms): %0.15f' % (float(container['rangeTimePix'][0])*1000)) print('Range_sampling_rate (computed, MHz): %0.6f' % (float(container['rangeRSR'][0])/1000000)) print('Total_range_band_width (MHz): %s' % (float(container['rangeBW'][0])/1000000)) print('Weighting_range: %s' % str.upper(container['rangeWind'][0])) print('') print('*******************************************************************') print('Datafile: %s' % container['imageData'][0]) print('Number_of_lines_original: %s' % container['imageLines'][0]) print('Number_of_pixels_original: %s' % container['imagePixels'][0]) print('*******************************************************************') print('* End_readfiles:_NORMAL') print('*******************************************************************') print('') print('') print('*******************************************************************') print('*_Start_leader_datapoints') print('*******************************************************************') print(' t(s) X(m) Y(m) Z(m)') print('NUMBER_OF_DATAPOINTS: %s' % len(container['orbitTime'])) print('') for i in range(len(container['orbitTime'])): print(' %s %s %s %s' % (hms2sec(container['orbitTime'][i].split('T')[1]),\ container['orbitX'][i],\ container['orbitY'][i],\ container['orbitZ'][i])) print('') print('*******************************************************************') print('* End_leader_datapoints:_NORMAL') print('*******************************************************************') # print('\n') # print(' Current time: %s\n' % time.asctime()) # print('\n') # close output file #outStream.close() Doris-5.0.3Beta/bin/viewanddel000077500000000000000000000047241312547014700162260ustar00rootroot00000000000000#!/bin/csh -f # note for cygwin: # csh is not standard in the distribution. # tcsh can be downloaded though, and put in /bin, # and then link /bin/csh to it. # same for linking /bin/awk --> /bin/gawk # gv is prefered to ghostview, search www.google.com. ### viewanddel is distributed with "Doris". ### used with scripts plotoffsets and plotcpm ### Bert Kampes, (c) 1998-2004 ### Check input set PSFILE = $1 set WRONG = 0; if ( $#argv != 1 ) set WRONG = 1 if ( ! -e "$PSFILE" ) set WRONG = 1 if ( $WRONG == 1 ) then echo "$0 file.ps" echo "View a temporary postscript file and" echo "then delete it afterwards." echo " " exit 1 endif ### Decreasing order of desiredness... ### First try to get gv, then ghostview, ### if not found, assume a program named "ghostview" ### exists. Do not use "which" command here. #%// BK 25-Sep-2001 which seems more robust than -x... #%// BK 16-Jun-2003 but which is extremely slow on SUN... #%// BK 16-Jun-2003 therefore simply use "ghostview" and assumes #%// BK 16-Jun-2003 everybody has that, or is smart enough to change it here ### If you want to use a different program, ### simply make sure it is known as "ghostview" using a link. ### or put it under that name in ~/bin/ghostview set PSVIEWERS = "gv ghostview gsview32" set BINDIRS = "/usr/X11R6/bin /bin /usr/bin /usr/local/bin /usr/sbin ~/bin ~/local/bin" set GV = ghostview foreach PSVIEWER ( $PSVIEWERS ) foreach BINDIR ( $BINDIRS ) if ( -x $BINDIR/$PSVIEWER ) then set GV = $BINDIR/$PSVIEWER break endif end end echo $GV ### set PSVIEWER = "/cygdrive/c/Program Files/gs3/Ghostgum/gsview/gsview32" ### cygwin: do not use a space in path to executable. ### cygwin: prepend X11R6/bin so correct gs is used ### to avoid "postscript interpreter failed in main window" error. ### Note also GS_LIB GS_FONTPATH may be set, but does not ### seem important (see gs -h). if ( -d /cygdrive ) then echo "Cygwin detected: prepending /usr/X11R6/bin to path" set path = ( /usr/X11R6/bin $path ) endif ### Add options to viewer. ### Finally call postscript viewer echo "Using $GV" $GV -fg black -bg white $PSFILE ### Remove postscript file if viewing was OK. if ( $status == 0 ) then echo "removing tmp postscript file $PSFILE" rm -f $PSFILE else echo "Something went wrong with viewer. Please have a look" echo "at postscript file $PSFILE yourself." echo "E.g., try following command from promt:" echo " $GV $PSFILE" echo " " exit 1 endif ### EOF exit 0 Doris-5.0.3Beta/doris_core/000077500000000000000000000000001312547014700155275ustar00rootroot00000000000000Doris-5.0.3Beta/doris_core/COPYING000077500000000000000000000431261312547014700165730ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) 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 this service 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 make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. 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. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. Doris-5.0.3Beta/doris_core/Makefile000066400000000000000000000207121312547014700171710ustar00rootroot00000000000000######################################################################### # Makefile for the Doris software. # # Created by: configure # # 04-Dec-1998 # # # # Delft University of Technology # # Delft Institute of Earth Observation and Space Systems # # http://doris.tudelft.nl # # See also the user manual, annex installation. # # # ### Usage ### # # The command: "make" creates and optimized version of doris. # # The command: "make install" installs it andcleans up. # # If this does not work, try a more controlled approach by: # # # # 0. inspect set up of this Makefile # # 1. set CC DEFS LIBS etc., first set these to debug values # # (read NOTE there if problems) # # 2. compile software sources to *.o: "make swobjs" # # 3. link object together to executable: "make doris" # # 4. install executable: "make install" # # 5. remove object files: "make clean" # # # # BTW. "make" does "swobjs doris" by default. # # # ### # # Successfully tested for compilers/platforms: # # GNU g++ version 2.7.2.2 on HP-UX B.10.20 A 9000/785 # # GNU g++ version 2.95.2 on HP-UX B.10.20 A 9000/785 # # HP aCC version A.01.07 on HP-UX B.10.20 A 9000/785 # # GNU g++ version ? on Linux X86 # # SGI ? # # Sun Studion 9,10,11 on Solaris Sparc and X86/AMD64 # # GNU g++ versions v3.4, v4.0, v4.1, v4.2, v4.3 on Linux X86 and AMD64 # # Sun Sudion v11 on Linux AMD64 # # Intel Compilers v9, v10, v11 on Linux AMD64 # ######################################################################### ################################################################### ################################################################### # Please change if required: DEF[1-6], CC, CFLAGS, LIBDIR, ### ################################################################### ### The shell used by this makefile ### SHELL = /bin/sh ### Specify compiler/installation directory ### INSTALLDIR = /data/src/Doris_s1_git/bin CC = g++ SCRIPTSDIR = ../bin ### Define statements controlling compilation ### # Comment out DEF[1-8] statements when appropriate. DEF1 = -D__DEBUGMAT1 # -1- range checking in matrix class DEF2 = -D__DEBUGMAT2 # -2- info matrix class (debug only) DEF3 = -D__DEBUG # -3- debug for other files DEF4 = -Wno-deprecated # -4- do not display warnings due to depricated entries DEF5 = -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE # -5- support for large files #DEF6 = -DNO_FASTTRIG # -6- extra functional switches #DEF9 = -D__NO_IOS_BINARY__ # -9- comment out if you ios::binary (most will) # ### Do not change following 2, simply comment DEF1-8 above DEFSDEBUG = $(DEF1) $(DEF2) $(DEF3) DEFS = $(DEF4) $(DEF5) $(DEF6) -D__USE_FFTW_LIBRARY__ -D__X86PROCESSOR__ -I/usr/include ### NOTE ### # If you get warnings like the following (I got them with g++, not with aCC) # then use define __GNUC__ to define these functions #%// BK 15-Aug-2000 #In file included from matrixbk.h:38, # from processor.cc:23: #constants.h: In method `real8 cn::dist(cn) const': #constants.h:106: implicit declaration of function `int sqr(...)' ### END NOTE ### # LOCAL dir LOCAL_INSTALLDIR = ../bin ### CFLAGS ### # Compiler options flag ### # Specify compiler flags (I selected these for g++) CFLAGSDEBUG = -g -O $(DEFS) $(DEFSDEBUG) CFLAGSOPT = -O $(DEFS) #CFLAGSOPT = -O2 $(DEFS) # this crashed doris! (?) #CFLAGSOPT = -O3 $(DEFS) # this crashed doris! (?) ### CCNOTE ### ### Change here ### ### set CFLAGS depending on if you compile debug version or working version ### #CFLAGS = $(CFLAGSDEBUG) CFLAGS = $(CFLAGSOPT) ### END CCNOTE ### ### Library locations flag ### ### -lcl : used for veclib ### -lm : used for fftw LFLAGS = -L/lib64 -lfftw3f -lm ##################################################### ### No need to change anything below here... #### ##################################################### EXECUTABLE = doris SWSRCS = processor.cc \ utilities.cc \ ioroutines.cc \ readinput.cc \ readdata.cc \ coregistration.cc \ filtering.cc \ referencephase.cc \ products.cc \ geocode.cc \ unwrap.cc \ matrixspecs.cc \ exceptions.cc \ estorbit.cc SWOBJS = $(SWSRCS:.cc=.o) ### scripts of doris.tar in SCRIPTSDIR, used at make install SCRIPTS = helpdoris \ baseline.doris.sh \ baseline.doris.csh \ construct_dem.sh \ coregpm.doris \ doris* \ heightamb \ phasefilt.doris \ plotcpm* \ plotoffsets* \ run \ viewanddel \ cpx2ps \ lonlathei2ascii \ ascii2ascii_UTM \ ascii2ps* \ tsx* \ rs2* \ csk* \ gammaReadfiles.csh \ hhmmss2sec.py \ sec2hhmmss.py ##################################################### ### And no need to change anything below here... #### ##################################################### ### what to do if make w/o arguments ### # first make all object files, then link them together default: $(EXECUTABLE) ### how to compile object code .o from C++ source files .cc (general rule) ### # space between -o and filename for SUN make (BK 7 july 2000) .cc.o: $(CC) $(CFLAGS) -c -o $(@) $< ##################################################### ### Make object code from source ### swobjs: $(SWOBJS) ### Load objects to executable ### ### The added .cc files contain class definitions ### matrixclass is explicitly included ### in the source code since we had some problems finding out how to do that ### here, since compilers treat the template class differently than normal classes. ### BK 07-Feb-2002 $(EXECUTABLE): $(SWOBJS) tmp_strptime.cc slcimage.cc productinfo.cc orbitbk.cc $(CC) $(CFLAGS) -c -o triangle.o -DTRILIBRARY -DANSI_DECLARATORS triangle.c $(CC) $(CFLAGS)\ tmp_strptime.cc $(SWOBJS) triangle.o\ slcimage.cc productinfo.cc orbitbk.cc\ $(LFLAGS) -o $@ @echo " " @echo "*******************************" @echo "* ...Compilation finished... *" @echo "*******************************" @echo " " ### Install executable in installdir ### install: $(EXECUTABLE) @echo "* Installing $(EXECUTABLE) in: $(INSTALLDIR)" @cp -f $(EXECUTABLE) $(INSTALLDIR)/. ( cd $(SCRIPTSDIR); cp -f $(SCRIPTS) $(INSTALLDIR)/. ) $(MAKE) cleaner @echo " " @echo "*******************************" @echo "* ...Installation finished... *" @echo "*******************************" @echo " " @echo "* Check that $(INSTALLDIR) is in your path search: echo \$$PATH ." @echo " " installcb: $(EXECUTABLE) @echo "* Installing $(EXECUTABLE) in: $(LOCAL_INSTALLDIR)" @cp -f $(EXECUTABLE) $(LOCAL_INSTALLDIR)/. $(MAKE) cleaner @echo " " @echo "*******************************" @echo "* ...Installation finished... *" @echo "*******************************" @echo " " @echo "* Check that $(LOCAL_INSTALLDIR) is in your path search: echo \$$PATH ." @echo " " ##################################################### ### Testers ### test: testdoris testdoris: $(EXECUTABLE) @echo " " @echo "* Executing command: $(EXECUTABLE) -v" $(EXECUTABLE) -v @echo " " ### Orbit test program for debugging ### test-orbit: ioroutines.o matrixspecs.o utilities.o exceptions.cc slcimage.cc orbitbk.cc matrixbk.cc bk_messages.hh $(CC) $(CFLAGS) -D__TESTMAIN__ \ ioroutines.o matrixspecs.o utilities.o exceptions.cc slcimage.cc orbitbk.cc \ $(LFLAGS) \ -o $@ ### Matrix test program for debugging ### ### fast_sin defined in utilities.cc, which requires ioroutines, which, etc. test-matrix: matrix_test.cc matrixspecs.o utilities.o utilities.o ioroutines.o matrixbk.cc $(CC) $(CFLAGS) matrix_test.cc matrixspecs.o \ utilities.o ioroutines.o exceptions.cc orbitbk.cc \ $(LFLAGS) \ -o $@ @echo " " ##################################################### ### Cleaners ### clean: cleanswobjs cleaner: clean cleanprog cleanest: clean cleanprog uninstall cleanprog: @rm -f $(EXECUTABLE) $(EXECUTABLE.debug) \ matrixbk_test testorbit @echo "* Removed executables in current dir." cleanswobjs: @rm -f $(SWOBJS) matrixbk_test.o orbitbk.o slcimage.o triangle.o @echo "* Removed object files." uninstall: @rm -f $(INSTALLDIR)/$(EXECUTABLE) @echo "* Removed executables in install dir: $(INSTALLDIR)." ### BK 12-Dec-2000 ### Doris-5.0.3Beta/doris_core/Makefile.bert000077500000000000000000000151641312547014700201340ustar00rootroot00000000000000######################################################################### # Makefile for the Doris software. # # Created by: configure # # 04-Dec-1998 Delft University of Technology, Geodesy # # Bert Kampes (b.m.kampes@lr.tudelft.nl) # # http://enterprise.geo.tudelft.nl/doris/ # # See also the user manual, annex installation. # # # ### Usage ### # # The command: "make" creates and optimized version of doris. # # The command: "make install" installs it andcleans up. # # If this does not work, try a more controlled approach by: # # # # 0. inspect set up of this Makefile # # 1. set CC DEFS LIBS etc., first set these to debug values # # (read NOTE there if problems) # # 2. compile software sources to *.o: "make swobjs" # # 3. link object together to executable: "make doris" # # 4. install executable: "make install" # # 5. remove object files: "make clean" # # # # BTW. "make" does "swobjs doris" by default. # # # ### # # Successfully tested for compilers/platforms: # # GNU g++ version 2.7.2.2 on HP-UX B.10.20 A 9000/785 # # GNU g++ version 2.95.2 on HP-UX B.10.20 A 9000/785 # # HP aCC version A.01.07 on HP-UX B.10.20 A 9000/785 # # GNU g++ version ? on Linux X86 # # SGI ? # ######################################################################### ################################################################### ################################################################### # Please change if required: DEF[1-6], CC, CFLAGS, LIBDIR, ### ################################################################### ### The shell used by this makefile ### SHELL = /bin/sh ### Specify compiler/installation directory ### INSTALLDIR = /users/kampes/local/bin CC = g++ SCRIPTSDIR = ../bin ### Define statements controlling compilation ### # Comment out DEF[1-8] statements when appropriate. DEF1 = -D__DEBUGMAT1 # -1- range checking in matrix class DEF2 = -D__DEBUGMAT2 # -2- info matrix class (debug only) DEF3 = -D__DEBUG # -3- debug for other files #DEF9 = -D__NO_IOS_BINARY__ # -9- comment out if you ios::binary (most will) # ### Do not change following 2, simply comment DEF1-8 above DEFSDEBUG = $(DEF1) $(DEF2) $(DEF3) DEFS = -D__USE_FFTW_LIBRARY__ -I../../fftw-3.0.1/include ### NOTE ### # If you get warnings like the following (I got them with g++, not with aCC) # then use define __GNUC__ to define these functions #%// BK 15-Aug-2000 #In file included from matrixbk.h:38, # from processor.cc:23: #constants.h: In method `real8 cn::dist(cn) const': #constants.h:106: implicit declaration of function `int sqr(...)' ### END NOTE ### ### CFLAGS ### # Compiler options flag ### # Specify compiler flags (I selected these for g++) CFLAGSDEBUG = -g -O $(DEFS) $(DEFSDEBUG) CFLAGSOPT = -O $(DEFS) #CFLAGSOPT = -O2 $(DEFS) # this crashed doris! (?) #CFLAGSOPT = -O3 $(DEFS) # this crashed doris! (?) ### CCNOTE ### ### Change here ### ### set CFLAGS depending on if you compile debug version or working version ### #CFLAGS = $(CFLAGSDEBUG) CFLAGS = $(CFLAGSOPT) ### END CCNOTE ### ### Library locations flag ### ### -lcl : used for veclib ### -lm : used for fftw LFLAGS = -L../../fftw-3.0.1/lib -lfftw3f -lm ##################################################### ### No need to change anything below here... #### ##################################################### EXECUTABLE = doris SWSRCS = processor.cc \ utilities.cc \ ioroutines.cc \ conversion.cc \ readinput.cc \ readdata.cc \ coregistration.cc \ filtering.cc \ referencephase.cc \ products.cc \ geocode.cc \ unwrap.cc \ matrixspecs.cc \ exceptions.cc SWOBJS = $(SWSRCS:.cc=.o) ### scripts of doris.tar in SCRIPTSDIR, used at make install SCRIPTS = helpdoris \ baseline.doris \ coregpm.doris \ heightamb \ phasefilt.doris \ plotcpm \ plotoffsets \ run \ viewanddel \ cpx2ps \ lonlathei2ascii \ ascii2ascii_UTM \ ascii2ps # philamh2ps ##################################################### ### And no need to change anything below here... #### ##################################################### ### what to do if make w/o arguments ### # first make all object files, then link them together default: $(EXECUTABLE) ### how to compile object code .o from C++ source files .cc (general rule) ### # space between -o and filename for SUN make (BK 7 july 2000) .cc.o: $(CC) $(CFLAGS) -c -o $(@) $< ##################################################### ### Make object code from source ### swobjs: $(SWOBJS) ### Load objects to executable ### ### The added .cc files contain class definitions ### matrixclass is explicitly included ### in the source code since we had some problems finding out how to do that ### here, since compilers treat the template class differently than normal classes. ### BK 07-Feb-2002 $(EXECUTABLE): $(SWOBJS) tmp_strptime.cc slcimage.cc productinfo.cc orbitbk.cc $(CC) $(CFLAGS)\ tmp_strptime.cc $(SWOBJS)\ slcimage.cc productinfo.cc orbitbk.cc\ $(LFLAGS) -o $@ @echo " " @echo "*******************************" @echo "* ...Compilation finished... *" @echo "*******************************" @echo " " ### Install executable in installdir ### install: $(EXECUTABLE) @echo "* Installing $(EXECUTABLE) in: $(INSTALLDIR)" @cp -f $(EXECUTABLE) $(INSTALLDIR)/. ( cd $(SCRIPTSDIR); cp -f $(SCRIPTS) $(INSTALLDIR)/. ) $(MAKE) cleaner @echo " " @echo "*******************************" @echo "* ...Installation finished... *" @echo "*******************************" @echo " " ##################################################### ### Testers ### test: testdoris testdoris: $(EXECUTABLE) @echo " " @echo "* Executing command: $(EXECUTABLE) -v" $(EXECUTABLE) -v @echo " " testorbit: ioroutines.o matrixspecs.o readinput.o conversion.o utilities.o $(CC) $(CFLAGS) orbitbk.cc -D__TESTMAIN__ \ ioroutines.o matrixspecs.o readinput.o conversion.o utilities.o \ -o $@ ### matrix ### matrixbk_test: matrixbk_test.o matrixspecs.o $(CC) $(CFLAGS) matrixbk_test.o \ matrixspecs.o \ $(LFLAGS) \ -o $@ ##################################################### ### Cleaners ### clean: cleanswobjs cleaner: clean cleanprog cleanest: clean cleanprog uninstall cleanprog: @rm -f $(EXECUTABLE) $(EXECUTABLE.debug) \ matrixbk_test testorbit @echo "* Removed executables in current dir." cleanswobjs: @rm -f $(SWOBJS) matrixbk_test.o orbitbk.o slcimage.o @echo "* Removed object files." uninstall: @rm -f $(INSTALLDIR)/$(EXECUTABLE) @echo "* Removed executables in install dir: $(INSTALLDIR)." ### BK 12-Dec-2000 ### Doris-5.0.3Beta/doris_core/Makefile.cygwin000077500000000000000000000152751312547014700205030ustar00rootroot00000000000000######################################################################### # Makefile for the Doris software. # # Created by: configure # # 04-Dec-1998 Delft University of Technology, Geodesy # # Bert Kampes (kampes@geo.tudelft.nl) # # http://www.geo.tudelft.nl/doris/ # # See also the user manual, annex installation. # # # ### Usage ### # # The command: "make" creates and optimized version of doris. # # The command: "make install" installs it andcleans up. # # If this does not work, try a more controlled approach by: # # # # 0. inspect set up of this Makefile # # 1. set CC DEFS LIBS etc., first set these to debug values # # (read NOTE there if problems) # # 2. compile software sources to *.o: "make swobjs" # # 3. link object together to executable: "make doris" # # 4. install executable: "make install" # # 5. remove object files: "make clean" # # # # BTW. "make" does "swobjs doris" by default. # # # ### # # Successfully tested for compilers/platforms: # # GNU g++ version 2.7.2.2 on HP-UX B.10.20 A 9000/785 # # GNU g++ version 2.95.2 on HP-UX B.10.20 A 9000/785 # # HP aCC version A.01.07 on HP-UX B.10.20 A 9000/785 # # GNU g++ version ? on Linux X86 # # SGI ? # ######################################################################### ################################################################### ################################################################### # Please change if required: DEF[1-6], CC, CFLAGS, LIBDIR, ### ################################################################### ### The shell we're using ### SHELL = /bin/sh ### Specify compiler/installation directory ### INSTALLDIR = /usr/local/bin CC = g++ SCRIPTSDIR = ../bin ### Define statements controlling compilation ### # Comment out DEF[1-8] statements when appropriate. DEF1 = -D__DEBUGMAT1 # -1- range checking in matrix class DEF2 = -D__DEBUGMAT2 # -2- info matrix class (debug only) DEF3 = -D__DEBUG # -3- debug for other files DEF4 = -DNO__VECLIB_LIBRARY # -4- comment out if lib n/a DEF5 = -DNO__LAPACK_LIBRARY # -5- comment out if lib n/a DEF6 = -D__GplusplusCOMPILER__ # -6- if compiler is g++ (__GNUG__) DEF7 = -D__X86PROCESSOR__ # -7- if on intel PC (swapbytes) (linux) #DEF8 = -D__NO_STRPTIME # -8- comment out if you have strptime #DEF9 = -D__NO_IOS_BINARY__ # -9- comment out if you ios::binary (most will) # ### Do not change following 2, simply comment DEF1-8 above DEFSDEBUG = $(DEF1) $(DEF2) $(DEF3) DEFS = $(DEF4) $(DEF5) $(DEF6) $(DEF7) $(DEF8) $(DEF9) ### NOTE ### # If you get warnings like the following (I got them with g++, not with aCC) # then use define __GplusplusCOMPILER__ (uncomment DEF6) to define these functions #%// BK 15-Aug-2000 #In file included from matrixbk.h:38, # from processor.cc:23: #constants.h: In method `real8 cn::dist(cn) const': #constants.h:106: implicit declaration of function `int sqr(...)' ### END NOTE ### ### CFLAGS ### # Compiler options flag ### # Specify compiler flags (I selected these for g++) CFLAGSDEBUG = $(DEFS) $(DEFSDEBUG) CFLAGSOPT = -O $(DEFS) ### CCNOTE ### ### Change here ### ### set CFLAGS depending on if you compile debug version or working version ### #CFLAGS = $(CFLAGSDEBUG) CFLAGS = $(CFLAGSOPT) ### END CCNOTE ### ### Library locations flag ### LFLAGS = ##################################################### ### No need to change anything below here... #### ##################################################### EXECUTABLE = doris SWSRCS = processor.cc \ utilities.cc \ ioroutines.cc \ readinput.cc \ readdata.cc \ coregistration.cc \ filtering.cc \ referencephase.cc \ products.cc \ geocode.cc \ unwrap.cc \ matrixspecs.cc SWOBJS = $(SWSRCS:.cc=.o) ### scripts of doris.tar in SCRIPTSDIR, used at make install SCRIPTS = helpdoris \ baseline.doris \ coregpm.doris \ phasefilt.doris \ plotcpm \ plotoffsets \ run \ viewanddel \ cpx2ps \ philamh2ps ##################################################### ### And no need to change anything below here... #### ##################################################### ### what to do if make w/o arguments ### # first make all object files, then link them together default: $(EXECUTABLE) ### how to compile object code .o from C++ source files .cc (general rule) ### # space between -o and filename for SUN make (BK 7 july 2000) .cc.o: $(CC) $(CFLAGS) $(MYIFLAGS) -c -o $(@) $< ##################################################### ### Make object code from source ### swobjs: $(SWOBJS) ### Load objects to executable ### ### The added .cc files contain class definitions ### matrixclass is explicitly included ### in the source code since we had some problems finding out how to do that ### here, since compilers treat the template class differently than normal classes. ### BK 07-Feb-2002 $(EXECUTABLE): $(SWOBJS) tmp_strptime.cc slcimage.cc productinfo.cc orbitbk.cc $(CC) $(CFLAGS)\ tmp_strptime.cc $(SWOBJS)\ slcimage.cc productinfo.cc orbitbk.cc\ $(LFLAGS) -o $@ @echo " " @echo "*******************************" @echo "* ...Compilation finished... *" @echo "*******************************" @echo " " ### Install executable in installdir ### install: $(EXECUTABLE) @echo "* Installing $(EXECUTABLE) in: $(INSTALLDIR)" @cp $(EXECUTABLE) $(INSTALLDIR)/. ( cd $(SCRIPTSDIR); cp $(SCRIPTS) $(INSTALLDIR)/. ) $(MAKE) cleaner @echo " " @echo "*******************************" @echo "* ...Installation finished... *" @echo "*******************************" @echo " " ##################################################### ### Testers ### test: testdoris testdoris: $(EXECUTABLE) @echo " " @echo "* Executing command: $(EXECUTABLE) -v" $(EXECUTABLE) -v @echo " " testorbit: ioroutines.o matrixspecs.o readinput.o conversion.o utilities.o $(CC) $(CFLAGSDEBUG) orbitbk.cc -D__TESTMAIN__ \ ioroutines.o matrixspecs.o readinput.o conversion.o utilities.o \ -o $@ ### matrix ### matrixbk_test: matrixbk_test.o matrixspecs.o $(CC) $(CFLAGSDEBUG) matrixbk_test.o \ matrixspecs.o \ $(LFLAGS) \ -o $@ ##################################################### ### Cleaners ### clean: cleanswobjs cleaner: clean cleanprog cleanest: clean cleanprog uninstall cleanprog: @rm -f $(EXECUTABLE) $(EXECUTABLE.debug) \ matrixbk_test testorbit @echo "* Removed executables in current dir." cleanswobjs: @rm -f $(SWOBJS) matrixbk_test.o orbitbk.o slcimage.o @echo "* Removed object files." uninstall: @rm -f $(INSTALLDIR)/$(EXECUTABLE) @echo "* Removed executables in install dir: $(INSTALLDIR)." ### BK 12-Dec-2000 ### Doris-5.0.3Beta/doris_core/Makefile.debug000077500000000000000000000160151312547014700202620ustar00rootroot00000000000000######################################################################### # Makefile for the Doris software. # # Created by: configure # # 04-Dec-1998 Delft University of Technology, Geodesy # # Bert Kampes (b.m.kampes@lr.tudelft.nl) # # http://enterprise.geo.tudelft.nl/doris/ # # See also the user manual, annex installation. # # # ### Usage ### # # The command: "make" creates and optimized version of doris. # # The command: "make install" installs it andcleans up. # # If this does not work, try a more controlled approach by: # # # # 0. inspect set up of this Makefile # # 1. set CC DEFS LIBS etc., first set these to debug values # # (read NOTE there if problems) # # 2. compile software sources to *.o: "make swobjs" # # 3. link object together to executable: "make doris" # # 4. install executable: "make install" # # 5. remove object files: "make clean" # # # # BTW. "make" does "swobjs doris" by default. # # # ### # # Successfully tested for compilers/platforms: # # GNU g++ version 2.7.2.2 on HP-UX B.10.20 A 9000/785 # # GNU g++ version 2.95.2 on HP-UX B.10.20 A 9000/785 # # HP aCC version A.01.07 on HP-UX B.10.20 A 9000/785 # # GNU g++ version ? on Linux X86 # # SGI ? # ######################################################################### ################################################################### ################################################################### # Please change if required: DEF[1-6], CC, CFLAGS, LIBDIR, ### ################################################################### ### The shell used by this makefile ### SHELL = /bin/sh ### Specify compiler/installation directory ### INSTALLDIR = /usr/local/bin CC = g++ SCRIPTSDIR = ../bin ### Define statements controlling compilation ### # Comment out DEF[1-8] statements when appropriate. DEF1 = -D__DEBUGMAT1 # -1- range checking in matrix class DEF2 = -D__DEBUGMAT2 # -2- info matrix class (debug only) DEF3 = -D__DEBUG # -3- debug for other files DEF4 = -Wno-deprecated -trigraphs # -4- do not display warnings DEF5 = -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE # support for large files #DEF9 = -D__NO_IOS_BINARY__ # -9- comment out if you ios::binary (most will) # ### Do not change following 2, simply comment DEF1-8 above #DEFSDEBUG = $(DEF1) $(DEF2) $(DEF3) DEFSDEBUG = $(DEF3) DEFS = $(DEF4) $(DEF5) -D__USE_FFTW_LIBRARY__ -D__X86PROCESSOR__ -I/usr/include ### NOTE ### # If you get warnings like the following (I got them with g++, not with aCC) # then use define __GNUC__ to define these functions #%// BK 15-Aug-2000 #In file included from matrixbk.h:38, # from processor.cc:23: #constants.h: In method `real8 cn::dist(cn) const': #constants.h:106: implicit declaration of function `int sqr(...)' ### END NOTE ### ### CFLAGS ### # Compiler options flag ### # Specify compiler flags (I selected these for g++) CFLAGSDEBUG = -g -O $(DEFS) $(DEFSDEBUG) CFLAGSOPT = -O $(DEFS) #CFLAGSOPT = -O2 $(DEFS) # this crashed doris! (?) #CFLAGSOPT = -O3 $(DEFS) # this crashed doris! (?) ### CCNOTE ### ### Change here ### ### set CFLAGS depending on if you compile debug version or working version ### CFLAGS = $(CFLAGSDEBUG) #CFLAGS = $(CFLAGSOPT) ### END CCNOTE ### ### Library locations flag ### ### -lcl : used for veclib ### -lm : used for fftw LFLAGS = -L/usr/lib -lfftw3f -lm ##################################################### ### No need to change anything below here... #### ##################################################### EXECUTABLE = doris.debug SWSRCS = processor.cc \ utilities.cc \ ioroutines.cc \ readinput.cc \ readdata.cc \ coregistration.cc \ filtering.cc \ referencephase.cc \ products.cc \ geocode.cc \ unwrap.cc \ matrixspecs.cc \ exceptions.cc SWOBJS = $(SWSRCS:.cc=.o) ### scripts of doris.tar in SCRIPTSDIR, used at make install SCRIPTS = helpdoris \ baseline.doris \ coregpm.doris \ heightamb \ phasefilt.doris \ plotcpm \ plotoffsets \ run \ viewanddel \ cpx2ps \ lonlathei2ascii \ ascii2ascii_UTM \ ascii2ps ##################################################### ### And no need to change anything below here... #### ##################################################### ### what to do if make w/o arguments ### # first make all object files, then link them together default: $(EXECUTABLE) ### how to compile object code .o from C++ source files .cc (general rule) ### # space between -o and filename for SUN make (BK 7 july 2000) .cc.o: $(CC) $(CFLAGS) -c -o $(@) $< ##################################################### ### Make object code from source ### swobjs: $(SWOBJS) ### Load objects to executable ### ### The added .cc files contain class definitions ### matrixclass is explicitly included ### in the source code since we had some problems finding out how to do that ### here, since compilers treat the template class differently than normal classes. ### BK 07-Feb-2002 $(EXECUTABLE): $(SWOBJS) tmp_strptime.cc slcimage.cc productinfo.cc orbitbk.cc $(CC) $(CFLAGS) -c -o triangle.o -DTRILIBRARY -DANSI_DECLARATORS triangle.c $(CC) $(CFLAGS)\ tmp_strptime.cc $(SWOBJS) triangle.o\ slcimage.cc productinfo.cc orbitbk.cc\ $(LFLAGS) -o $@ @echo " " @echo "*******************************" @echo "* ...Compilation finished... *" @echo "*******************************" @echo " " ### Install executable in installdir ### install: $(EXECUTABLE) @echo "* Installing $(EXECUTABLE) in: $(INSTALLDIR)" @cp -f $(EXECUTABLE) $(INSTALLDIR)/. ( cd $(SCRIPTSDIR); cp -f $(SCRIPTS) $(INSTALLDIR)/. ) $(MAKE) cleaner @echo " " @echo "*******************************" @echo "* ...Installation finished... *" @echo "*******************************" @echo " " ##################################################### ### Testers ### test: testdoris testdoris: $(EXECUTABLE) @echo " " @echo "* Executing command: $(EXECUTABLE) -v" $(EXECUTABLE) -v @echo " " testorbit: ioroutines.o matrixspecs.o readinput.o utilities.o $(CC) $(CFLAGS) orbitbk.cc -D__TESTMAIN__ \ ioroutines.o matrixspecs.o readinput.o utilities.o \ -o $@ ### Matrix test program for debugging ### ### fast_sin defined in utilities.cc, which requires ioroutines, which, etc. matrixbk_test: matrixbk_test.o matrixspecs.o utilities.o $(CC) $(CFLAGS) matrixbk_test.o matrixspecs.o \ utilities.o ioroutines.o exceptions.cc orbitbk.cc \ $(LFLAGS) \ -o $@ ##################################################### ### Cleaners ### clean: cleanswobjs cleaner: clean cleanprog cleanest: clean cleanprog uninstall cleanprog: @rm -f $(EXECUTABLE) $(EXECUTABLE.debug) \ matrixbk_test testorbit @echo "* Removed executables in current dir." cleanswobjs: @rm -f $(SWOBJS) matrixbk_test.o orbitbk.o slcimage.o triangle.o @echo "* Removed object files." uninstall: @rm -f $(INSTALLDIR)/$(EXECUTABLE) @echo "* Removed executables in install dir: $(INSTALLDIR)." ### BK 12-Dec-2000 ### Doris-5.0.3Beta/doris_core/Makefile.debug-full000077500000000000000000000157721312547014700212330ustar00rootroot00000000000000######################################################################### # Makefile for the Doris software. # # Created by: configure # # 04-Dec-1998 Delft University of Technology, Geodesy # # Bert Kampes (b.m.kampes@lr.tudelft.nl) # # http://enterprise.geo.tudelft.nl/doris/ # # See also the user manual, annex installation. # # # ### Usage ### # # The command: "make" creates and optimized version of doris. # # The command: "make install" installs it andcleans up. # # If this does not work, try a more controlled approach by: # # # # 0. inspect set up of this Makefile # # 1. set CC DEFS LIBS etc., first set these to debug values # # (read NOTE there if problems) # # 2. compile software sources to *.o: "make swobjs" # # 3. link object together to executable: "make doris" # # 4. install executable: "make install" # # 5. remove object files: "make clean" # # # # BTW. "make" does "swobjs doris" by default. # # # ### # # Successfully tested for compilers/platforms: # # GNU g++ version 2.7.2.2 on HP-UX B.10.20 A 9000/785 # # GNU g++ version 2.95.2 on HP-UX B.10.20 A 9000/785 # # HP aCC version A.01.07 on HP-UX B.10.20 A 9000/785 # # GNU g++ version ? on Linux X86 # # SGI ? # ######################################################################### ################################################################### ################################################################### # Please change if required: DEF[1-6], CC, CFLAGS, LIBDIR, ### ################################################################### ### The shell used by this makefile ### SHELL = /bin/sh ### Specify compiler/installation directory ### INSTALLDIR = /usr/local/bin CC = g++ SCRIPTSDIR = ../bin ### Define statements controlling compilation ### # Comment out DEF[1-8] statements when appropriate. DEF1 = -D__DEBUGMAT1 # -1- range checking in matrix class DEF2 = -D__DEBUGMAT2 # -2- info matrix class (debug only) DEF3 = -D__DEBUG # -3- debug for other files DEF4 = -Wno-deprecated -trigraphs # -4- do not display warnings DEF5 = -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE # support for large files #DEF9 = -D__NO_IOS_BINARY__ # -9- comment out if you ios::binary (most will) # ### Do not change following 2, simply comment DEF1-8 above DEFSDEBUG = $(DEF1) $(DEF2) $(DEF3) DEFS = $(DEF4) $(DEF5) -D__USE_FFTW_LIBRARY__ -D__X86PROCESSOR__ -I/usr/include ### NOTE ### # If you get warnings like the following (I got them with g++, not with aCC) # then use define __GNUC__ to define these functions #%// BK 15-Aug-2000 #In file included from matrixbk.h:38, # from processor.cc:23: #constants.h: In method `real8 cn::dist(cn) const': #constants.h:106: implicit declaration of function `int sqr(...)' ### END NOTE ### ### CFLAGS ### # Compiler options flag ### # Specify compiler flags (I selected these for g++) CFLAGSDEBUG = -g -O $(DEFS) $(DEFSDEBUG) CFLAGSOPT = -O $(DEFS) #CFLAGSOPT = -O2 $(DEFS) # this crashed doris! (?) #CFLAGSOPT = -O3 $(DEFS) # this crashed doris! (?) ### CCNOTE ### ### Change here ### ### set CFLAGS depending on if you compile debug version or working version ### CFLAGS = $(CFLAGSDEBUG) #CFLAGS = $(CFLAGSOPT) ### END CCNOTE ### ### Library locations flag ### ### -lcl : used for veclib ### -lm : used for fftw LFLAGS = -L/usr/lib -lfftw3f -lm ##################################################### ### No need to change anything below here... #### ##################################################### EXECUTABLE = doris394.debug SWSRCS = processor.cc \ utilities.cc \ ioroutines.cc \ readinput.cc \ readdata.cc \ coregistration.cc \ filtering.cc \ referencephase.cc \ products.cc \ geocode.cc \ unwrap.cc \ matrixspecs.cc \ exceptions.cc SWOBJS = $(SWSRCS:.cc=.o) ### scripts of doris.tar in SCRIPTSDIR, used at make install SCRIPTS = helpdoris \ baseline.doris \ coregpm.doris \ heightamb \ phasefilt.doris \ plotcpm \ plotoffsets \ run \ viewanddel \ cpx2ps \ lonlathei2ascii \ ascii2ascii_UTM \ ascii2ps ##################################################### ### And no need to change anything below here... #### ##################################################### ### what to do if make w/o arguments ### # first make all object files, then link them together default: $(EXECUTABLE) ### how to compile object code .o from C++ source files .cc (general rule) ### # space between -o and filename for SUN make (BK 7 july 2000) .cc.o: $(CC) $(CFLAGS) -c -o $(@) $< ##################################################### ### Make object code from source ### swobjs: $(SWOBJS) ### Load objects to executable ### ### The added .cc files contain class definitions ### matrixclass is explicitly included ### in the source code since we had some problems finding out how to do that ### here, since compilers treat the template class differently than normal classes. ### BK 07-Feb-2002 $(EXECUTABLE): $(SWOBJS) tmp_strptime.cc slcimage.cc productinfo.cc orbitbk.cc $(CC) $(CFLAGS) -c -o triangle.o -DTRILIBRARY -DANSI_DECLARATORS triangle.c $(CC) $(CFLAGS)\ tmp_strptime.cc $(SWOBJS) triangle.o\ slcimage.cc productinfo.cc orbitbk.cc\ $(LFLAGS) -o $@ @echo " " @echo "*******************************" @echo "* ...Compilation finished... *" @echo "*******************************" @echo " " ### Install executable in installdir ### install: $(EXECUTABLE) @echo "* Installing $(EXECUTABLE) in: $(INSTALLDIR)" @cp -f $(EXECUTABLE) $(INSTALLDIR)/. ( cd $(SCRIPTSDIR); cp -f $(SCRIPTS) $(INSTALLDIR)/. ) $(MAKE) cleaner @echo " " @echo "*******************************" @echo "* ...Installation finished... *" @echo "*******************************" @echo " " ##################################################### ### Testers ### test: testdoris testdoris: $(EXECUTABLE) @echo " " @echo "* Executing command: $(EXECUTABLE) -v" $(EXECUTABLE) -v @echo " " testorbit: ioroutines.o matrixspecs.o readinput.o utilities.o $(CC) $(CFLAGS) orbitbk.cc -D__TESTMAIN__ \ ioroutines.o matrixspecs.o readinput.o utilities.o \ -o $@ ### Matrix test program for debugging ### ### fast_sin defined in utilities.cc, which requires ioroutines, which, etc. matrixbk_test: matrixbk_test.o matrixspecs.o utilities.o $(CC) $(CFLAGS) matrixbk_test.o matrixspecs.o \ utilities.o ioroutines.o exceptions.cc orbitbk.cc \ $(LFLAGS) \ -o $@ ##################################################### ### Cleaners ### clean: cleanswobjs cleaner: clean cleanprog cleanest: clean cleanprog uninstall cleanprog: @rm -f $(EXECUTABLE) $(EXECUTABLE.debug) \ matrixbk_test testorbit @echo "* Removed executables in current dir." cleanswobjs: @rm -f $(SWOBJS) matrixbk_test.o orbitbk.o slcimage.o triangle.o @echo "* Removed object files." uninstall: @rm -f $(INSTALLDIR)/$(EXECUTABLE) @echo "* Removed executables in install dir: $(INSTALLDIR)." ### BK 12-Dec-2000 ### Doris-5.0.3Beta/doris_core/Makefile.doris_v3.17_MacOSX10.4_gcc4000077500000000000000000000164421312547014700235330ustar00rootroot00000000000000######################################################################### # Makefile for the Doris software. # # Created by: configure # # 04-Dec-1998 Delft University of Technology, Geodesy # # Bert Kampes (b.m.kampes@lr.tudelft.nl) # # http://enterprise.geo.tudelft.nl/doris/ # # See also the user manual, annex installation. # # # ### Usage ### # # The command: "make" creates and optimized version of doris. # # The command: "make install" installs it andcleans up. # # If this does not work, try a more controlled approach by: # # # # 0. inspect set up of this Makefile # # 1. set CC DEFS LIBS etc., first set these to debug values # # (read NOTE there if problems) # # 2. compile software sources to *.o: "make swobjs" # # 3. link object together to executable: "make doris" # # 4. install executable: "make install" # # 5. remove object files: "make clean" # # # # BTW. "make" does "swobjs doris" by default. # # # ### # # Successfully tested for compilers/platforms: # # GNU g++ version 2.7.2.2 on HP-UX B.10.20 A 9000/785 # # GNU g++ version 2.95.2 on HP-UX B.10.20 A 9000/785 # # HP aCC version A.01.07 on HP-UX B.10.20 A 9000/785 # # GNU g++ version ? on Linux X86 # # SGI ? # ######################################################################### ################################################################### ################################################################### # Please change if required: DEF[1-6], CC, CFLAGS, LIBDIR, ### ################################################################### ### The shell we're using ### SHELL = /bin/sh ### Specify compiler/installation directory ### INSTALLDIR = /usr/local/bin CC = g++ SCRIPTSDIR = ../bin ### Define statements controlling compilation ### # Comment out DEF[1-8] statements when appropriate. DEF1 = -D__DEBUGMAT1 # -1- range checking in matrix class DEF2 = -D__DEBUGMAT2 # -2- info matrix class (debug only) DEF3 = -D__DEBUG # -3- debug for other files #DEF9 = -D__NO_IOS_BINARY__ # -9- comment out if you ios::binary (most will) # ### Do not change following 2, simply comment DEF1-8 above DEFSDEBUG = $(DEF1) $(DEF2) $(DEF3) #DEFS = -D__USE_VECLIB_LIBRARY__ -D__USE_FFTW_LIBRARY__ -I/usr/local/include #DEFS = -Dcdotu=cdotu_ -Dcgemv=cgemv_ -Dcgemm=cgemm_ -Ddgemm=dgemm_ -Ddpotrf=dpotrf_ -Ddpotri=dpotri_ -Ddpotrs=dpotrs_ -Dsgemm=sgemm_ -Dspotrf=spotrf_ -Dspotri=spotri_ -Dspotrs=spotrs_ -Dzgemm=zgemm_ ### NOTE ### # If you get warnings like the following (I got them with g++, not with aCC) # then use define __GNUC__ to define these functions #%// BK 15-Aug-2000 #In file included from matrixbk.h:38, # from processor.cc:23: #constants.h: In method `real8 cn::dist(cn) const': #constants.h:106: implicit declaration of function `int sqr(...)' ### END NOTE ### ### CFLAGS ### # Compiler options flag ### # Specify compiler flags (I selected these for g++) CFLAGSDEBUG = $(DEFS) $(DEFSDEBUG) CFLAGSOPT = -O $(DEFS) #CFLAGSOPT = -O2 $(DEFS) # this crashed doris! (?) #CFLAGSOPT = -O3 $(DEFS) # this crashed doris! (?) ### CCNOTE ### ### Change here ### ### set CFLAGS depending on if you compile debug version or working version ### #CFLAGS = $(CFLAGSDEBUG) CFLAGS = $(CFLAGSOPT) ### END CCNOTE ### ### Library locations flag ### ### -lcl is used for veclib -lm is used for fftw #LFLAGS = -L/System/Library/Frameworks/vecLib.framework/ -lveclib -lcl -L/usr/local/lib/ -llibfftw3f -lm LFLAGS = -faltivec -framework vecLib -lfftw3 -lm ##################################################### ### No need to change anything below here... #### ##################################################### EXECUTABLE = doris SWSRCS = processor.cc \ utilities.cc \ ioroutines.cc \ readinput.cc \ readdata.cc \ coregistration.cc \ filtering.cc \ referencephase.cc \ products.cc \ geocode.cc \ unwrap.cc \ matrixspecs.cc \ exceptions.cc SWOBJS = $(SWSRCS:.cc=.o) ### scripts of doris.tar in SCRIPTSDIR, used at make install SCRIPTS = helpdoris \ baseline.doris \ coregpm.doris \ phasefilt.doris \ plotcpm \ plotoffsets \ run \ viewanddel \ cpx2ps \ lonlathei2ascii \ ascii2ascii_UTM \ ascii2ps # philamh2ps ##################################################### ### And no need to change anything below here... #### ##################################################### ### what to do if make w/o arguments ### # first make all object files, then link them together default: $(EXECUTABLE) ### how to compile object code .o from C++ source files .cc (general rule) ### # space between -o and filename for SUN make (BK 7 july 2000) .cc.o: $(CC) -c -o $(@) $(CFLAGS) $< ##################################################### ### Make object code from source ### swobjs: $(SWOBJS) ### Load objects to executable ### ### The added .cc files contain class definitions ### matrixclass is explicitly included ### in the source code since we had some problems finding out how to do that ### here, since compilers treat the template class differently than normal classes. ### BK 07-Feb-2002 $(EXECUTABLE): $(SWOBJS) tmp_strptime.cc slcimage.cc productinfo.cc orbitbk.cc $(CC) -o $@ $(CFLAGS)\ tmp_strptime.cc $(SWOBJS)\ slcimage.cc productinfo.cc orbitbk.cc\ $(LFLAGS) @echo " " @echo "*******************************" @echo "* ...Compilation finished... *" @echo "*******************************" @echo " " ### Install executable in installdir ### install: $(EXECUTABLE) @echo "* Installing $(EXECUTABLE) in: $(INSTALLDIR)" @cp -f $(EXECUTABLE) $(INSTALLDIR)/. ( cd $(SCRIPTSDIR); cp -f $(SCRIPTS) $(INSTALLDIR)/. ) $(MAKE) cleaner @echo " " @echo "*******************************" @echo "* ...Installation finished... *" @echo "*******************************" @echo " " ##################################################### ### Testers ### test: testdoris testdoris: $(EXECUTABLE) @echo " " @echo "* Executing command: $(EXECUTABLE) -v" $(EXECUTABLE) -v @echo " " testorbit: ioroutines.o matrixspecs.o readinput.o conversion.o utilities.o $(CC) $(CFLAGS) orbitbk.cc -D__TESTMAIN__ \ ioroutines.o matrixspecs.o readinput.o conversion.o utilities.o \ -o $@ ### matrix ### matrixbk_test: matrixbk_test.o matrixspecs.o $(CC) $(CFLAGS) matrixbk_test.o \ matrixspecs.o \ $(LFLAGS) \ -o $@ ##################################################### ### Cleaners ### clean: cleanswobjs cleaner: clean cleanprog cleanest: clean cleanprog uninstall cleanprog: @rm -f $(EXECUTABLE) $(EXECUTABLE.debug) \ matrixbk_test testorbit @echo "* Removed executables in current dir." cleanswobjs: @rm -f $(SWOBJS) matrixbk_test.o orbitbk.o slcimage.o @echo "* Removed object files." uninstall: @rm -f $(INSTALLDIR)/$(EXECUTABLE) @echo "* Removed executables in install dir: $(INSTALLDIR)." ### BK 12-Dec-2000 ### Doris-5.0.3Beta/doris_core/Makefile.sun000077500000000000000000000177761312547014700200200ustar00rootroot00000000000000######################################################################### ######################################################################### # # # This is an example Makefile. It is for a big endian platform (e.g., # # SUN/HP, not a PC). It does not use external libraries. It assumes # # the g++ compiler. Finally, installation is in directory # # "/usr/local/bin". # # # # In principle, create your own Makefile by executing the script # # "configure" which is also in this directory. # # # # Further see the files README and INSTALLATION # # # ######################################################################### ### Options used with configure script ################################## ######################################################################### # Creating Makefile for: # # compiler: g++ # # fftw: n # # veclib: n # # lapack: n # # Little endian: n # # DEBUG version: n # # Install in dir: /usr/local/bin # ######################################################################### ######################################################################### ### Usage ### # # The command: "make" creates and optimized version of doris. # # The command: "make install" installs it andcleans up. # # If this does not work, try a more controlled approach by: # # # # 0. inspect set up of this Makefile # # 1. set CC DEFS LIBS etc., first set these to debug values # # (read NOTE there if problems) # # 2. compile software sources to *.o: "make swobjs" # # 3. link object together to executable: "make doris" # # 4. install executable: "make install" # # 5. remove object files: "make clean" # # # # BTW. "make" does "swobjs doris" by default. # # # ### # # Successfully tested for compilers/platforms: # # GNU g++ version 2.7.2.2 on HP-UX B.10.20 A 9000/785 # # GNU g++ version 2.95.2 on HP-UX B.10.20 A 9000/785 # # HP aCC version A.01.07 on HP-UX B.10.20 A 9000/785 # # GNU g++ version ? on Linux X86 # # SGI ? # ######################################################################### ################################################################### ################################################################### # Please change if required: DEF[1-6], CC, CFLAGS, LIBDIR, ### ################################################################### ### The shell we're using ### SHELL = /bin/sh ### Specify compiler/installation directory ### INSTALLDIR = /usr/local/bin CC = g++ SCRIPTSDIR = ../bin ### Define statements controlling compilation ### # Comment out DEF[1-8] statements when appropriate. DEF1 = -D__DEBUGMAT1 # -1- range checking in matrix class DEF2 = -D__DEBUGMAT2 # -2- info matrix class (debug only) DEF3 = -D__DEBUG # -3- debug for other files #DEF9 = -D__NO_IOS_BINARY__ # -9- comment out if you ios::binary (most will) # ### Do not change following 2, simply comment DEF1-8 above DEFSDEBUG = $(DEF1) $(DEF2) $(DEF3) DEFS = ### NOTE ### # If you get warnings like the following (I got them with g++, not with aCC) # then use define __GNUC__ to define these functions #%// BK 15-Aug-2000 #In file included from matrixbk.h:38, # from processor.cc:23: #constants.h: In method `real8 cn::dist(cn) const': #constants.h:106: implicit declaration of function `int sqr(...)' ### END NOTE ### ### CFLAGS ### # Compiler options flag ### # Specify compiler flags (I selected these for g++) CFLAGSDEBUG = $(DEFS) $(DEFSDEBUG) CFLAGSOPT = -O $(DEFS) #CFLAGSOPT = -O2 $(DEFS) # this crashed doris! (?) #CFLAGSOPT = -O3 $(DEFS) # this crashed doris! (?) ### CCNOTE ### ### Change here ### ### set CFLAGS depending on if you compile debug version or working version ### #CFLAGS = $(CFLAGSDEBUG) CFLAGS = $(CFLAGSOPT) ### END CCNOTE ### ### Library locations flag ### ### -lcl is used for veclib -lm is used for fftw LFLAGS = ##################################################### ### No need to change anything below here... #### ##################################################### EXECUTABLE = doris SWSRCS = processor.cc \ utilities.cc \ ioroutines.cc \ conversion.cc \ readinput.cc \ step1routines.cc \ coregistration.cc \ filtering.cc \ referencephase.cc \ products.cc \ geocode.cc \ unwrap.cc \ matrixspecs.cc SWOBJS = $(SWSRCS:.cc=.o) ### scripts of doris.tar in SCRIPTSDIR, used at make install SCRIPTS = helpdoris \ baseline.doris \ coregpm.doris \ phasefilt.doris \ plotcpm \ plotoffsets \ run \ viewanddel \ cpx2ps \ lonlathei2ascii \ ascii2ascii_UTM \ ascii2ps # philamh2ps ##################################################### ### And no need to change anything below here... #### ##################################################### ### what to do if make w/o arguments ### # first make all object files, then link them together default: $(EXECUTABLE) ### how to compile object code .o from C++ source files .cc (general rule) ### # space between -o and filename for SUN make (BK 7 july 2000) .cc.o: $(CC) $(CFLAGS) -c -o $(@) $< ##################################################### ### Make object code from source ### swobjs: $(SWOBJS) ### Load objects to executable ### ### The added .cc files contain class definitions ### matrixclass is explicitly included ### in the source code since we had some problems finding out how to do that ### here, since compilers treat the template class differently than normal classes. ### BK 07-Feb-2002 $(EXECUTABLE): $(SWOBJS) tmp_strptime.cc slcimage.cc productinfo.cc orbitbk.cc $(CC) $(CFLAGS)\ tmp_strptime.cc $(SWOBJS)\ slcimage.cc productinfo.cc orbitbk.cc\ $(LFLAGS) -o $@ @echo " " @echo "*******************************" @echo "* ...Compilation finished... *" @echo "*******************************" @echo " " ### Install executable in installdir ### install: $(EXECUTABLE) @echo "* Installing $(EXECUTABLE) in: $(INSTALLDIR)" @cp -f $(EXECUTABLE) $(INSTALLDIR)/. ( cd $(SCRIPTSDIR); cp -f $(SCRIPTS) $(INSTALLDIR)/. ) $(MAKE) cleaner @echo " " @echo "*******************************" @echo "* ...Installation finished... *" @echo "*******************************" @echo " " ##################################################### ### Testers ### test: testdoris testdoris: $(EXECUTABLE) @echo " " @echo "* Executing command: $(EXECUTABLE) -v" $(EXECUTABLE) -v @echo " " testorbit: ioroutines.o matrixspecs.o readinput.o conversion.o utilities.o $(CC) $(CFLAGS) orbitbk.cc -D__TESTMAIN__ \ ioroutines.o matrixspecs.o readinput.o conversion.o utilities.o \ -o $@ ### matrix ### matrixbk_test: matrixbk_test.o matrixspecs.o $(CC) $(CFLAGS) matrixbk_test.o \ matrixspecs.o \ $(LFLAGS) \ -o $@ ##################################################### ### Cleaners ### clean: cleanswobjs cleaner: clean cleanprog cleanest: clean cleanprog uninstall cleanprog: @rm -f $(EXECUTABLE) $(EXECUTABLE.debug) \ matrixbk_test testorbit @echo "* Removed executables in current dir." cleanswobjs: @rm -f $(SWOBJS) matrixbk_test.o orbitbk.o slcimage.o @echo "* Removed object files." uninstall: @rm -f $(INSTALLDIR)/$(EXECUTABLE) @echo "* Removed executables in install dir: $(INSTALLDIR)." ### BK 12-Dec-2000 ### Doris-5.0.3Beta/doris_core/README000077500000000000000000000302031312547014700164100ustar00rootroot00000000000000-------------------------------------------------------------------- CONTENTS: 1. Welcome message. 2. Please acknowledge the usage of Doris in your publications. 3. List of files. -------------------------------------------------------------------- Congratulations! If you are reading this message you have managed to unzip and untar the C++ source code for the Doris radar interferometric software. This directory is the one from where the core of Doris is compiled and installed. The Doris InSAR software (Delft University of Technology) can be freely used for non-commercial applications. It is released under the GPL, see the file "COPYRIGHT". For up-to-date information, see "http://doris.tudelft.nl". To install Doris, please refer to the file "INSTALL" in the root directory! The following is a summary which may be useful if the information in the INSTALL file is not enough. To install Doris, first create a "Makefile" for compilation of the source. This can be done by running the interactive csh script "configure". If you experience trouble running this script, try changing the first line to tcsh (e.g., on Cygwin systems, there is tcsh but no csh.) Please follow the instructions on the screen after the Makefile has been created. (The "Makefile" is used for convenient compilation of the source code. Basicaly execute the commands: "make", and, when compiled successfully, "make install".) Doris should compile on all (Unix like) platforms without difficulty. It has been installed on, e.g., HP-UX, SUN solaris, Linux, Windows XP running Cygwin. The GNU g++ (gcc) compiler is best used (e.g., version 2.95.2). Please consult the trouble shoot section of the manual in case of trouble. One can also send an email to the doris users email list with problems on compilation. (And later with questions on processing.) See our website how to join this email list. As said, a Makefile should be generated by typing "./configure". If this however somehow fails, I also provided some example Makefiles. The Makefile I used on our system ("Makefile.sun") is for big endian, not using any libraries. The "Makefile.linux" is the result of the "configure" script for a little endian PC w/o the FFTW, Lapack, and Veclib libraries. These examples may be outdated, they only serve as examples to extend on. Then, also compile the programs in SARtools and ENVISAT_TOOLS sub directories. Perform a "make install" in all three directories to install the software. The executable (named "doris") can be tested with the test dataset that is provided on our web page (download area). Data for both big and little endian machines are available. Interferometric data processing with Doris is simplified by using the script "run" in the "bin" directory. (This utility is copied to the INSTALLDIR after "make install" is performed. Make sure the INSTALLDIR is in your path. Possibly you have to open a new terminal, or give the command "rehash" to find it.) You can test correct installation by typing "run -h", which should explain its usage. It uses the environment variables EDITOR and PAGER. Please set them to appropriate values, for example in csh add the lines setenv PAGER more setenv EDITOR nedit to your "~/.cshrc" csh resource file. Help on the keywords can be found in the manual, or by typing the command "helpdoris". Optionally a debug version can be compiled, by editing the CFLAGS variable in the Makefile. Please do this before reporting errors, and in this way try to find out more information where the error originates from. Also, a matrixclass test program can be compiled. If you are interested in using this matrix class in C++ programs of your own, it is recommended to have a look at this example program. Please also install the utility programs in the SARtools archive. With these programs you can for example view the output of Doris, and the PREVIEW card relies on proper installation of the program "cpxfiddle". It is highly recommended to install the GMT tools. Doris uses GMT for plotting the estimated offset vectors and coregistration errors. Also, the geocoded matrices latitude/longitude/height can be interpolated to a regular grid with these tools. I appreciate a message that you are using Doris, for example by sending an email to the doris_users list describing the system you compiled Doris on, and with which compiler. Please acknowledge the usage of Doris by citing the paper Bert Kampes, Ramon Hanssen and Zbigniew Perski. "Radar Interferometry with Public Domain Tools". Proceedings of FRINGE 2003, December 1-5, Frascati, Italy, 2003. Have fun! TUDelft Deos 2000-2011 doris_users@tudelft.nl ------------------------ filelist: ------------------------ -rwxr-xr-x 27098 2009-01-13 20:16 bk_baseline.hh -rwxr-xr-x 14441 2009-05-30 19:58 bk_messages.hh -rwxr-xr-x 26125 2009-06-09 09:02 configure -rwxr-xr-x 28693 2009-06-08 18:03 constants.hh -rwxr-xr-x 18006 2008-09-08 13:48 COPYING -rwxr-xr-x 244256 2009-06-05 00:33 coregistration.cc -rwxr-xr-x 8086 2009-01-13 20:17 coregistration.hh -rwxr-xr-x 1528036 2009-06-09 11:47 doris -rwxr-xr-x 5708 2008-12-25 00:25 exceptions.cc -rwxr-xr-x 7405 2009-01-13 20:17 exceptions.hh -rwxr-xr-x 115971 2009-01-13 20:08 filtering.cc -rwxr-xr-x 5862 2009-01-13 20:17 filtering.hh -rwxr-xr-x 62551 2009-06-05 00:35 geocode.cc -rwxr-xr-x 4029 2009-01-13 20:17 geocode.hh -rwxr-xr-x 105179 2009-06-08 21:23 ioroutines.cc -rwxr-xr-x 7679 2009-06-08 21:18 ioroutines.hh -rwxr-xr-x 6772 2008-09-08 13:48 Makefile.bert -rwxr-xr-x 6845 2008-09-08 13:48 Makefile.cygwin -rwxr-xr-x 7181 2008-12-18 23:43 Makefile.debug -rwxr-xr-x 7162 2008-09-08 13:48 Makefile.debug-full -rwxr-xr-x 7458 2008-09-08 13:48 Makefile.doris_v3.17_MacOSX10.4_gcc4 -rwxr-xr-x 8190 2008-09-08 13:48 Makefile.sun -rwxr-xr-x 69105 2009-06-08 18:07 matrixbk.cc -rwxr-xr-x 34042 2009-06-08 17:42 matrixbk.hh -rwxr-xr-x 115649 2009-06-05 00:58 matrixspecs.cc -rwxr-xr-x 8941 2009-01-13 20:14 matrix_test.cc -rwxr-xr-x 19276 2009-06-04 23:05 newsincev2.4 -rwxr-xr-x 49146 2009-05-30 19:30 orbitbk.cc -rwxr-xr-x 8983 2009-01-13 20:18 orbitbk.hh -rwxr-xr-x 151533 2009-06-09 11:42 processor.cc -rwxr-xr-x 22899 2009-05-30 19:34 productinfo.cc -rwxr-xr-x 4888 2009-01-13 20:18 productinfo.hh -rwxr-xr-x 142235 2009-06-08 17:56 products.cc -rwxr-xr-x 5383 2009-01-13 20:18 products.hh -rwxr-xr-x 193217 2009-05-30 19:39 readdata.cc -rwxr-xr-x 3689 2009-04-12 22:00 readdata.hh -rwxr-xr-x 262556 2009-05-30 19:55 readinput.cc -rwxr-xr-x 32324 2009-05-30 19:07 readinput.hh -rwxr-xr-x 12484 2009-06-09 11:55 README -rwxr-xr-x 106922 2009-06-08 17:58 referencephase.cc -rwxr-xr-x 6959 2009-01-13 20:19 referencephase.hh -rwxr-xr-x 44130 2009-05-30 19:50 slcimage.cc -rwxr-xr-x 11725 2009-01-13 20:19 slcimage.hh -rwxr-xr-x 29405 2009-01-13 20:16 tmp_strptime.cc -rwxr-xr-x 5212 2008-09-08 13:48 TODO -rwxr-xr-x 651039 2009-03-21 23:07 triangle.c -rwxr-xr-x 21911 2008-09-08 13:48 triangle.h -rwxr-xr-x 35898 2009-01-13 20:16 unwrap.cc -rwxr-xr-x 2938 2009-01-13 20:19 unwrap.hh -rwxr-xr-x 68632 2009-06-05 00:17 utilities.cc -rwxr-xr-x 28475 2009-06-05 00:29 utilities.hh -rwxr-xr-x 2582 2008-09-06 20:08 ascii2ascii_UTM -rwxr--r-- 9202 2009-04-14 16:38 ascii2ps -rwxr-xr-x 8867 2008-09-06 20:08 ascii2ps.gmt-v3 -rwxr-xr-x 2282 2008-09-06 20:08 baseline.doris.csh -rwxr-xr-x 5506 2008-12-24 14:18 baseline.doris.sh -rwxr-x--- 17778 2009-06-04 23:37 construct_dem.sh -rwxr-xr-x 11108 2008-09-06 20:08 coregpm.doris -rwxr-xr-x 20028 2008-09-06 20:08 cpx2ps lrwxrwxrwx 15 2009-06-09 11:34 doris.process-reset.sh -> doris.rmstep.sh -rwxr-xr-x 1826 2009-05-19 16:03 doris.rmstep.sh -rwxr-xr-x 1788 2008-09-06 20:08 heightamb -rwxr-xr-x 26873 2008-09-06 20:08 helpdoris -rwxr-xr-x 3295 2008-09-06 20:08 lonlathei2ascii -rwxr-xr-x 5484 2008-09-06 20:08 phasefilt.doris -rwxr-xr-x 17927 2009-05-27 10:33 plotcpm -rwxr-xr-x 17927 2009-05-27 10:31 plotcpm.erroffsets -rwxr-xr-x 17402 2008-09-06 20:08 plotoffsets -rwxr-xr-x 17255 2008-09-06 20:08 plotoffsets.bruno -rwxr-xr-x 2771 2009-04-14 16:35 README -rwxr-x--- 64594 2009-05-30 21:02 run -rwxr--r-- 4841 2009-04-13 13:21 tsx_dump_data.py -rwxr--r-- 10496 2009-04-14 16:29 tsx_dump_header2doris_noxpath.py -rwxr--r-- 9621 2009-04-14 16:11 tsx_dump_header2doris.py -rwxr-xr-x 2516 2008-09-06 20:08 viewanddel -r--r--r-- 3582 Apr 14 18:15 2003 SARtools/Makefile -r--r--r-- 12312 Apr 14 08:30 2003 SARtools/bkconvert.cc -r--r--r-- 80779 Apr 14 08:31 2003 SARtools/cpxfiddle.cc -r--r--r-- 5040 Apr 14 08:30 2003 SARtools/cpxmult.cc -r--r--r-- 4680 Apr 14 08:30 2003 SARtools/flapjack.cc -r--r--r-- 3545 Apr 14 08:30 2003 SARtools/floatmult.cc -r--r--r-- 4789 Apr 14 08:30 2003 SARtools/rasterheader.cc -r--r--r-- 4425 Apr 14 08:30 2003 SARtools/readrasterheader.cc -r--r--r-- 5029 Apr 14 08:30 2003 SARtools/wrap.cc -r--r--r-- 2490 Jun 16 09:14 2003 ./ENVISAT_TOOLS/Makefile -r--r--r-- 5032 Jun 16 09:13 2003 ./ENVISAT_TOOLS/envisat_dump_data.c -r--r--r-- 3655 Jun 16 09:13 2003 ./ENVISAT_TOOLS/envisat_dump_header.c -r--r--r-- 836 Jun 16 09:14 2003 ./ENVISAT_TOOLS/README -r--r--r-- 4528 Jun 13 18:36 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/CHANGELOG.txt -r--r--r-- 15439 Jun 13 18:36 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/LICENSE.txt -r--r--r-- 6794 Jun 13 18:36 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/README.txt -r--r--r-- 17 Jun 13 18:36 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/VERSION.txt -r--r--r-- 4022 Jun 15 16:54 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_api.c -r--r--r-- 48996 Jun 14 14:59 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_api.h -r--r--r-- 64026 Jun 15 16:54 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_band.c -r--r--r-- 11740 Jun 14 15:00 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_band.h -r--r--r-- 29518 Jun 15 16:54 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_bitmask.c -r--r--r-- 15202 Jun 14 15:00 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_bitmask.h -r--r--r-- 12251 Jun 15 16:54 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_core.c -r--r--r-- 8473 Jun 14 15:00 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_core.h -r--r--r-- 10985 Jun 15 16:55 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_dataset.c -r--r--r-- 1723 Jun 14 15:00 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_dataset.h -r--r--r-- 527553 Jun 15 16:55 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_dddb.c -r--r--r-- 2322 Jun 14 15:00 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_dddb.h -r--r--r-- 22176 Jun 15 16:55 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_dsd.c -r--r--r-- 2922 Jun 14 15:00 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_dsd.h -r--r--r-- 7271 Jun 15 16:55 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_dump.c -r--r--r-- 9326 Jun 15 16:55 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_field.c -r--r--r-- 2131 Jun 14 15:00 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_field.h -r--r--r-- 19287 Jun 15 16:55 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_msph.c -r--r--r-- 1527 Jun 14 15:00 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_msph.h -r--r--r-- 6174 Jun 15 16:55 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_param.c -r--r--r-- 1646 Jun 14 15:00 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_param.h -r--r--r-- 14552 Jun 14 14:56 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_product.c -r--r--r-- 3357 Jun 14 14:56 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_ptrarray.c -r--r--r-- 3957 Jun 14 15:00 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_ptrarray.h -r--r--r-- 12815 Jun 15 16:56 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_record.c -r--r--r-- 2478 Jun 14 15:00 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_record.h -r--r--r-- 8945 Jun 15 16:56 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_string.c -r--r--r-- 2030 Jun 14 15:00 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_string.h -r--r--r-- 6370 Jun 15 16:56 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_swap.c -r--r--r-- 1400 Jun 14 15:01 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_swap.h -r--r--r-- 29212 Jun 15 16:56 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/epr_typconv.c -r--r--r-- 553 Jun 15 19:38 2003 ./ENVISAT_TOOLS/epr_api-2.0.1/src/Makefile -r-xr-xr-x 7316 Jun 16 09:13 2003 ./ENVISAT_TOOLS/envisat_dump_header2doris.csh Doris-5.0.3Beta/doris_core/TODO000077500000000000000000000136001312547014700162220ustar00rootroot00000000000000This file describes things that still need to be done to improve the Doris software. It may not be complete, but it focuses on the most important general aspects. TUDelft, July 2001-2010. Mahmut ideas: 1) report precise orbital model in .res file like dgm-0e4 Example entry in .res: Start_precise: (model name) 2) ERS put info in .res if it is nominal replica: CEOS reader modification required remove wrong error msgs for ALOS 3) put fdc to coarse orbits results. 4) cpxfiddle: logo for [processed by Doris] 5) ellipsodial parameters revisit. i.e. WGS84, GRS80 6) Revist OVS code 7) Resampling: in .res put width and height of the rsmp slave 8) Finalize Radarsat-2 reader 9) Plot scripts to be updated for GMT and internal consistancy: plotoffsets, plotcpm etc. 10) mtiming: Get # of cpu cores + distribute nwindows 11) log getorb call and Warnings to .log file using scratchlogfile("scratchlogcallsandwarnings") ================================================== 0) check accuracy of geocoding. compute wavelength from radar frequency, do not use annotated wavelength. compute prf again from (t_end-t_start)/#bins, do not use annotated prf. 1) add method for readfiles: "asar" done 200X [BK] 2) add method for crop: "asar" done 200X [BK] 3) add method for unwrap: "snaphu" done 200X [BK] A) Phase Unwrapping module. *Delft users: integrate the DLR MCF algorithm with Doris. (mostly file conversions, system call from within Doris, input cards, output to resultfiles.) *For users outside Delft. This should either be an integration with an existing software, or implemented by someone. If we implement it ourselves it cannot be as good as other software. *Curtis Cheng's "snaphu" statistical MCF algorithm was released to the public domain. Make an interface with this software. done 200X [BK] B) Improve external DEM subtraction module. With the shuttle mission data, and general for eg. 'permanent scatterers' method. Interpolation to a regular grid in WGS84 (GRS80) orbit system in a sufficient spatial resolution with Matlab or GMT. Coregistration of the radarcoded DEM to the complex IFG. still requires some work #%// Bert Kampes, 10-Mar-2005 C) Usage of ground control points (GCP). -geolocation, bias, trend correction -baseline parameter improvement (Massonet's algorithm). still needs to be done #%// Bert Kampes, 10-Mar-2005 D) Improve usersmanual. add a FAQ with "best" answers from yahoo group. E) ellipsoid card for other orbit system/extern DEM. (+transformation routines, or use proj (program see d4 disk). ---- #%// Bert Kampes, 10-Mar-2005 --- -------------------------------------- <> GEOID subtraction of model used for SRTM-C band dem <> speed improvement: fDC as constant per image; implement this in member function slcimage.get_fdc(pixel) if max diff in fdc < 0.5*(PRF-ABW) This will speed up the resampling step probably quite a bit. <> class for input handling <> class for parameter pool handling (read/write, no update) <> class for products: add bperp ? think about classes: image::master image::slave product::interferogram (etc.) is function of images orbit::masterorbit <--- should inherit from image ? be part of image? orbit::slaveorbit then interferogram.getbperp() <--- images <--- orbits implement smarter way of getbperp(), e.g., use a polynomial; <> algorithm eineder for dem2phase <> ps processing: convert DEM to master grid in meters. <> class polynomial (2d,1d, etc.) (is in matrix class?, but why is fdc_coefficients not part of it) <> add method for interpolation of scatterered data to regular grid use this to, e.g., interpolate the COMPREFDEM phase in line,pixel buffers (alternatively implement quickly an linear interpolation) also use this to map other DEMs to regular grid in WGS84 etc. <> this can be easily implemented at line "~/DEVELOP/DORIS/doris/src/referencephase.cc" [readonly] line 1115 of 1384 --80%-- col 7 sqrdistance: closest_one, next_closest; third_closest; and to use those three (unique points) to interpolate to integer l,p; this is a small change that really will improve results and speed, since also extradense is not important than anymore. still, of course, the input dem should contain all peaks of the data. <> add UTM class, conversions to WGS84, DEM etc. <> add RD class, conversions to WGS84, DEM etc. <> check concept of memory mapping; this could save time when relatively small overlapping buffers need to be loaded from disk; A memory map is a virtual access (IDL associate?) Matlab (template???) to a file. it does not cost memory, but you can treat a file as a single matrix. Only when you access the data it is actually read from disk. <> make a class for fasttrig (a lookup table for sin/cos of 2K length or so) expected to be factor 10 faster or so cmp to std:sin() <> BASELINE class:: add functions (3d polynomials) for phi=f(lat,lon,hei) line=f(lat,lon,hei) pixel=f(lat,lon,hei) ---> use these in comprefdem directly as alternative method. hei=f(phi,l,p) ---> use this in slant2h my_method (cmp schwaebisch) lat=f(hei,l,p) lon=f(hei,l,p) ---> use these in geocode (however, geocode is already fast and now "exact") <> use strings instead of strstr in bk_message class, to parse inputfile. <> use class to read records in ceos format cpxfiddle: option invert/negative: seems amplitude image is quite nice if negative ovs: check BW is not changed. matrixclass: reorganize, good testprogram; oversample: avoid copying of data to oversample a real4 matrix. fft: avoid changing plan if fft size changes check matrix class: -what is faster A[i][j] or A(i,j) or is it the same. currently in matmult, etc. A(i,j) is used, so if Veclib is not available, it is important. furthermore, i changed it to be operator() (const uint &l, const uint &p) but maybe better to inline somehow. -use BLAS library for matmult, particularly for resampling this may be faster. Doris-5.0.3Beta/doris_core/bk_baseline.hh000077500000000000000000000637101312547014700203200ustar00rootroot00000000000000/* * Copyright (c) 1999-2005 Bert Kampes * Copyright (c) 1999-2005 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/bk_baseline.hh,v $ * * $Revision: 1.7 $ * * $Date: 2005/10/06 11:09:20 $ * * $Author: kampes $ * * * definition of BASELINE class * * * During computations these should be used with care, they * may be a bit approximate. Better is to do what Doris does, * i.e., evaluate positions and relate that to timing. * But i guess it is OK. Use this for ultra fast geocoding... * #%// Bert Kampes, 06-Apr-2005 ****************************************************************/ #ifndef BK_BASELINE_H #define BK_BASELINE_H using namespace std; // Jia defined this for compilation under windows // Bert Kampes, 24-Aug-2005 #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include // cout #include // exit() #include "constants.hh" // types etc. #include "bk_messages.hh" // info etc. #include "slcimage.hh" // my slc image class #include "productinfo.hh" // my products class #include "orbitbk.hh" // my orbit class #include "utilities.hh" // eye(); normalize(); rad2deg() // BASELINE is a new type (class) that is initialized using orbits // and then either models the baseline parameters such as Bperp // or can give them exact. // Usage in the programs is something like in main do: // BASELINE baseline; // baseline.init(orbit1,orbit2,product?master?); // and pass baseline to subprograms, there use baseline.get_bperp(x,y) etc. // Bert Kampes, 31-Mar-2005 // For stability of normalmatrix, internally data are normalized // using line/1024 pixel/1024 height/1024 // probably it is better to only do this in model_param // but I also did it in eval_param because no time to check for correctness. // Bert Kampes, 02-Aug-2005 // ---------------------------------------------------------------- // ---------------------------------------------------------------- // ---------------------------------------------------------------- class BASELINE { // ______ Private data of BASELINE class ______ private: bool initialized;// real8 master_wavelength;// tmp for now used for h_amb real8 nearrange;// range=nearrange+drange_dp*pixel real8 drange_dp;// range=nearrange+drange_dp*pixel real8 orbit_convergence;// tmp for now constant real8 orbit_heading;// tmp for now NOT USED real8 L_min;// for normalization real8 L_max;// for normalization real8 P_min;// for normalization real8 P_max;// for normalization real8 H_min;// height at which parameters are modeled real8 H_max;// to model phase=f(line,pix,hei) and hei=g(line,pix,phase) // --- B(l,p,h) = a000 + // a100*l + a010*p + a001*h + // a110*l*p + a101*l*h + a011*p*h + // a200*l^2 + a020*p^2 + a002*h^2 int32 N_coeffs;// ==10 degree of 3D-poly to model B(l,p,h) // --- Coefficients --- matrix BPERP_cf;// perpendicular baseline matrix BPAR_cf;// parallel baseline matrix THETA_cf;// viewing angle matrix THETA_INC_cf;// incidence angle to satellite //real8 avg_height_ambiguity;//center height ambiguity // copy constructor; copy matrices etc as public. BASELINE(const BASELINE& A) {};// prevent copy constructor usage by privatizing /**************************************************************** // --- B(l,p,h) = a000 + // a100*l + a010*p + a001*h + // a110*l*p + a101*l*h + a011*p*h + // a200*l^2 + a020*p^2 + a002*h^2 ****************************************************************/ real8 polyval( const matrix &C, const real8 line, const real8 pixel, const real8 height) const { #ifdef __DEBUG TRACE_FUNCTION("BASELINE::polyval (BK 05-Mar-2005)") #endif if (C.size()!=10) throw("error"); return C(0,0) + C(1,0)*line + C(2,0)*pixel + C(3,0)*height + C(4,0)*line*pixel + C(5,0)*line*height + C(6,0)*pixel*height + C(7,0)*sqr(line) + C(8,0)*sqr(pixel) + C(9,0)*sqr(height); }// END polyval /**************************************************************** * Return baselineparameters * ****************************************************************/ void BBparBperpTheta(real8 &B, real8 &Bpar, real8 &Bperp, real8 &theta, const cn Master, const cn Point, const cn Slave) const { #ifdef __DEBUG TRACE_FUNCTION("BBparBperpTheta (BK 05-Mar-2005)") #endif B = Master.dist(Slave);// baseline. abs. value (in plane M,P,S) const real8 range1 = Master.dist(Point); const real8 range2 = Slave.dist(Point); Bpar = range1-range2; // parallel baseline, sign ok const cn r1 = Master.min(Point);// points from P to M const cn r2 = Slave.min(Point); theta = Master.angle(r1);// viewing angle Bperp = sqr(B)-sqr(Bpar); if (Bperp < 0.0) Bperp=0.0; else Bperp = (theta > Master.angle(r2)) ? // perpendicular baseline, sign ok sqrt(Bperp) : -sqrt(Bperp); }// END BBparBperpTheta /**************************************************************** * returns incidence angle in radians based on coordinate of * * point P on ellips and point M in orbit * #%// Bert Kampes, 06-Apr-2005 ****************************************************************/ real8 IncidenceAngle(const cn Master, const cn Point) const { #ifdef __DEBUG TRACE_FUNCTION("IncidenceAngle (BK 05-Mar-2005)") #endif const cn r1 = Master.min(Point);// points from P to M const real8 inc = Point.angle(r1);// incidence angle (assume P on ellips) return inc; }; // END BBparBperpTheta // ______ Public function of bk_message class ______ public: // ___Constructor/Destructor___ BASELINE() { TRACE_FUNCTION("BASELINE() (BK 06-Mar-2005)"); initialized = false;// N_coeffs = 10; L_min = 0.0;// for normalization L_max = 25000.0;// for normalization P_min = 0.0;// for normalization P_max = 5000.0;// for normalization H_min = 0.0;// height at which baseline is computed. H_max = 5000.0;// height at which baseline is computed. master_wavelength = 0.0; orbit_convergence = 0.0;// tmp for now constant orbit_heading = 0.0;// tmp for now NOT USED } // ___Constructor/Destructor___ ~BASELINE() //{;}// nothing to destruct { TRACE_FUNCTION("~BASELINE() (BK 06-Mar-2005)"); ;// nothing to destruct ? }// dealloc // ___Helper functions___ void model_parameters( const slcimage &master, const slcimage &slave, orbit &masterorbit, orbit &slaveorbit, const input_ell &ellips) { TRACE_FUNCTION("model_parameters (BK 06-Mar-2005)"); if (masterorbit.is_initialized() == false) { DEBUG.print("Baseline cannot be computed, master orbit not initialized."); return; } if (slaveorbit.is_initialized() == false) { DEBUG.print("Baseline cannot be computed, slave orbit not initialized."); return; } // --- Get on with it --------------------------------------- if (initialized==true) { WARNING.print("baseline already initialized??? (returning)"); return; } initialized = true;// master_wavelength = master.wavelength;// // ______ Model r=nearrange+drange_dp*p, p starts at 1 ______ nearrange = master.pix2range(1.0); drange_dp = master.pix2range(2.0)-master.pix2range(1.0); nearrange -= drange_dp;// (p starts at 1) // ______ Set min/max for normalization ______ L_min = master.currentwindow.linelo;// also used during polyval L_max = master.currentwindow.linehi;// also used during polyval P_min = master.currentwindow.pixlo;// also used during polyval P_max = master.currentwindow.pixhi;// also used during polyval H_min = 0.0;// also used during polyval H_max = 5000.0;// also used during polyval // ______ Loop counters ______ register int32 cnt = 0;// matrix index const int N_pointsL = 10;// every 10km in azimuth const int N_pointsP = 10;// every 10km ground range const int N_heights = 4;// one more level than required for poly const real8 deltapixels = master.currentwindow.pixels() / N_pointsP; const real8 deltalines = master.currentwindow.lines() / N_pointsL; const real8 deltaheight = (H_max-H_min) / N_heights; // ______ Matrices for modeling Bperp (BK 21-mar-01) ______ // --- For stability of normalmatrix, fill AMATRIX with normalized line, etc. matrix BPERP(N_pointsL*N_pointsP*N_heights,1);// perpendicular baseline matrix BPAR(N_pointsL*N_pointsP*N_heights,1);// parallel baseline matrix THETA(N_pointsL*N_pointsP*N_heights,1);// viewing angle matrix THETA_INC(N_pointsL*N_pointsP*N_heights,1);// inc. angle matrix AMATRIX(N_pointsL*N_pointsP*N_heights,N_coeffs);// design matrix // ______ Loop over heights, lines, pixels to compute baseline param. ______ for (register int32 k=0; k N = matTxmat(AMATRIX,AMATRIX); matrix rhsBperp = matTxmat(AMATRIX,BPERP); matrix rhsBpar = matTxmat(AMATRIX,BPAR); matrix rhsT = matTxmat(AMATRIX,THETA); matrix rhsT_INC = matTxmat(AMATRIX,THETA_INC); matrix Qx_hat = N; choles(Qx_hat); // Cholesky factorisation normalmatrix solvechol(Qx_hat,rhsBperp); // Solution Bperp coefficients in rhsB solvechol(Qx_hat,rhsBpar); // Solution Theta coefficients in rhsT solvechol(Qx_hat,rhsT); // Solution Theta coefficients in rhsT solvechol(Qx_hat,rhsT_INC); // Solution Theta_inc coefficients in rhsT_INC invertchol(Qx_hat); // Covariance matrix of normalized unknowns // ______Some other stuff, normalization is ok______ //matrix Qy_hat = AMATRIX * (matxmatT(Qx_hat,AMATRIX)); matrix y_hatBperp = AMATRIX * rhsBperp; matrix e_hatBperp = BPERP - y_hatBperp; //matrix Qe_hat = Qy - Qy_hat; //matrix y_hatT = AMATRIX * rhsT; //matrix e_hatT = THETA - y_hatT; // === Copy estimated coefficients to private members === BPERP_cf = rhsBperp;// BPAR_cf = rhsBpar;// THETA_cf = rhsT;// THETA_INC_cf = rhsT_INC;// // ______Test inverse______ for (uint i=0; i .001) { WARNING << "BASELINE: max. deviation N*inv(N) from unity = " << maxdev << ". This is between 0.01 and 0.001 (maybe not use it)"; WARNING.print(); } // ______ Output solution and give max error ______ // --- B(l,p,h) = a000 + // a100*l + a010*p + a001*h + // a110*l*p + a101*l*h + a011*p*h + // a200*l^2 + a020*p^2 + a002*h^2 DEBUG.print("--------------------"); DEBUG.print("Result of modeling: Bperp(l,p) = a000 + a100*l + a010*p + a001*h + "); DEBUG.print(" a110*l*p + a101*l*h + a011*p*h + a200*l^2 + a020*p^2 + a002*h^2"); DEBUG.print("l,p,h in normalized coordinates [-2:2]."); DEBUG << "Bperp_a000 = " << rhsBperp(0,0); DEBUG.print(); DEBUG << "Bperp_a100 = " << rhsBperp(1,0); DEBUG.print(); DEBUG << "Bperp_a010 = " << rhsBperp(2,0); DEBUG.print(); DEBUG << "Bperp_a001 = " << rhsBperp(3,0); DEBUG.print(); DEBUG << "Bperp_a110 = " << rhsBperp(4,0); DEBUG.print(); DEBUG << "Bperp_a101 = " << rhsBperp(5,0); DEBUG.print(); DEBUG << "Bperp_a011 = " << rhsBperp(6,0); DEBUG.print(); DEBUG << "Bperp_a200 = " << rhsBperp(7,0); DEBUG.print(); DEBUG << "Bperp_a020 = " << rhsBperp(8,0); DEBUG.print(); DEBUG << "Bperp_a002 = " << rhsBperp(9,0); DEBUG.print(); real8 maxerr = max(abs(e_hatBperp)); if (maxerr > 2.00)// { WARNING << "Max. error bperp modeling at 3D datapoints: " << maxerr << "m"; WARNING.print(); } else { INFO << "Max. error bperp modeling at 3D datapoints: " << maxerr << "m"; INFO.print(); } DEBUG.print(""); DEBUG.print("--------------------"); DEBUG.print("Range: r(p) = r0 + dr*p"); DEBUG.print("l and p in unnormalized, absolute, coordinates (1:N)."); const real8 range1 = master.pix2range(1.0); const real8 range5000 = master.pix2range(5000.0); const real8 drange = (range5000-range1)/5000.0; DEBUG << "range = " << range1-drange << " + " << drange << "*p"; DEBUG.print(); // ====== Tidy up ====== }; // END model_parameters() // ___ Return RANGE to user ___ inline real8 get_range(const real8 pixel) const { return nearrange + drange_dp*pixel; };// END get_bperp() // === Polyval modeled quantities === // --- B(l,p,h) = a000 + // a100*l + a010*p + a001*h + // a110*l*p + a101*l*h + a011*p*h + // a200*l^2 + a020*p^2 + a002*h^2 // // l,p,h coefficients take normalized input // Bert Kampes, 25-Aug-2005 // ___ Return BPERP to user ___ inline real8 get_bperp(const real8 line, const real8 pixel, const real8 height=0.0) const { return polyval(BPERP_cf, normalize(line,L_min,L_max), normalize(pixel,P_min,P_max), normalize(height,H_min,H_max)); } // ___ Return BPAR to user ___ inline real8 get_bpar(const real8 line, const real8 pixel, const real8 height=0.0) const { return polyval(BPAR_cf, normalize(line,L_min,L_max), normalize(pixel,P_min,P_max), normalize(height,H_min,H_max)); } // ___ Return THETA to user ___ inline real8 get_theta(const real8 line, const real8 pixel, const real8 height=0.0) const { return polyval(THETA_cf, normalize(line,L_min,L_max), normalize(pixel,P_min,P_max), normalize(height,H_min,H_max)); } // ___ Return THETA_INC to user ___ inline real8 get_theta_inc(const real8 line, const real8 pixel, const real8 height=0.0) const { return polyval(THETA_INC_cf, normalize(line,L_min,L_max), normalize(pixel,P_min,P_max), normalize(height,H_min,H_max)); } // === Derived quantities: do not normalize these! === // ___ Return B to user ___ inline real8 get_b(const real8 line, const real8 pixel, const real8 height=0.0) const { return sqrt(sqr(get_bpar(line,pixel,height))+sqr(get_bperp(line,pixel,height))); };// END get_b() // ___ Return alpha baseline orientation to user ___ inline real8 get_alpha(const real8 line, const real8 pixel, const real8 height=0.0) const { const real8 Bperp = get_bperp(line,pixel,height); const real8 Bpar = get_bpar(line,pixel,height); const real8 theta = get_theta(line,pixel,height); const real8 alpha = (Bpar==0 && Bperp==0) ? NaN : theta-atan2(Bpar,Bperp); // sign ok atan2 return alpha;// sign ok };// END get_bhor() // ___ Return Bh to user ___ inline real8 get_bhor(const real8 line, const real8 pixel, const real8 height=0.0) const { const real8 B = get_b(line,pixel,height); const real8 alpha = get_alpha(line,pixel,height); return B*cos(alpha);// sign ok };// END get_bhor() // ___ Return Bv to user ___ inline real8 get_bvert(const real8 line, const real8 pixel, const real8 height=0.0) const { const real8 B = get_b(line,pixel,height); const real8 alpha = get_alpha(line,pixel,height); return B*sin(alpha);// sign ok };// END get_bvert() // ___ Return Height ambiguity to user ___ inline real8 get_hamb(const real8 line, const real8 pixel, const real8 height=0.0) const { //const real8 theta = get_theta(line,pixel,height); const real8 theta_inc = get_theta_inc(line,pixel,height); const real8 Bperp = get_bperp(line,pixel,height); const real8 range_MP = get_range(pixel);// > const real8 h_amb = (Bperp==0) ? Inf : // inf -master_wavelength*range_MP*sin(theta_inc)/(2.0*Bperp);// this is wrt local //-master_wavelength*range_MP*sin(theta)/(2.0*Bperp);// this is wrt return h_amb; };// END get_hamb() // ___ Return orbit convergence to user ___ inline real8 get_orb_conv(const real8 line, const real8 pixel, const real8 height=0.0) const { // do not use l,p.. return orbit_convergence; };// END get_orb_conv() // --- Dump overview of all --- void dump(const real8 line, const real8 pixel, const real8 height=0.0) { if (initialized==false) { DEBUG.print("Exiting dumpbaseline, not initialized."); return; } // ______ Modeled quantities ______ const real8 Bperp = get_bperp(line,pixel,height); const real8 Bpar = get_bpar(line,pixel,height); const real8 theta = get_theta(line,pixel,height); const real8 theta_inc = get_theta_inc(line,pixel,height); // ______ Derived quantities ______ const real8 B = get_b(line,pixel,height); const real8 alpha = get_alpha(line,pixel,height); const real8 Bh = get_bhor(line,pixel,height); const real8 Bv = get_bvert(line,pixel,height); const real8 h_amb = get_hamb(line,pixel,height); // ______ Height ambiguity: [h] = -lambda/4pi * (r1sin(theta)/Bperp) * phi==2pi ______ // ====== Write output to screen as INFO ====== INFO << "The baseline parameters for (l,p,h) = " << line << ", " << pixel << ", " << height; INFO.print(); INFO << "\tBpar, Bperp: \t" << Bpar << " \t" << Bperp; INFO.print(); DEBUG << "\tB, alpha (deg): \t" << B << " \t" << rad2deg(alpha); DEBUG.print(); DEBUG << "\tBh, Bv: \t" << Bh << " \t" << Bv; DEBUG.print(); INFO << "\tHeight ambiguity: \t" << h_amb; INFO.print(); INFO << "\tLook angle (deg): \t" << rad2deg(theta); INFO.print(); DEBUG << "\tIncidence angle (deg): \t" << rad2deg(theta_inc); DEBUG.print(); }// END dump() };// eof BASELINE class #endif // BK_BASELINE_H Doris-5.0.3Beta/doris_core/bk_messages.hh000077500000000000000000000331271312547014700203440ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/bk_messages.hh,v $ * * $Revision: 3.12 $ * * $Date: 2005/08/24 10:03:18 $ * * $Author: kampes $ * * * definition of bk_message class * #%// BK 10-Apr-2003 ****************************************************************/ #ifndef BK_MESSAGES_H #define BK_MESSAGES_H using namespace std; // Jia defined this for compilation under windows // Bert Kampes, 24-Aug-2005 #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include // cout #include // setw() #include // mem.buf #include // strcpy() #include // exit() // #if majorversion>3 and g++ //#include // new mem.buf //#include // ---------------------------------------------------------------- // --- Choice was either to make something like: // --- message ERROR; // --- message DEBUG; // --- message INFO; // --- with functions like: ERROR.doprint(1); ERROR.setidentifyer("ERROR"); // --- ERROR << "dsaada" << 4.5 << setw(4) << nw; // --- ERROR.print(); // --- with separate bufs, or to combine them in a single object // --- like: // --- messages logging; // --- logging.setlevel("INFO"); // --- logging << "dsaada" << 4.5 << setw(4) << nw; // --- logging.info(); // --- The first is nice, different separated bufs, and easy to change // --- existing code. However, // --- The latter is better with Doris, since it allows things like // --- if (good) then logging.info() else logging.warning(); // --- But by using construction like // --- WARNING.print(INFO.get_str()); this is solved // --- #%// BK 10-Apr-2003 // // most important member functions: // get_str(): leave buffer unaffected, pointer to a copy // print("sss"): leave buffer unaffected, print a copy // print(): leave buffer unaffected, terminate buffer, rewind buffer; // this means that you have to rrewind the buffer yourself if you misuse it // as storage, like TRACE.rewind(); // INFO.precision(10); /* permanent */ INFO << setp(13)<freeze(0); // Unfreeze // //buf.rdbuf()->freeze(); // freeze string, keep allocated mem // buf.freeze();// freeze string, keep allocated memory ??? } // ___Constructor/Destructor___ ~bk_messages() //{;}// nothing to destruct { delete []buf.str(); }// dealloc // ___Helper functions___ void terminate() {buf<=10) { strncpy(name_,id, 9); strcat(name_,'\0');// terminate id } else { strcpy(name_,id);// identifyer } // ___ default message behavior for some identifyers ___ if (!strcmp(id,"ERROR")) { do_exit_ = true;// default message behavior print_cerr = true; ringbell_ = 3; } else if (!strcmp(id,"WARNING")) { ringbell_ = 2; print_cerr = true; } else if (!strcmp(id,"PROGRESS")) { ringbell_ = 1; print_cerr = true; } } // ___ problem that buf.str() empties string buffer, thus do cp ___ // ___ append a null, since common use will be to get a copy after written fully ___ // ___ this returns a pointer to buf, thus, that may be changed afterwards ___ // ___ use immediately? ___ //char* get_str() {return buf.str();} char* get_str() { char *s = buf.str(); buf.freeze(0);// unfreeze, since str() freezes it (does not seem to work?) return s; } // ___What it is all about, print the message___ // ___the buffer pointer is set to (0), but the message is not deleted___ // ___so people can access the buffer multiple times___ // ___but you cannot add to it later...____ void print() { // --- Allways rewind string to prevent unlimited growth --- // --- Only terminate it when new info is there ------------ //cerr << "pcount: " << buf.pcount() << endl; if (buf.pcount()>0) {terminate(); rewind();} print(buf.str()); buf.freeze(); } // ___What it is all about, print the message___ // ___the buffer pointer is set to (0), but the message is not deleted___ // ___so people can access the buffer multiple times___ // ___but you cannot add to it later...____ void print(const char *s) { if (nummessages<6) strcpy(first_messages[nummessages],s); nummessages++; // --- only print if level has been set ---------------------- if(print_cout==true) { if (do_exit_==true) cout << endl << "!!! ABNORMAL TERMINATION !!!" << endl; cout << setw(8) << setiosflags(ios::left) << name_ << ": " << s << endl; #ifndef WIN32 if (print_cerr==true) cerr << setw(8) << setiosflags(ios::left) << name_ << ": " << s << endl; #endif // --- Ring bell ----------------------------------------- for (int i=0;i ostream& operator << (const Type X) {return buf << X;} // ___ e.g., cout << info; ___ // ___ e.g., ofile << info; ___ // friend ostream& operator << (ostream& s) // ostream& operator << (ostream& s, const bk_message &X) // { // if(print_cout==true) // { // X.terminate(); // s << X.getid() << ": " << X.getstr() << endl; // X.rewind(); // buf << ends; // s << name_ << ": " << buf.str() << endl; // buf.seekp(0); // } // return s; // } };// eof class #endif // BK_MESSAGES_H Doris-5.0.3Beta/doris_core/configure000077500000000000000000000641351312547014700174470ustar00rootroot00000000000000#!/bin/csh -f ######################################################################## # This is a "makefile generator" for the doris software. It creates # a makefile for compilation of the Doris source code. Follow the # on the screen please. # # For CYGWIN: change the first line to "tcsh -f". (Download tcsh from # ------ redhat site, together with the develop package.) # ######################################################################### # based on interactive questions, and ls commands. #%// BK 24-Aug-2000 # Added check for strptime #%// BK 08-Mar-2001 # Changed name of script to "configure". # Added big endian check. #%// BK 19-Apr-2001 # Added large file support and -Wno-deprecated warnings #%// PM 18-Aug-2004 # Added more path options for fftw.higher versions and different compilers #%// PM 01-Sep-2004 # baseline.doris.sh and baseline.doris.csh #%// PM 15-Feb-2007 # Added compilation and linking of Triangulate #%// FvL 02-OKT-2007 # Added check .so for fftw and libsearch dir as /usr/lib64 #%// MA 02-Mar-2009 # Update testorbit build #%// MA 22-May-2009 # if ( -x /bin/clear ) /bin/clear #set PRG = `basename "$0"` set PRG = "configure" set VER = "v1.7, DEOS software" set AUT = "TUDelft, 19-May-2009" set MAKEFILE = "Makefile" echo "$PRG $VER, $AUT" echo " " echo " Welcome to the Makefile generator for the Doris insar software." echo " I will ask you some questions on compilers, etc." echo " The output of this program is a makefile named: $MAKEFILE" echo " that you can use to compile Doris." echo " More instructions will follow afterwards. (Please read them.)" echo " " echo "===> Press enter to continue." set key = $< # Declare variables. set CC = "" set GppCOMPILER = n set FFTW = n set VECLIB = n set LAPACK = n set X86 = n set DEBUG = n set FFTWLIBDIR = "" set FFTWINCLDIR = "" set VECLIBDIR = "" set LAPACKDIR = "" set LIBDIRS = "../fftw-3.2.1/lib ../../fftw-3.2.1/lib /lib /lib64 /usr/lib /usr/lib64 /usr/lib32 /usr/local/lib" ### for fftw include dirs, assume they installed it with doris distributed. ### by doing what we said in install. set INCLDIRS = "../fftw-3.2.1/include ../../fftw-3.2.1/include /include /usr/include /usr/local/include" set DEFINSTALLDIR = "/home/dummy/bin" if ( ! -d $DEFINSTALLDIR ) set DEFINSTALLDIR = "/usr/local/bin" if ( ! -d $DEFINSTALLDIR ) set DEFINSTALLDIR = "../bin" # set TMPDIR = "/tmp" if ( ! -w $TMPDIR ) set TMPDIR = . echo " Using temp dir: $TMPDIR" # Get most likely compiler, first check g++ foreach TMPCC ( g++ g++-3.4 g++-4.0 g++-4.1 g++-4.2 g++-4.3 CC aCC icpc ) echo Checking compiler: \"$TMPCC\"... $TMPCC -v > & /dev/null if ( ! $status ) then echo " I found a working(?) compiler: $TMPCC" set CC = "$TMPCC" break endif end # # Set flag for g++, this define enables some functions like sqr(int) # that are not standard C++, but were provided with, e.g., HP aCC compiler. # if ( "$CC" == "g++" ) set GppCOMPILER = "y" # # Check little Endian integers: # Compile this program and run it. # set TSTPRG = "$TMPDIR/Doris_endian" echo "Checking endianness for integers..." echo "Creating test program: $TSTPRG.cc" cat << __EOFDH > $TSTPRG.cc /* *** Test program to find out if little endian *** */ /* * Generated by Doris software install script * */ /* * Exits with 0 if big, 1 if little endian integer. * */ /* *** Bert Kampes, 19-Apr-2001 *** */ // #include int main() { int i; int littleendian=0;// thus big assumed char test[64]={0}; for (i=0;i<32;i++) test[i]=0; test[0]=0x01; if (0x0001==*(int *)(&test[0])) littleendian=1; return littleendian; } __EOFDH echo "Compiling test program: $TSTPRG" $CC $TSTPRG.cc -o $TSTPRG > & /dev/null if ( $status != 0 ) then echo " ---------------------------------------------------------------" echo " Sorry, could not compile test program, continuing." echo " THIS WILL LIKELY CAUSE TROUBLE IF YOUR COMPILER DOESN'T WORK" echo " Please change endianness interactively in a moment if required." echo " ---------------------------------------------------------------" echo " " set X86 = "n" endif echo "Running test program: $TSTPRG" if ( -x $TSTPRG ) then $TSTPRG > & /dev/null if ( $status != 0 ) then set X86 = "y" echo " Your system seems Little Endian, using -D__X86PROCESSOR__" echo " (or program failed to execute for another reason)" else echo " Your system is Big Endian (not using a define)." endif rm -f $TSTPRG.cc $TSTPRG.o $TSTPRG endif echo " " # # Check library function strptime works: # echo "Checking whether library function strptime works ok..." set STRPTIME = "1" set TSTPRG = "$TMPDIR/Doris_strptime" echo "Creating test program: $TSTPRG.cc" cat << __EOFDH > $TSTPRG.cc /* *** Test program to find out if function strptime works *** */ /* * Generated by Doris software install script * */ /* *** Bert Kampes, 14-Mar-2001 *** */ //#include // #include #include int main() { struct tm tm_ref; char utc_ref[100] = "05-JAN-1985 01:02:03.000"; strptime(utc_ref,"%d-%b-%Y %T",&tm_ref); int status = 0; if (tm_ref.tm_mday != 5) status=1; if (tm_ref.tm_mon != 0) status=1; if (tm_ref.tm_year != 85) status=1; if (tm_ref.tm_hour != 1) status=1; if (tm_ref.tm_min != 2) status=1; if (tm_ref.tm_sec != 3) status=1; //cerr << "tm_ref.tm_mday: " << tm_ref.tm_mday << endl; return status; } __EOFDH echo "Compiling test program: $TSTPRG" $CC $TSTPRG.cc -o $TSTPRG > & /dev/null if ( $status != 0 ) then echo " function strptime not found in library, using internal definition." echo " by define -D__NO_STRPTIME (change by editing DEF8 in $MAKEFILE)" set STRPTIME = "0" endif echo "Running test program: $TSTPRG" if ( -x $TSTPRG ) then $TSTPRG > & /dev/null if ( $status != 0 ) then echo " strptime does not work properly, using internal definition." echo " by define -D__NO_STRPTIME (change by editing DEF8 in $MAKEFILE)" echo " (or program failed to execute for another reason)" set STRPTIME = "0" else rm -f $TSTPRG.cc $TSTPRG.o $TSTPRG endif endif if ( "$STRPTIME" == "1" ) then echo " Library function strptime works fine, using it." endif echo " " # # Try to find veclib library # foreach DIR ( $LIBDIRS ) echo Checking directory: \"$DIR\" for Veclib... if ( -e $DIR/libveclib.a ) then echo " I found libveclib.a in $DIR" set VECLIBDIR = "$DIR" set VECLIB = "y" break endif end # # Try to find lapack library (careful, most people have fortran version) # foreach DIR ( $LIBDIRS ) echo Checking directory: \"$DIR\" for Lapack... if ( -e $DIR/liblapack.a ) then echo " I found liblapack.a in $DIR" set LAPACKDIR = "$DIR" set LAPACK = "y" break endif end if ( "$VECLIB" == "n" ) echo " I could not find libveclib.a" if ( "$LAPACK" == "n" ) echo " I could not find liblapack.a" echo " " # # Try to find fftw library # foreach DIR ( $INCLDIRS ) echo Checking directory: \"$DIR\" for fftw3.h... if ( -e $DIR/fftw3.h ) then echo " I found fftw3.h in $DIR" set FFTWINCLDIR = "$DIR" #set FFTW = "y" break endif end foreach DIR ( $LIBDIRS ) echo "Checking directory: $DIR for libfftw3f.[a|so]..." if ( -e $DIR/libfftw3f.a ) then echo " I found libfftw3f.a in $DIR" set FFTWLIBDIR = "$DIR" set FFTW = "y" break else if ( -e $DIR/libfftw3f.so ) then echo " I found libfftw3f.so in $DIR" set FFTWLIBDIR = "$DIR" set FFTW = "y" break endif end if ( "$FFTW" == "n" ) echo " I could not find libfftw3f.a or libfftw3f.so" if ( "$FFTW" == "y" ) if ( "$VECLIB" == "y" ) echo " NOT POSSIBLE TO USE VECLIB AND FFTW" echo " " ########################################################################## # # Interactive questions/check by user: # echo "===> What is your C++ compiler? [$CC] " set key = $< if ( "X$key" != "X" ) set CC = "$key" if ( "$CC" == "g++" ) set GppCOMPILER = y echo "===> Do you have the FFTW library (y/n)? [$FFTW] " set key = $< if ( "$key" == "y" || "$key" == "Y" ) then set FFTW = "y" else if ( "$key" == "n" || "$key" == "N" ) then set FFTW = "n" else echo " Using default: [$FFTW]" endif if ( "$FFTW" == "y" ) then echo "===> What is the path to the FFTW library (libfftw3f.a or libfftw3f.so)? [$FFTWLIBDIR] " set key = $< if ( "X$key" != "X" ) set FFTWLIBDIR = "$key" if ( "X$FFTWLIBDIR" == "X" || ! -d $FFTWLIBDIR ) then echo " you entered a non existing directory: $FFTWLIBDIR" echo "===> What is the path to the FFTW library? [$FFTWLIBDIR] " set key = $< if ( "X$key" != "X" ) set FFTWLIBDIR = "$key" endif echo "===> What is the path to the FFTW include file (fftw3.h)? [$FFTWINCLDIR] " set key = $< if ( "X$key" != "X" ) set FFTWINCLDIR = "$key" if ( "X$FFTWINCLDIR" == "X" || ! -d $FFTWINCLDIR ) then echo " you entered a non existing directory: $FFTWINCLDIR" echo "===> What is the path to the FFTW library? [$FFTWINCLDIR] " set key = $< if ( "X$key" != "X" ) set FFTWINCLDIR = "$key" endif endif echo "===> Do you have the VECLIB library (y/n)? [$VECLIB] " set key = $< if ( "$key" == "y" || "$key" == "Y" ) then set VECLIB = "y" else if ( "$key" == "n" || "$key" == "N" ) then set VECLIB = "n" else echo " Using default: [$VECLIB]" endif if ( "$VECLIB" == "y" ) then echo "===> What is the path to the VECLIB library? [$VECLIBDIR] " set key = $< if ( "X$key" != "X" ) set VECLIBDIR = "$key" if ( "X$VECLIBDIR" == "X" || ! -d $VECLIBDIR ) then echo " you entered a non existing directory: $VECLIBDIR" echo "===> What is the path to the VECLIB library? [$VECLIBDIR] " set key = $< if ( "X$key" != "X" ) set VECLIBDIR = "$key" endif endif echo "===> Do you have the LAPACK library (y/n)? [$LAPACK] " set key = $< if ( "$key" == "y" || "$key" == "Y" ) then set LAPACK = "y" else if ( "$key" == "n" || "$key" == "N" ) then set LAPACK = "n" else echo " Using default: [$LAPACK]" endif if ( "$LAPACK" == "y" ) then echo "===> What is the path to the LAPACK library liblapack.a? [$LAPACKDIR] " set key = $< if ( "X$key" != "X" ) set LAPACKDIR = "$key" if ( ! -d $LAPACKDIR ) then echo " you entered a non existing directory: $LAPACKDIR" echo "===> What is the path to the LAPACK library? [$LAPACKDIR] " set key = $< if ( "X$key" != "X" ) set LAPACKDIR = "$key" endif ### Check LAPACK dir fortran version (underscore appended) echo " Checking whether you have FORTRAN LAPACK library:" nm $LAPACKDIR/liblapack.a | grep spotrf_ >& /dev/null if ( $status == 0 ) then echo " FORTRAN" else echo " C (or nm failed?)" echo " If compilation fails, please do not use LAPACK" echo " or change in the source code file matrixspecs.cc" endif endif echo "===> Are you working on a Little Endian (X86 PC, Intel) machine (y/n)? [$X86] " set key = $< if ( "$key" == "y" || "$key" == "Y" ) set X86 = "y" if ( "$key" == "n" || "$key" == "N" ) set X86 = "n" echo "===> Do you want to compile a more verbose DEBUG version (y/n)? [$DEBUG] " echo " (You can first compile an optimal version, then perform a make clean," echo " and then compile a debug version, which you can use in case doris " echo " does not produce expected results)" set key = $< if ( "$key" == "y" || "$key" == "Y" ) set DEBUG = "y" set INSTALLDIR = "dummy.$$.$$.$$" while ( ! -d $INSTALLDIR ) set INSTALLDIR = "$DEFINSTALLDIR" echo "===> Installation of Doris in directory: $INSTALLDIR (y/n)? [y]" set key = $< if ( "$key" == "n" || "$key" == "N" ) then echo "===> Enter installation directory (use absolute path): " set INSTALLDIR = $< if ( ! -d $INSTALLDIR ) then echo "===> Installation directory: $INSTALLDIR does not exist." echo "===> Should I create it (y/n)? [y]" set key = $< if ( "$key" != "n" && "$key" != "N" ) mkdir $INSTALLDIR endif endif end ################################################### echo " " echo " Creating Makefile for:" echo " compiler: $CC" echo " fftw: $FFTW" if ( "$FFTW" == "y" ) echo " FFTW LIB DIR: $FFTWLIBDIR" if ( "$FFTW" == "y" ) echo " FFTW INCLUDE DIR: $FFTWINCLDIR" echo " veclib: $VECLIB" if ( "$VECLIB" == "y" ) echo " VECLIB dir: $VECLIBDIR" echo " lapack: $LAPACK" if ( "$LAPACK" == "y" ) echo " LAPACK dir: $LAPACKDIR" echo " Little endian: $X86" echo " DEBUG version: $DEBUG" echo " Install in dir: $INSTALLDIR" echo " " if ( -e $MAKEFILE ) then echo " file: $MAKEFILE will be OVERWRITTEN." else echo " file: $MAKEFILE will be created." endif echo "===> Press enter to continue (CTRL-C to exit)." set key = $< # # Set variable for LFLAGS, IFLAGS, DEFINES # # +++ At 17:49, August 29th, Robert J. Mellors wrote: # $MAKEFILE ######################################################################### # Makefile for the Doris software. # # Created by: $PRG # # 04-Dec-1998 # # # # Delft University of Technology # # Delft Institute of Earth Observation and Space Systems # # http://doris.tudelft.nl # # See also the user manual, annex installation. # # # ### Usage ### # # The command: "make" creates and optimized version of doris. # # The command: "make install" installs it andcleans up. # # If this does not work, try a more controlled approach by: # # # # 0. inspect set up of this Makefile # # 1. set CC DEFS LIBS etc., first set these to debug values # # (read NOTE there if problems) # # 2. compile software sources to *.o: "make swobjs" # # 3. link object together to executable: "make doris" # # 4. install executable: "make install" # # 5. remove object files: "make clean" # # # # BTW. "make" does "swobjs doris" by default. # # # ### # # Successfully tested for compilers/platforms: # # GNU g++ version 2.7.2.2 on HP-UX B.10.20 A 9000/785 # # GNU g++ version 2.95.2 on HP-UX B.10.20 A 9000/785 # # HP aCC version A.01.07 on HP-UX B.10.20 A 9000/785 # # GNU g++ version ? on Linux X86 # # SGI ? # # Sun Studion 9,10,11 on Solaris Sparc and X86/AMD64 # # GNU g++ versions v3.4, v4.0, v4.1, v4.2, v4.3 on Linux X86 and AMD64 # # Sun Sudion v11 on Linux AMD64 # # Intel Compilers v9, v10, v11 on Linux AMD64 # ######################################################################### ################################################################### ################################################################### # Please change if required: DEF[1-6], CC, CFLAGS, LIBDIR, ### ################################################################### ### The shell used by this makefile ### SHELL = /bin/sh ### Specify compiler/installation directory ### INSTALLDIR = $INSTALLDIR CC = $CC SCRIPTSDIR = ../bin ### Define statements controlling compilation ### # Comment out DEF[1-8] statements when appropriate. DEF1 = -D__DEBUGMAT1 # -1- range checking in matrix class DEF2 = -D__DEBUGMAT2 # -2- info matrix class (debug only) DEF3 = -D__DEBUG # -3- debug for other files DEF4 = -Wno-deprecated # -4- do not display warnings due to depricated entries DEF5 = -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE # -5- support for large files #DEF6 = -DNO_FASTTRIG # -6- extra functional switches #DEF9 = -D__NO_IOS_BINARY__ # -9- comment out if you ios::binary (most will) # ### Do not change following 2, simply comment DEF1-8 above DEFSDEBUG = \$(DEF1) \$(DEF2) \$(DEF3) DEFS = \$(DEF4) \$(DEF5) \$(DEF6) $CFLAGS ### NOTE ### # If you get warnings like the following (I got them with g++, not with aCC) # then use define __GNUC__ to define these functions #%// BK 15-Aug-2000 #In file included from matrixbk.h:38, # from processor.cc:23: #constants.h: In method \`real8 cn::dist(cn) const': #constants.h:106: implicit declaration of function \`int sqr(...)' ### END NOTE ### # LOCAL dir LOCAL_INSTALLDIR = ../bin ### CFLAGS ### # Compiler options flag ### # Specify compiler flags (I selected these for g++) CFLAGSDEBUG = -g -O \$(DEFS) \$(DEFSDEBUG) CFLAGSOPT = -O \$(DEFS) #CFLAGSOPT = -O2 \$(DEFS) # this crashed doris! (?) #CFLAGSOPT = -O3 \$(DEFS) # this crashed doris! (?) __EOFHD # # See if you want a DEBUG version # if ( "$DEBUG" == "n" ) then cat << __EOFHD >> $MAKEFILE ### CCNOTE ### ### Change here ### ### set CFLAGS depending on if you compile debug version or working version ### #CFLAGS = \$(CFLAGSDEBUG) CFLAGS = \$(CFLAGSOPT) ### END CCNOTE ### __EOFHD else cat << __EOFHD >> $MAKEFILE ### CCNOTE ### ### Change here ### ### set CFLAGS depending on if you compile debug version or working version ### CFLAGS = \$(CFLAGSDEBUG) #CFLAGS = \$(CFLAGSOPT) ### END CCNOTE ### __EOFHD endif # # Add LFLAGS to Makefile # cat << __EOFHD >> $MAKEFILE ### Library locations flag ### ### -lcl : used for veclib ### -lm : used for fftw LFLAGS = $LFLAGS ##################################################### ### No need to change anything below here... #### ##################################################### EXECUTABLE = doris SWSRCS = processor.cc \ utilities.cc \ ioroutines.cc \ readinput.cc \ readdata.cc \ coregistration.cc \ filtering.cc \ referencephase.cc \ products.cc \ geocode.cc \ unwrap.cc \ matrixspecs.cc \ exceptions.cc \ estorbit.cc SWOBJS = \$(SWSRCS:.cc=.o) ### scripts of doris.tar in SCRIPTSDIR, used at make install SCRIPTS = helpdoris \ baseline.doris.sh \ baseline.doris.csh \ construct_dem.sh \ coregpm.doris \ doris* \ heightamb \ phasefilt.doris \ plotcpm* \ plotoffsets* \ run \ viewanddel \ cpx2ps \ lonlathei2ascii \ ascii2ascii_UTM \ ascii2ps* \ tsx* \ rs2* \ csk* \ gammaReadfiles.csh \ hhmmss2sec.py \ sec2hhmmss.py ##################################################### ### And no need to change anything below here... #### ##################################################### ### what to do if make w/o arguments ### # first make all object files, then link them together default: \$(EXECUTABLE) ### how to compile object code .o from C++ source files .cc (general rule) ### # space between -o and filename for SUN make (BK 7 july 2000) .cc.o: \$(CC) \$(CFLAGS) -c -o \$(@) \$< ##################################################### ### Make object code from source ### swobjs: \$(SWOBJS) ### Load objects to executable ### ### The added .cc files contain class definitions ### matrixclass is explicitly included ### in the source code since we had some problems finding out how to do that ### here, since compilers treat the template class differently than normal classes. ### BK 07-Feb-2002 \$(EXECUTABLE): \$(SWOBJS) tmp_strptime.cc slcimage.cc productinfo.cc orbitbk.cc \$(CC) \$(CFLAGS) -c -o triangle.o -DTRILIBRARY -DANSI_DECLARATORS triangle.c \$(CC) \$(CFLAGS)\ tmp_strptime.cc \$(SWOBJS) triangle.o\ slcimage.cc productinfo.cc orbitbk.cc\ \$(LFLAGS) -o \$@ @echo " " @echo "*******************************" @echo "* ...Compilation finished... *" @echo "*******************************" @echo " " ### Install executable in installdir ### install: \$(EXECUTABLE) @echo "* Installing \$(EXECUTABLE) in: \$(INSTALLDIR)" @cp -f \$(EXECUTABLE) \$(INSTALLDIR)/. ( cd \$(SCRIPTSDIR); cp -f \$(SCRIPTS) \$(INSTALLDIR)/. ) \$(MAKE) cleaner @echo " " @echo "*******************************" @echo "* ...Installation finished... *" @echo "*******************************" @echo " " @echo "* Check that \$(INSTALLDIR) is in your path search: echo \\\$\$PATH ." @echo " " installcb: \$(EXECUTABLE) @echo "* Installing \$(EXECUTABLE) in: \$(LOCAL_INSTALLDIR)" @cp -f \$(EXECUTABLE) \$(LOCAL_INSTALLDIR)/. \$(MAKE) cleaner @echo " " @echo "*******************************" @echo "* ...Installation finished... *" @echo "*******************************" @echo " " @echo "* Check that \$(LOCAL_INSTALLDIR) is in your path search: echo \\\$\$PATH ." @echo " " ##################################################### ### Testers ### test: testdoris testdoris: \$(EXECUTABLE) @echo " " @echo "* Executing command: \$(EXECUTABLE) -v" \$(EXECUTABLE) -v @echo " " ### Orbit test program for debugging ### test-orbit: ioroutines.o matrixspecs.o utilities.o exceptions.cc slcimage.cc orbitbk.cc matrixbk.cc bk_messages.hh \$(CC) \$(CFLAGS) -D__TESTMAIN__ \ ioroutines.o matrixspecs.o utilities.o exceptions.cc slcimage.cc orbitbk.cc \ \$(LFLAGS) \ -o \$@ ### Matrix test program for debugging ### ### fast_sin defined in utilities.cc, which requires ioroutines, which, etc. test-matrix: matrix_test.cc matrixspecs.o utilities.o utilities.o ioroutines.o matrixbk.cc \$(CC) \$(CFLAGS) matrix_test.cc matrixspecs.o \ utilities.o ioroutines.o exceptions.cc orbitbk.cc \ \$(LFLAGS) \ -o \$@ @echo " " ##################################################### ### Cleaners ### clean: cleanswobjs cleaner: clean cleanprog cleanest: clean cleanprog uninstall cleanprog: @rm -f \$(EXECUTABLE) \$(EXECUTABLE.debug) \ matrixbk_test testorbit @echo "* Removed executables in current dir." cleanswobjs: @rm -f \$(SWOBJS) matrixbk_test.o orbitbk.o slcimage.o triangle.o @echo "* Removed object files." uninstall: @rm -f \$(INSTALLDIR)/\$(EXECUTABLE) @echo "* Removed executables in install dir: \$(INSTALLDIR)." ### BK 12-Dec-2000 ### __EOFHD ### Finish with some hints. set LINE = `grep -n CFLAGSOPT $MAKEFILE | cut -f1 -d":"` cat << __EOFHD $PRG has finished creating: $MAKEFILE ------------------------------------------------- To compile the Doris software do the following: 1. Inspect the created Makefile named: $MAKEFILE *TIP* If you like to use other compiler flags (CFLAGS), change them in file: $MAKEFILE change them at line: $LINE[1] in file: $MAKEFILE *TIP* the command: make -f $MAKEFILE -n will show what happens without executing. 2. At the prompt, enter the command: make -f $MAKEFILE to compile an version of Doris. *TIP* if compilation FAILS due to strptime, try uncommenting DEF8 *TIP* if compilation FAILS due to something else, please report the problem to the mailing list, after checking the user manual and the FAQ. 3. Enter the command: make -f $MAKEFILE install to install the executable in directory: $INSTALLDIR This will also install the scripts residing in directory ../bin and it will clean up this directory (remove the object files). 4. After installation, the command: doris -v [should now give the version number] doris -h [should give help] doris -c [should give the copyright notice] doris -q [should give help also] *TIP* Make sure the installation directory is in your path. (do a rehash or login again) 5. You are adviced to create a (slower, much more verbose) debug version of Doris. If you get an error during running the normal version of Doris, you can repeat the processing with this debug executable. In order to compile a debug version, make sure the normal version is installed. next, run the configure script again (or set appropriate CFLAGS in file $MAKEFILE at line $LINE[2]), and indicate that you do want a debug version. Then give the commands: make clean make -f $MAKEFILE This compiles a debug version, named "doris". Do not use make install, instead move this executable to "doris.debug" in the installation directory by hand. ---------------------------------------------------------------------- DO NOT FORGET to go to directory SARtools and do a make install, and also in directory ENVISAT_TOOLS. The programs in these directories are used in doris. Before compiling doris, create the fftw library if you want to use it. ---------------------------------------------------------------------- MORE INFORMATION ---------------- - See the README file, the $MAKEFILE, or the users manual (at: http://doris.tudelft.nl/) - Consider installing the Matlab InSAR toolbox. __EOFHD ### EOF. Doris-5.0.3Beta/doris_core/constants.hh000077500000000000000000001020501312547014700200650ustar00rootroot00000000000000/* * Copyright (c) 1999-2012 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/constants.hh,v $ * * $Revision: 3.33 $ * * $Date: 2005/10/18 14:15:26 $ * * $Author: TUDelft $ * * * * Definitions of some global (external) structs +functions, * * constants * * define: SWNAME SWVERSION * * __GplusplusCOMPILER__ then implement T sqr(T), cause no ansi c++ * * pragma: aCC things (removed since v3.8) * * * * CLASSES IN THIS FILE: * * - ellips: struct + functions * * - cn: 3D coordinates + functions * * - window: in matrices/files + functions * ****************************************************************/ #ifndef CONSTANTS_H #define CONSTANTS_H using namespace std; // BK 29-Mar-2003, new compiler? // TODO: SLiu avoid namespace declaration in the header file. // Jia defined this for compilation under windows // Bert Kampes, 24-Aug-2005 #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "bk_messages.hh" #include "exceptions.hh" // [MA] #include "cstring" // strcpy for exceptions //#if defined __GNUC__ && __GNUC__ >= 2 //#else //#endif // g++ -v -c processor.cc gives (ao): // -D__GNUC__=2 -D__GNUG__=2 -D__GNUC_MINOR__=95 #include // for pi (atan) #include // default known complex type #include // cout etc. #include // for memory stream // ====== Globals for messages to stdout ====== extern bk_messages TRACE; extern bk_messages DEBUG; extern bk_messages INFO; extern bk_messages PROGRESS; extern bk_messages WARNING; extern bk_messages ERROR; // _____ Macros for abbreviation ______ // ___ Note that useage could be like PRINT_ERROR(WARNING.get_str()) ___ // ___ (normally WARNING.rewind() required after this, but exited) ___ // ___ PRINT_ERROR(".") ___ // ___ w/o the ";" (since in an if/else construction without {}{} // ___ it will otherwise crash ___ // ___ use TRACE_FUNCTION ONLY SIMPLE WITH CHAR ARRAY "dadsa" ___ #define TRACE_FUNCTION(s) {TRACE.reset();\ TRACE<<"["<<__FILE__<<"["<<__LINE__<<"]]: "< .hh //#define SWVERSION "Version 3.15 (14-JUL-2005)" // baseline class, exceptions //#define SWVERSION "Version 3.16 (01-SEP-2005)" // OVS az.; small bugs; coreg better //#define SWVERSION "Version 3.17 (05-NOV-2005)" // code reorg. g++-4.0 compiler //#define SWVERSION "Version 3.18test3 (11-JUL-2006)" // //#define SWVERSION "Version 3.18test5 (26-FEB-2007)" // alos, bug.fix, rsmp.dbow.geo //#define SWVERSION "Version 3.19test8 (30-JUL-2007)" // bug.fix, dem.interpolator.fix //#define SWVERSION "Version 3.20 (02-JAN-2008)" // bug.fix, coregistration //#define SWVERSION "Version 3.94 (22-AUG-2007)" // Freek: DEM assistant coregistration [LG] + timing error //#define SWVERSION "Version 3.95 (21-AUG-2008)" // PM & MA & GJ: bug fixes , compiler support updates, counter bug, > 4GB filesupport in 32-bit //#define SWVERSION "Version 3.96 (06-SEP-2008)" // merge v3.20 and v3.95 //#define SWVERSION "Version 3.97 (29-OCT-2008)" // Don, MA, Fvl: DEMA bug fixed //#define SWVERSION "Version 3.98 (06-Nov-2008)" // Don coherence est. w/ removal topo. slope, BO & FvL & MA: simamp + master_timing, MA: several additional fixes //#define SWVERSION "Version 3.99 (23-Dec-2008)" // wrapping up updates //#define SWVERSION "Version 4.01 (24-Dec-2008)" // release candidate v4.01 rc3, ALOS and RADARSAT1 fixes, some improvement in SIMAMP, casting fixes for compilers //#define SWVERSION "Version 4.01_rc8 (21-Mar-2009)" // release candidate v4.01 rc8 //#define SWVERSION "Version 4.01_rc9 (27-Mar-2009)" // release candidate v4.01 rc9 //#define SWVERSION "Version 4.01_rc10 (13-Apr-2009)" // release candidate v4.01 rc10 PM TERRASAR-X sensor //#define SWVERSION "Version 4.01 (14-Apr-2009)" // release v4.01 finally! :-) //#define SWVERSION "Version 4.02 (08-Jun-2009)" // release v4.02, fixes on comprefdem buffer when multilooked [HB]; [MA] lapack warnings fix and lib versions, fix on sinus lut and NO_FASTTRIG //#define SWVERSION "Version 4.03-beta (14-Jul-2009)" // release v4.03, //#define SWVERSION "Version 4.03-beta2 (22-Aug-2009)" // release v4.03, rf_nlmean fix, mte_distwinfile fix. //#define SWVERSION "Version 4.03-beta3 (06-Sep-2009)" // fix readres at oversample slave //#define SWVERSION "Version 4.03-beta4 (06-Oct-2009)" // added Radarsat-2 reader //#define SWVERSION "Version 4.03-beta5 (08-11-2009)" // added Radarsat-2 reader //#define SWVERSION "Version 4.03-beta7 (04-01-2010)" // fix productfill for long pathnames, MCC Envisat alternating polarization update. //#define SWVERSION "Version 4.03-beta8 (09-04-2010)" " Build: " __TIMESTAMP__ // [MA] add SAM: demhei_lp and theta_lp //#define SWVERSION "version 4.03-beta9 (15-04-2010)" "\n\t\t build \t" __TIMESTAMP__ // [MA] crosscorrelate: drop correlation >1 affects mtiming, coarsecorr(magfft), filename update for DEMA, CRD, screen info update //#define SWVERSION "version 4.03-beta10 (23-06-2010)" "\n\t\t build \t" __TIMESTAMP__ // [MA] TSX heading info, [PD] CSK reader, SLIU important comments //#define SWVERSION "version 4.03-beta11 (16-09-2010)" "\n\t\t build \t" __TIMESTAMP__ // [BO] GAMMA SLC, KML Generation, TSX dumpheader bugfix. //#define SWVERSION "version 4.03-beta12 (11-11-2010)" "\n\t\t build \t" __TIMESTAMP__ // [MA] Read only the parameters of the step to run, not all ex: for simamp is done, see products.cc // coarsewindow size updated, simamp multilook factor is fixed to 1 due to Doris convention. defined memory_max in constants.hh, read necessart inputs for processing not all see simamp part in readinput.cc //#define SWVERSION "version 4.03-beta13 (01-12-2010)" "\n\t\t build \t" __TIMESTAMP__ // [MA] fix to Read only the parameters issues on simamp, skip loop1 update. //#define SWVERSION "version 4.04-beta1 (06-12-2010)" "\n\t\t build \t" __TIMESTAMP__ // start to merge two branches //#define SWVERSION "version 4.04-beta2 (05-01-2011)" "\n\t\t build \t" __TIMESTAMP__ // [MA] ERS_N1 support Doris part //#define SWVERSION "version 4.04-beta3 (07-02-2011)" "\n\t\t build \t" __TIMESTAMP__ // [MA] ERS_N1 support fix //#define SWVERSION "version 4.04-beta4 (10-03-2011)" "\n\t\t build \t" __TIMESTAMP__ // [MA] master printout crop numlines+numpixels //#define SWVERSION "version 4.05-beta1 (28-03-2011)" "\n\t\t build \t" __TIMESTAMP__ // [HB] ESTORBIT module //#define SWVERSION "version 4.06-beta1 (23-10-2011)" "\n\t\t build \t" __TIMESTAMP__ // [BA] Modified Goldstein Filter //#define SWVERSION "version 4.06-beta2 (28-12-2011)" "\n\t\t build \t" __TIMESTAMP__ // [MA] path length fix for demassist at productfill and the rest. //#define SWVERSION "version 4.06-beta3 (31-10-2013)" "\n\t\t build \t" __TIMESTAMP__ // [FvL] path length fix in readcoeff function (ioroutines.cc). //#define SWVERSION "version 4.0.7 (23-07-2014)" "\n\t\t build \t" __TIMESTAMP__ // [FvL] removed unwanted automatic removal of pre-calculated reference phase in INTERFERO step #define SWVERSION "version 4.0.8 (04-09-2014)" "\n\t\t build \t" __TIMESTAMP__ // [FvL] new version based on svn trunk with still untested spotlight developments. // ====== Typedefs for portability ====== typedef short int int16; // 16 bits --> 2 bytes. It has a range of -32768 to 32767. [ from -2^15 to (2^15 - 1) ] [MA] typedef unsigned short int uint16; // 16 bits --> 2 bytes. It has a range of 0 to 65535. [ 2^16 - 1] typedef int int32; // 32 bits --> 4 bytes. It has a range of -2,147,483,648 to 2,147,483,647, [ -(2^31) to (2^31 - 1) ] typedef unsigned int uint32; // 32 bits --> 4 bytes. It has a range of 0 to 4,294,967,295. [ 2^32 - 1 ] typedef unsigned int uint; // sizeof (int) = sizeof (long) on 32bit data model; sizeof (int) < sizeof (long) on 64 bit. typedef long long int64; // 64 bits --> 8 bytes. It has a range of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 . [ -(2^63) to 2^63 - 1] typedef unsigned long long uint64; // 64 bits --> 8 bytes. It has a range of 0 to 18,446,744,073,709,551,615. [ 2^64 - 1 ] typedef float real4; // 7 digits x.1xxxx6e(-126 and +127) typedef double real8; // 16 digits x.1xxxxxxxxxxxxx15(-1022 and +1023) typedef complex compli16; typedef complex compli32; typedef complex complr4; typedef complex complr8; #if defined (__GNUC__) && __GNUC__ >= 4 typedef long double real16; // 34 digits x.1xxxxxxxxxxxxx33(-16382 and +16383) // quadruple precision [MA] //# else # endif /* GCC. */ // ====== function: Type sqr(Type) not in stdlib math.h! ====== // ====== Possibly also for other compilers that have errors this define will fix it === // note though that this is not save-casted #ifdef __GNUC__ inline int16 sqr(const int16 &x) {return(x*x);} inline uint16 sqr(const uint16 &x) {return(x*x);} inline int32 sqr(const int32 &x) {return(x*x);} inline int64 sqr(const int64 &x) {return(x*x);} inline uint64 sqr(const uint64 &x) {return(x*x);} inline uint sqr(const uint &x) {return(x*x);} inline real4 sqr(const real4 &x) {return(x*x);} inline real8 sqr(const real8 &x) {return(x*x);} #endif // For windows, it seems max,min is already defined, but with different arguments. // I cannot believe this, but Jia changed all call`s to min/max to _min _max (?) // He also changed the names of DEBUG to DEBUG1 and INFO to INFO1, etc. // in processor.cc: // Bert Kampes, 24-Aug-2005 //#ifdef WIN32 //#define max _MAX //#define min _MIN //#endif // ====== Global constants ====== // ______ General constants ______ const real8 SOL = 299792458.0; // speed of light in m/s const real8 EPS = 1e-13; // small number const int32 NaN = -999; // Not a Number const int32 Inf = 99999; // Infinity #ifdef M_PI const real8 PI = M_PI;// conform to standard value in math.h #else const real8 PI = real8(4)*atan(real8(1)); #endif //const int16 EIGHTY = 80; const int16 EIGHTY = 200;// 80 seems to short for ASAR filenames const int16 ONE27 = 127; // doris memory for buffer operations const uint32 MEMORY_DEF = 500; // default memory (~500MB), unit Mbits [MA] const uint32 MEMORY_MAX = 12000; // maximum memory (~12GB) // ______ Handy for software, IDs have to be enumerated (used in loop) ______ const int16 LOGID = 1; // general identifier for log const int16 MASTERID = 2; // general identifier for master const int16 SLAVEID = 3; // general identifier for slave const int16 INTERFID = 4; // general identifier for interferogram const int16 FORMATCI2 = 11; // formatflag const int16 FORMATCR4 = 12; // formatflag const int16 FORMATR4 = 13; // formatflag const int16 FORMATI2 = 14; // formatflag const int16 FORMATI2_BIGENDIAN = 17; // formatflag const int16 FORMATHGT = 15; // formatflag unwrapped band interleaved ampl(1)/phase(2) const int16 FORMATR8 = 16; // formatflag const int16 FORMATI4 = 18; // formatflag // TODO MA revisit to order and out to enum const int16 FORMATCR8 = 19; // formatflag // ______ product specifier ______ const int16 SLC_ERS = 1; // ERS const int16 SLC_ERS_N1 = 11; // ERS in N1 format const int16 SLC_ASAR = 2; // ENVISAT const int16 SLC_ASAR_AP_HH = 21; // ENVISAT AP HH const int16 SLC_ASAR_AP_VV = 22; // ENVISAT AP VV const int16 SLC_S1A = 30; //Sentinel-1 A (TOPS mode)) const int16 SLC_RSAT = 3; // RadarSAT (and Atlantis processor??) const int16 SLC_JERS = 4; // JERS (ceos?) // for ALOS: [PM] const int16 SLC_ALOS = 5; // ALOS (ceos) // [MA] TODO what about different polarizations: single 5 --> 51; dual == 52 etc. const int16 SLC_TSX = 6; // TSX stripmap // for Radarsat-2: [MA] const int16 SLC_RS2 = 70; // RS2 [Default for Radarsat-2 SLC] [MA] const int16 SLC_RS2_QUAD = 71; // RS2 71 --> QUADPOL // for CSK: [PD] const int16 SLC_CSK = 80; // CSK stripmap SLC const int16 SLC_CSK_POL = 81; // CSK POL template const int16 SLC_GAMMA = 9; // GAMMA SLC. Only for readfiles step. [BO] // ______ processor specifier ______ const int16 SARPR_VMP = 11; // ESA PAFs SAR processor SLC const int16 SARPR_ATL = 12; // Atlantis created SLC const int16 SARPR_TUD = 13; // TUDelft processor created SLC // Modified by LG for reading ALOS Fine const int16 SARPR_JAX = 14; // JAXA processor created SLC const int16 SARPR_TSX = 15; // TSX processor created COSAR const int16 SARPR_GAM = 16; // GAMMA processor created SLC [BO] const int16 SARPR_RS2 = 17; // RS2 processor created ... const int16 SARPR_CSK = 18; // CSK processor created H5 // ====== Unique method selectors for interpolation ====== // ====== For ASAR (only 5 points), spline is not good ====== const int16 ORB_SPLINE = -11; // else degree of polynomial const int16 ORB_DEFAULT = -12; // [degree of polynomial=numpoints-1, max=5] const int16 ORB_PRM_POS = 30; // POSITION default [MA] [TODO] const int16 ORB_PRM_VEL = 31; // POSIVELO [MA] // ====== ELLIPSOID CLASS ====== // ______flatting is different: grs80: 298,25722101 // ______flatting is different: wgs84: 298,25723563 const double WGS84_A = 6378137.000; // semimajor axis wgs84 const double WGS84_B = 6356752.3141; // semiminor axis wgs84 // ____ used in matric.cc: convert_type ____ [GJ] && [MA] 2009 inline int getformat( const int16 x ) { return FORMATI2; } // cannot detect endianness !! inline int getformat( const int32 x ) { return FORMATI4; } // cannot detect endianness !! inline int getformat( const real4 x ) { return FORMATR4; } inline int getformat( const real8 x ) { return FORMATR8; } inline int getformat( const complr4 x ) { return FORMATCR4; } inline int getformat( const complr8 x ) { return FORMATCR8; } // ====== class cn for coordinates + functions ======================= class cn // coordinates { public: real8 x, // y, // z; // // ______ Constructors ______ cn() {x=0.0; y=0.0; z=0.0;} cn(real8 Px, real8 Py, real8 Pz) {x=Px; y=Py; z=Pz;} // ______ Copy constructor ______ cn(const cn& P) {x=P.x; y=P.y; z=P.z;} // ______ Destructor ______ ~cn() {;}// nothing to destruct that isn't destructed automatically // ______ Operators ______ inline cn& operator = (const cn &P)// assignment operator {if (this != &P) {x=P.x; y=P.y; z=P.z;} return *this;} inline cn& operator += (const cn &P) {x+=P.x; y+=P.y; z+=P.z; return *this;} inline cn& operator -= (const cn &P) {x-=P.x; y-=P.y; z-=P.z; return *this;} inline cn& operator *= (const real8 s)// multiply by scalar {x*=s; y*=s; z*=s; return *this;} inline cn& operator *= (const cn &P) {x*=P.x; y*=P.y; z*=P.z; return *this;} inline cn& operator /= (const real8 s)// divide by scalar {x/=s; y/=s; z/=s; return *this;} inline cn& operator /= (const cn &P) {x/=P.x; y/=P.y; z/=P.z; return *this;} inline cn operator + () // unary plus {return cn(x,y,z);} inline cn operator + (const cn &P) // binary plus {return cn(x,y,z)+=P;} inline cn operator - ()// unary min {return cn(-x, -y, -z);} inline cn operator - (const cn &P)// binary min {return cn(x,y,z)-=P;} inline cn operator * (const real8 s) // Q=P*s {return cn(x,y,z)*=s;} inline cn operator * (const cn &P) // Q=P*Q {return cn(x,y,z)*=P;} inline cn operator / (const real8 s) // Q=P/s {return cn(x,y,z)/=s;} inline cn operator / (const cn &P) // Q=P/Q {return cn(x,y,z)/=P;} inline bool operator == (const cn &P) const // isequal operator {return (P.x==x && P.y==y && P.z==z) ? true : false;} inline bool operator != (const cn &P) const // isnotequal operator {return (P.x==x && P.y==y && P.z==z) ? false : true;} // ______ Public function in struct ______ inline real8 in(cn P) const // scalar product: r=P.in(Q) {return x*P.x+y*P.y+z*P.z;} inline cn out(cn P) const // cross product cn r=P.out(Q) {return cn(y*P.z-z*P.y, z*P.x-x*P.z, x*P.y-y*P.x);} inline real8 dist(cn P) const // distance: d=P.dist(Q) {return sqrt(sqr(x-P.x)+sqr(y-P.y)+sqr(z-P.z));} // ___ WIN32: Jia defined following, but I don;t know why: // cn _min(cn P) const // cn r=P.min(Q); // Jia YouLiang // {return cn(x-P.x, y-P.y, z-P.z);} inline cn min(cn P) const // cn r=P.min(Q) {return cn(x-P.x, y-P.y, z-P.z);} inline real8 norm2() const // n=P.norm2() {return sqr(x)+sqr(y)+sqr(z);} inline real8 norm() const // n=P.norm() {return sqrt(sqr(x)+sqr(y)+sqr(z));} inline cn normalize() const // cn R=P.normalize() {return cn(x,y,z)/norm();} //{const real8 n=norm(); return cn(x/n, y/n, z/n);} inline real8 angle(cn A) const // angle=A.angle(B); //0,pi; {return acos(in(A)/(norm()*A.norm()));} inline cn scale(real8 val) const // scaling of a point by a scalar KKM-05 {return cn(x*val, y*val, z*val);} inline void showdata() const // displays a point by KKM-05 Mar 9, 2005 {DEBUG << "cn.x=" << x << "; cn.y=" << y << "; cn.z=" << z; DEBUG.print();} // --- Test program for coordinate class ---------------------------- // --- This test is executed in inittest() -------------------------- inline void test() { // constructors cn X(1,2,3); DEBUG << "cn X(1,2,3): "; X.showdata(); cn Y; DEBUG << "cn Y: "; Y.showdata(); Y.x=4; Y.y=5; Y.z=6; DEBUG << "Y.x=4;Y.y=5;Y.z=6: "; Y.showdata(); cn Z=Y; DEBUG << "Z=Y: "; Z.showdata(); // operators Z*=X; DEBUG << "Z*=X: "; Z.showdata(); Z/=X; DEBUG << "Z/=X: "; Z.showdata(); Z+=X; DEBUG << "Z+=X: "; Z.showdata(); Z-=X; DEBUG << "Z-=X: "; Z.showdata(); // operators DEBUG << "X+Y: "; (X+Y).showdata(); DEBUG << "X-Y: "; (X-Y).showdata(); DEBUG << "X/Y: "; (X/Y).showdata(); DEBUG << "X*Y: "; (X*Y).showdata(); DEBUG << "+X: "; (+X).showdata(); DEBUG << "-X: "; (-X).showdata(); DEBUG << "X==Y: " << (X==Y); DEBUG.print(); DEBUG << "X!=Y: " << (X!=Y); DEBUG.print(); // functions DEBUG << "X.min(Y): "; (X.min(Y)).showdata(); DEBUG << "X.normalize(): "; (X.normalize()).showdata(); DEBUG << "X.scale(5): "; (X.scale(5)).showdata(); DEBUG << "X.out(Y): "; (X.out(Y)).showdata(); DEBUG << "X.dist(Y): " << X.dist(Y); DEBUG.print(); DEBUG << "X.norm(): " << X.norm(); DEBUG.print(); DEBUG << "X.norm2(): " << X.norm2(); DEBUG.print(); DEBUG << "X.angle(Y): " << X.angle(Y); DEBUG.print(); DEBUG << "X.in(Y): " << X.in(Y); DEBUG.print(); } }; // ====== Class for ellips ===================================== class input_ell // ellips a,b { private: real8 e2; // squared first eccentricity (derived) real8 e2b; // squared second eccentricity (derived) // ______ Helpers should be private ______ inline void set_ecc1st_sqr() // first ecc. {e2=1.0-sqr(b/a);}// faster than e2=(sqr(a)-sqr(b))/sqr(a); inline void set_ecc2nd_sqr() // second ecc. {e2b=sqr(a/b)-1.0;}// faster than e2b=(sqr(a)-sqr(b))/sqr(b); public: real8 a; // semi major real8 b; // semi minor char name[EIGHTY]; inline void set_name(const char *s) {strcpy(name,s);} // ______ Default constructor ______ input_ell() {a = WGS84_A; b = WGS84_B; e2 = 0.00669438003551279091; e2b = 0.00673949678826153145; //set_ecc1st_sqr();// compute e2 //set_ecc2nd_sqr();// compute e2b set_name("WGS84"); } // ______ constructor ellips(a,b) ______ input_ell(const real8 &semimajor, const real8 &semiminor) {a = semimajor; b = semiminor; set_ecc1st_sqr();// compute e2 (not required for zero-doppler iter.) set_ecc2nd_sqr();// compute e2b (not required for zero-doppler iter.) //set_name("unknown"); set_name("Default"); } // ______ Copy constructor ______ input_ell(const input_ell& ell) {a=ell.a; b=ell.b; e2=ell.e2; e2b=ell.e2b; strcpy(name,ell.name);} // ______ Destructor ______ ~input_ell() {;}// nothing to destruct that isn't destructed automatically // ______ Public function in struct ______ inline input_ell& operator = (const input_ell &ell)// assignment operator { if (this != &ell) {a=ell.a; b=ell.b; e2=ell.e2; e2b=ell.e2b; strcpy(name,ell.name);} return *this; } inline void showdata() const { INFO << "ELLIPSOID: \tEllipsoid used (orbit, output): " << name << "."; INFO.print(); INFO << "ELLIPSOID: a = " << setw(15) << setprecision(13) << a; INFO.print(); INFO << "ELLIPSOID: b = " << setw(15) << setprecision(13) << b; INFO.print(); INFO << "ELLIPSOID: e2 = " << e2; INFO.print(); INFO << "ELLIPSOID: e2' = " << e2b; INFO.print(); INFO.reset(); } // ______ Convert xyz cartesian coordinates to ______ // ______ Geodetic ellipsoid coordinates latlonh ______ /**************************************************************** * xyz2ell * * * * Converts geocentric cartesian coordinates in the XXXX * * reference frame to geodetic coordinates. * * method of bowring see globale en locale geodetische systemen* * input: * * - ellipsinfo, xyz, (phi,lam,hei) * * output: * * - void (updated lam<-pi,pi>, phi<-pi,pi>, hei) * * * * Bert Kampes, 05-Jan-1999 * ****************************************************************/ inline void xyz2ell(const cn &xyz, real8 &phi, real8 &lambda, real8 &height) const { TRACE_FUNCTION("xyz2ell (BK 05-Jan-1999)"); const real8 r = sqrt(sqr(xyz.x)+sqr(xyz.y)); const real8 nu = atan2((xyz.z*a),(r*b)); const real8 sin3 = pow(sin(nu),3); const real8 cos3 = pow(cos(nu),3); phi = atan2((xyz.z+e2b*b*sin3),(r-e2*a*cos3)); lambda = atan2(xyz.y,xyz.x); const real8 N = a / sqrt(1.0-e2*sqr(sin(phi))); height = (r/cos(phi)) - N; } // END xyz2ell // --- Same but without height --- inline void xyz2ell(const cn &xyz, real8 &phi, real8 &lambda) const { TRACE_FUNCTION("xyz2ell (BK 05-Jan-1999)"); const real8 r = sqrt(sqr(xyz.x)+sqr(xyz.y)); const real8 nu = atan2((xyz.z*a),(r*b)); const real8 sin3 = pow(sin(nu),3); const real8 cos3 = pow(cos(nu),3); phi = atan2((xyz.z+e2b*b*sin3),(r-e2*a*cos3)); lambda = atan2(xyz.y,xyz.x); } // END xyz2ell /**************************************************************** * ell2xyz * * * * Converts wgs84 ellipsoid cn to geocentric cartesian coord. * * input: * * - phi,lam,hei (geodetic co-latitude, longitude, [rad] h [m] * * output: * * - cn XYZ * * * * Bert Kampes, 05-Jan-1999 * ****************************************************************/ cn ell2xyz(const real8 &phi, const real8 &lambda, const real8 &height) const { const real8 N = a / sqrt(1.0-e2*sqr(sin(phi))); const real8 Nph = N + height; return cn(Nph * cos(phi) * cos(lambda), Nph * cos(phi) * sin(lambda), (Nph - e2*N) * sin(phi)); } // END ell2xyz // --- Test program for ellips class ---------------------------- // --- This test is executed in inittest() -------------------------- inline void test() { // constructors input_ell X; DEBUG << "ELLIPS: " << X.name << ": X.a=" << X.a << "; X.b=" << X.b << "; X.e2=" << X.e2 << "; X.e2b=" << X.e2b; DEBUG.print(); } }; /*************************************************************** * * * Class window + functions * * image starts at 1, matrix starts at 0 * * * * Bert Kampes, 19-Dec-1999 * * [MA] Window extend error check - 2008 * ****************************************************************/ class window // window file={1,N,1,N} { public: uint linelo, // min. line coord. linehi, // max. line coord. pixlo, // min. pix coord. pixhi; // max. pix coord. // ______ Constructors ______ window() {linelo=0; linehi=0; pixlo=0; pixhi=0;} window(uint ll, uint lh, uint pl, uint ph) { TRACE_FUNCTION("window() (BK 19-Dec-1998)"); linelo=ll; linehi=lh; pixlo=pl; pixhi=ph; // ______ Check window extend ______ [MA] if( int32(linelo) > int32(linehi) ) { ERROR << "Window: Impossible to continue... l0 coordinate [" << linelo << "] > linehi [" << linehi << "]."; ERROR.print(); throw(usage_error) ; } else if( int32(pixlo) > int32(pixhi) ) { ERROR << "Window: Impossible to continue... p0 coordinate [" << pixlo << "] > pixelhi [" << pixhi << "]."; ERROR.print(); throw(usage_error) ; } } // ______ Copy constructor ______ window(const window& w) {linelo=w.linelo; linehi=w.linehi; pixlo=w.pixlo; pixhi=w.pixhi;} // ______ Destructor ______ ~window() {;};// nothing to destruct that isn't destructed automatically // ______ Public function in struct ______ inline void disp() const // show content { DEBUG << "window [l0:lN, p0:pN] = [" << linelo << ":" << linehi << ", " << pixlo << ":" << pixhi << "]"; DEBUG.print(); } inline uint lines() const // return number of lines {return linehi-int32(linelo)+1;} inline uint pixels() const // return number of pixels {return pixhi-int32(pixlo)+1;} inline window& operator = (const window &X)// assignment operator {if (this != &X) {linelo=X.linelo;linehi=X.linehi;pixlo=X.pixlo;pixhi=X.pixhi;} return *this;} inline bool operator == (const window &X) const {return (linelo==X.linelo&&linehi==X.linehi && pixlo==X.pixlo && pixhi==X.pixhi) ? true : false;} inline bool operator != (const window &X) const {return (linelo==X.linelo&&linehi==X.linehi && pixlo==X.pixlo && pixhi==X.pixhi) ? false : true;} // --- Test program for coordinate class ---------------------------- // --- This test is executed in inittest() -------------------------- inline void test() { // constructors window X; DEBUG << "window X: "; X.disp(); window Y(11,21,103,114); DEBUG << "window Y(11,21,103,114): "; Y.disp(); // functions X=Y; DEBUG << "X=Y: "; X.disp(); DEBUG << "X.lines(): " << X.lines(); DEBUG.print(); DEBUG << "X.pixels(): " << X.pixels(); DEBUG.print(); DEBUG << "X==Y: " << (X==Y); DEBUG.print(); DEBUG << "X!=Y: " << (X!=Y); DEBUG.print(); } }; // ====== Class slavewindow + functions ================================ // added by FvL class slavewindow // window file={l00,p00,l0N,p0N,lN0,pN0,lNN,pNN} { public: real8 l00, p00, l0N, p0N, lN0, pN0, lNN, pNN; // ______ Constructors ______ slavewindow() {l00=0; p00=0; l0N=0; p0N=0; lN0=0; pN0=0; lNN=0; pNN=0;} slavewindow(real8 ll00, real8 pp00, real8 ll0N, real8 pp0N, real8 llN0, real8 ppN0, real8 llNN, real8 ppNN) {l00=ll00; p00=pp00; l0N=ll0N; p0N=pp0N; lN0=llN0; pN0=ppN0; lNN=llNN; pNN=ppNN;} // ______ Copy constructor ______ slavewindow(const slavewindow& w) {l00=w.l00; p00=w.p00; l0N=w.l0N; p0N=w.p0N; lN0=w.lN0; pN0=w.pN0; lNN=w.lNN; pNN=w.pNN;} // ______ Destructor ______ ~slavewindow() {;};// nothing to destruct that isn't destructed automatically }; #endif // CONSTANTS_H Doris-5.0.3Beta/doris_core/coregistration.cc000066400000000000000000010522341312547014700211010ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/coregistration.cc,v $ * * $Revision: 3.40 $ * * $Date: 2005/10/18 13:46:51 $ * * $Author: kampes $ * * * * -coarse based on orbits. * * -coarse based on correlation with fft/in space domain. * * -fine coregistration offset vector computation. * * -computation coregistration parameters. * * -computation flat earth correction. * * -resampling of slave to master grid. * ****************************************************************/ #include "constants.hh" // typedefs etc. #include "ioroutines.hh" // error function etc. #include "utilities.hh" // isodd #include "coregistration.hh" // header file #include "orbitbk.hh" // my orbit class #include "slcimage.hh" // my slc image class #include "productinfo.hh" // my 'products' class #include "exceptions.hh" // my exceptions class #include "bk_baseline.hh" // my exceptions class #include // setw #include // system #include // sqrt rint #include // max #include // some compilers, remove function #ifdef WIN32 // Jia defined min max here, but I did this in constants.hh //#define max _MAX //#define min _MIN #endif /**************************************************************** * coarseporbit * * * * computes translation of slave w.r.t. master * * slave(some point) = master(same point) + trans(l,p) => * * trans = slavecoordinates - mastercoordinates * * uses orbits to find coordinates of center of master * * then solves for lin,pix of these cn. for slave. * * * * input: * * - * * output: * * - * * * * Bert Kampes, 12-Dec-1998 * ****************************************************************/ void coarseporbit( const input_ell &ell, const slcimage &master, const slcimage &slave, orbit &masterorbit, // cannot be const for spline orbit &slaveorbit, // cannot be const for spline const BASELINE &baseline) { TRACE_FUNCTION("coarseporbit (BK 12-Dec-1998)"); const int16 MAXITER = 10; // maximum number of iterations const real8 CRITERPOS = 1e-6; // 1micrometer const real8 CRITERTIM = 1e-10; // seconds (~10-6 m) // ______Initial values______ :master.approxcentreoriginal.x .y .z // ______Window______ :master.currentwindow.linelo/hi , pixlo/hi // ______Time______ :master.t_azi0/N , t_range0/N // ______Get (approx) center pixel of current window master______ const uint cen_lin = (master.currentwindow.linelo+master.currentwindow.linehi)/2; const uint cen_pix = (master.currentwindow.pixlo +master.currentwindow.pixhi) /2; const real8 HEI = 0.0; // ______ Compute x,y,z (fill P) ______ // ______ P.x/y/z contains (converged) solution ______ cn P; const int32 lp2xyziter = lp2xyz(cen_lin,cen_pix,ell,master,masterorbit,P,MAXITER,CRITERPOS); // ______Compute line,pixel for slave of this xyz______ real8 lin,pix; const int32 xyz2lpiter = xyz2lp(lin,pix,slave,slaveorbit,P,MAXITER,CRITERTIM); // ______ Some extra parameters (not used, just info) ______ // BK 19-Oct-2000 const int Bt = Btemp(master.utc1,slave.utc1); // ______ Modeled quantities ______ const real8 Bperp = baseline.get_bperp(cen_lin,cen_pix,HEI); const real8 Bpar = baseline.get_bpar(cen_lin,cen_pix,HEI); const real8 theta = rad2deg(baseline.get_theta(cen_lin,cen_pix,HEI)); const real8 inc_angle = rad2deg(baseline.get_theta_inc(cen_lin,cen_pix,HEI)); // ______ Derived quantities ______ const real8 B = baseline.get_b(cen_lin,cen_pix,HEI); const real8 alpha = rad2deg(baseline.get_alpha(cen_lin,cen_pix,HEI)); const real8 Bh = baseline.get_bhor(cen_lin,cen_pix,HEI); const real8 Bv = baseline.get_bvert(cen_lin,cen_pix,HEI); const real8 Hamb = baseline.get_hamb(cen_lin,cen_pix,HEI); const real8 orb_conv = rad2deg(baseline.get_orb_conv(cen_lin,cen_pix,HEI)); // ______ offset = P_slave - P_master = lin - cen_lin ______ INFO << "Estimated translation (l,p): " << floor(lin-cen_lin +.5) << ", " << floor(pix-cen_pix +.5); INFO.print(); // ______ Write to tmp files ______ ofstream scratchlogfile("scratchlogcoarse", ios::out | ios::trunc); bk_assert(scratchlogfile,"coarseporbit: scratchlogcoarse",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* COARSE_COREGISTRATION Orbits" << "\n*******************************************************************" << "\n(Approximate) center master (line,pixel,hei): " << cen_lin << ", " << cen_pix << ", " << HEI << "\nEllipsoid WGS84 coordinates of this pixel (x,y,z): (" << P.x << ", " << P.y << ", " << P.z << ")" << "\n(line,pixel) of these coordinates in slave: " << lin << ", " << pix << "\nEstimated translation slave w.r.t. master (l,p):" << rint(lin-cen_lin) //round << ", " << rint(pix-cen_pix) // round << "\nMaximum number of iterations: " << MAXITER << "\nCriterium for position (m): " << CRITERPOS << "\nCriterium for azimuth time (s): " << CRITERTIM << " (=~ " << CRITERTIM*7.e3 << "m)" << "\nNumber of iterations conversion line,pixel to xyz: " << lp2xyziter << "\nNumber of iterations conversion xyz to line,pixel: " << xyz2lpiter << "\n*******************************************************************\n"; scratchlogfile.close(); // ______ give some extra info in resfile: Bperp, Bpar, Bh, Bv, Btemp ______ ofstream scratchresfile("scratchrescoarse", ios::out | ios::trunc); bk_assert(scratchresfile,"coarseporbit: scratchrescoarse",__FILE__,__LINE__); scratchresfile.setf(ios::right, ios::adjustfield); scratchresfile << "\n\n*******************************************************************" << "\n*_Start_" << processcontrol[pr_i_coarse] << "\n*******************************************************************" << "\nSome info for pixel: " << cen_lin << ", " << cen_pix << " (not used):" << "\n Btemp: [days]: " << setw(10) << setiosflags(ios::right) << Bt << " \t// Temporal baseline" << "\n Bperp [m]: " << setw(10) << setiosflags(ios::right) << onedecimal(Bperp) << " \t// Perpendicular baseline" << "\n Bpar [m]: " << setw(10) << setiosflags(ios::right) << onedecimal(Bpar) << " \t// Parallel baseline" << "\n Bh [m]: " << setw(10) << setiosflags(ios::right) << onedecimal(Bh) << " \t// Horizontal baseline" << "\n Bv [m]: " << setw(10) << setiosflags(ios::right) << onedecimal(Bv) << " \t// Vertical baseline" << "\n B [m]: " << setw(10) << setiosflags(ios::right) << onedecimal(B) << " \t// Baseline (distance between sensors)" << "\n alpha [deg]: " << setw(10) << setiosflags(ios::right) << onedecimal(alpha) << " \t// Baseline orientation" << "\n theta [deg]: " << setw(10) << setiosflags(ios::right) << onedecimal(theta) << " \t// look angle" << "\n inc_angle [deg]: " << setw(10) << setiosflags(ios::right) << onedecimal(inc_angle) << " \t// incidence angle" << "\n orbitconv [deg]: " << setw(10) << setiosflags(ios::right) << orb_conv << " \t// angle between orbits" << "\n Height_amb [m]: " << setw(10) << setiosflags(ios::right) << onedecimal(Hamb) << " \t// height = h_amb*phase/2pi (approximately)" << "\n Control point master (line,pixel,hei) = (" << cen_lin << ", " << cen_pix << ", " << HEI << ")" << "\n Control point slave (line,pixel,hei) = (" << lin << ", " << pix << ", " << HEI << ")" // ______ this is read/used: ______ << "\nEstimated translation slave w.r.t. master (slave-master):" << "\n Positive offsetL: slave image is to the bottom" << "\n Positive offsetP: slave image is to the right" << "\nCoarse_orbits_translation_lines: \t" << rint(lin-cen_lin) //round << "\nCoarse_orbits_translation_pixels: \t" << rint(pix-cen_pix) //round << "\n*******************************************************************" << "\n* End_" << processcontrol[pr_i_coarse] << "_NORMAL" << "\n*******************************************************************\n"; // ______Tidy up______ scratchresfile.close(); PROGRESS.print("Coarse precise orbits coregistration finished."); } // END coarseporbit /**************************************************************** * coarsecorrel * * * * computes translation of slave w.r.t. master * * slave(some point) = master(same point) + trans(l,p) => * * trans = slavecoordinates - mastercoordinates * * uses correlation between magnitude of slave/master image * * * * requires things on disk, input * * input: * * - * * output: * * - * * * * Bert Kampes, 12-Dec-1998 * ****************************************************************/ void coarsecorrel( const input_coarsecorr &coarsecorrinput, const slcimage &minfo, const slcimage &sinfo) { TRACE_FUNCTION("coarsecorrel (BK 12-Dec-1998)"); char dummyline[ONE27]; // for errormessages //const uint Mfilelines = minfo.currentwindow.lines(); //const uint Sfilelines = sinfo.currentwindow.lines(); const uint Nwin = coarsecorrinput.Nwin; // number of windows uint NwinNANrm = coarsecorrinput.Nwin; ///MA number of windows w/o -999 const int32 initoffsetL = coarsecorrinput.initoffsetL; // initila offset const int32 initoffsetP = coarsecorrinput.initoffsetP; // initila offset uint MasksizeL = coarsecorrinput.MasksizeL; // size of correlation window uint MasksizeP = coarsecorrinput.MasksizeP; // size of correlation window const uint AccL = coarsecorrinput.AccL; // accuracy of initial offset const uint AccP = coarsecorrinput.AccP; // accuracy of initial offset bool pointsrandom = true; if (specified(coarsecorrinput.ifpositions)) // filename specified pointsrandom = false; // only use those points // INFO("Masksize ... // ______Only odd Masksize possible_____ bool forceoddl = false; bool forceoddp = false; if (!isodd(MasksizeL)) { forceoddl = true; MasksizeL+=1; // force oddness } if (!isodd(MasksizeP)) { forceoddp = true; MasksizeP+=1; // force oddness } // ______Corners of slave in master system______ // ______offset = A(slave system) - A(master system)______ const int32 sl0 = sinfo.currentwindow.linelo - initoffsetL; const int32 slN = sinfo.currentwindow.linehi - initoffsetL; const int32 sp0 = sinfo.currentwindow.pixlo - initoffsetP; const int32 spN = sinfo.currentwindow.pixhi - initoffsetP; // ______Corners of useful overlap master,slave in master system______ //const uint BORDER = 20;// slightly smaller //const uint l0 = uint(max(int32(minfo.currentwindow.linelo),sl0) + 0.5*MasksizeL + AccL + BORDER); //const uint lN = uint(min(int32(minfo.currentwindow.linehi),slN) - 0.5*MasksizeL - AccL - BORDER); //const uint p0 = uint(max(int32(minfo.currentwindow.pixlo),sp0) + 0.5*MasksizeP + AccP + BORDER); //const uint pN = uint(min(int32(minfo.currentwindow.pixhi),spN) - 0.5*MasksizeP - AccP - BORDER); // [FvL] const uint BORDER = 20;// slightly smaller const int l0 = uint(max(int32(minfo.currentwindow.linelo),sl0) + 0.5*MasksizeL + AccL + BORDER); const int lN = uint(min(int32(minfo.currentwindow.linehi),slN) - 0.5*MasksizeL - AccL - BORDER); const int p0 = uint(max(int32(minfo.currentwindow.pixlo),sp0) + 0.5*MasksizeP + AccP + BORDER); const int pN = uint(min(int32(minfo.currentwindow.pixhi),spN) - 0.5*MasksizeP - AccP - BORDER); const window overlap(l0,lN,p0,pN); // ______Distribute Nwin points over window______ // ______Centers(i,0): line, (i,1): pixel, (i,2) flagfromdisk______ //matrix Centers; // [FvL] for correct folding of points outside overlap window matrix Centers; if (pointsrandom) // no filename specified { Centers = distributepoints(real4(Nwin),overlap); } else // read in points (center of windows) from file { Centers.resize(Nwin,3); ifstream ifpos; openfstream(ifpos,coarsecorrinput.ifpositions); bk_assert(ifpos,coarsecorrinput.ifpositions,__FILE__,__LINE__); uint ll,pp; for (uint i=0; i> ll >> pp; //Centers(i,0) = uint(ll); // correct for lower left corner //Centers(i,1) = uint(pp); // correct for lower left corner //Centers(i,2) = uint(1); // flag from file // [FvL] for correct folding of points outside overlap window Centers(i,0) = int(ll); // correct for lower left corner Centers(i,1) = int(pp); // correct for lower left corner Centers(i,2) = int(1); // flag from file ifpos.getline(dummyline,ONE27,'\n'); // goto next line. } ifpos.close(); // ______ Check last point ivm. EOL after last position in file ______ if (Centers(Nwin-1,0) == Centers(Nwin-2,0) && Centers(Nwin-1,1) == Centers(Nwin-2,1)) { Centers(Nwin-1,0) = uint(.5*(lN + l0) + 27); // random Centers(Nwin-1,1) = uint(.5*(pN + p0) + 37); // random WARNING << "CC: there should be no EOL after last point in file: " << coarsecorrinput.ifpositions; WARNING.print(); } // ______ Check if points are in overlap ______ // ______ no check for uniqueness of points ______ bool troubleoverlap = false; for (uint i=0; i lN) { troubleoverlap=true; WARNING << "COARSE_CORR: point from file: " << i+1 << " " << Centers(i,0) << " " << Centers(i,1) << " outside overlap master, slave. New position: "; Centers(i,0) = lN + lN-Centers(i,0); WARNING << Centers(i,0) << " " << Centers(i,1); WARNING.print(); } if (Centers(i,1) < p0) { troubleoverlap=true; WARNING << "COARSE_CORR: point from file: " << i+1 << " " << Centers(i,0) << " " << Centers(i,1) << " outside overlap master, slave. New position: "; Centers(i,1) = p0 + p0-Centers(i,1); WARNING << Centers(i,0) << " " << Centers(i,1); WARNING.print(); } if (Centers(i,1) > pN) { troubleoverlap=true; WARNING << "COARSE_CORR: point from file: " << i+1 << " " << Centers(i,0) << " " << Centers(i,1) << " outside overlap master, slave. New position: "; Centers(i,1) = pN + pN-Centers(i,1); WARNING << Centers(i,0) << " " << Centers(i,1); WARNING.print(); } } if (troubleoverlap) // give some additional info { WARNING << "FINE: there were points from file outside overlap (l0,lN,p0,pN): " << l0 << " " << lN << " " << p0 << " " << pN << ends; WARNING.print(); } } // ______Compute correlation of these points______ matrix Mcmpl; matrix Scmpl; matrix Master; // amplitude master matrix Mask; // amplitude slave matrix Correl; // matrix with correlations matrix Result(Nwin,3);// R(i,0)=correlation; (i,1)=delta l; (i,2)=delta p; // ______ Progress messages ______ int32 percent = 0; int32 tenpercent = int32(rint(Nwin/10.0)); // round if (tenpercent==0) tenpercent = 1000; // avoid error: x%0 for (uint i=0;i * * trans = slavecoordinates - mastercoordinates * * uses correlation between magnitude of slave/master image * * uses fft to compute coherence, no subtraction of mean * * * * requires thingsa on disk, input * * input: * * - * * output: * * - * * * * Bert Kampes, 12-Dec-1998 * ****************************************************************/ void coarsecorrelfft( const input_coarsecorr &coarsecorrinput, const slcimage &minfo, const slcimage &sinfo) { TRACE_FUNCTION("coarsecorrelfft (BK 12-Dec-1998)"); if (coarsecorrinput.method != cc_magfft) { PRINT_ERROR("unknown method, This routine is only for cc_magfft method.") throw(argument_error); } char dummyline[ONE27];// for errormessages //const uint Mfilelines = minfo.currentwindow.lines(); //const uint Sfilelines = sinfo.currentwindow.lines(); const uint Nwin = coarsecorrinput.Nwin; // number of windows uint NwinNANrm = coarsecorrinput.Nwin; ///MA number of windows w/o -999 const int32 initoffsetL = coarsecorrinput.initoffsetL;// initial offset const int32 initoffsetP = coarsecorrinput.initoffsetP;// initial offset const uint MasksizeL = coarsecorrinput.MasksizeL; // size of correlation window const uint MasksizeP = coarsecorrinput.MasksizeP; // size of correlation window bool pointsrandom = true; if (specified(coarsecorrinput.ifpositions)) // filename specified pointsrandom = false; // only use these points // ______Only pow2 Masksize possible_____ if (!ispower2(MasksizeL)) { PRINT_ERROR("coarse correl fft: MasksizeL should be 2^n") throw(input_error); } if (!ispower2(MasksizeP)) { PRINT_ERROR("coarse correl fft: MasksizeP should be 2^n") throw(input_error); } // ______Corners of slave in master system______ // ______offset = [A](slave system) - [A](master system)______ const int32 sl0 = sinfo.currentwindow.linelo - initoffsetL; const int32 slN = sinfo.currentwindow.linehi - initoffsetL; const int32 sp0 = sinfo.currentwindow.pixlo - initoffsetP; const int32 spN = sinfo.currentwindow.pixhi - initoffsetP; // ______Corners of useful overlap master,slave in master system______ //const uint BORDER = 20;// slightly smaller //const uint l0 = max(int32(minfo.currentwindow.linelo),sl0) + BORDER; //const uint lN = min(int32(minfo.currentwindow.linehi),slN) - MasksizeL - BORDER; //const uint p0 = max(int32(minfo.currentwindow.pixlo),sp0) + BORDER; //const uint pN = min(int32(minfo.currentwindow.pixhi),spN) - MasksizeP - BORDER; // [FvL] for correct folding of points outside overlap window const uint BORDER = 20;// slightly smaller const int l0 = max(int32(minfo.currentwindow.linelo),sl0) + BORDER; const int lN = min(int32(minfo.currentwindow.linehi),slN) - MasksizeL - BORDER; const int p0 = max(int32(minfo.currentwindow.pixlo),sp0) + BORDER; const int pN = min(int32(minfo.currentwindow.pixhi),spN) - MasksizeP - BORDER; const window overlap(l0,lN,p0,pN); // ______Distribute Nwin points over window______ // ______Minlminp(i,0): line, (i,1): pixel, (i,2) flagfromdisk______ //matrix Minlminp; matrix Minlminp; //[FvL] if (pointsrandom) // no filename specified { Minlminp = distributepoints(real4(Nwin),overlap); } else // read in points (center of windows) from file { Minlminp.resize(Nwin,3); ifstream ifpos; openfstream(ifpos,coarsecorrinput.ifpositions); bk_assert(ifpos,coarsecorrinput.ifpositions,__FILE__,__LINE__); uint ll,pp; for (uint i=0; i> ll >> pp; //Minlminp(i,0) = uint(ll-0.5*MasksizeL); // correct for lower left corner //Minlminp(i,1) = uint(pp-0.5*MasksizeP); // correct for lower left corner //Minlminp(i,2) = uint(1); // flag from file // [FvL] Minlminp(i,0) = int(ll-0.5*MasksizeL); // correct for lower left corner Minlminp(i,1) = int(pp-0.5*MasksizeP); // correct for lower left corner Minlminp(i,2) = int(1); // flag from file ifpos.getline(dummyline,ONE27,'\n'); // goto next line. } ifpos.close(); // ______ Check last point ivm. EOL after last position in file ______ if (Minlminp(Nwin-1,0) == Minlminp(Nwin-2,0) && Minlminp(Nwin-1,1) == Minlminp(Nwin-2,1)) { Minlminp(Nwin-1,0) = uint(.5*(lN + l0) + 27); // random Minlminp(Nwin-1,1) = uint(.5*(pN + p0) + 37); // random } // ______ Check if points are in overlap ______ // ______ no check for uniqueness of points ______ bool troubleoverlap = false; for (uint i=0; i lN) { troubleoverlap=true; WARNING << "COARSECORR: point from file: " << i+1 << " " << Minlminp(i,0) +.5*MasksizeL << " " << Minlminp(i,1) +.5*MasksizeP << " outside overlap master, slave. New position: "; Minlminp(i,0) = lN + lN-Minlminp(i,0); WARNING << Minlminp(i,0) << " " << Minlminp(i,1); WARNING.print(); } if (Minlminp(i,1) < p0) { troubleoverlap=true; WARNING << "COARSECORR: point from file: " << i+1 << " " << Minlminp(i,0) +.5*MasksizeL << " " << Minlminp(i,1) +.5*MasksizeP << " outside overlap master, slave. New position: "; Minlminp(i,1) = p0 + p0-Minlminp(i,1); WARNING << Minlminp(i,0) << " " << Minlminp(i,1); WARNING.print(); } if (Minlminp(i,1) > pN) { troubleoverlap=true; WARNING << "COARSECORR: point from file: " << i+1 << " " << Minlminp(i,0) + 0.5*MasksizeL << " " << Minlminp(i,1) + 0.5*MasksizeP << " outside overlap master, slave. New position: "; Minlminp(i,1) = pN + pN-Minlminp(i,1); WARNING << Minlminp(i,0) << " " << Minlminp(i,1); WARNING.print(); } } if (troubleoverlap) // give some additional info { WARNING << "COARSECORR: point in input file outside overlap (l0,lN,p0,pN): " << l0 << " " << lN << " " << p0 << " " << pN; WARNING.print(); } } // ______Compute coherence of these points______ matrix Master; matrix Mask; matrix Result(Nwin,3); // R(i,0):delta l; // R(i,1):delta p; R(i,2):correl // ______ Progress messages ______ int32 percent = 0; int32 tenpercent = int32(rint(Nwin/10.0)); // round if (tenpercent==0) tenpercent = 1000; // avoid error: x%0 for (uint i=0; i indHigh(initNobs,1); real8 thCoh = 0.2; //get number of Obs above a threshold for (uint k=0; kthCoh) { // INFO<<"Good"; // INFO<rhsL(2,1); matrixrhsP(2,1); //the means are used to calculate the value of the linear poly at the mean line and pixel uint32 meanP = 0; //mean PX number uint32 meanL = 0;//mean line number //if there are not values above the coehrence then used the iunitial offsets e.g., based on orbits if (Nobs<1) { offsetLines = initoffsetL; offsetPixels = initoffsetP; rhsL(0,0) = 0; rhsL(1,0) = offsetLines; rhsP(0,0) = 0; rhsP(1,0) = offsetPixels; } //if there are not too enough to calculate the poly then used the traditional "weighted mean" method else if (Nobs<10) { getoffset(Result,offsetLines,offsetPixels); rhsL(0,0) = 0; rhsL(1,0) = offsetLines; rhsP(0,0) = 0; rhsP(1,0) = offsetPixels; } // do estimations using BLUE else { //To exot the while loop which is used to remove outliers bool flagExit = false; matrix yL(Nobs,1); // observation matrix yP(Nobs,1); // observation matrix AL(Nobs,2); // designmatrix matrix AP(Nobs,2); // designmatrix matrix Qy_1(Nobs,1); // diagonal covariance matrix defined as vector to save memory matrix indeces(Nobs,1); //While loop is perfomed until the maximum residual are very small or not enough obs while (Nobs>9 & flagExit != true) {INFO << "Nobs " << Nobs; INFO.print(); //down there we remove the worst obs, then we need to resize the matrices yL.resize(Nobs,1); yP.resize(Nobs,1); AL.resize(Nobs,2); AP.resize(Nobs,2); Qy_1.resize(Nobs,1); indeces.resize(Nobs,1); uint32 newK =0; // select values with good coherence for (uint k=0; kthCoh) { Qy_1(newK,0)= real8(Result(k,0) ) ; yL(newK,0) = real8(Result(k,1) ) ; yP(newK,0) = real8(Result(k,2) ); AL(newK,0) = real8(Minlminp(k,0) ); AL(newK,1) = 1 ; AP(newK,0) = real8(Minlminp(k,1) ) ; AP(newK,1) = 1 ; meanP = meanP + uint32(Minlminp(k,1) ) ; meanL = meanL + uint32(Minlminp(k,0) ) ; indeces(newK,0) = k; newK++; } } INFO << "Nof new Obs : " << newK; INFO.print(); Qy_1 = Qy_1 / mean(Qy_1);// normalize weights (for tests!) meanP = meanP/newK; meanL = meanL/newK; // //matrixrhsL(2,1); //getLS(yL,AL,Qy_1,xhat_rhsL); //LS Qx_hat for lines and pixels matrix Qx_hat_L = matTxmat(AL,diagxmat(Qy_1,AL)); matrix Qx_hat_P = matTxmat(AP,diagxmat(Qy_1,AP)); //xhat for lines and pixels, still it needs to be multiplied times inverse of Qxhat, see below rhsL = matTxmat(AL,diagxmat(Qy_1,yL)); rhsP = matTxmat(AP,diagxmat(Qy_1,yP)); // ______Compute solution______ choles(Qx_hat_L); // Cholesky factorisation normalmatrix choles(Qx_hat_P); // Cholesky factorisation normalmatrix // final solution solvechol(Qx_hat_L,rhsL); // Solution unknowns in rhs solvechol(Qx_hat_P,rhsP); // Solution unknowns in rhs // estimation of residuals and removal of ouliers matrix yL_hat = AL * rhsL; matrix yP_hat = AP * rhsP; matrix eL_hat = yL - yL_hat; matrix eP_hat = yP - yP_hat; real4 max_eL =0; real4 max_eP =0; uint32 indMaxL =0; uint32 indMaxP =0; // looks for the obs which has whose residual norm is maximum, for both lines and pixels for (uint32 k=0; kmax_eL) { max_eL = sqrt(eL_hat(k,0)*eL_hat(k,0)); indMaxL = k; } if ( sqrt(eP_hat(k,0)*eP_hat(k,0))>max_eP) { max_eP=sqrt(eP_hat(k,0)*eP_hat(k,0)); indMaxP =k; } } INFO<< "max_eL : " << max_eL; INFO<< ", max_eP : " << max_eP; INFO.print(); //if residuals are small then exit if (max_eL <3.0 && max_eP<3.0) { INFO<<"exiting estimation loop"; INFO.print(); flagExit = true; break; } else { INFO<<"removing obs " <10 offsetLines = int32(meanL*rhsL(0,0)) + int32(rhsL(1,0)) ; offsetPixels = int32(meanP*rhsP(0,0)) + int32( rhsP(1,0)) ; }//else if Nof<10 //MCC // ______ Write to files ______ ofstream scratchlogfile("scratchlogcoarse2", ios::out | ios::trunc); bk_assert(scratchlogfile,"coarsecorrelfft: scratchlogcoarse2",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* COARSE_COREGISTRATION: Correlation" << "\n*******************************************************************" << "\nNumber of correlation windows: \t" << Nwin << "\nwindow size (l,p): \t" << MasksizeL << ", " << MasksizeP << "\n\nNumber \tposL \tposP \toffsetL offsetP\tcorrelation\n"; for (uint k=0; k * * trans = mastercoordinates - simamp.coordinates * * uses correlation between magnitude of master and simamp * * image to estimate overall shift. * * * * requires things on disk, input * * input: * * - input settings, * * - master info * * - simulated amplitude info * * output: * * - coarse offsets between dem and the master * * * * Bert Kampes, 12-Dec-1998 (coarsecorr) * * Batuhan Osmanoglu, 30-JUL-2007 (demcorr for phase) * * Mahmut Arikan, 12-Nov-2008 * ****************************************************************/ void mtiming_correl( const input_mtiming &mtiminginput, const slcimage &minfo, const productinfo &sinfo) // simamp { TRACE_FUNCTION("mtiming_correl (MA,BO 12-Nov-2008)"); const string STEP="MTIMING: "; // step name char dummyline[ONE27]; // for errormessages //const uint Mfilelines = minfo.currentwindow.lines(); //const uint Sfilelines = sinfo.currentwindow.lines(); const uint Nwin = mtiminginput.Nwin; // number of windows uint NwinNANrm = mtiminginput.Nwin; ///MA number of windows w/o -999 const int32 initoffsetL = mtiminginput.initoffsetL; // initial offset not nec for simamp const int32 initoffsetP = mtiminginput.initoffsetP; // initial offset uint MasksizeL = mtiminginput.MasksizeL; // size of correlation window uint MasksizeP = mtiminginput.MasksizeP; // size of correlation window const uint AccL = mtiminginput.AccL; // accuracy of initial offset const uint AccP = mtiminginput.AccP; // accuracy of initial offset bool pointsrandom = true; if (specified(mtiminginput.ifpositions)) // filename specified pointsrandom = false; // only use these points // INFO("Masksize ... // ______Only odd Masksize possible_____ bool forceoddl = false; bool forceoddp = false; if (!isodd(MasksizeL)) { forceoddl = true; MasksizeL+=1; // force oddness } if (!isodd(MasksizeP)) { forceoddp = true; MasksizeP+=1; // force oddness } // ______Corners of simamp(dem) in master system______ // ______offset = A(master system) - A(slave system)______ const int32 sl0 = sinfo.win.linelo - initoffsetL; // [MA] sim. ampl. image extend should be const int32 slN = sinfo.win.linehi - initoffsetL; // the same as master crop extend. Kept for the convience. const int32 sp0 = sinfo.win.pixlo - initoffsetP; const int32 spN = sinfo.win.pixhi - initoffsetP; DEBUG << "slave l0: " << sl0 << " slN " << slN << " sp0 " << sp0 << " spN " << spN; DEBUG.print(); // ______Corners of useful overlap master,slave in master system______ //const uint BORDER = 20;// slightly smaller //const uint l0 = uint(max(int32(minfo.currentwindow.linelo),sl0) + 0.5*MasksizeL + AccL + BORDER); //const uint lN = uint(min(int32(minfo.currentwindow.linehi),slN) - 0.5*MasksizeL - AccL - BORDER); //const uint p0 = uint(max(int32(minfo.currentwindow.pixlo),sp0) + 0.5*MasksizeP + AccP + BORDER); //const uint pN = uint(min(int32(minfo.currentwindow.pixhi),spN) - 0.5*MasksizeP - AccP - BORDER); // [FvL] const uint BORDER = 20;// slightly smaller const int l0 = uint(max(int32(minfo.currentwindow.linelo),sl0) + 0.5*MasksizeL + AccL + BORDER); const int lN = uint(min(int32(minfo.currentwindow.linehi),slN) - 0.5*MasksizeL - AccL - BORDER); const int p0 = uint(max(int32(minfo.currentwindow.pixlo),sp0) + 0.5*MasksizeP + AccP + BORDER); const int pN = uint(min(int32(minfo.currentwindow.pixhi),spN) - 0.5*MasksizeP - AccP - BORDER); /* // ______Check masksize against height and width of the crop______ if( int32(MasksizeL) > int32(lN-l0) || int32(MasksizeP) > int32(pN-p0) ) { ERROR << "MTE: Impossible to continue! Masksize larger than the overlapping crop width or height. Please check."; ERROR.print(); ERROR << "MTE: MasksizeL [" << MasksizeL << "] > crop height [" << int32(lN-l0) << "] ?"; ERROR.print(); ERROR << "MTE: MasksizeP [" << MasksizeP << "] > crop width [" << int32(pN-p0) << "] ?"; ERROR.print(); throw(input_error) ; } */ DEBUG << "mastercurrentwinl0: " << minfo.currentwindow.linelo << " lN " << minfo.currentwindow.linehi << " p0 " << minfo.currentwindow.pixlo << " pN " << minfo.currentwindow.pixhi; DEBUG.print(); DEBUG << " master l0: " << l0 << " lN " << lN << " p0 " << p0 << " pN " << pN; DEBUG.print(); const window overlap(l0,lN,p0,pN); DEBUG << "overlap l0: " << l0 << " lN " << lN << " p0 " << p0 << " pN " << pN; DEBUG.print(); // ______Distribute Nwin points over window______ // ______Centers(i,0): line, (i,1): pixel, (i,2) flagfromdisk______ //matrix Centers; [FvL] matrix Centers; if (pointsrandom) // no filename specified { Centers = distributepoints(real4(Nwin),overlap); } else // read in points (center of windows) from file { Centers.resize(Nwin,3); ifstream ifpos; openfstream(ifpos,mtiminginput.ifpositions); bk_assert(ifpos,mtiminginput.ifpositions,__FILE__,__LINE__); uint ll,pp; for (uint i=0; i> ll >> pp; //Centers(i,0) = uint(ll); // correct for lower left corner //Centers(i,1) = uint(pp); // correct for lower left corner //Centers(i,2) = uint(1); // flag from file // [FvL] Centers(i,0) = int(ll); // correct for lower left corner Centers(i,1) = int(pp); // correct for lower left corner Centers(i,2) = int(1); // flag from file ifpos.getline(dummyline,ONE27,'\n'); // goto next line. } ifpos.close(); // ______ Check last point ivm. EOL after last position in file ______ if (Centers(Nwin-1,0) == Centers(Nwin-2,0) && Centers(Nwin-1,1) == Centers(Nwin-2,1)) { Centers(Nwin-1,0) = uint(.5*(lN + l0) + 27); // random Centers(Nwin-1,1) = uint(.5*(pN + p0) + 37); // random WARNING << "MTE: there should be no EOL after last point in file: " << mtiminginput.ifpositions; WARNING.print(); } // ______ Check if points are in overlap ______ // ______ no check for uniqueness of points ______ bool troubleoverlap = false; for (uint i=0; i lN) { troubleoverlap=true; WARNING << STEP << "point from file: " << i+1 << " " << Centers(i,0) << " " << Centers(i,1) << " outside overlap master, slave. New position: "; Centers(i,0) = lN + lN-Centers(i,0); WARNING << Centers(i,0) << " " << Centers(i,1); WARNING.print(); } if (Centers(i,1) < p0) { troubleoverlap=true; WARNING << STEP << "point from file: " << i+1 << " " << Centers(i,0) << " " << Centers(i,1) << " outside overlap master, slave. New position: "; Centers(i,1) = p0 + p0-Centers(i,1); WARNING << Centers(i,0) << " " << Centers(i,1); WARNING.print(); } if (Centers(i,1) > pN) { troubleoverlap=true; WARNING << STEP << "point from file: " << i+1 << " " << Centers(i,0) << " " << Centers(i,1) << " outside overlap master, slave. New position: "; Centers(i,1) = pN + pN-Centers(i,1); WARNING << Centers(i,0) << " " << Centers(i,1); WARNING.print(); } } if (troubleoverlap) // give some additional info { WARNING << STEP << "there were points in input file which lie outside overlap (l0,lN,p0,pN): " << l0 << " " << lN << " " << p0 << " " << pN << ends; WARNING.print(); } } // ______Compute correlation of these points______ matrix Mcmpl; // Master complex image matrix Sampl; // Simulated amplitude matrix mMag; // amplitude master matrix Correl; // matrix with correlations matrix Result(Nwin,3); // R(i,0)=correlation; (i,1)=delta l; (i,2)=delta p; // ______ Progress messages ______ int32 percent = 0; int32 tenpercent = int32(rint(Nwin/10.0)); // round if (tenpercent==0) tenpercent = 1000; // avoid error: x%0 for (uint i=0; i &sMask = mMag ; // amplitude small patch from master that shifts over matrix &mMask = Sampl ; // amplitude big patch from simamp // ______Compute correlation matrix and find maximum______ //#Correl = correlate(Master,Mask); Correl = correlate(mMask,sMask); // correlate(simamp,masteramp) uint L, P; // MA: if maximum correlation is 0, which is due to NaNs, assign -999 // so in getoffset they are disregarded. // real4 corr = max(Correl, L, P); // returns also L,P real4 corr = ( max(Correl, L, P) == 0 ) ? -999 : max(Correl, L, P) ; // returns also L,P uint relcenML = mwin.linehi - cenMwinL;// system of matrix uint relcenMP = mwin.pixhi - cenMwinP;// system of matrix int32 reloffsetL = relcenML - L; int32 reloffsetP = relcenMP - P; DEBUG << "Offset between chips (l,p) = " << reloffsetL << ", " << reloffsetP; DEBUG.print(); // ______ Store result of this patch ______ Result(i,0) = corr; Result(i,1) = initoffsetL + reloffsetL; // total estimated offset lines Result(i,2) = initoffsetP + reloffsetP; // total estimated offset pixels DEBUG << "Offset between images on disk = " << Result(i,1) << ", " << Result(i,2) << " (corr=" << corr << ")"; DEBUG.print(); } // for nwin // ______ Get good general estimate for offsetL, offsetP ______ int32 offsetLines = -999; // NaN int32 offsetPixels = -999; //getoffset(Result,offsetLines,offsetPixels); // getoffsets based on Mean getmodeoffset(Result,offsetLines,offsetPixels); // [MA] max occurence // ______ Convert offsets to seconds and write master time offset to res file ______ // using overall coarse offsets determing master timing error // ______ Initialize Variables ______ real8 masterAztime = -999; real8 masterRatime = -999; // ______ Compute Time ______ // minus sign is due to the offsets being reference to DEM (offset = master-dem) offsets2timing(minfo, -offsetLines, -offsetPixels, masterAztime, masterRatime); // using overall offsets to // determine master timing error INFO << "Estimated master azimuth timing error [sec]: " << masterAztime << " sec."; INFO.print(); INFO << "Estimated master range timing error [sec]: " << masterRatime << " sec."; INFO.print(); // azimuth and range time are later updated at proccess.cc // ______ End of conversion offset to timing errors______ // ______ Write to files ______ ofstream scratchlogfile("scratchlogmtiming", ios::out | ios::trunc); bk_assert(scratchlogfile,"mtiming_correl: scratchlogmtiming",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* MTIMING_CORRELATION: Offset Table" << "\n*******************************************************************" << "\nCorrelation method: \t\t" << " magspace" // [MA] informational << "\nNumber of correlation windows: \t" << Nwin << "\nCorrelation window size (l,p): \t" << MasksizeL << ", " << MasksizeP; if (forceoddl) scratchlogfile << " (l forced odd)"; if (forceoddp) scratchlogfile << " (p forced odd)"; scratchlogfile << "\nSearchwindow size (l,p): \t\t" << MasksizeL + 2*AccL << ", " << MasksizeP + 2*AccP << "\nNumber \tposl \tposp \toffsetl offsetp \tcorrelation\n"; for (uint k=0; k * * trans = mastercoordinates - simamp.coordinates * * uses correlation between magnitude of master and simamp * * image to estimate overall shift. * * uses fft to compute coherence * * * * requires things on disk, input * * input: * * - input settings, * * - master info * * - simulated amplitude info * * output: * * - coarse offsets between dem and the master * * * * Bert Kampes, 12-Dec-1998 (coarsecorrelfft) * * Mahmut Arikan, 04-Dec-2008 ****************************************************************/ void mtiming_correlfft( const input_mtiming &mtiminginput, const slcimage &minfo, const productinfo &sinfo) // simamp { TRACE_FUNCTION("mtiming_correlfft (MA 04-Dec-2008)"); if (mtiminginput.method != cc_magfft) { PRINT_ERROR("unknown method, This routine is only for cc_magfft method.") throw(argument_error); } const string STEP="MTIMING: "; // step name char dummyline[ONE27]; // for errormessages //const uint Mfilelines = minfo.currentwindow.lines(); //const uint Sfilelines = sinfo.currentwindow.lines(); const uint Nwin = mtiminginput.Nwin; // number of windows uint NwinNANrm = mtiminginput.Nwin; ///MA number of windows w/o -999 const int32 initoffsetL = mtiminginput.initoffsetL; // initial offset const int32 initoffsetP = mtiminginput.initoffsetP; // initial offset const uint MasksizeL = mtiminginput.MasksizeL; // size of correlation window const uint MasksizeP = mtiminginput.MasksizeP; // size of correlation window bool pointsrandom = true; if (specified(mtiminginput.ifpositions)) // filename specified pointsrandom = false; // only use these points // ______Only pow2 Masksize possible_____ if (!ispower2(MasksizeL)) { PRINT_ERROR("mtiming correl fft: MasksizeL should be 2^n") throw(input_error); } if (!ispower2(MasksizeP)) { PRINT_ERROR("mtiming correl fft: MasksizeP should be 2^n") throw(input_error); } // ______Corners of simamp(dem) in master system______ // ______offset = [A](slave system) - [A](master system)______ const int32 sl0 = sinfo.win.linelo - initoffsetL; const int32 slN = sinfo.win.linehi - initoffsetL; const int32 sp0 = sinfo.win.pixlo - initoffsetP; const int32 spN = sinfo.win.pixhi - initoffsetP; DEBUG << "slave l0: " << sl0 << " slN " << slN << " sp0 " << sp0 << " spN " << spN; DEBUG.print(); // ______Corners of useful overlap master,slave in master system______ //const uint BORDER = 20;// slightly smaller //const uint l0 = max(int32(minfo.currentwindow.linelo),sl0) + BORDER; //const uint lN = min(int32(minfo.currentwindow.linehi),slN) - MasksizeL - BORDER; //const uint p0 = max(int32(minfo.currentwindow.pixlo),sp0) + BORDER; //const uint pN = min(int32(minfo.currentwindow.pixhi),spN) - MasksizeP - BORDER; // [FvL] const uint BORDER = 20;// slightly smaller const int l0 = max(int32(minfo.currentwindow.linelo),sl0) + BORDER; const int lN = min(int32(minfo.currentwindow.linehi),slN) - MasksizeL - BORDER; const int p0 = max(int32(minfo.currentwindow.pixlo),sp0) + BORDER; const int pN = min(int32(minfo.currentwindow.pixhi),spN) - MasksizeP - BORDER; const window overlap(l0,lN,p0,pN); DEBUG << "overlap l0: " << l0 << " lN " << lN << " p0 " << p0 << " pN " << pN; DEBUG.print(); // ______Distribute Nwin points over window______ // ______Minlminp(i,0): line, (i,1): pixel, (i,2) flagfromdisk______ //matrix Minlminp; // [FvL] matrix Minlminp; if (pointsrandom) // no filename specified { Minlminp = distributepoints(real4(Nwin),overlap); } else // read in points (center of windows) from file { Minlminp.resize(Nwin,3); ifstream ifpos; openfstream(ifpos,mtiminginput.ifpositions); bk_assert(ifpos,mtiminginput.ifpositions,__FILE__,__LINE__); uint ll,pp; for (uint i=0; i> ll >> pp; //Minlminp(i,0) = uint(ll-0.5*MasksizeL); // correct for lower left corner //Minlminp(i,1) = uint(pp-0.5*MasksizeP); // correct for lower left corner //Minlminp(i,2) = uint(1); // flag from file // [FvL] Minlminp(i,0) = int(ll-0.5*MasksizeL); // correct for lower left corner Minlminp(i,1) = int(pp-0.5*MasksizeP); // correct for lower left corner Minlminp(i,2) = int(1); // flag from file ifpos.getline(dummyline,ONE27,'\n'); // goto next line. } ifpos.close(); // ______ Check last point ivm. EOL after last position in file ______ if (Minlminp(Nwin-1,0) == Minlminp(Nwin-2,0) && Minlminp(Nwin-1,1) == Minlminp(Nwin-2,1)) { Minlminp(Nwin-1,0) = uint(.5*(lN + l0) + 27); // random Minlminp(Nwin-1,1) = uint(.5*(pN + p0) + 37); // random WARNING << "MTE: there should be no EOL after last point in file: " << mtiminginput.ifpositions; WARNING.print(); } // ______ Check if points are in overlap ______ // ______ no check for uniqueness of points ______ bool troubleoverlap = false; for (uint i=0; i lN) { troubleoverlap=true; WARNING << STEP << "point from file: " << i+1 << " " << Minlminp(i,0) +.5*MasksizeL << " " << Minlminp(i,1) +.5*MasksizeP << " outside overlap master, slave. New position: "; Minlminp(i,0) = lN + lN-Minlminp(i,0); WARNING << Minlminp(i,0) << " " << Minlminp(i,1); WARNING.print(); } if (Minlminp(i,1) < p0) { troubleoverlap=true; WARNING << STEP << "point from file: " << i+1 << " " << Minlminp(i,0) +.5*MasksizeL << " " << Minlminp(i,1) +.5*MasksizeP << " outside overlap master, slave. New position: "; Minlminp(i,1) = p0 + p0-Minlminp(i,1); WARNING << Minlminp(i,0) << " " << Minlminp(i,1); WARNING.print(); } if (Minlminp(i,1) > pN) { troubleoverlap=true; WARNING << STEP << "point from file: " << i+1 << " " << Minlminp(i,0) + 0.5*MasksizeL << " " << Minlminp(i,1) + 0.5*MasksizeP << " outside overlap master, slave. New position: "; Minlminp(i,1) = pN + pN-Minlminp(i,1); WARNING << Minlminp(i,0) << " " << Minlminp(i,1); WARNING.print(); } } if (troubleoverlap) // give some additional info { WARNING << STEP << "there were points in input file which lie outside overlap (l0,lN,p0,pN): " << l0 << " " << lN << " " << p0 << " " << pN << ends; WARNING.print(); } } // ______Compute coherence of these points______ matrix Mcmpl; // Master complex image matrix Sampl; // Simulated amplitude matrix Scmpl; // real4 simamp --> creal4 simamp matrix Result(Nwin,3); // R(i,0):delta l; // R(i,1):delta p; R(i,2):correl // ______ Progress messages ______ int32 percent = 0; int32 tenpercent = int32(rint(Nwin/10.0)); // round if (tenpercent==0) tenpercent = 1000; // avoid error: x%0 for (uint i=0; i &sMask = Mcmpl ; // complex patch from the master that shifts over matrix &mMask = Scmpl ; // complex patch from the simamp // patch sizes are equal but // shifted patch can have initial // offset // ______ Coherence/max correlation ______ real4 offsetL, offsetP; //const real4 coheren = corrfft(absMaster,absMask,offsetL,offsetP); //const real4 coheren = coherencefft(Master, Mask, // 1, MasksizeL/2, MasksizeP/2, //do not ovs, search full matrix for max // offsetL,offsetP);// returned const real4 coheren = crosscorrelate(mMask, sMask, 1, MasksizeL/2, MasksizeP/2, //do not ovs, search full matrix for max offsetL,offsetP); // returned DEBUG << "Offset between chips (l,p) = " << offsetL << ", " << offsetP; DEBUG.print(); if ( coheren > 1 ) continue; // MA ignore correlation > 1. // ______ Store result of this patch ______ Result(i,0) = coheren; Result(i,1) = initoffsetL + offsetL;// total estimated offset Result(i,2) = initoffsetP + offsetP;// total estimated offset DEBUG << "Offset between images on disk = " << Result(i,1) << ", " << Result(i,2) << " (corr=" << coheren << ")"; DEBUG.print(); } // for nwin // ______ Position approx. with respect to center of window ______ // ______ correct position array for center instead of lower left ______ for (uint i=0; i &Master, // magnitude image const matrix &Mask, // magnitude image real4 &offsetL, // updated real4 &offsetP) // updated { TRACE_FUNCTION("corrfft (BK 18-Oct-1999)"); // ______ Internal variables ______ const int32 L = Master.lines(); const int32 P = Master.pixels(); const int32 twoL = 2*L; const int32 twoP = 2*P; const int32 halfL = L/2; const int32 halfP = P/2; // ______ Check input ______ if (L != Mask.lines() || P != Mask.pixels()) { PRINT_ERROR("Mask, Master not same size.") throw(input_error); } if (!(ispower2(L) || ispower2(P))) { PRINT_ERROR("Mask, Master size not power of 2.") throw(input_error); } // ======Compute powers for submatrices====== register int32 i; register int32 j; const complr4 ONE(1.0); matrix Master2(twoL,twoP);// init 0 matrix Mask2(twoL,twoP); // init 0 matrix blok2(twoL,twoP); // init 0 // ====== Powers, misuse Master2, blok2 ====== // ______ First powers to use one matrix less; 3 is minimum ______ const real4 meanMaster = mean(Master); const real4 meanMask = mean(Mask); for (i=0; i maxcoher) { maxcoher = coher; offsetL = -halfL + i; // update by reference offsetP = -halfP + j; // update by reference } } } return maxcoher; } // END corrfft */ /**************************************************************** * distributepoints * * * * Returns matrix with distributed points in of input. * * First window at (win.linelo,win.pixlo), * * divided over wl lines, * * with dp distance in pixel direction. * * * * input: * * - number of windows * * - window which should be divided * * output: * * - matrix (NW,3) =(l,p, flagfromdisk==0) * * * * Bert Kampes, 21-Jan-1999 * ****************************************************************/ //matrix distributepoints( // [FvL] for correct folding of points outside overlap window when inserted by file matrix distributepoints( real4 nW, const window &win) { TRACE_FUNCTION("distributepoints (BK 21-Jan-1999)") real4 lines = win.linehi - win.linelo + 1; real4 pixels = win.pixhi - win.pixlo + 1; uint numw = uint(nW); //matrix Result(numw,uint(3)); // [FvL] matrix Result(numw,uint(3)); // ______ Distribution for dl=dp ______ real4 wp = sqrt(nW/(lines/pixels)); // wl: #windows in line direction real4 wl = nW / wp; // wp: #windows in pixel direction if (wl < wp) // switch wl,wp : later back wl = wp; int32 wlint = int32(rint(wl));// round largest real4 deltal = (lines-1) / (real4(wlint-1)); int32 totp = int32(pixels*wlint); real4 deltap = (real4(totp-1)) / (real4(nW-1)); real4 p = -deltap; real4 l = 0.; uint lcnt = 0; register int32 i; for (i=0; i=pixels)// round { p -= pixels; lcnt++; } l = lcnt * deltal; //Result(i,0) = uint(rint(l)); //Result(i,1) = uint(rint(p)); // [FvL] Result(i,0) = int(rint(l)); Result(i,1) = int(rint(p)); } // ______ Correct distribution to window ______ for (i=0; i with corr,offsets(l,p) * * output: * * - (offL,offP) * * * * See also Documentation page 6. * * * * Bert Kampes, 21-Jan-1999 * ****************************************************************/ void getoffset( const matrix &Result, int32 &offsetLines, int32 &offsetPixels) { TRACE_FUNCTION("getoffset (BK 21-Jan-1999)") if (Result.pixels() != 3) { PRINT_ERROR("code 901: input not 3 width"); throw(input_error); } // --- First sort estimated offsets on coherence ascending! --- DEBUG.print("sorting on coherence."); //DEBUG.print("unsorted input matrix:"); //Result.showdata(); matrix sortResult = -Result; mysort2(sortResult);// sort matrix on first column (coh) sortResult = -sortResult; //DEBUG.print("sorted matrix:"); //sortResult.showdata(); // --- Set offset to highest coherence estimate --- offsetLines = int32(rint(sortResult(0,1)));//rounds negative too offsetPixels = int32(rint(sortResult(0,2)));//rounds negative too const uint nW = sortResult.lines(); uint nWNANrm = sortResult.lines(); //MA added for removal of -999 values if (nW==1) return; // --- Threshold on coherence --- real4 var_coh = 0.0; real4 mean_coh = 0.0; for (uint i=0; i=thresh_coh) { cnt++; mean_coh += sortResult(i,0); offsetLines += int32(rint(sortResult(i,1)));// round offsetPixels += int32(rint(sortResult(i,2)));// round INFO << sortResult(i,0) << " " << sortResult(i,1) << " " << sortResult(i,2); INFO.print(); } } // ___ Report stats ___ if (cnt > 1) { mean_coh /= real4(cnt); const real4 meanL = real4(offsetLines)/real4(cnt);// float mean const real4 meanP = real4(offsetPixels)/real4(cnt);// float mean offsetLines = int32(rint(real8(offsetLines)/real8(cnt)));// round offsetPixels = int32(rint(real8(offsetPixels)/real8(cnt)));// round real4 var_L = 0.0; real4 var_P = 0.0; for (int32 i=0; i highestcorrel) highestcorrel = correl; cnt = 0; for (j=0; j highestcnt) { highestcnt = cnt; offsetLines = valueL; // Return offsetLines offsetPixels = valueP; // Return offsetPixels } } // ______ Check result ______ real4 THRESHOLD = 0.3; if (nW < 6) { WARNING.print("getoffset: number of windows to estimate offset < 6"); WARNING.print("(please check bottom of LOGFILE)"); } if (highestcnt < 0.2*nW) { WARNING.print("getoffset: estimated offset not consistent with other estimates."); WARNING.print("(check bottom of LOGFILE)"); } if (highestcorrel < THRESHOLD) { WARNING << "getoffset: estimated translation has correlation of: " << highestcorrel; WARNING.print(); WARNING.print("(please check bottom of LOGFILE)"); } */ } // END getoffset /**************************************************************** * getmodeoffset * * * * Returns offset in line and pixel direction * * based on matrix with estimated offests * * by correlation * * Checks on consistency, THRESHOLD 0.4 for correlation * * * * input: * * - matrix with corr,offsets(l,p) * * output: * * - (offL,offP) * * * * See also Documentation page 6. * * * * Bert Kampes, 21-Jan-1999 (getoffset) * * Mahmut Arikan, 09-Dec-2008 * ****************************************************************/ void getmodeoffset( const matrix &Result, int32 &offsetLines, int32 &offsetPixels) { TRACE_FUNCTION("getmodeoffset (MA 09-Dec-2008)") if (Result.pixels() != 3) { PRINT_ERROR("code 901: input not 3 width"); throw(input_error); } // --- First sort estimated offsets on coherence ascending! --- DEBUG.print("getmodeoffset: sorting on coherence."); //DEBUG.print("unsorted input matrix:"); //Result.showdata(); /* Result(0,0)=0.1 ; Result(0,1)=3 ; Result(0,2)=2 ; Result(1,0)=0.2 ; Result(1,1)=1 ; Result(1,2)=4 ; Result(2,0)=0.3 ; Result(2,1)=4 ; Result(2,2)=1 ; Result(3,0)=0.2 ; Result(3,1)=1 ; Result(3,2)=3 ; Result(4,0)=0.2 ; Result(4,1)=3 ; Result(4,2)=1 ; Result(5,0)=0.3 ; Result(5,1)=1 ; Result(5,2)=-1 ; Result(6,0)=0.2 ; Result(6,1)=4 ; Result(6,2)=0 ; Result(7,0)=0.1 ; Result(7,1)=1 ; Result(7,2)=-2 ; Result.showdata(); cerr << endl; */ matrix sortResult = -Result; mysort2(sortResult); // sort matrix on first column (coh) // sorts ascending // sortResult.showdata(); cout << endl; // mysort2selcol(sortResult, 1); sortResult = -sortResult; // max coh at top //DEBUG.print("sorted matrix:"); //sortResult.showdata(); // --- Set offset to highest coherence estimate --- offsetLines = int32(rint(sortResult(0,1))); // rounds negative too, was -999 offsetPixels = int32(rint(sortResult(0,2))); // rounds negative too // [ why set to highes coherence mean // loop index could start from i==0.] // ______ Remove window offests with -999 (NaN) coherence values _____ // added by [MA] const uint nW = sortResult.lines(); // Number of windows uint nWNANrm = nW; // Number of windows without NAN values if (nW==1) return; // --- Threshold on coherence --- real4 var_coh = 0.0; real4 mean_coh = 0.0; for (uint i=0; i=thresh_coh) { cnt++; mean_coh += sortResult(i,0); offsetLines += int32(rint(sortResult(i,1)));// round offsetPixels += int32(rint(sortResult(i,2)));// round DEBUG << sortResult(i,0) << " " << sortResult(i,1) << " " << sortResult(i,2); DEBUG.print(); } // values above threshold } // end loop and print // ___ Report stats ___ if (cnt > 1) { mean_coh /= real4(cnt); const real4 meanL = real4(offsetLines)/real4(cnt);// float mean const real4 meanP = real4(offsetPixels)/real4(cnt);// float mean offsetLines = int32(rint(real8(offsetLines)/real8(cnt)));// round offsetPixels = int32(rint(real8(offsetPixels)/real8(cnt)));// round real4 var_L = 0.0; real4 var_P = 0.0; for (register int32 i=0; i=thresh_coh) { // _____ frequency of offsets _____ [MA] if ( L != int32(rint(sortResult(i,1))) || // skip initializing of P != int32(rint(sortResult(i,2))) ) // the same offset multiple times { L=int32(rint(sortResult(i,1))); // get initial values P=int32(rint(sortResult(i,2))); } else { continue ; // L, P equal to previous values then skip counting // since matrix is sorted on L,P } offset_freq=0; // reset offset_mcoh=0; for (register uint j=0; j mode_val) { mode_val=offset_freq; mode_idx=i; // index of mode value // in magfft if you correlate the same // slc patches. index get a value other than // 1. that's okay when all offset are zero. } else if (mode_val == offset_freq) { if ( evenmode_val != offset_freq ) nEven=1; // initialize with one evenmode_val=offset_freq; nEven++; } offset_mcoh /= real4(offset_freq) ; // _____ for each offset pair above threshold list frequency _____ INFO << offset_mcoh << "\t " << L << "\t " << P << "\t\t" << offset_freq << "\t " << mode_idx; // print to terminal INFO.print(); scratchlogfile << '\n' << offset_mcoh << "\t " << L << "\t " << P << "\t\t" << offset_freq << "\t " << mode_idx; // pass to .log } // above threshold } // end mode scratchlogfile << "\n\n*******************************************************************"; scratchlogfile.close(); // close scratchlogmtiminghtr // _____ Even occurence check _____ if (mode_val == evenmode_val) // there are even values of mode. { WARNING << "There are " << nEven << " offset pairs which has equal mode values are equal."; WARNING.print(); WARNING << "Check offset results and logs, and increase the number and/or the size of the correlation windows."; WARNING.print(); } offsetLines = int32(rint(sortResult(mode_idx,1))); // update mode offsets offsetPixels = int32(rint(sortResult(mode_idx,2))); PROGRESS.print("getmodeoffset: End of mode analysis "); // ___ Warn if appropriate ___ if (mean_coh < 0.2) { WARNING.print("getmodeoffset: mean coherence of estimates used < 0.2"); WARNING.print("(please check bottom of LOGFILE to see if offset is OK)"); } if (mode_val == 1) { WARNING.print("getmodeoffset: all the offset occurence == 1. There is no mode value. "); WARNING.print("(please check bottom of LOGFILE to see if offset is OK or change window size.)"); } if (nW < 6) { WARNING.print("getmodeoffset: number of windows to estimate offset < 6"); WARNING.print("(please check bottom of LOGFILE to see if offset is OK)"); } } // END getmodeoffset /**************************************************************** * finecoreg * * * * computes translation of slave w.r.t. master * * slave(some point) = master(same point) + trans(l,p) => * * trans = slavecoordinates - mastercoordinates * * in NWIN windows. * * Then solves polynomial for best transformation to master * * with coregpm routine/step * * * * input: * * - * * output: * * - * * Bert Kampes, 12-Dec-1998 * * distribute points can be with input file as well, besides * * letting Doris randomly distribute npoints. * * BK 29-Oct-99 * ****************************************************************/ void finecoreg( const input_fine &fineinput, const slcimage &minfo, const slcimage &sinfo, const input_ell &ell, orbit &masterorbit, // cannot be const for spline orbit &slaveorbit, // cannot be const for spline const BASELINE &baseline) //input_ellips, master, slave, masterorbit, slaveorbit, baseline); { if (fineinput.shiftazi == 0) { INFO << "I assume you have already deramped or centered the data spectrum..." ; INFO.print(); } else if (fineinput.shiftazi == 2) { INFO << "\nPROCESS: Deramp Master and Slave spectrum in FINE COREGISTRATION..." ; INFO.print(); // deramp( minfo, fineinput ,masterorbit); } TRACE_FUNCTION("finecoreg (BK 29-Oct-99)") char dummyline[ONE27]; //const uint Mfilelines = minfo.currentwindow.lines(); //const uint Sfilelines = sinfo.currentwindow.lines(); const uint Nwin = fineinput.Nwin; // n windows, from file or random uint NwinNANrm = fineinput.Nwin; // [MA] number of windows w/o NaN int32 initoffsetL = fineinput.initoffsetL; // initial offset int32 initoffsetP = fineinput.initoffsetP; // initial offset uint MasksizeL = fineinput.MasksizeL; // size of correlation window uint MasksizeP = fineinput.MasksizeP; // size of correlation window uint AccL = fineinput.AccL; // size of small chip uint AccP = fineinput.AccP; // size of small chip const uint OVS = fineinput.osfactor; // factor bool pointsrandom = true; if (specified(fineinput.ifpositions)) // filename specified pointsrandom = false; // only use these points // ______Correct sizes if in space domain______ if (fineinput.method == fc_magspace || fineinput.method == fc_cmplxspace) { INFO.print("Adapting size of window for space method"); MasksizeL += 2*fineinput.AccL; MasksizeP += 2*fineinput.AccP; } // ______Corners of slave in master system______ // ______offset = [A](slave system) - [A](master system)______ const int32 sl0 = sinfo.currentwindow.linelo - initoffsetL; const int32 slN = sinfo.currentwindow.linehi - initoffsetL; const int32 sp0 = sinfo.currentwindow.pixlo - initoffsetP; const int32 spN = sinfo.currentwindow.pixhi - initoffsetP; // ______Corners of useful overlap master,slave in master system______ //const uint BORDER = 20;// make slightly smaller //const uint l0 = max(int32(minfo.currentwindow.linelo),sl0) + BORDER; //const uint lN = min(int32(minfo.currentwindow.linehi),slN) - MasksizeL - BORDER; //const uint p0 = max(int32(minfo.currentwindow.pixlo),sp0) + BORDER; //const uint pN = min(int32(minfo.currentwindow.pixhi),spN) - MasksizeP - BORDER; const uint BORDER = 20;// make slightly smaller const int l0 = max(int32(minfo.currentwindow.linelo),sl0) + BORDER; const int lN = min(int32(minfo.currentwindow.linehi),slN) - MasksizeL - BORDER; const int p0 = max(int32(minfo.currentwindow.pixlo),sp0) + BORDER; const int pN = min(int32(minfo.currentwindow.pixhi),spN) - MasksizeP - BORDER; const window overlap(l0,lN,p0,pN); // ______ Distribute Nwin points over window, or read from file ______ // ______ Minlminp(i,0): line, (i,1): pixel, (i,2) flagfromdisk ______ //matrix Minlminp; // [FvL] matrix Minlminp; if (pointsrandom) // no filename specified { Minlminp = distributepoints(real4(Nwin),overlap); } else // read in points (center of windows) from file { Minlminp.resize(Nwin,3); ifstream ifpos(fineinput.ifpositions, ios::in); bk_assert(ifpos,fineinput.ifpositions,__FILE__,__LINE__); uint ll,pp; for (uint i=0; i> ll >> pp; //Minlminp(i,0) = uint(ll - 0.5*MasksizeL); // correct for lower left corner //Minlminp(i,1) = uint(pp - 0.5*MasksizeP); // correct for lower left corner //Minlminp(i,2) = uint(1); // flag from file // [FvL] Minlminp(i,0) = int(ll - 0.5*MasksizeL); // correct for lower left corner Minlminp(i,1) = int(pp - 0.5*MasksizeP); // correct for lower left corner Minlminp(i,2) = int(1); // flag from file ifpos.getline(dummyline,ONE27,'\n'); // goto next line. } ifpos.close(); // ______ Check last point for possible EOL after last position in file ______ if (Minlminp(Nwin-1,0) == Minlminp(Nwin-2,0) && Minlminp(Nwin-1,1) == Minlminp(Nwin-2,1)) { Minlminp(Nwin-1,0) = uint(0.5*(lN + l0) + 27); // random Minlminp(Nwin-1,1) = uint(0.5*(pN + p0) + 37); // random } // ______ Check if points are in overlap ______ // ______ no check for uniqueness of points ______ bool troubleoverlap = false; for (uint i=0; i lN) { troubleoverlap=true; WARNING << "FINE: point from file: " << i+1 << " " << Minlminp(i,0) + 0.5*MasksizeL << " " << Minlminp(i,1) + 0.5*MasksizeP << " outside overlap master, slave. New position: "; Minlminp(i,0) = lN + lN-Minlminp(i,0); WARNING << Minlminp(i,0) << " " << Minlminp(i,1); WARNING.print(); } if (Minlminp(i,1) < p0) { troubleoverlap=true; WARNING << "FINE: point from file: " << i+1 << " " << Minlminp(i,0) + 0.5*MasksizeL << " " << Minlminp(i,1) + 0.5*MasksizeP << " outside overlap master, slave. New position: "; Minlminp(i,1) = p0 + p0-Minlminp(i,1); WARNING << Minlminp(i,0) << " " << Minlminp(i,1); WARNING.print(); } if (Minlminp(i,1) > pN) { troubleoverlap=true; WARNING << "FINE: point from file: " << i+1 << " " << Minlminp(i,0) + 0.5*MasksizeL << " " << Minlminp(i,1) + 0.5*MasksizeP << " outside overlap master, slave. New position: "; Minlminp(i,1) = pN + pN-Minlminp(i,1); WARNING << Minlminp(i,0) << " " << Minlminp(i,1); WARNING.print(); } } if (troubleoverlap) // give some additional info { WARNING << "FINE: there were points from file outside overlap (l0,lN,p0,pN): " << l0 << " " << lN << " " << p0 << " " << pN; WARNING.print(); } } // ______Compute coherence of these points______ matrix Master; matrix Mask; matrix Result(Nwin,3); // R(i,0):delta l; // R(i,1):delta p; R(i,2):correl // ______ Progress message ______ int32 tenpercent = int32(rint(Nwin/10.0)); if (tenpercent==0) tenpercent = 1000; int32 percent = 0; int32 fivepercent = int32(rint(Nwin/5.0)); if (fivepercent==0) fivepercent = 1000; //if (fineinput.method== fc_coherence) // input file () // radarcodedem(fineinput, input_ellips, input_i_comprefdem, // master, slave, interferogram, masterorbit, slaveorbit); // ====== Compute for all locations ====== for (uint i=0;i MasksizeL/2 ) // [MA] fix for Acc being half of Masksize at max { AccL = MasksizeL/2 ; WARNING << "FINE: AccL for magfft can be half of the window size at max, changing to " << AccL ; WARNING.print(); } else if ( AccP > MasksizeP/2 ) { AccP = MasksizeP/2 ; WARNING << "FINE: AccP for magfft can be half of the window size at max, changing to " << AccP ; WARNING.print(); } coheren = crosscorrelate(Master, Mask, OVS, AccL, AccP, offsetL, offsetP);// returned break; } // ====== New method (BK 13 Aug 2005) ====== // ====== This should work for ERS/N1; different PRFs ====== case fc_oversample: // slow (better): oversample complex data first { if ( AccL > MasksizeL/2 ) // [MA] fix for Acc being half of Masksize at max { AccL = MasksizeL/2 ; WARNING << "FINE: AccL for magfft can be half of the window size at max, changing to " << AccL ; WARNING.print(); } else if ( AccP > MasksizeP/2 ) { AccP = MasksizeP/2 ; WARNING << "FINE: AccP for magfft can be half of the window size at max, changing to " << AccP ; WARNING.print(); } // ______ Oversample complex chips by factor two ______ // ______ neg.shift input shifts to -> 0 if (fineinput.shiftazi == 1)//Using the DC poly only { DEBUG.print("Centering azimuth spectrum patches around 0 using the DC polynomial"); const real4 m_pixlo = real4(master.pixlo);// neg.shift -> 0 const real4 s_pixlo = real4(mask.pixlo);// neg.shift -> 0 shiftazispectrum(Master,minfo,-m_pixlo);// shift from fDC to zero shiftazispectrum(Mask, sinfo,-s_pixlo);// shift from fDC to zero } DEBUG.print("Oversampling patches with factor two using zero padding"); const matrix m_ovs_chip = oversample(Master,2,2); const matrix s_ovs_chip = oversample(Mask, 2,2); // ______ Peak in cross-corr of magnitude of ovs data ______ DEBUG.print("Cross-correlating magnitude of ovs patches"); DEBUG.print("(no need to shift spectrum back)");// (else account for ovs..) //coheren = coherencefft(m_ovs_chip, s_ovs_chip, // OVS/2, 2*AccL, 2*AccP, // offsetL,offsetP); coheren = crosscorrelate(m_ovs_chip, s_ovs_chip, OVS/2, 2*AccL, 2*AccP, offsetL,offsetP); offsetL /= 2.0;// orig data oversampled by factor 2 offsetP /= 2.0;// orig data oversampled by factor 2 break; } // ====== This should work for ERS/N1; different PRFs ====== case fc_intensity: // slow (better): oversample complex data first { INFO<< "intensity method "< MasksizeL/2 ) // [MA] fix for Acc being half of Masksize at max { AccL = MasksizeL/2 ; WARNING << "FINE: AccL for magfft can be half of the window size at max, changing to " << AccL ; WARNING.print(); } else if ( AccP > MasksizeP/2 ) { AccP = MasksizeP/2 ; WARNING << "FINE: AccP for magfft can be half of the window size at max, changing to " << AccP ; WARNING.print(); } // ______ Oversample complex chips by factor two ______ // ______ neg.shift input shifts to -> 0 // bool doCenterSpec = true; //Do not remove if the radar is Sentinel-1 // if (minfo.sensor == SLC_S1A) // doCenterSpec = false; if (fineinput.shiftazi == 1) { DEBUG.print("Centering azimuth spectrum patches around 0 using the DC polynomial"); const real4 m_pixlo = real4(master.pixlo);// neg.shift -> 0 const real4 s_pixlo = real4(mask.pixlo);// neg.shift -> 0 shiftazispectrum(Master,minfo,-m_pixlo);// shift from fDC to zero shiftazispectrum(Mask, sinfo,-s_pixlo);// shift from fDC to zero } DEBUG.print("Oversampling patches with factor two using zero padding"); const matrix m_ovs_chip = oversample(Master,2,2); const matrix s_ovs_chip = oversample(Mask, 2,2); // ______ Peak in cross-corr of magnitude of ovs data ______ DEBUG.print("Cross-correlating magnitude of ovs patches"); DEBUG.print("(no need to shift spectrum back)");// (else account for ovs..) //coheren = coherencefft(m_ovs_chip, s_ovs_chip, // OVS/2, 2*AccL, 2*AccP, // offsetL,offsetP); coheren = intensity(m_ovs_chip, s_ovs_chip, OVS/2, 2*AccL, 2*AccP, offsetL,offsetP); offsetL /= 2.0;// orig data oversampled by factor 2 offsetP /= 2.0;// orig data oversampled by factor 2 break; } // ====== New method (MCC Sept 2014) ====== case fc_coherence: // { if ( AccL > MasksizeL/2 ) // [MA] fix for Acc being half of Masksize at max { AccL = MasksizeL/2 ; WARNING << "FINE: AccL for magfft can be half of the window size at max, changing to " << AccL ; WARNING.print(); } else if ( AccP > MasksizeP/2 ) { AccP = MasksizeP/2 ; WARNING << "FINE: AccP for magfft can be half of the window size at max, changing to " << AccP ; WARNING.print(); } matrix refPhaseDEM(mask.lines(),mask.pixels());//only for CCC, but I need to define it here // slcimage deminfo = minfo; if (specified(fineinput.forefdem)) // if spec. then read the needed window { window zerooffset (0,0,0,0) ; window demWin = master; demWin.linelo -= minfo.currentwindow.linelo + 1; demWin.linehi -= minfo.currentwindow.linelo + 1; demWin.pixlo -= minfo.currentwindow.pixlo + 1; demWin.pixhi -= minfo.currentwindow.pixlo + 1; // INFO << "reading DEM phases from: " << fineinput.forefdem << "\n"; // INFO << " nof lines : " < 0 if (fineinput.shiftazi == 1) { DEBUG.print("Centering azimuth spectrum patches around 0 using the DC polynomial"); const real4 m_pixlo = real4(master.pixlo);// neg.shift -> 0 const real4 s_pixlo = real4(mask.pixlo);// neg.shift -> 0 shiftazispectrum(Master,minfo,-m_pixlo);// shift from fDC to zero shiftazispectrum(Mask, sinfo,-s_pixlo);// shift from fDC to zero } DEBUG.print("Oversampling patches with factor two using zero padding"); uint ovsFc = 2;//2^4 const matrix m_ovs_chip = oversample(Master,ovsFc,ovsFc); // MCC //s_ovs_chip is the oversample salve //It is going to be modified // s_ovs_chip spectrum will be centered at the same frequency as the master. // Otherwise the coherence is way understimated matrix s_ovs_chip = oversample(Mask, ovsFc,ovsFc); //size matrix uint L = m_ovs_chip.lines(); uint P = m_ovs_chip.pixels(); //reference phase matrix REFPHASE(Master.lines(),Master.pixels()); matrix allPixels(Master.lines(),Master.pixels()); matrix allLines(Master.lines(),Master.pixels()); const int16 MAXITER = 10; // maximum number of iterations const real8 CRITERPOS = 1e-6; // 1micrometer const real8 CRITERTIM = 1e-10; // seconds (~10-6 m) const real8 m_minpi4cdivlam = (-4*PI*SOL)/minfo.wavelength; const real8 s_minpi4cdivlam = (-4*PI*SOL)/sinfo.wavelength; real8 pixel = 0; // master coord. system real8 line = 0; // ______ Compute ref. phase for this buffer ______ for (register int32 ll=0; ll detr_s_ovs_chip = s_ovs_chip; coheren = coherencefft(m_ovs_chip, detr_s_ovs_chip, OVS/2, 2*AccL, 2*AccP, offsetL,offsetP); offsetL /= real8(ovsFc);// orig data oversampled by factor 2 offsetP /= real8(ovsFc);// orig data oversampled by factor 2 break; } case fc_magspace: coheren = coherencespace(fineinput, Master, Mask, offsetL, offsetP); break; default: PRINT_ERROR("unknown method for fine coregistration.") throw(unhandled_case_error); } // switch method Result(i,0) = initoffsetL + offsetL; Result(i,1) = initoffsetP + offsetP; Result(i,2) = coheren; INFO << "Fine offset between small patches: " << Result(i,0) << ", " << Result(i,1) << " (coh="< &Master, // data const matrix &Mask, // data const int32 ovsfactor, // ovs factor (1 for not) (not uint) const int32 AccL, // search window (not uint) const int32 AccP, // search window (not uint) real4 &offsetL, // returned peak corr real4 &offsetP) // returned peak corr { TRACE_FUNCTION("coherencefft (MCC Sept-2014)") // ______ Internal variables ______ const int32 L = Master.lines(); const int32 P = Master.pixels(); const int32 twoL = 2*L; const int32 twoP = 2*P; const int32 halfL = L/2; const int32 halfP = P/2; // ______ Check input ______ if (Master.lines() != Mask.lines() || Master.pixels() != Mask.pixels()) { PRINT_ERROR("Mask, Master not same size.") throw(input_error); } if (!(ispower2(L) || ispower2(P))) { PRINT_ERROR("Mask, Master size not power of 2.") throw(input_error); } if (!ispower2(ovsfactor)) { PRINT_ERROR("coherencefft factor not power of 2.") throw(input_error); } DEBUG.print("Calculating sum of the pixel power for COHerent cross-correlation"); // sum pixel power master and Mask real4 sumPowMaster =0.0; real4 sumPowMask =0.0; //Calculate sum of square norms to normalize coherence // //register int32 l,p; for (register int32 l=0; l<=L-1; ++l) // all shifts { for (register int32 p=0; p<=P-1; ++p) // all shifts { sumPowMaster += (sqr(Master(l,p).real()) + sqr(Master(l,p).imag())); sumPowMask += (sqr(Mask(l,p).real()) + sqr(Mask(l,p).imag())); } } //Normalization constant see eq. 4.3.2 in Hanssen, (2001). real4 prodSum = sqrt(sumPowMaster*sumPowMask); // ====== (1) Compute cross-products of Master/Mask ====== // ______ Pad with N zeros to prevent periodical convolution ______ matrix Master2(twoL,twoP); // initial 0 matrix Mask2(twoL,twoP); // initial 0 window windef(0,0,0,0); // defaults to total matrix window win1(0, L-1, 0, P-1); window win2(halfL, halfL+L-1, halfP, halfP+P-1); Master2.setdata(win1,Master,windef); // copy of master mcc Mask2.setdata(win2,Mask,windef); // copy of slave mcc // ______ Crossproducts in spectral/space domain ______ // ______ Use Mask2 to store cross products temporarly ______ // fft(Master2,2); // forward transform over rows // fft(Master2,1); fft2d(Master2); //MCC DEBUG #ifdef REALLYDEBUG INFO << "nof lines ifftMask2 : "<< Master2.lines() ; INFO.print(); ofstream ofileccoh; openfstream(ofileccoh, "fftMaster.bin", true); bk_assert(ofileccoh, "fftMaster.bin", __FILE__, __LINE__); ofileccoh << Master2; ofileccoh.close(); //MCC DEBUG #endif //fft(Mask2,2); // forward transform over rows //fft(Mask2,1); fft2d(Mask2); Master2.conj(); Mask2 *= Master2; // corr = conj(M).*S //ifft(Mask2,2); // ifft(Mask2,1); ifft2d(Mask2); // real(Mask2): cross prod. in space //MCC DEBUG #ifdef REALLYDEBUG INFO << "nof lines ifftMask2 : "<< Mask2.lines() ; INFO.print(); ofstream ofileccoh; openfstream(ofileccoh, "iffMask2r.bin", true); bk_assert(ofileccoh, "iffMask2.bin", __FILE__, __LINE__); ofileccoh << Mask2; ofileccoh.close(); //MCC DEBUG #endif // ====== (2) compute norms for all shifts ====== // ______ use tricks to do this efficient ______ // ______ real(Mask2) contains cross-products ______ // ______ Mask2(0,0):Mask2(N,N) for shifts = -N/2:N/2 ______ // ______ rest of this matrix should not be used ______ // ______ Use Master2 to store intensity here in re,im ______ Master2.clean(); // reset to zeros // ====== (3) find maximum correlation at pixel level ====== matrix Coherence(L+1,P+1);//coherence for each shift mcc real4 maxcorr = -999.0; int32 maxcorrL = 0;// local index in Covar of maxcorr int32 maxcorrP = 0;// local index in Covar of maxcorr //max Corr Mag real4 currentMagCoh = 0.0; for (register int32 l=halfL-AccL; l 1 ) { Covar(l,p) = -999.0 ; } // MA quick fix for values bigger then 1 if ( currentMagCoh > maxcorr) { maxcorr = currentMagCoh; maxcorrL = l;// local index in Magnitude of Coh of maxcorr maxcorrP = p;// local index in Magnitude Coh of maxcorr if (maxcorr > 1 ) continue; // [MA] stop checking this chip further for maxcorr } } } //From here the rest is the same as in correlation offsetL = -halfL + maxcorrL; // update by reference offsetP = -halfP + maxcorrP; // update by reference DEBUG << "Pixel level offset: " << offsetL << ", " << offsetP << " (corr=" << maxcorr << ")"; DEBUG.print(); // ====== (4) oversample to find peak sub-pixel ====== // ====== Estimate shift by oversampling estimated correlation ====== if (ovsfactor>1) { // --- (4a) get little chip around max. corr, if possible --- // --- make sure that we can copy the data --- if (maxcorrL(L-AccL)) { DEBUG << "Careful, decrease AccL or increase winsizeL"; DEBUG.print(); maxcorrL = L-AccL; } if (maxcorrP>(P-AccP)) { DEBUG << "Careful, decrease AccP or increase winsizeP"; DEBUG.print(); maxcorrP = P-AccP; } // --- Now get the chip around max corr --- //Using the magnitude of the coherence window win3(maxcorrL-AccL,maxcorrL+AccL-1, maxcorrP-AccP,maxcorrP+AccP-1); const matrix chip(win3,magnitude(Coherence));// construct as part // --- (4b) oversample chip to obtain sub-pixel max --- uint offL; uint offP; maxcorr = max(oversample(chip, ovsfactor, ovsfactor), offL,offP); offsetL = -halfL + maxcorrL - AccL + real4(offL) / real4(ovsfactor); offsetP = -halfP + maxcorrP - AccP + real4(offP) / real4(ovsfactor); DEBUG << "Sub-pixel level offset: " << offsetL << ", " << offsetP << " (corr=" << maxcorr << ")"; DEBUG.print(); } return maxcorr; } // END coherencefft /**************************************************************** * crosscorrelate * * * * cross correlation of zero-meaned magnitude of two patches * * uses ffts, some tricks for speed-up. * * optionally improves peak position to sub-pixel. * * This is an improvement upon coherencefft: faster and local peak * * Better to put this in matrixspecs * * * * input: * * - Master * * - Mask (same size as Master) * * output: * * - peak correlation value [-1 1] * * - updated offsetL, P * * positive offsetL: Mask is shifted up * * positive offsetP: Mask is shifted left * * * * Bert Kampes, 12-Aug-2005 * ****************************************************************/ real4 crosscorrelate( const matrix &Master, // data const matrix &Mask, // data const int32 ovsfactor, // ovs factor (1 for not) (not uint) const int32 AccL, // search window (not uint) const int32 AccP, // search window (not uint) real4 &offsetL, // returned peak corr real4 &offsetP) // returned peak corr { TRACE_FUNCTION("crosscorrelate (BK 12-Aug-2005)") // ______ Internal variables ______ const int32 L = Master.lines(); const int32 P = Master.pixels(); const int32 twoL = 2*L; const int32 twoP = 2*P; const int32 halfL = L/2; const int32 halfP = P/2; const int32 minIfgAmp = -99999; // Minimum amplitude of a ifg to be considered as window for coarse coreg // ______ Check input ______ if (Master.lines() != Mask.lines() || Master.pixels() != Mask.pixels()) { PRINT_ERROR("Mask, Master not same size.") throw(input_error); } if (!(ispower2(L) || ispower2(P))) { PRINT_ERROR("Mask, Master size not power of 2.") throw(input_error); } if (!ispower2(ovsfactor)) { PRINT_ERROR("coherencefft factor not power of 2") throw(input_error); } // ______ Zero mean magnitude images ______ DEBUG.print("Using de-meaned magnitude patches for incoherent cross-correlation"); matrix magMaster = magnitude(Master); matrix magMask = magnitude(Mask); magMaster -= mean(magMaster); magMask -= mean(magMask); // ====== (1) Compute cross-products of Master/Mask ====== // ______ Pad with N zeros to prevent periodical convolution ______ matrix Master2(twoL,twoP); // initial 0 matrix Mask2(twoL,twoP); // initial 0 window windef(0,0,0,0); // defaults to total matrix window win1(0, L-1, 0, P-1); window win2(halfL, halfL+L-1, halfP, halfP+P-1); Master2.setdata(win1,mat2cr4(magMaster),windef); // zero-mean magnitude Mask2.setdata(win2,mat2cr4(magMask),windef); // zero-mean magnitude // ______ Crossproducts in spectral/space domain ______ // ______ Use Mask2 to store cross products temporarly ______ fft2d(Master2); fft2d(Mask2); Master2.conj(); Mask2 *= Master2; // corr = conj(M).*S ifft2d(Mask2); // real(Mask2): cross prod. in space // ====== (2) compute norms for all shifts ====== // ______ use tricks to do this efficient ______ // ______ real(Mask2) contains cross-products ______ // ______ Mask2(0,0):Mask2(N,N) for shifts = -N/2:N/2 ______ // ______ rest of this matrix should not be used ______ // ______ Use Master2 to store intensity here in re,im ______ Master2.clean(); // reset to zeros register int32 l,p; // --- flipud(fliplr(master^2) in real --- // --- mask^2 in imag part; this saves a fft --- // --- automatically the real/imag parts contain the norms --- for (l=L; l BLOCK;// initial 0 if (int32(BLOCK.lines())!=twoL || int32(BLOCK.pixels())!=twoP) { DEBUG << "crosscorrelate:changing static block to size [" << twoL << ", " << twoP << "]"; DEBUG.print(); BLOCK.resize(twoL,twoP); for (l=halfL; l Covar(L+1,P+1);// correlation for each shift real4 maxcorr = -999.0; real4 maxCorrAmp = 0; int32 maxcorrL = 0;// local index in Covar of maxcorr int32 maxcorrP = 0;// local index in Covar of maxcorr for (register int32 l=halfL-AccL; l 1 ) { Covar(l,p) = -999.0 ; } // MA quick fix for values bigger then 1 //if (Covar(l,p) > maxcorr && Covar(l,p)<1.09)// MCC Covar(l,p)<1.09 fixed problem for amplitude =0, which produces a covar=Inf if (Covar(l,p) > maxcorr && maxCorrAmp>minIfgAmp) { maxcorr = Covar(l,p); maxcorrL = l;// local index in Covar of maxcorr maxcorrP = p;// local index in Covar of maxcorr if (maxcorr > 1 ) continue; // [MA] stop checking this chip further for maxcorr } } } // INFO << "PowMaster : " << sqrt(real(Master2(maxcorrL,maxcorrP))*imag(Master2(maxcorrL,maxcorrP))); // INFO.print(); offsetL = -halfL + maxcorrL; // update by reference offsetP = -halfP + maxcorrP; // update by reference DEBUG << "Pixel level offset: " << offsetL << ", " << offsetP << " (corr=" << maxcorr << ")"; DEBUG.print(); // ====== (4) oversample to find peak sub-pixel ====== // ====== Estimate shift by oversampling estimated correlation ====== if (ovsfactor>1) { // --- (4a) get little chip around max. corr, if possible --- // --- make sure that we can copy the data --- if (maxcorrL(L-AccL)) { DEBUG << "Careful, decrease AccL or increase winsizeL"; DEBUG.print(); maxcorrL = L-AccL; } if (maxcorrP>(P-AccP)) { DEBUG << "Careful, decrease AccP or increase winsizeP"; DEBUG.print(); maxcorrP = P-AccP; } // --- Now get the chip around max corr --- //matrix chip(2*AccL,2*AccP);// locally oversample corr //for (l=maxcorrL-AccL; l chip(win3,Covar);// construct as part // --- (4b) oversample chip to obtain sub-pixel max --- uint offL; uint offP; maxcorr = max(oversample(chip, ovsfactor, ovsfactor), offL,offP); offsetL = -halfL + maxcorrL - AccL + real4(offL)/real4(ovsfactor); offsetP = -halfP + maxcorrP - AccP + real4(offP)/real4(ovsfactor); DEBUG << "Sub-pixel level offset: " << offsetL << ", " << offsetP << " (corr=" << maxcorr << ")"; DEBUG.print(); } return maxcorr; } // END crosscorrelate /**************************************************************** * intensity * * * * cross correlation of normalized intensity of two patches * * uses ffts, some tricks for speed-up. * * optionally improves peak position to sub-pixel. * * This is an improvement upon coherencefft: faster and local peak * * Better to put this in matrixspecs * * * * input: * * - Master * * - Mask (same size as Master) * * output: * * - peak correlation value [-1 1] * * - updated offsetL, P * * positive offsetL: Mask is shifted up * * positive offsetP: Mask is shifted left * * * * Bert Kampes, 12-Aug-2005 * MCC change magnitude for intensity Dec 2014 * ****************************************************************/ real4 intensity( const matrix &Master, // data const matrix &Mask, // data const int32 ovsfactor, // ovs factor (1 for not) (not uint) const int32 AccL, // search window (not uint) const int32 AccP, // search window (not uint) real4 &offsetL, // returned peak corr real4 &offsetP) // returned peak corr { TRACE_FUNCTION("crosscorrelate (BK 12-Aug-2005)") // ______ Internal variables ______ const int32 L = Master.lines(); const int32 P = Master.pixels(); const int32 twoL = 2*L; const int32 twoP = 2*P; const int32 halfL = L/2; const int32 halfP = P/2; const int32 minIfgAmp = -99999; // Minimum amplitude of a ifg to be considered as window for coarse coreg // ______ Check input ______ if (Master.lines() != Mask.lines() || Master.pixels() != Mask.pixels()) { PRINT_ERROR("Mask, Master not same size.") throw(input_error); } if (!(ispower2(L) || ispower2(P))) { PRINT_ERROR("Mask, Master size not power of 2.") throw(input_error); } if (!ispower2(ovsfactor)) { PRINT_ERROR("coherencefft factor not power of 2") throw(input_error); } // ______ Zero mean magnitude images ______ DEBUG.print("Using de-meaned magnitude patches for incoherent cross-correlation"); //matrix magMaster = magnitude(Master); //matrix magMask = magnitude(Mask); matrix magMaster = intensity(Master); matrix magMask = intensity(Mask); magMaster /= mean(magMaster); magMask /= mean(magMask); // ====== (1) Compute cross-products of Master/Mask ====== // ______ Pad with N zeros to prevent periodical convolution ______ matrix Master2(twoL,twoP); // initial 0 matrix Mask2(twoL,twoP); // initial 0 window windef(0,0,0,0); // defaults to total matrix window win1(0, L-1, 0, P-1); window win2(halfL, halfL+L-1, halfP, halfP+P-1); Master2.setdata(win1,mat2cr4(magMaster),windef); // zero-mean magnitude Mask2.setdata(win2,mat2cr4(magMask),windef); // zero-mean magnitude // ______ Crossproducts in spectral/space domain ______ // ______ Use Mask2 to store cross products temporarly ______ fft2d(Master2); fft2d(Mask2); Master2.conj(); Mask2 *= Master2; // corr = conj(M).*S ifft2d(Mask2); // real(Mask2): cross prod. in space // ====== (2) compute norms for all shifts ====== // ______ use tricks to do this efficient ______ // ______ real(Mask2) contains cross-products ______ // ______ Mask2(0,0):Mask2(N,N) for shifts = -N/2:N/2 ______ // ______ rest of this matrix should not be used ______ // ______ Use Master2 to store intensity here in re,im ______ Master2.clean(); // reset to zeros register int32 l,p; // --- flipud(fliplr(master^2) in real --- // --- mask^2 in imag part; this saves a fft --- // --- automatically the real/imag parts contain the norms --- for (l=L; l BLOCK;// initial 0 if (int32(BLOCK.lines())!=twoL || int32(BLOCK.pixels())!=twoP) { DEBUG << "crosscorrelate:changing static block to size [" << twoL << ", " << twoP << "]"; DEBUG.print(); BLOCK.resize(twoL,twoP); for (l=halfL; l Covar(L+1,P+1);// correlation for each shift real4 maxcorr = -999.0; real4 maxCorrAmp = 0; int32 maxcorrL = 0;// local index in Covar of maxcorr int32 maxcorrP = 0;// local index in Covar of maxcorr for (register int32 l=halfL-AccL; l 1 ) { Covar(l,p) = -999.0 ; } // MA quick fix for values bigger then 1 //if (Covar(l,p) > maxcorr && Covar(l,p)<1.09)// MCC Covar(l,p)<1.09 fixed problem for amplitude =0, which produces a covar=Inf if (Covar(l,p) > maxcorr && maxCorrAmp>minIfgAmp) { maxcorr = Covar(l,p); maxcorrL = l;// local index in Covar of maxcorr maxcorrP = p;// local index in Covar of maxcorr if (maxcorr > 1 ) continue; // [MA] stop checking this chip further for maxcorr } } } // INFO << "PowMaster : " << sqrt(real(Master2(maxcorrL,maxcorrP))*imag(Master2(maxcorrL,maxcorrP))); // INFO.print(); offsetL = -halfL + maxcorrL; // update by reference offsetP = -halfP + maxcorrP; // update by reference DEBUG << "Pixel level offset: " << offsetL << ", " << offsetP << " (corr=" << maxcorr << ")"; DEBUG.print(); // ====== (4) oversample to find peak sub-pixel ====== // ====== Estimate shift by oversampling estimated correlation ====== if (ovsfactor>1) { // --- (4a) get little chip around max. corr, if possible --- // --- make sure that we can copy the data --- if (maxcorrL(L-AccL)) { DEBUG << "Careful, decrease AccL or increase winsizeL"; DEBUG.print(); maxcorrL = L-AccL; } if (maxcorrP>(P-AccP)) { DEBUG << "Careful, decrease AccP or increase winsizeP"; DEBUG.print(); maxcorrP = P-AccP; } // --- Now get the chip around max corr --- //matrix chip(2*AccL,2*AccP);// locally oversample corr //for (l=maxcorrL-AccL; l chip(win3,Covar);// construct as part // --- (4b) oversample chip to obtain sub-pixel max --- uint offL; uint offP; maxcorr = max(oversample(chip, ovsfactor, ovsfactor), offL,offP); offsetL = -halfL + maxcorrL - AccL + real4(offL)/real4(ovsfactor); offsetP = -halfP + maxcorrP - AccP + real4(offP)/real4(ovsfactor); DEBUG << "Sub-pixel level offset: " << offsetL << ", " << offsetP << " (corr=" << maxcorr << ")"; DEBUG.print(); } return maxcorr; } // END intensity /**************************************************************** * coherencespace * * * * coherence in space domain based on magnitude * * uses extension with zeros * * * * input: * * - Master * * - Mask (size Master) * * output: * * - coherence value * * - updated offsetL, P * * * * Bert Kampes, 03-Feb-1999 * ****************************************************************/ real4 coherencespace( const input_fine &fineinput, const matrix &Master, // complex data const matrix &Mask, // complex data real4 &offsetL, // returned real4 &offsetP) // returned { TRACE_FUNCTION("coherencespace (BK 03-Feb-1999)") // ______ Internal variables ______ const int32 L = Master.lines(); const int32 P = Master.pixels(); const int32 AccL = fineinput.AccL; const int32 AccP = fineinput.AccP; const uint factor = fineinput.osfactor; // ______Select parts of Master/slave______ const int32 MasksizeL = L - 2*AccL; const int32 MasksizeP = P - 2*AccP; // ______ Check input ______ if (!ispower2(AccL) || !ispower2(AccP)) { PRINT_ERROR("AccL should be power of 2 for oversampling.") throw(input_error); } if (MasksizeL < 4 || MasksizeP < 4) { PRINT_ERROR("Correlationwindow size too small (<4; size= FC_winsize-2*FC_Acc).") throw(input_error); } // ______Shift center of Slave over Master______ window winmask(AccL, AccL+MasksizeL-1, AccP, AccP+MasksizeP-1); matrix coher(2*AccL,2*AccP); // store result // 1st element: shift==AccL window windef(0, 0, 0, 0); // defaults to total switch (fineinput.method) { case fc_cmplxspace: { PRINT_ERROR("not implemented in v1.0") throw(unhandled_case_error); break; } case fc_magspace: { matrix magMask = magnitude(Mask); // magnitude magMask -= mean(magMask); // subtract mean matrix Mask2(winmask,magMask); // construct as part real4 normmask = norm2(Mask2); matrix Master2(MasksizeL, MasksizeP); matrix magMaster = magnitude(Master); magMaster -= mean(magMaster); window winmaster; for (register int32 i=0;i<2*AccL;i++) { winmaster.linelo = i; winmaster.linehi = i+MasksizeL-1; for (register int32 j=0;j<2*AccP;j++) { winmaster.pixlo = j; winmaster.pixhi = j+MasksizeP-1; Master2.setdata(windef,magMaster,winmaster); // ______Coherence for this position______ real4 cohs1s2 = 0.; real4 cohs1s1 = 0.; for (register int32 k=0;k coher8 = oversample(coher,factor,factor); const real4 maxcor = max(coher8,offL,offP); offsetL = AccL - offL/real4(factor); // update by reference offsetP = AccP - offP/real4(factor); // update by reference return maxcor; } // END coherencespace /**************************************************************** * coregpm * * * * Compute coregistration parameters (least squares) * * * * input: * * - Position of windows * * - Computed offsets * * * * output: * * - coregistration parameters to file * * (wrt. normalized master grid) * * * * Bert Kampes, 22-Feb-1999 * * Bert Kampes, 26-Oct-1999 normalized coordinates * * changed matrices from real4 to real8, * #%// BK 22-Mar-2001 * ****************************************************************/ void coregpm( const slcimage &master, // normalization factors,ovs_rg/az const slcimage &slave, //[FvL] const char* i_resfile, const input_coregpm &coregpminput, const int16 &demassist) //[FvL] //const uint oversamplingsfactorfine) { TRACE_FUNCTION("coregpm (BK 26-Oct-1999)") // ______Names of variables in this routine______ // unknowns: x // solution unknowns: placed in rhsL/P // observations: y // covariance obs.: Qy_1 // designmatrix: A // normalmatrix: N = At. Qy-1. A // covariance unkn.: N_1 (Qx_hat, inverse normalmatrix) // estimates: *_hat const real4 THRESHOLD = coregpminput.threshold;// threshold ... const int32 DEGREE = coregpminput.degree; // degree of polynomial const int32 MAX_ITERATIONS = coregpminput.maxiter;// max. of pnts to remove const real4 CRIT_VALUE = coregpminput.k_alpha;// crit. value outlier removal const int32 Nunk = Ncoeffs(DEGREE); // Number of unknowns/direction // ______ Normalize data for polynomial ______ const real8 minL = master.originalwindow.linelo; const real8 maxL = master.originalwindow.linehi; const real8 minP = master.originalwindow.pixlo; const real8 maxP = master.originalwindow.pixhi; // ______ A priori sigma of offset ______ // ______ Read this factor from the result file // ______ "Oversampling factor: 32" // ______ "Window_size_L_for_correlation: 4" // ______ "Window_size_P_for_correlation: 121" DEBUG.print("Reading oversampling factor from result file"); uint osfactor = 32;// oversamplingsfactor int32 corrwinL = 64;// window size to compute FINE correlation int32 corrwinP = 64;// window size to compute FINE correlation char c4osfactor[4]; char c10corrwinL[10]; char c10corrwinP[10]; bool found = readres(c4osfactor,sizeof(c4osfactor),i_resfile, "Oversampling", 1); if (found) osfactor = uint(atoi(c4osfactor)); found = readres(c10corrwinL,sizeof(c10corrwinL),i_resfile, "Window_size_L_for_correlation:", 0); if (found) corrwinL = int32(atoi(c10corrwinL)); found = readres(c10corrwinP,sizeof(c10corrwinP),i_resfile, "Window_size_P_for_correlation:", 0); if (found) corrwinP = int32(atoi(c10corrwinP)); corrwinL = max(10,corrwinL-8);// if fft method peak is not at center corrwinP = max(10,corrwinP-8);// +then effective number of samples is smaller // _____ oversampling factor is bin in which maximum can be found _____ // _____ ovsf=16-->apriorisigma=0.03 const real4 ACCURACY = 0.5 * (1.0/(real4(osfactor))); // but we need coreg accuracy of 0.1 pixel about. therefore use a priori // based on experience here, and different for azimuth and range // this also helps our automated outlier detection and testing hopefully. // BK 15-Apr-2003 // if the image is oversampled, then still use orig spacing real4 SIGMAL=-999.9;// sigma in orig pixels real4 SIGMAP=-999.9;// seems range direction is better??? if (coregpminput.weightflag!=3) { SIGMAL = 0.15/master.ovs_az;// sigma in orig pixels SIGMAP = 0.10/master.ovs_rg;// seems range direction is better??? DEBUG.print("Using a smaller sigma in range, because it seems that can be estimated better"); INFO << "a priori std.dev offset vectors line direction [samples]: " << SIGMAL; INFO.print(); INFO << "a priori std.dev offset vectors pixel direction [samples]: " << SIGMAP; INFO.print(); } // ______ Find #points > threshold ______ matrix Data = getofffile(i_resfile, THRESHOLD); // ______ Data contains the following: ______ // Data(i,0) = winnumber; Data(i,1) = posL; Data(i,2) = posP; // Data(i,3) = offL; Data(i,4) = offP; Data(i,5) = corr; // ______ start added by FvL ______ ifstream DeltaLfile, DeltaPfile; streampos pos; if (demassist) { openfstream(DeltaLfile,"dac_delta_line.raw"); bk_assert(DeltaLfile,"dac_delta_line.raw",__FILE__,__LINE__); openfstream(DeltaPfile,"dac_delta_pixel.raw"); bk_assert(DeltaPfile,"dac_delta_pixel.raw",__FILE__,__LINE__); int32 posL, posP; real4 offL, offP; real8 deltaL,deltaP; const int32 sizer8 = sizeof(real8); real4 ms_az_timing_error_L = real4(slave.az_timing_error); // ms = masterslave: relative timing error real4 ms_r_timing_error_P = real4(slave.r_timing_error); for (register int32 ii=0; ii eL_hat; matrix eP_hat; matrix wtestL; matrix wtestP; matrix rhsL; matrix rhsP; matrix Qx_hat; real8 maxdev = 0.0; real8 overallmodeltestL = 0.0; real8 overallmodeltestP = 0.0; real8 maxwL; real8 maxwP; register int32 i,j,k,index; while (DONE != 1) { PROGRESS << "Start iteration " << ITERATION; PROGRESS.print(); // ______ Remove identified outlier from previous estimation ______ if (ITERATION != 0) { matrix tmp_DATA = Data; //(remove_observation_i,*); Data.resize(Data.lines()-1, Data.pixels()); j = 0;// counter over reduced obs.vector for (i=0; i threshold if (Nobs < Nunk) { PRINT_ERROR("coregpm: Number of windows > threshold is smaller than parameters solved for.") throw(input_error); } // ______Set up system of equations______ // ______Order unknowns: A00 A10 A01 A20 A11 A02 A30 A21 A12 A03 for degree=3______ matrix yL(Nobs,1); // observation matrix yP(Nobs,1); // observation matrix A(Nobs,Nunk); // designmatrix matrix Qy_1(Nobs,1); // a priori covariance matrix (diag) // ______ Normalize data for polynomial ______ INFO << "coregpm: polynomial normalized by factors: " << minL << " " << maxL << " " << minP << " " << maxP << " to [-2,2]"; INFO.print(); // ______Fill matrices______ DEBUG.print("Setting up design matrix for LS adjustment"); for (i=0; i N = matTxmat(A,diagxmat(Qy_1,A)); //matrix rhsL = matTxmat(A,diagxmat(Qy_1,yL)); //matrix rhsP = matTxmat(A,diagxmat(Qy_1,yP)); //matrix Qx_hat = N; rhsL = matTxmat(A,diagxmat(Qy_1,yL)); rhsP = matTxmat(A,diagxmat(Qy_1,yP)); Qx_hat = N; // ______Compute solution______ choles(Qx_hat); // Cholesky factorisation normalmatrix solvechol(Qx_hat,rhsL); // Solution unknowns in rhs solvechol(Qx_hat,rhsP); // Solution unknowns in rhs invertchol(Qx_hat); // Covariance matrix of unknowns // ______Test inverse______ for (i=0; i .001) { WARNING << "coregpm: maximum deviation N*inv(N) from unity = " << maxdev << ". This is between 0.01 and 0.001"; WARNING.print(); } // ______Some other stuff, scale is ok______ matrix Qy_hat = A * (matxmatT(Qx_hat,A)); matrix yL_hat = A * rhsL; matrix yP_hat = A * rhsP; //matrix eL_hat = yL - yL_hat; //matrix eP_hat = yP - yP_hat; eL_hat = yL - yL_hat; eP_hat = yP - yP_hat; // matrix Qe_hat = Qy - Qy_hat; matrix Qe_hat = -Qy_hat; for (i=0; i wtestsum = sqr(wtestL)+sqr(wtestP);// (Nobs,1) real8 maxwsum = max(wtestsum,winL,dumm);// idx to remove INFO << "Detected outlier: summed sqr.wtest = " << maxwsum << "; observation: " << winL << "; window number: " << Data(winL,0); INFO.print(); // ______ Test if we are done yet ______ if (Nobs <= Nunk) { WARNING.print("NO redundancy! Exiting iterations."); DONE = 1;// cannot remove more than this } // seems something fishy here..., b-method of testing delft // if (max(overallmodeltestL,overallmodeltestP) < 1.0) // { // INFO.print("OMTs accepted, not iterating anymore (final solution reached)."); // DONE = 1;// ok (?). // } if (max(maxwL,maxwP) <= CRIT_VALUE)// all tests accepted? { INFO.print("All outlier tests accepted! (final solution computed)"); DONE = 1;// yeah! } if (ITERATION >= MAX_ITERATIONS) { INFO.print("max. number of iterations reached (exiting loop)."); DONE = 1;// we reached max. (or no max_iter specified) } // ______ Only warn if last iteration has been done ______ if (DONE == 1) { // ___ use trace buffer to store string, remember to rewind it ___ if (overallmodeltestL > 10) { WARNING << "coregpm: overallmodeltest Lines = " << overallmodeltestL << ends; WARNING.print(); WARNING << " is larger than 10. (Suggest model or a priori sigma not correct.)"; WARNING.print(); } // ___ use trace buffer to store string, remember to rewind it ___ if (overallmodeltestP > 10) { WARNING << "coregpm: overallmodeltest Pixels = " << overallmodeltestP; WARNING.print(); WARNING << " is larger than 10.\n(suggests a priori sigma not correct.)"; WARNING.print(); } // if a priori sigma is correct, max wtest should be something like 1.96 if (max(maxwL,maxwP)>200.0) { WARNING << "Recommendation: remove window number: " << Data(winL,0) << " and re-run step COREGPM. max. wtest is: " << max(maxwL,maxwP) << "."; WARNING.print(); } // this test seems to generate too many warnings... // ______Test of Jaron Samson's thesis: not ok/ depends on SIGMA ...______ // //real4 expected = 1. / 400.; // WRONG, 1./sqr(28) ??? // real8 expected = 1.0 / sqr(28); //784.; // expected /= sqr(SIGMAL); // correct for variance factor // for (i=0; i expected) // { // WARNING << "coregpm: Qy_hat too large for window: " // << Data(i,0); // WARNING.print(); // } }// Only warn when done iterating. ITERATION++;// update counter here! }// iterations remove outliers // ____ start added by FvL _________ // Determine inverse transformation // (slave corners only, needed for overlap) // ______ Normalize data for polynomial ______ const real8 sminL = slave.originalwindow.linelo; const real8 smaxL = slave.originalwindow.linehi; const real8 sminP = slave.originalwindow.pixlo; const real8 smaxP = slave.originalwindow.pixhi; // ______Check redundancy______ int32 Nobs = Data.lines(); // Number of points > threshold // ______Set up system of equations for slave______ // ______Order unknowns: A00 A10 A01 A20 A11 A02 A30 A21 A12 A03 for degree=3______ matrix srhsL; matrix srhsP; matrix yL(Nobs,1); // observation matrix yP(Nobs,1); // observation matrix A(Nobs,Nunk); // designmatrix matrix Qy_1(Nobs,1); // a priori covariance matrix (diag) // ______ Normalize data for polynomial ______ INFO << "coregpm: slave polynomial normalized by factors: " << sminL << " " << smaxL << " " << sminP << " " << smaxP << " to [-2,2]"; INFO.print(); // ______Fill matrices______ DEBUG.print("Setting up design matrix for LS adjustment"); for (i=0; i N = matTxmat(A,diagxmat(Qy_1,A)); //use same Qy_1 srhsL = matTxmat(A,diagxmat(Qy_1,yL)); srhsP = matTxmat(A,diagxmat(Qy_1,yP)); Qx_hat = N; // ______Compute solution______ choles(Qx_hat); // Cholesky factorisation normalmatrix solvechol(Qx_hat,srhsL); // Solution unknowns in rhs solvechol(Qx_hat,srhsP); // Solution unknowns in rhs invertchol(Qx_hat); // Covariance matrix of unknowns real8 slave_l0 = slave.currentwindow.linelo; real8 slave_lN = slave.currentwindow.linehi; real8 slave_p0 = slave.currentwindow.pixlo; real8 slave_pN = slave.currentwindow.pixhi; real8 deltaline_slave00,deltapixel_slave00, deltaline_slave0N,deltapixel_slave0N, deltaline_slaveN0,deltapixel_slaveN0, deltaline_slaveNN,deltapixel_slaveNN; deltaline_slave00 = polyval(normalize(slave_l0,sminL,smaxL), normalize(slave_p0,sminP,smaxP), srhsL,DEGREE); deltapixel_slave00 = polyval(normalize(slave_l0,sminL,smaxL), normalize(slave_p0,sminP,smaxP), srhsP,DEGREE); deltaline_slave0N = polyval(normalize(slave_l0,sminL,smaxL), normalize(slave_pN,sminP,smaxP), srhsL,DEGREE); deltapixel_slave0N = polyval(normalize(slave_l0,sminL,smaxL), normalize(slave_pN,sminP,smaxP), srhsP,DEGREE); deltaline_slaveN0 = polyval(normalize(slave_lN,sminL,smaxL), normalize(slave_p0,sminP,smaxP), srhsL,DEGREE); deltapixel_slaveN0 = polyval(normalize(slave_lN,sminL,smaxL), normalize(slave_p0,sminP,smaxP), srhsP,DEGREE); deltaline_slaveNN = polyval(normalize(slave_lN,sminL,smaxL), normalize(slave_pN,sminP,smaxP), srhsL,DEGREE); deltapixel_slaveNN = polyval(normalize(slave_lN,sminL,smaxL), normalize(slave_pN,sminP,smaxP), srhsP,DEGREE); // ____ end added by FvL _________ // ______ Create dump file for making plots ______ ofstream cpmdata("CPM_Data", ios::out | ios::trunc); bk_assert(cpmdata,"coregpm: CPM_DATA",__FILE__,__LINE__); cpmdata << "File: CPM_Data" << "\nThis file contains information on the least squares" << "\n estimation of the coregistration parameters." << "\nThis info is used in the plotcmp script." << "\nThere are 10 columns with:" << "\nWindow number, position L, position P, " << "\n offsetL (observation), offsetP (observation), correlation," << "\n estimated errorL, errorP, w-test statistics for L, P." << "\nwin posL posP offL offP corr eL eP wtstL wtstP" << "\n------------------------------------------------------------\n"; cpmdata.close(); // ______ Only way to format in c++ since stupid iomanip dont work? ______ FILE *cpm; cpm=fopen("CPM_Data","a"); //for (i=0; i Lcoeff = readcoeff("scratchrescpm", "Estimated_coefficientsL:",Ncoeffs(DEGREE)); // read rhsP from file due top format... double matrix Pcoeff = readcoeff("scratchrescpm", "Estimated_coefficientsP:",Ncoeffs(DEGREE)); matrix x_axis(2,1); matrix y_axis(2,1); x_axis(0,0) = minL; x_axis(1,0) = maxL; y_axis(0,0) = minP; y_axis(1,0) = maxP; normalize(x_axis,minL,maxL); normalize(y_axis,minP,maxP); matrix offsetcornersL = polyval(x_axis,y_axis,Lcoeff); // MA matrix offsetcornersP = polyval(x_axis,y_axis,Pcoeff); INFO.print(" "); INFO.print("Modeled transformation in azimuth:"); INFO.print("-------------------------------------------------"); INFO << " First line: " << offsetcornersL(0,0) << " ... " << offsetcornersL(0,1); INFO.print(); INFO.print(" : :"); INFO << " Last line: " << offsetcornersL(1,0) << " ... " << offsetcornersL(1,1); INFO.print(); INFO.print("\n"); INFO.print("Modeled transformation in range:"); INFO.print("-------------------------------------------------"); INFO << " First line: " << offsetcornersP(0,0) << " ... " << offsetcornersP(0,1); INFO.print(); INFO.print(" : :"); INFO << " Last line: " << offsetcornersP(1,0) << " ... " << offsetcornersP(1,1); INFO.print(); INFO.print(" "); // ====== Dump evaluated polynomial if requested ====== // BK 17-May-2000 if (coregpminput.dumpmodel) { DEBUG.print("Do evaluation of coreg model with stepsize 100 pixels or so..."); DEBUG.print("And account for currentwindow, not orig window..."); PROGRESS.print("Started dumping evaluated model azimuth."); TRACE.print();// empty buffer to be sure TRACE << "offsetazi_" << master.originalwindow.lines() << "_" << master.originalwindow.pixels() << ".r4"; char fileazi[ONE27]; strcpy(fileazi,TRACE.get_str()); TRACE.print();// empty buffer to be sure ofstream dumpfile; openfstream(dumpfile,fileazi,true); bk_assert(dumpfile,fileazi,__FILE__,__LINE__); // polyval both standing x,y... (?) // matrix p_axis(1,master.originalwindow.pixels()); matrix l_axis(1,1); // ... matrix p_axis(master.originalwindow.pixels(),1); for (i=0; i MODEL = polyval(l_axis,p_axis,Lcoeff); dumpfile << MODEL; } dumpfile.close(); INFO << "Dumped model azimuth offset to file: " << fileazi << " format: real4; number of lines: " << master.originalwindow.lines() << " number of pixels: " << master.originalwindow.pixels(); INFO.print(); // ______ same for range ______ PROGRESS.print("Started dumping evaluated model range."); TRACE.print();// empty buffer to be sure TRACE << "offsetrange_" << master.originalwindow.lines() << "_" << master.originalwindow.pixels() << ".r4"; char filerange[ONE27]; strcpy(filerange,TRACE.get_str()); TRACE.print();// empty buffer to be sure ofstream dumpfile2; openfstream(dumpfile2,filerange,true); bk_assert(dumpfile2,filerange,__FILE__,__LINE__); for (i =master.originalwindow.linelo; i<=master.originalwindow.linehi; ++i) // all lines { l_axis(0,0) = normalize(real8(i),minL,maxL); matrix MODEL = polyval(l_axis,p_axis,Pcoeff); dumpfile2 << MODEL; } INFO << "Dumped model range offset to file: " << filerange << " format: real4; number of lines: " << master.originalwindow.lines() << " number of pixels: " << master.originalwindow.pixels(); INFO.print(); dumpfile2.close(); } // ====== Tidy up ====== PROGRESS.print("finished computation of coregistration parameters."); } // END coregpm /**************************************************************** * getofffile * * * * Returns matrix (real4) with data of fine coreg from file * * mat(i,0)=window number * * mat(i,1)=position: line coordinate * * mat(i,2)=position: pixels coordinate * * mat(i,3)=offset: line direction * * mat(i,4)=offset: pixle direction * * mat(i,5)=correlation: * * searches for "Number_of_correlation_windows:" * * * * Bert Kampes, 24-Feb-1999 * ****************************************************************/ matrix getofffile( const char* file, real4 threshold) { TRACE_FUNCTION("getofffile (BK 24-Feb-1999)"); char dummyline[ONE27]; char word[EIGHTY]; bool foundsection = false; ifstream infile; openfstream(infile,file); bk_assert(infile,file,__FILE__,__LINE__); // ======Search file for data section====== while (infile) { infile >> word; if (strcmp("Number_of_correlation_windows:",word)) // no pattern match. { infile.getline(dummyline,ONE27,'\n'); // goto next line. } else // in data section { foundsection=true; int32 N; // number of points infile >> N; infile.getline(dummyline,ONE27,'\n'); // next line infile.getline(dummyline,ONE27,'\n'); // skip line with info int32 pos = infile.tellg(); // position of start data int32 Nobs = 0; // number points > threshold real4 winnumber, posL, posP, offL, offP, corr; // on file register int32 i; for (i=0;i> winnumber >> posL >> posP >> offL >> offP >> corr; infile.getline(dummyline,ONE27,'\n'); // goto next data record if (corr > threshold) Nobs++; } if (Nobs == 0) { PRINT_ERROR("code ???: No data found > threshold.") throw(some_error); } matrix Data(Nobs,6); infile.seekg(pos); // return to start data int32 cnti = -1; for (i=0;i> winnumber >> posL >> posP >> offL >> offP >> corr; infile.getline(dummyline,ONE27,'\n'); // goto next data record if (corr > threshold) { cnti++; Data(cnti,0) = winnumber; Data(cnti,1) = posL; Data(cnti,2) = posP; Data(cnti,3) = offL; Data(cnti,4) = offP; Data(cnti,5) = corr; } } infile.close(); return Data; } // else } // file // ______Tidy up______ if (!foundsection) { PRINT_ERROR("code 401: getofffile: couldn't find data section in file."); throw(some_error); } infile.close(); // --- return a dummy here since some compiler like that --- return matrix(999,999);// BK 07-Apr-2003 } // END getofffile /**************************************************************** * cc4 * * * * cubic convolution 4 points * * * * input: * * - x-axis * * output: * * - y=f(x); function evaluated at x * * * * Bert Kampes, 16-Mar-1999 * ****************************************************************/ matrix cc4( const matrix &x) { TRACE_FUNCTION("cc4 (BK 16-Mar-1999)"); if (x.pixels() != 1) { PRINT_ERROR("cc4: standing vectors only.") throw(input_error); } real4 alpha = -1.0; matrix y(x.lines(),1); for (register uint i=0;i(alfa-beta) after correction in paper * * by Ramon Hanssen * * Bert Kampes, 16-Mar-1999 * ****************************************************************/ matrix cc6( const matrix &x) { TRACE_FUNCTION("cc6 (BK 16-Mar-1999)"); if (x.pixels() != 1) { PRINT_ERROR("cc6: standing vectors only.") throw(input_error); } real4 alpha = -.5; real4 beta = .5; matrix y(x.lines(),1); for (register uint i=0;i ts6( const matrix &x) { TRACE_FUNCTION("ts6 (BK 16-Mar-1999)"); if (x.pixels() != 1) { PRINT_ERROR("ts6: standing vectors only.") throw(input_error); } matrix y(x.lines(),1); for (register uint i=0;i ts8( const matrix &x) { TRACE_FUNCTION("ts8 (BK 16-Mar-1999)"); if (x.pixels() != 1) { PRINT_ERROR("ts8: standing vectors only.") throw(input_error); } matrix y(x.lines(),1); for (register uint i=0;i ts16( const matrix &x) { TRACE_FUNCTION("ts16 (BK 16-Mar-1999)"); if (x.pixels() != 1) { PRINT_ERROR("ts16: standing vectors only.") throw(input_error); } matrix y(x.lines(),1); for (register uint i=0;i rect( const matrix &x) { TRACE_FUNCTION("rect (BK 16-Mar-1999)"); if (x.pixels() != 1) { PRINT_ERROR("rect: standing vectors only."); throw(input_error); } matrix y(x.lines(),1); for (register uint i=0;i tri( const matrix &x) { TRACE_FUNCTION("tri (BK 16-Mar-1999)") if (x.pixels() != 1) { PRINT_ERROR("tri: standing vectors only.") throw(input_error); } matrix y(x.lines(),1); for (register uint i=0;i knab( const matrix &x, const real4 CHI, const int32 N) { TRACE_FUNCTION("knab (BK 22-Dec-2003)"); if (x.pixels() != 1) { PRINT_ERROR("knab: standing vectors only.") throw(input_error); } matrix y(x.lines(),1); real4 v = 1.0-1.0/CHI; real4 vv = PI*v*real4(N)/2.0; for (register uint i=0;i rc_kernel( const matrix &x, const real4 CHI, const int32 N) { TRACE_FUNCTION("rc_kernel (BK 28-Jul-2005)"); if (x.pixels() != 1) { PRINT_ERROR("rc_kernel: standing vectors only.") throw(input_error); } matrix y(x.lines(),1); real4 v = 1.0-1.0/CHI;// alpha in paper cho05 for (register uint i=0;i &cpmL, // coregistration parameters const matrix &cpmP, // coregistration parameters const int16 &demassist, const matrix &minMaxL, const matrix &minMaxP ) { TRACE_FUNCTION("resample (BK 16-Mar-1999; BK 09-Nov-2000)") if (resampleinput.shiftazi == 1) DEBUG.print("shifting kernelL to data fDC BK 26-Oct-2002"); // ___ Handle input ___ //const uint BUFFERMEMSIZE = generalinput.memory; // Bytes 500MB --> 500 000 000 bytes const real8 BUFFERMEMSIZE = generalinput.memory; // Bytes 500MB --> 500 000 000 bytes const int32 Npoints = resampleinput.method%100; // #pnts interpolator if (isodd(Npoints)) { PRINT_ERROR("resample only even point interpolators.") throw(input_error); } const int32 Npointsd2 = Npoints/2; const int32 Npointsd2m1 = Npointsd2-1; //const uint Sfilelines = slave.currentwindow.lines(); const uint sizeofci16 = sizeof(compli16); const uint sizeofcr4 = sizeof(complr4); const uint sizeofr4 = sizeof(real4); //[FvL] // ______ Normalize data for polynomial ______ // const real8 minL = master.originalwindow.linelo; // const real8 maxL = master.originalwindow.linehi; // const real8 minP = master.originalwindow.pixlo; // const real8 maxP = master.originalwindow.pixhi; const real8 minL = minMaxL(0,0); const real8 maxL = minMaxL(1,0); const real8 minP = minMaxP(0,0); const real8 maxP = minMaxP(1,0); INFO << "resample: polynomial normalized by factors: " << minL << " " << maxL << " " << minP << " " << maxP << " to [-2,2]"; INFO.print(); // ______ For KNAB/Raised Cosine kernel if requested ______ // ______ Because kernel is same in az. and rg. min. must be used. const real4 CHI_az = slave.prf/slave.abw;// oversampling factor az const real4 CHI_rg = (slave.rsr2x/2.0)/slave.rbw;// oversampling factor rg const real4 CHI = min(CHI_az,CHI_rg);// min. oversampling factor of data INFO << "Oversampling ratio azimuth (PRF/ABW): " << CHI_az; INFO.print(); INFO << "Oversampling ratio azimuth (RSR/RBW): " << CHI_rg; INFO.print(); INFO << "KNAB/RC kernel uses: oversampling ratio: " << CHI; INFO.print(); if (CHI < 1.1) { WARNING << "Oversampling ratio: " << CHI << " not optimal for KNAB/RC"; WARNING.print(); } // ====== Create lookup table ====== // ______ e.g. four point interpolator // ______ interpolating point: p=6.4925 // ______ required points: 5, 6, 7, 8 // ______ kernel number from lookup table: floor(.4925*INTERVAL+.5) // ______ table[0]= 0 1 0 0 ;table[INTERVAL]= 0 0 1 0 // ______ intervals in lookup table: dx // ______ for high doppler 100 is OK (fdc=3prf; 6pi --> 10deg error?) // ______ 2047? 4095? which one is better for Sentinel-1 (Wu Wenhao) const int32 INTERVAL = 2047; // precision: 1./INTERVAL [pixel] const int32 Ninterval = INTERVAL + 1; // size of lookup table const real8 dx = 1.0/INTERVAL; // interval look up table INFO << "resample: lookup table size: " << Ninterval; INFO.print(); register int32 i; matrix x_axis(Npoints,1); for (i=0; i *pntKernelAz[Ninterval];// kernel in azimuth matrix *pntKernelRg[Ninterval];// kernel in range // ______ same axis required for shift azimuth spectrum as used ______ // ______ for kernel to avoid phase shift (Raffaele Nutricato) ______ matrix *pntAxis[Ninterval]; for (i=0; i (Npoints,1); pntKernelRg[i] = new matrix (Npoints,1); pntAxis[i] = new matrix (Npoints,1);// only used for azishift switch(resampleinput.method) { // --- Extremely simple kernels (not good, but fast) --- case rs_rect: (*pntKernelAz[i]) = mat2cr4(rect(x_axis)); (*pntKernelRg[i]) = mat2cr4(rect(x_axis)); break; case rs_tri: (*pntKernelAz[i]) = mat2cr4(tri(x_axis)); (*pntKernelRg[i]) = mat2cr4(tri(x_axis)); break; // --- Truncated sinc --- case rs_ts6p: (*pntKernelAz[i]) = mat2cr4(ts6(x_axis)); (*pntKernelRg[i]) = mat2cr4(ts6(x_axis)); break; case rs_ts8p: (*pntKernelAz[i]) = mat2cr4(ts8(x_axis)); (*pntKernelRg[i]) = mat2cr4(ts8(x_axis)); break; case rs_ts16p: (*pntKernelAz[i]) = mat2cr4(ts16(x_axis)); (*pntKernelRg[i]) = mat2cr4(ts16(x_axis)); break; // --- Cubic Convolution kernel: theoretical better than truncated sinc. --- case rs_cc4p: (*pntKernelAz[i]) = mat2cr4(cc4(x_axis)); (*pntKernelRg[i]) = mat2cr4(cc4(x_axis)); break; case rs_cc6p: (*pntKernelAz[i]) = mat2cr4(cc6(x_axis)); (*pntKernelRg[i]) = mat2cr4(cc6(x_axis)); break; // --- KNAB kernel: theoretical better than cubic conv. --- case rs_knab4p: (*pntKernelAz[i]) = mat2cr4(knab(x_axis,CHI_az,4)); (*pntKernelRg[i]) = mat2cr4(knab(x_axis,CHI_rg,4)); break; case rs_knab6p: (*pntKernelAz[i]) = mat2cr4(knab(x_axis,CHI_az,6)); (*pntKernelRg[i]) = mat2cr4(knab(x_axis,CHI_rg,6)); break; case rs_knab8p: (*pntKernelAz[i]) = mat2cr4(knab(x_axis,CHI_az,8)); (*pntKernelRg[i]) = mat2cr4(knab(x_axis,CHI_rg,8)); break; case rs_knab10p: (*pntKernelAz[i]) = mat2cr4(knab(x_axis,CHI_az,10)); (*pntKernelRg[i]) = mat2cr4(knab(x_axis,CHI_rg,10)); break; case rs_knab16p: (*pntKernelAz[i]) = mat2cr4(knab(x_axis,CHI_az,16)); (*pntKernelRg[i]) = mat2cr4(knab(x_axis,CHI_rg,16)); break; // --- Raised cosine: theoretical best --- case rs_rc6p: (*pntKernelAz[i]) = mat2cr4(rc_kernel(x_axis,CHI_az,6)); (*pntKernelRg[i]) = mat2cr4(rc_kernel(x_axis,CHI_rg,6)); break; case rs_rc12p: (*pntKernelAz[i]) = mat2cr4(rc_kernel(x_axis,CHI_az,12)); (*pntKernelRg[i]) = mat2cr4(rc_kernel(x_axis,CHI_rg,12)); break; default: PRINT_ERROR("impossible.") throw(unhandled_case_error); }//kernel selector (*pntAxis[i]) = x_axis;// to shift kernelL use: k*=exp(-i*2pi*axis*fdc/prf) x_axis -= dx; // Note: 'wrong' way (mirrored) } // ====== Usage: pntKernelAz[0]->showdata(); or (*pntKernelAz[0][0]).showdata(); ====== // ______ Log kernels to check sum, etc. ______ DEBUG.print("Overview of LUT for interpolation kernel follows:"); DEBUG.print("-------------------------------------------------"); for (i=0; i overlap.linehi) { PRINT_ERROR("RS_DBOW: specified min. line larger than max. line of overlap.") throw(input_error); } if (resampleinput.dbow.linehi < overlap.linelo) { PRINT_ERROR("RS_DBOW: specified max. line smaller than min. line of overlap.") throw(input_error); } if (resampleinput.dbow.pixlo > overlap.pixhi) { PRINT_ERROR("RS_DBOW: specified min. pixel larger than max. pixel of overlap.") throw(input_error); } if (resampleinput.dbow.pixhi < overlap.pixlo) { PRINT_ERROR("RS_DBOW: specified max. pixel smaller than min. pixel of overlap.") throw(input_error); } write0lines1 = overlap.linelo - resampleinput.dbow.linelo; if ( write0lines1 < 0 ) write0lines1 = 0; // smaller window selected write0linesN = -overlap.linehi + resampleinput.dbow.linehi; if ( write0linesN < 0 ) write0linesN = 0; // smaller window selected write0pixels1 = overlap.pixlo - resampleinput.dbow.pixlo; if ( write0pixels1 < 0 ) write0pixels1 = 0; // smaller window selected write0pixelsN = -overlap.pixhi + resampleinput.dbow.pixhi; if ( write0pixelsN < 0 ) write0pixelsN = 0; // smaller window selected if (resampleinput.dbow.linelo < overlap.linelo) { WARNING << "RS_DBOW: min. line < overlap (writing: " << write0lines1 << " lines with zeros before first resampled line)."; WARNING.print(); } else overlap.linelo = resampleinput.dbow.linelo; // correct it if (resampleinput.dbow.linehi > overlap.linehi) { WARNING << "RS_DBOW: max. line > overlap (writing: " << write0linesN << " lines with zeros after last resampled line)."; WARNING.print(); } else overlap.linehi = resampleinput.dbow.linehi; // correct it if (resampleinput.dbow.pixlo < overlap.pixlo) { WARNING << "RS_DBOW: min. pixel < overlap (writing: " << write0pixels1 << " columns with zeros before first resampled column)."; WARNING.print(); } else overlap.pixlo = resampleinput.dbow.pixlo; // correct it if (resampleinput.dbow.pixhi > overlap.pixhi) { WARNING << "RS_DBOW: max. pixel > overlap (writing: " << write0pixelsN << " columns with zeros after last resampled column)."; WARNING.print(); } else overlap.pixhi = resampleinput.dbow.pixhi; // correct it } // adjust overlap // ______ Buffersize output matrix ______ const int32 Npointsxsize = Npoints*sizeofcr4; // size for memcpy (fill PART) const int32 npixels = slave.currentwindow.pixels(); const real8 bytesperline = sizeofcr4 * npixels; // ___ COMMENTED OUT, OLD WAY SHIFT DATA, now shiftkernel ___ const real8 bigmatrices = 2.5; // BUFFER, RESULT & PART buffers //const int32 nlines = int32((BUFFERMEMSIZE/bigmatrices)/bytesperline); // buffer nlines const int32 nlines = int32(ceil( (BUFFERMEMSIZE/bigmatrices)/bytesperline )); // buffer nlines [MA] DEBUG << "BUFFERMEMSIZE: " << BUFFERMEMSIZE << ")"; DEBUG.print(); DEBUG << "nlines: " << nlines << ")"; DEBUG.print(); // ______ Declare/allocate matrices ______ matrix BUFFER; // load after output is written matrix RESULT(nlines,overlap.pixhi-overlap.pixlo+1); matrix SLAVE_LINE(nlines,overlap.pixhi-overlap.pixlo+1); // for output final shifts [FvL] matrix SLAVE_PIXEL(nlines,overlap.pixhi-overlap.pixlo+1); // for output final shifts [FvL] matrix PART(Npoints,Npoints); #ifdef __USE_VECLIB_LIBRARY__ matrix TMPRES(Npoints,1); int32 Np = Npoints; // must be non-constant int32 ONEint = 1; // must have pointer to 1 complr4 c4alpha(1.,0.0); complr4 c4beta(0.0,0.0); STUPID_cr4 ANS; // VECLIB struct return type #endif // ====== Open output files ====== ofstream ofile; openfstream(ofile,resampleinput.fileout,generalinput.overwrit); bk_assert(ofile,resampleinput.fileout,__FILE__,__LINE__); ofstream slavelineofile; openfstream(slavelineofile,"rsmp_orig_slave_line.raw",generalinput.overwrit); bk_assert(slavelineofile,"rsmp_orig_slave_line.raw",__FILE__,__LINE__); ofstream slavepixelofile; openfstream(slavepixelofile,"rsmp_orig_slave_pixel.raw",generalinput.overwrit); bk_assert(slavepixelofile,"rsmp_orig_slave_pixel.raw",__FILE__,__LINE__); //ofstream slavelineofile("rsmp_orig_slave_line.raw", ios::out | ios::trunc); //[FvL] //bk_assert(slavelineofile,"rsmp_orig_slave_line.raw",__FILE__,__LINE__); //ofstream slavepixelofile("rsmp_orig_slave_pixel.raw", ios::out | ios::trunc); //[FvL] //bk_assert(slavepixelofile,"rsmp_orig_slave_pixel.raw",__FILE__,__LINE__); // ________ First write zero lines if appropriate (DBOW) ______ const real4 zeror4(0); //[FvL] switch (resampleinput.oformatflag) { case FORMATCR4: { const complr4 zerocr4(0,0); for (int32 thisline=0; thisline int32(master.currentwindow.linehi)) { DEBUG << "Variable line2: [ACTUAL Value: " << line2 << " - NEW Value: " << master.currentwindow.linehi << "]"; DEBUG.print(); line2 = master.currentwindow.linehi; } // end added by don pos = (streampos)((line2-master.currentwindow.linelo)*master.currentwindow.pixels() + overlap.pixlo - master.currentwindow.pixlo); pos = (streampos)(pos * sizer8); DeltaLfile.seekg(pos,ios::beg); DeltaLfile.read((char*)&deltaL_dem,sizeof(deltaL_dem)); // [MA] sizer8 --> sizeof(deltaL_dem) if ( DeltaLfile.fail() ) { // [MA] put it to a proper class WARNING << "Failed to read position: " << pos ; // coherence will be lost in lastbuffer WARNING.print() ; // exit(1) } deltaL_poly = polyval(normalize(real4(line2),minL,maxL), normalize(real4(overlap.pixlo),minP,maxP), cpmL,degree_cpmL); real4 lastline_pixlo = (real4)(line2 + deltaL_dem + deltaL_poly + ms_az_timing_error_L); pos = (streampos)((line2-master.currentwindow.linelo)*master.currentwindow.pixels() + overlap.pixhi - master.currentwindow.pixlo); pos = (streampos)(pos * sizer8); DeltaLfile.seekg(pos,ios::beg); DeltaLfile.read((char*)&deltaL_dem,sizer8); deltaL_poly = polyval(normalize(real4(line2),minL,maxL), normalize(real4(overlap.pixhi),minP,maxP), cpmL,degree_cpmL); real4 lastline_pixhi = (real4)(line2 + deltaL_dem + deltaL_poly + ms_az_timing_error_L); firstline = int32(ceil(min(firstline_pixlo,firstline_pixhi)))-Npoints; lastline = int32(ceil(min(lastline_pixlo,lastline_pixhi)))+Npoints; } else { firstline = int32(ceil(min(line + polyval(normalize(real4(line),minL,maxL), normalize(real4(overlap.pixlo),minP,maxP), cpmL,degree_cpmL), line + polyval(normalize(real4(line),minL,maxL), normalize(real4(overlap.pixhi),minP,maxP), cpmL,degree_cpmL)))) - Npoints; int32 line2 = line + nlines - 1; lastline = int32(ceil(min(line2 + polyval(normalize(real4(line2),minL,maxL), normalize(real4(overlap.pixlo),minP,maxP), cpmL,degree_cpmL), line2 + polyval(normalize(real4(line2),minL,maxL), normalize(real4(overlap.pixhi),minP,maxP), cpmL,degree_cpmL)))) + Npoints; } //const int32 FORSURE = 25; // extend buffer by 2*FORSURE start/end int32 FORSURE = 25; // extend buffer by 2*FORSURE start/end if ( master.ovs_az > 1 && master.ovs_az < 32 ) // [MA] To avoid any extreme value in the result file. { FORSURE = FORSURE*master.ovs_az; // [MA] the value should scale with oversampling otherwise it may fail. DEBUG << "FORSURE: " << FORSURE << " extra lines before and after each buffer (oversampled)"; DEBUG.print(); } else { DEBUG << "FORSURE: " << FORSURE << " extra lines before and after each buffer (zero-looked)"; DEBUG.print(); } firstline -= FORSURE; // extend buffer lastline += FORSURE; // extend buffer // ______ Don't compare apples with pears, uint<->int! ______ if (firstline < int32(slave.currentwindow.linelo)) firstline = slave.currentwindow.linelo; if (lastline > int32(slave.currentwindow.linehi)) lastline = slave.currentwindow.linehi; // ______ Fill slave BUFFER from disk ______ window winslavefile(firstline, lastline, // part of slave loaded slave.currentwindow.pixlo, // from file in BUFFER. slave.currentwindow.pixhi); DEBUG << "Reading slave: [" << winslavefile.linelo << ":" << winslavefile.linehi << ", " << winslavefile.pixlo << ":" << winslavefile.pixhi << "]"; DEBUG.print(); BUFFER = slave.readdata(winslavefile); } // ___end: Read new slave buffer to resample outputbuffer // ====== Actual resample all pixels this output line ====== for (pixel=overlap.pixlo; pixel<=int32(overlap.pixhi); pixel++) { if (demassist) { //pos = overlap.pixels() * ( line - overlap.linelo ) + pixel - overlap.pixlo; pos = (streampos)((line-master.currentwindow.linelo)*master.currentwindow.pixels() + pixel - master.currentwindow.pixlo); pos = (streampos)(pos * sizer8); DeltaLfile.seekg(pos,ios::beg); DeltaPfile.seekg(pos,ios::beg); DeltaLfile.read((char*)&deltaL_dem,sizer8); DeltaPfile.read((char*)&deltaP_dem,sizer8); deltaL_poly = polyval(normalize(real4(line),minL,maxL), normalize(real4(pixel),minP,maxP), cpmL,degree_cpmL); deltaP_poly = polyval(normalize(real4(line),minL,maxL), normalize(real4(pixel),minP,maxP), cpmP,degree_cpmP); interpL = real4(line + deltaL_dem + deltaL_poly + ms_az_timing_error_L); interpP = real4(pixel + deltaP_dem + deltaP_poly + ms_r_timing_error_P); } else { // ______ Evaluate coregistration polynomial ______ // bk 25-10-99 why don't i do this per buffer, that's faster. (but more mem) //interpL = line + polyval(line,pixel,cpmL,degree_cpmL); // e.g. 255.35432 //interpP = pixel + polyval(line,pixel,cpmP,degree_cpmP); // e.g. 2.5232 // ______ BK USE normalized coordinates, do this smarter .... !!!! interpL = line + polyval(normalize(real4(line),minL,maxL), normalize(real4(pixel),minP,maxP), cpmL,degree_cpmL); // e.g. 255.35432 interpP = pixel + polyval(normalize(real4(line),minL,maxL), normalize(real4(pixel),minP,maxP), cpmP,degree_cpmP); // e.g. 2.5232 } // ______ Get correct lines for interpolation ______ const int32 fl_interpL = int32(interpL); const int32 fl_interpP = int32(interpP); const int32 firstL = fl_interpL - Npointsd2m1; // e.g. 254 (5 6 7) const int32 firstP = fl_interpP - Npointsd2m1; // e.g. 1 (2 3 4) const real4 interpLdec = interpL - fl_interpL; // e.g. .35432 const real4 interpPdec = interpP - fl_interpP; // e.g. .5232 // ______ Copy kernels here, change kernelL if required _ // BK 26-Oct-2002 // ______ Faster to have two kernel lookup tables ! _____ // ______ I have that now, but still make copy (slow) ______ const int32 kernelnoL = int32(interpLdec*INTERVAL+0.5); // lookup table index const int32 kernelnoP = int32(interpPdec*INTERVAL+0.5); // lookup table index matrix kernelL = (*pntKernelAz[kernelnoL]); // local copy to change const matrix kernelP = (*pntKernelRg[kernelnoP]);// local copy #ifdef __DEBUG //turn this on as default in case of seg. faults, //maybe modify... [FvL] // ______This shouldn't be possible...______ const int32 Npointsm1 = Npoints-1; if (firstL < slave.currentwindow.linelo) { WARNING.print("firstL smaller than on disk (required for interpolation). continuing"); RESULT(linecnt,pixel-overlap.pixlo) = complr4(0.,0.); continue; // with next pixel } if (firstL+Npointsm1 > slave.currentwindow.linehi) { WARNING << "lastL larger than on disk (required for interpolation). continuing" << "lineL: " << firstL+Npointsm1 << " > " << slave.currentwindow.linehi ; WARNING.print(); RESULT(linecnt,pixel-overlap.pixlo) = complr4(0.,0.); continue; // with next pixel } if (firstP < slave.currentwindow.pixlo) { WARNING.print("firstP smaller than on disk (required for interpolation). continuing"); RESULT(linecnt,pixel-overlap.pixlo) = complr4(0.,0.); continue; // with next pixel } if (firstP+Npointsm1 > slave.currentwindow.pixhi) { WARNING.print("lastP larger than on disk (required for interpolation). continuing"); RESULT(linecnt,pixel-overlap.pixlo) = complr4(0.,0.); continue; // with next pixel } #endif // ______ Shift azimuth kernel with fDC before interpolation ______ if (resampleinput.shiftazi == 1) { // ___ Doppler centroid is function of range only ____ const real4 tmp = 2.0*PI*slave.pix2fdc(interpP)/slave.prf; // ___ to shift spectrum of convolution kernel to fDC of data, multiply // ___ in the space domain with a phase trend of -2pi*t*fdc/prf // ___ (to shift back (no need) you would use +fdc), see manual; for (i=0; i thisBuffer(nofLinesBuf,RESULT.pixels()+write0pixels1+write0pixelsN); matrix thisBuffer_line(nofLinesBuf,SLAVE_LINE.pixels()+write0pixels1+write0pixelsN); matrix thisBuffer_pixel(nofLinesBuf,SLAVE_PIXEL.pixels()+write0pixels1+write0pixelsN); DEBUG << "thisBuffer pixels : " << thisBuffer.pixels() << "\n"; DEBUG << "thisBuffer lines: " << thisBuffer.lines(); DEBUG.print(); for (int32 thisline=0; thisline<=linecnt; thisline++) { //Use loop to create buffer not to write each pixel results //Write the results per line //First allocate the results to the corresponding window window windef(0,0,0,0); // default, thus copy to total matrix //The allocation window starts at 0 and ends at 0 // Starts at pixel write0pixels1 and ends at pixel RESULT.pixels()-1 //the rest are atutimatically set to zero window win1(0, 0,write0pixels1, RESULT.pixels()-1); //Allocate the corresponding line to the buffer this buffer thisBuffer.setdata(win1,RESULT.getrow(thisline),windef) ; thisBuffer_line.setdata(win1,SLAVE_LINE.getrow(thisline),windef) ; thisBuffer_pixel.setdata(win1,SLAVE_PIXEL.getrow(thisline),windef) ; //Dump data to file // ______ WRITE the interpolated data per row ______ ofile.write((char*)&thisBuffer[0][0],thisBuffer.pixels()*sizeof(thisBuffer(0,0))); slavelineofile.write((char*)&thisBuffer_line[0][0],thisBuffer_line.pixels()*sizeof(thisBuffer_line(0,0))); //[FvL] slavepixelofile.write((char*)&thisBuffer_pixel[0][0],thisBuffer_pixel.pixels()*sizeof(thisBuffer_pixel(0,0))); } break; } case FORMATCI2: { const compli16 zeroci16(0,0); compli16 castedresult; matrix thisBuffer(nofLinesBuf,RESULT.pixels()+write0pixels1+write0pixelsN); matrix thisBuffer_line(nofLinesBuf,SLAVE_LINE.pixels()+write0pixels1+write0pixelsN); matrix thisBuffer_pixel(nofLinesBuf,SLAVE_PIXEL.pixels()+write0pixels1+write0pixelsN); DEBUG << "thisBuffer pixels : " << thisBuffer.pixels() << "\n"; DEBUG << "thisBuffer lines: " << thisBuffer.lines(); DEBUG.print(); for (int32 thisline=0; thisline<=linecnt; thisline++) { //Use loop to create buffer not to write the each pixel results //Write the results per line //First allocate the results to the corresponding window window windef(0,0,0,0); // default, thus copy to total matrix window win1(0, 0,write0pixels1, RESULT.pixels()-1); //The allocation window starts at 0 and ends at 0 // Starts at pixel write0pixels1 and ends at pixel RESULT.pixels()-1 //the rest are atutimatically set to zero //Need loop for casted data for (int32 thisPx = write0pixels1; thisPx<= RESULT.pixels()-1;thisPx++) thisBuffer(0,thisPx) = cr4toci2(RESULT(thisline,thisPx-write0pixels1)); thisBuffer_line.setdata(win1,SLAVE_LINE.getrow(thisline),windef) ; thisBuffer_pixel.setdata(win1,SLAVE_PIXEL.getrow(thisline),windef) ; //Dump data to file // ______ WRITE the interpolated data per row ______ ofile.write((char*)&thisBuffer[0][0],thisBuffer.pixels()*sizeof(thisBuffer(0,0))); slavelineofile.write((char*)&thisBuffer_line[0][0],thisBuffer_line.pixels()*sizeof(thisBuffer_line(0,0))); //[FvL] slavepixelofile.write((char*)&thisBuffer_pixel[0][0],thisBuffer_pixel.pixels()*sizeof(thisBuffer_pixel(0,0))); } break; } default: PRINT_ERROR("impossible format") throw(unhandled_case_error); } // ====== Write last zero lines if appropriate (DBOW card) ====== switch (resampleinput.oformatflag) { case FORMATCR4: { complr4 zerocr4(0,0); for (int32 thisline=0; thislineapriorisigma=0.03 const real4 ACCURACY = 0.5 * (1.0/(real4(osfactor))); // but we need coreg accuracy of 0.1 pixel about. therefore use a priori // based on experience here, and different for azimuth and range // this also helps our automated outlier detection and testing hopefully. // BK 15-Apr-2003 // if the image is oversampled, then still use orig spacing real4 SIGMAL = 0.15/master.ovs_az;// sigma in orig pixels real4 SIGMAP = 0.10/master.ovs_rg;// seems range direction is better??? INFO.print("Using a smaller sigma in range, because it seems that can be estimated better"); INFO << "a priori std.dev offset vectors line direction [samples]: " << SIGMAL; INFO.print(); INFO << "a priori std.dev offset vectors pixel direction [samples]: " << SIGMAP; INFO.print(); // ______ Find #points > threshold ______ matrix Data = getofffile(i_resfile, THRESHOLD); // ______ Data contains the following: ______ // Data(i,0) = winnumber; Data(i,1) = posL; Data(i,2) = posP; // Data(i,3) = offL; Data(i,4) = offP; Data(i,5) = corr; int32 ITERATION = 0; int32 DONE = 0; // sqr: level significance: alpha=0.001; power of test: gamma=0.80 //real4 CRIT_VALUE = sqrt(3.29); INFO << "Critical value for outlier test: " << CRIT_VALUE; INFO.print(); uint winL = 0;// window number to be removed uint winP = 0;// window number of largest w -test in range matrix eL_hat; matrix eP_hat; matrix wtestL; matrix wtestP; matrix rhsL; matrix rhsP; matrix Qx_hat; real8 maxdev = 0.0; real8 overallmodeltestL = 0.0; real8 overallmodeltestP = 0.0; real8 maxwL; real8 maxwP; register int32 i,j,k,index; while (DONE != 1) { DEBUG << "Start iteration " << ITERATION; DEBUG.print(); // ______ Remove identified outlier from previous estimation ______ if (ITERATION != 0) { matrix tmp_DATA = Data; //(remove_observation_i,*); Data.resize(Data.lines()-1, Data.pixels()); j = 0;// counter over reduced obs.vector for (i=0; i threshold if (Nobs < Nunk) { PRINT_ERROR("ms_timing_error: Number of windows > threshold is smaller than parameters solved for.") throw(input_error); } // ______Set up system of equations______ // ______Order unknowns: A00 A10 A01 A20 A11 A02 A30 A21 A12 A03 for degree=3______ matrix yL(Nobs,1); // observation matrix yP(Nobs,1); // observation matrix A(Nobs,Nunk); // designmatrix matrix Qy_1(Nobs,1); // a priori covariance matrix (diag) // ______ Normalize data for polynomial ______ DEBUG << "ms_timing_error: polynomial normalized by factors: " << minL << " " << maxL << " " << minP << " " << maxP << " to [-2,2]"; DEBUG.print(); // ______Fill matrices______ DEBUG.print("Setting up design matrix for LS adjustment"); for (i=0; i N = matTxmat(A,diagxmat(Qy_1,A)); rhsL = matTxmat(A,diagxmat(Qy_1,yL)); rhsP = matTxmat(A,diagxmat(Qy_1,yP)); Qx_hat = N; // ______Compute solution______ choles(Qx_hat); // Cholesky factorisation normalmatrix solvechol(Qx_hat,rhsL); // Solution unknowns in rhs solvechol(Qx_hat,rhsP); // Solution unknowns in rhs invertchol(Qx_hat); // Covariance matrix of unknowns // ______Test inverse______ for (i=0; i .001) { WARNING << "ms_timing_error: maximum deviation N*inv(N) from unity = " << maxdev << ". This is between 0.01 and 0.001"; WARNING.print(); } // ______Some other stuff, scale is ok______ matrix Qy_hat = A * (matxmatT(Qx_hat,A)); matrix yL_hat = A * rhsL; matrix yP_hat = A * rhsP; eL_hat = yL - yL_hat; eP_hat = yP - yP_hat; matrix Qe_hat = -Qy_hat; for (i=0; i wtestsum = sqr(wtestL)+sqr(wtestP);// (Nobs,1) real8 maxwsum = max(wtestsum,winL,dumm);// idx to remove DEBUG << "Detected outlier: summed sqr.wtest = " << maxwsum << "; observation: " << winL << "; window number: " << Data(winL,0); DEBUG.print(); // ______ Test if we are done yet ______ if (Nobs <= Nunk) { WARNING.print("NO redundancy! Exiting iterations."); DONE = 1;// cannot remove more than this } // seems something fishy here..., b-method of testing delft // if (max(overallmodeltestL,overallmodeltestP) < 1.0) // { // INFO.print("OMTs accepted, not iterating anymore (final solution reached)."); // DONE = 1;// ok (?). // } if (max(maxwL,maxwP) <= CRIT_VALUE)// all tests accepted? { INFO.print("All outlier tests accepted! (final solution computed)"); DONE = 1;// yeah! } if (ITERATION >= MAX_ITERATIONS) { INFO.print("max. number of iterations reached (exiting loop)."); DONE = 1;// we reached max. (or no max_iter specified) } // ______ Only warn if last iteration has been done ______ if (DONE == 1) { // ___ use trace buffer to store string, remember to rewind it ___ if (overallmodeltestL > 10) { WARNING << "ms_timing_error: overallmodeltest Lines = " << overallmodeltestL << ends; WARNING.print(); WARNING << " is larger than 10. (Suggest model or a priori sigma not correct.)"; WARNING.print(); } // ___ use trace buffer to store string, remember to rewind it ___ if (overallmodeltestP > 10) { WARNING << "ms_timing_error: overallmodeltest Pixels = " << overallmodeltestP; WARNING.print(); WARNING << " is larger than 10.\n(suggests a priori sigma not correct.)"; WARNING.print(); } }// Only warn when done iterating. ITERATION++;// update counter here! }// iterations remove outliers // Calculate master-slave timing errors int32 ms_az_timing_error_L = coarse_orbit_offsetL-int32(rint(rhsL(0,0))); int32 ms_r_timing_error_P = coarse_orbit_offsetP-int32(rint(rhsP(0,0))); real8 ms_az_timing_error = real8(ms_az_timing_error_L)/master.prf; real8 ms_r_timing_error = real8(ms_r_timing_error_P)/master.rsr2x; INFO << "Orbit azimuth offset (master-slave): " << coarse_orbit_offsetL << " lines."; INFO.print(); INFO << "Orbit range offset (master-slave): " << coarse_orbit_offsetP << " pixels."; INFO.print(); INFO << "Estimated azimuth offset (master-slave): " << rhsL(0,0) << " lines."; INFO.print(); INFO << "Estimated range offset (master-slave): " << rhsP(0,0) << " pixels."; INFO.print(); INFO << "Estimated azimuth timing error (master-slave): " << ms_az_timing_error_L << " lines."; INFO.print(); INFO << "Estimated range timing error (master-slave): " << ms_r_timing_error_P << " pixels."; INFO.print(); INFO << "Estimated azimuth timing error (master-slave) [sec]: " << ms_az_timing_error << " sec."; INFO.print(); INFO << "Estimated range timing error (master-slave) [sec]: " << ms_r_timing_error << " sec."; INFO.print(); // ______ Write to tmp files ______ ofstream scratchlogfile("scratchlogtiming", ios::out | ios::trunc); bk_assert(scratchlogfile,"timing: scratchlogtiming",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* RELATIVE_TIMING_ERROR" << "\n*******************************************************************" << "\nOrbit_azimuth_offset (master-slave): \t" << coarse_orbit_offsetL << " lines." << "\nOrbit_range_offset (master-slave): \t" << coarse_orbit_offsetP << " pixels." << "\nEstimated_azimuth_offset (master-slave): " << rhsL(0,0) << " lines." << "\nEstimated_range_offset (master-slave): " << rhsP(0,0) << " pixels." << "\nEstimated_azimuth_timing_error_lines (master-slave): " << ms_az_timing_error_L << " lines." << "\nEstimated_range_timing_error_pixels (master-slave): " << ms_r_timing_error_P << " pixels." << "\nEstimated_azimuth_timing_error_sec (master-slave): " << ms_az_timing_error << " sec." << "\nEstimated_range_timing_error_sec (master-slave): " << ms_r_timing_error << " sec." << "\n*******************************************************************\n"; scratchlogfile.close(); ofstream scratchresfile("scratchrestiming", ios::out | ios::trunc); bk_assert(scratchresfile,"timing: scratchrestiming",__FILE__,__LINE__); scratchresfile.setf(ios::right, ios::adjustfield); scratchresfile << "\n\n*******************************************************************" << "\n*_Start_" << processcontrol[pr_i_timing] << "\n*******************************************************************" << "\nOrbit_azimuth_offset (master-slave): \t" << coarse_orbit_offsetL << " lines." << "\nOrbit_range_offset (master-slave): \t" << coarse_orbit_offsetP << " pixels." << "\nEstimated_azimuth_offset (master-slave): " << rhsL(0,0) << " lines." << "\nEstimated_range_offset (master-slave): " << rhsP(0,0) << " pixels." << "\nEstimated_azimuth_timing_error_lines (master-slave): " << ms_az_timing_error_L << " lines." << "\nEstimated_range_timing_error_pixels (master-slave): " << ms_r_timing_error_P << " pixels." << "\nEstimated_azimuth_timing_error_sec (master-slave): " << ms_az_timing_error << " sec." << "\nEstimated_range_timing_error_sec (master-slave): " << ms_r_timing_error << " sec." << "\n*******************************************************************" << "\n* End_" << processcontrol[pr_i_timing] << "_NORMAL" << "\n*******************************************************************\n"; // ====== Tidy up ====== scratchresfile.close(); PROGRESS.print("Finished computation of master-slave timing error."); } // END rel_timing_error Doris-5.0.3Beta/doris_core/coregistration.hh000077500000000000000000000204561312547014700211160ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/coregistration.hh,v $ * $Revision: 3.13 $ * $Date: 2005/08/24 10:03:18 $ * $Author: kampes $ * * Routines for coregistration. ****************************************************************/ #ifndef COREGISTRATION_H #define COREGISTRATION_H using namespace std; // BK 29-Mar-2003, new compiler? // Jia defined this for compilation under windows // Bert Kampes, 24-Aug-2005 #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "constants.hh" // typedefs #include "readinput.hh" // input structs #include "orbitbk.hh" // my orbit class, includes my matrix class #include "slcimage.hh" // my slc image class #include "productinfo.hh" // my 'products' class #include "bk_baseline.hh" // my 'baseline' class // ______ Prototypes ______ #ifdef __USE_VECLIB_LIBRARY__ // ______This typedef is needed for output of veclib routine cdot?______ typedef struct {real4 re,im;} STUPID_cr4; extern "C" { void cgemv (char*, int32*, int32*, complr4*, complr4*, int32*, complr4*, int32*, complr4*, complr4*, int32*, int32); } extern "C" { STUPID_cr4 cdotu (int32*, complr4*, int32*, complr4*, int32*); } #endif // ====== Prototypes ====== // ______ Compute coarse coregistration ______ void coarseporbit( const input_ell &ell, const slcimage &master, const slcimage &slave, orbit &masterorbit, orbit &slaveorbit, const BASELINE &baseline); // ______ Coarse coregistration ______ void coarsecorrel( const input_coarsecorr &input, const slcimage &minfo, const slcimage &sinfo); // ______ Corr by fft ______ void coarsecorrelfft( const input_coarsecorr &input, const slcimage &minfo, const slcimage &sinfo); // ______ Sim. Amplitude coregistration (magspace) ______ void mtiming_correl( // const input_coarsecorr &input, const input_mtiming &input, const slcimage &minfo, // master const productinfo &sinfo); // simulated amplitude // ______ Sim. Amplitude coregistration (magfft) ______ void mtiming_correlfft( const input_mtiming &input, const slcimage &minfo, const productinfo &sinfo); // ______ Corr by fft ______ // superseded by coherencefft with factor=1 //real4 corrfft( // const matrix &magnitudeMaster, // const matrix &magnitudeMask, // real4 &offsetL, // real4 &offsetP); // ______ Distribute nW windows over win ______ //matrix distributepoints( // [FvL] for correct folding of points outside overlap window when inserted by file matrix distributepoints( real4 numberofpoints, const window &win); // ______ Estimate offset based on consistency ______ void getoffset( const matrix &Result,// not sorted on output int32 &offsetLines, int32 &offsetPixels); // ______ Estimate offset based on consistency ______ void getmodeoffset( const matrix &Result,// not sorted on output int32 &offsetLines, int32 &offsetPixels); // ______ Fine coregistration ______ //void finecoreg( // const input_fine &fineinput, // const slcimage &minfo, // const slcimage &sinfo); void finecoreg( const input_fine &fineinput, const slcimage &minfo, const slcimage &sinfo, const input_ell &ell, orbit &masterorbit, // cannot be const for spline orbit &slaveorbit, // cannot be const for spline const BASELINE &baseline); // ______ Correlation with FFT MCC______ real4 coherencefft( const matrix &Master, const matrix &Mask, const int32 factor, // ovs factor (1 for not) const int32 AccL, // search window to oversample const int32 AccP, // search window to oversample real4 &offsetL, real4 &offsetP); // ______ Correlation with FFT ______ real4 crosscorrelate( const matrix &Master, const matrix &Mask, const int32 factor, // ovs factor (1 for not) const int32 AccL, // search window to oversample const int32 AccP, // search window to oversample real4 &offsetL, real4 &offsetP); // ______ Correlation with FFT ______ real4 intensity( const matrix &Master, const matrix &Mask, const int32 factor, // ovs factor (1 for not) const int32 AccL, // search window to oversample const int32 AccP, // search window to oversample real4 &offsetL, real4 &offsetP); // ______ Correlation in space domain ______ real4 coherencespace( const input_fine &fineinput, const matrix &Master, const matrix &Mask, real4 &offsetL, real4 &offsetP); // ______ Compute coregistration parameters ______ // const window &originalmaster, void coregpm( const slcimage &master, const slcimage &slave, //[FvL] const char *i_resfile, const input_coregpm &coregpminput, const int16 &demassist); //[FvL] //const uint oversamplingsfactor); // ______ Read observations from file ______ matrix getofffile( const char *file, real4 threshold); // ______ Resample slave ______ void resample( const input_gen &generalinput, const input_resample &resampleinput, const slcimage &master, const slcimage &slave, const matrix &cpmL, const matrix &cpmP, const int16 &demassist, const matrix &minMaxL,//[MCC] const matrix &minMaxP);//[MCC] // ______ Compute master-slave timing error ______ void ms_timing_error( const slcimage &master, const char *i_resfile, const input_reltiming &timinginput, int32 &coarse_orbit_offsetL, int32 &coarse_orbit_offsetP); // ______Interpolation kernals______ matrix cc4(const matrix &x); matrix cc6(const matrix &x); matrix ts6(const matrix &x); matrix ts8(const matrix &x); matrix ts16(const matrix &x); matrix rect(const matrix &x); matrix tri(const matrix &x); // ___ knab: oversampling factor of signal CHI, number of points N ___ matrix knab(const matrix &x, const real4 CHI, const int32 N); // ___ raised cosine: oversampling factor of signal CHI, number of points N ___ matrix rc_kernel(const matrix &x, const real4 CHI, const int32 N); #endif // COREGISTRATION_H Doris-5.0.3Beta/doris_core/estorbit.cc000066400000000000000000002563721312547014700177100ustar00rootroot00000000000000#include "constants.hh" #include "ioroutines.hh" #include "orbitbk.hh" #include "slcimage.hh" #include "productinfo.hh" #include "exceptions.hh" #include "bk_baseline.hh" #include "coregistration.hh" #include "estorbit.hh" #include #include #include #include #include /**************************************************************** * estorbits * * * * estimate baseline error polynomials in horizontal (Bh) and * * vertical (Bv) baseline. If d is the polynomial degree, the * * output (coeff) is a 2*(d+1) x 1 vector containing the * * following baseline error coefficients: * * * * (dBh0;dBh1;...;dBv0;dBv1;...) * * * * Hermann Baehr, 17-Mar-2011 * ****************************************************************/ void estorbits(const input_estorbits &estorbitsinput, const input_gen &generalinput, const input_ell &ellips, const slcimage &master, const slcimage &slave, orbit &masterorbit, orbit &slaveorbit, const productinfo &interferogram, const productinfo &coherence, const BASELINE &baseline) { TRACE_FUNCTION("estorbits (HB 17-Mar-2011)"); // ______ check if cutout windows of interferogram and coherence image are congruent ______ if (!(specified(estorbitsinput.ifpositions) && estorbitsinput.weighting==eo_noweighting && estorbitsinput.threshold==0)) if (interferogram.win.linelo != coherence.win.linelo || interferogram.win.pixlo != coherence.win.pixlo || int(interferogram.win.lines()/interferogram.multilookL) != int(coherence.win.lines()/coherence.multilookL) || int(interferogram.win.pixels()/interferogram.multilookP) != int(coherence.win.pixels()/coherence.multilookP) || interferogram.multilookL != coherence.multilookL || interferogram.multilookP != coherence.multilookP) // direct comparison of the two windows is not possible, since linehi or pixhi // might differ although lines() and pixels() are the same. { ERROR << "Interferogram and coherence image are not congruent " << "(same cutout window, same multilook factors), which is required " << "for step ESTORBITS." << endl << "Int: ln(" << interferogram.win.linelo << "," << interferogram.win.linehi << "), px(" << interferogram.win.pixlo << "," << interferogram.win.pixhi << "), size(" << interferogram.multilookL << "," << interferogram.multilookP << ")" << endl << "Coh : ln(" << coherence.win.linelo << "," << coherence.win.linehi << "), px(" << coherence.win.pixlo << "," << coherence.win.pixhi << "), size(" << coherence.multilookL << "," << coherence.multilookP << ")" << endl; PRINT_ERROR(ERROR.get_str()) throw(some_error); } const real4 meanLine = (master.currentwindow.linelo+master.currentwindow.linehi)/2; const real4 meanPix = (master.currentwindow.pixlo+master.currentwindow.pixhi)/2; const int16 degree = estorbitsinput.poldegree; // degree of polynomial to be estimated const int16 npar = 2*(degree+1); // number of parameters in polynomial (*2 for Bh and Bv) real8 theta; // mean look angle matrix Bh, Bv, Bpar, Bperp; // baseline parameters // ______ choose reference ______ const slcimage *reference; orbit *referenceorbit; if (specified(estorbitsinput.reforbitfile)) { slcimage *tempptr = new slcimage(); (*tempptr).fillslcimage(estorbitsinput.reforbitfile); reference = tempptr; referenceorbit = new orbit(); (*referenceorbit).set_interp_method(generalinput.orb_interp); (*referenceorbit).initialize(estorbitsinput.reforbitfile); INFO << "Using reference orbit from file: " << estorbitsinput.reforbitfile; INFO.print(); } else { INFO.print("Using master orbit as reference orbit."); reference = &master; referenceorbit = &masterorbit; } // ______ read observation data ______ observationdata obs(estorbitsinput,generalinput,ellips,&master,&slave,reference, &masterorbit,&slaveorbit,referenceorbit,interferogram,coherence); // ______ check estimability and compute redundancy ______ uint minimum_number_of_obs = npar+1; if (estorbitsinput.method==eo_gridsearch) minimum_number_of_obs -= estorbitsinput.constraints.lines(); // For the sake of an easier implementation, estimability of the unconstrained solution // is required for method LSQ, even if the solution is constrained. if (obs.nUsed() " << estorbitsinput.threshold << "."; ERROR.print(); ERROR << "At least " << minimum_number_of_obs << " observations are required."; ERROR.print(); throw(unhandled_case_error); } int32 redundancy = obs.nUsed()-npar-1+estorbitsinput.constraints.lines(); // "minus one" for the eliminated constant phase shift parameter DEBUG << "Initial redundancy: " << redundancy; DEBUG.print(); real4 averageredundancy = real4(redundancy)/obs.nUsed(); DEBUG << "Average redundancy number per observation (0...1): " << setprecision(8) << averageredundancy; DEBUG.print(); if (averageredundancy<0.5) WARNING.print("Reliability of estimates is questionable due to poor redundancy."); // ====== frist output to logfile ====== ofstream scratchlogfile("scratchlogestorbit", ios::out | ios::trunc); bk_assert(scratchlogfile,"estorbit: scratchlogestorbit",__FILE__,__LINE__); scratchlogfile.setf(ios_base::fixed); scratchlogfile << "\n\n*******************************************************************" << "\n* ORBIT ERROR ESTIMATION" << "\n*******************************************************************" << "\nMethod: "; switch (estorbitsinput.method) { case eo_lsq: scratchlogfile << "Least Squares Adjustment"; break; case eo_gridsearch: scratchlogfile << "Gridsearch"; break; } scratchlogfile << "\nPolynomial degree: " << estorbitsinput.poldegree << "\nConstraints: "; if (estorbitsinput.constrained) for (uint i=0; ioriginalwindow.lines()-1) * reference->prf; const real8 dBperp_one_fringe = -(master.wavelength+slave.wavelength)/4/deltaTheta; const real8 timeOfAcquisition = (master.currentwindow.lines()-1)/master.prf;; const real8 dBparRate_one_fringe = -(master.wavelength+slave.wavelength)/4/timeOfAcquisition; // ====== setup normal equations, compute mean theta ====== matrix NEQ(npar+1,npar+1); // bordered normal equation matrix [A'*P*A , A'*P*y ; y'*P*A , y'*P*y] matrix NEQc(npar+1,npar+1); // bordered normal equation matrix after Cholesky decomposition matrix Qxx(npar,npar); // cofactor matrix of estimated polynomial coefficients matrix schreibersums(1,npar+1); // columnsums of [A,l] matrix rhs(npar,1); // estimated polynomial coefficients ("right hand side") real8 weightsum=0; // sum of al weights NEQ = 0; schreibersums = 0; // ______ stack normal equations ______ for (uint i=0; i Ai = obs.lineOfDesignMatrix(i,observationdata::DESIGN_EXTENDED); NEQ += obs.getWeight(i) * matTxmat(Ai,Ai); schreibersums += obs.getWeight(i) * Ai; weightsum += obs.getWeight(i); } NEQ -= matTxmat(schreibersums,schreibersums)/weightsum; // apply Schreiber's sum equation // This accounts for constant phase shift parameter phi_0. // ______ compute mean theta ______ if (redundancy-int32(estorbitsinput.constraints.lines()) >= 0) // estimability of unconstrained solution required for determination of theta { // invert normal equation matrix and compute mean theta from the eigenspaces rhs = NEQ.getdata(window(0,npar-1,npar,npar)); NEQc = NEQ; choles(NEQc); Qxx = NEQc.getdata(window(0,npar-1,0,npar-1)); solvechol(Qxx, rhs); invertchol(Qxx); repairMatrix(Qxx); theta = getEigenTheta(Qxx); } else { // define theta as the look angle to the scene centre cn M, P; M = masterorbit.getxyz(master.line2ta(meanLine)); lp2xyz(meanLine,meanPix,ellips,master,masterorbit,P); theta = acos((-M.normalize()).in((P-M).normalize())); } // ====== method GRIDSEARCH ====== if (estorbitsinput.method==eo_gridsearch) { PROGRESS.print("Selected method: GRIDSEARCH."); // some empirical parameters for iterative refinement of search space const uint numberOfIterations = 6; real4 step[numberOfIterations] = {0.8,0.2,0.05,0.02,0.008,0.003}; // gridwidth [fringes] uint zoom[numberOfIterations-1] = {7,10,2,2,2}; // define initial searchspace real4 dBparRateUpperBound = abs(estorbitsinput.maxfringesaz*dBparRate_one_fringe)/rateConversion; real4 dBperpUpperBound = abs(estorbitsinput.maxfringesrg*dBperp_one_fringe); real4 dBparRateLowerBound = -dBparRateUpperBound; real4 dBperpLowerBound = -dBperpUpperBound; // some parameters for reliability assessment real4 maxGamma; // maximum coherence value real4 ratioOfTwoHighestMaxima; real4 distanceOfTwoHighestMaxima; // [fringes] // ______ initialisation ______ Bpar = matrix(2,1); Bpar = 0; Bperp = matrix(2,1); Bperp = 0; matrix T(4,2); T = 0; T(0,1) = cos(theta); T(1,0) = sin(theta); T(2,1) = sin(theta); T(3,0) = -cos(theta); // ====== iteration loop ====== for (uint it=0;;it++) { PROGRESS << "Iteration " << it+1 << " of 6."; PROGRESS.print(); real4 dBparRateStep = step[it]*abs(dBparRate_one_fringe)/rateConversion; real4 dBperpStep = step[it]*abs(dBperp_one_fringe); uint n1 = ceil((dBparRateUpperBound-dBparRateLowerBound)/dBparRateStep)+1; uint n2 = ceil((dBperpUpperBound-dBperpLowerBound)/dBperpStep)+1; real4 dBparRateGrid[n1], dBperpGrid[n2]; matrix GAMMA(n1,n2); // ______ initialise search grid ______ GAMMA=0; dBparRateGrid[0] = dBparRateLowerBound; dBperpGrid[0] = dBperpLowerBound; for (uint i=1;i Ai = obs.lineOfDesignMatrix(i,observationdata::DESIGN_NORMAL); Ai -= schreibersums.getdata(window(0,0,0,npar-1)) / weightsum; Ai = Ai*T; for (uint i1=0;i1 x(2,1); x(0,0) = dBparRateGrid[i1]; for (uint i2=0;i2 GAMMAabs(n1,n2); for (uint i1=0;i1=n1 || max2b>=n2 || GAMMAabs(max1b,max2b)==-1) { ratioOfTwoHighestMaxima = NaN; distanceOfTwoHighestMaxima = NaN; break; } if ( (max1b>0 && max2b>0 && GAMMAabs(max1b-1,max2b-1)==-1) || (max1b>0 && GAMMAabs(max1b-1,max2b)==-1) || (max1b>0 && max2b<(n2-1) && GAMMAabs(max1b-1,max2b+1)==-1) || (max2b>0 && GAMMAabs(max1b,max2b-1)==-1) || (max2b<(n2-1) && GAMMAabs(max1b,max2b+1)==-1) || (max1b<(n1-1) && max2b>0 && GAMMAabs(max1b+1,max2b-1)==-1) || (max1b<(n1-1) && GAMMAabs(max1b+1,max2b)==-1) || (max1b<(n1-1) && max2b<(n2-1) && GAMMAabs(max1b+1,max2b+1)==-1) ) GAMMAabs(max1b,max2b) = -1; else { ratioOfTwoHighestMaxima = maxGAMMA/GAMMAabs(max1b,max2b); distanceOfTwoHighestMaxima = (abs(int(max1-max1b))+abs(int(max2-max2b)))*step[it]; // [fringes] INFO << "Ratio of highest and second-highest local maximum: " << ratioOfTwoHighestMaxima; INFO.print(); if (ratioOfTwoHighestMaxima<1.5) WARNING.print("No distinct local maximum found (ratio<1.5). There is a high chance of unreliable estimates."); break; } } } // ______ refine search space ______ if (it==numberOfIterations-1) break; dBparRateUpperBound = Bpar(1,0) + zoom[it] * step[it] * abs(dBparRate_one_fringe) / rateConversion; dBperpUpperBound = Bperp(0,0) + zoom[it] * step[it] * abs(dBperp_one_fringe); dBparRateLowerBound = 2*Bpar(1,0) - dBparRateUpperBound; dBperpLowerBound = 2*Bperp(0,0) - dBperpUpperBound; } if (strcmp(estorbitsinput.foresiduals," ")) // output if filename has been specified by EO_RESIDUALS writeResiduals(estorbitsinput,obs); // ______ convert (Bpar1,Bperp) -> (Bh0,Bh1,Bv0,Bv1) ______ Bh = matrix(2,1); Bh(0,0) = cos(theta)*Bperp(0,0); Bh(1,0) = sin(theta)*Bpar(1,0); Bv = matrix(2,1); Bv(0,0) = sin(theta)*Bperp(0,0); Bv(1,0) = -cos(theta)*Bpar(1,0); // ====== second output to logfile (gridsearch) ====== scratchlogfile << "\nSearchspace in azimuth [fringes]: " << estorbitsinput.maxfringesaz << "\nSearchspace in range [fringes]: " << estorbitsinput.maxfringesrg << "\nOrbit coherence maximum (gridsearch) " << setprecision(3) << maxGamma << "\nRatio of two highest local maxima: " << setprecision(3) << ratioOfTwoHighestMaxima << "\nDistance of 2 highest maxima [fringes]: " << setprecision(1) << distanceOfTwoHighestMaxima; // ______ write baseline error parameters ______ scratchlogfile.precision(8); scratchlogfile.width(13); scratchlogfile << "\n\nEstimated coefficients:\n" << "\ndBh_hat\n"; for (uint i=0; i<=degree; i++) { if (Bh(i,0) >= 0.) scratchlogfile << " "; scratchlogfile << Bh(i,0) << endl; } scratchlogfile << "\ndBv_hat\n"; for (uint i=0; i<=degree; i++) { if (Bv(i,0) >= 0.) scratchlogfile << " "; scratchlogfile << Bv(i,0) << endl; } scratchlogfile << "\ndBpar_hat\n"; for (uint i=0; i<=degree; i++) { if (Bpar(i,0) >= 0.) scratchlogfile << " "; scratchlogfile << Bpar(i,0) << endl; } scratchlogfile << "\ndBperp_hat\n"; for (uint i=0; i<=degree; i++) { if (Bperp(i,0) >= 0.) scratchlogfile << " "; scratchlogfile << Bperp(i,0) << endl; } } // END iteration loop // ====== method LSQ ====== else { PROGRESS.print("Selected method: LSQ."); if (estorbitsinput.constrained) constrainSolution(Qxx,rhs,estorbitsinput.constraints); // ______ compute residuals and iterate for outlier removal ______ uint iteration=0, iTmax; real8 Omega=0; // ______ intitial computation of Omega (weighted sum of squared residuals) ______ for (uint i=0; i Ai = obs.lineOfDesignMatrix(i,observationdata::DESIGN_NORMAL); Ai -= schreibersums.getdata(window(0,0,0,npar-1)) / weightsum; matrix vi = Ai*rhs; obs.setRes(i, vi(0,0)-(obs(i)-schreibersums(0,npar)/weightsum)); Omega += obs.getRes(i)*obs.getWeight(i)*obs.getRes(i); } // ______ prepare logfile for data snooping ______ scratchlogfile << "\n\nData snooping, rejected observations:\n" << "\n__line _pixel residual ____test" << endl; // ====== data snooping loop (iterative outlier detection and rejection) ====== real4 Tmax; while (true) { Tmax = 0; // ______ computation of residuals, redundancy numbers and tests ______ for (uint i=0; i Ai = obs.lineOfDesignMatrix(i,observationdata::DESIGN_NORMAL); Ai -= schreibersums.getdata(window(0,0,0,npar-1)) / weightsum; matrix vi = Ai*rhs; obs.setRes(i, vi(0,0)-(obs(i)-schreibersums(0,npar)/weightsum)); real8 qvivi = 1/obs.getWeight(i)-matxmatT(Ai*Qxx,Ai)[0][0]; real8 redund = qvivi * obs.getWeight(i); real8 sigma_test_sqr = (Omega-obs.getRes(i)*obs.getRes(i)/qvivi)/(redundancy-1); obs.setT(i, obs.getRes(i)/sqrt(sigma_test_sqr*qvivi)); if (abs(obs.getT(i))>abs(Tmax)) { Tmax = obs.getT(i); iTmax = i; } } // ______ check if residuals have been computed correctly ______ if (!estorbitsinput.constrained) { DEBUG << "sigma from residuals: " << setprecision(15) << sqrt(Omega/redundancy); DEBUG.print(); DEBUG << "sigma from cholesky: " << setprecision(15) << NEQc(npar,npar)/sqrt(real8(redundancy)); DEBUG.print(); } // ______ check if more iterations are required ______ if (iteration==estorbitsinput.maxiter || redundancy==0) { PROGRESS << "Maximum number of iterations reached." << ends; PROGRESS.print(); break; } else if (abs(obs.getT(iTmax)) Ai = obs.lineOfDesignMatrix(iTmax,observationdata::DESIGN_EXTENDED); NEQ += matTxmat(schreibersums,schreibersums)/weightsum; NEQ -= obs.getWeight(iTmax) * matTxmat(Ai,Ai); schreibersums -= obs.getWeight(iTmax) * Ai; weightsum -= obs.getWeight(iTmax); NEQ -= matTxmat(schreibersums,schreibersums)/weightsum; Omega -= obs.getRes(iTmax)*obs.getWeight(iTmax)*obs.getRes(iTmax); redundancy--; // ______ report rejection to logfile ______ scratchlogfile << setw(6) << setprecision(0) << obs.getLine(iTmax)+1 << " " << setw(6) << setprecision(0) << obs.getPixel(iTmax)+1 << " " << setw(8) << setprecision(3) << obs.getRes(iTmax) << " " << setw(8) << setprecision(3) << obs.getT(iTmax) << " " << endl; DEBUG << "Iteration " << ++iteration << ", rejecting (l,p)=(" << obs.getLine(iTmax)+1 << "," << obs.getPixel(iTmax)+1 << "), T=" << setprecision(4) << obs.getT(iTmax) << ", v=" << setprecision(4) << obs.getRes(iTmax) << ends; DEBUG.print(); if (iteration%100==0) { PROGRESS << "Outlier rejection, iteration " << setw(3) << iteration << " of max. " << estorbitsinput.maxiter << "."; PROGRESS.print(); } // ______ re-estimation with updated normal equations ______ rhs = NEQ.getdata(window(0,npar-1,npar,npar)); NEQc = NEQ; choles(NEQc); Qxx = NEQc.getdata(window(0,npar-1,0,npar-1)); solvechol(Qxx, rhs); invertchol(Qxx); repairMatrix(Qxx); theta = getEigenTheta(Qxx); if (estorbitsinput.constrained) constrainSolution(Qxx,rhs,estorbitsinput.constraints); } // END data snooping loop if (strcmp(estorbitsinput.foresiduals," ")) // output if filename has been specified by EO_RESIDUALS writeResiduals(estorbitsinput,obs); // ______ compute baseline components ______ Bh = rhs.getdata(window(0,degree,0,0)); Bv = rhs.getdata(window(degree+1,npar-1,0,0)); Bpar = Bh * sin(theta) - Bv * cos(theta); Bperp = Bh * cos(theta) + Bv * sin(theta); // ______ error propagation for (par,perp) baseline components ______ matrix Rot(npar,npar); for (uint i=0; i<=degree; i++) { uint i2 = i + degree + 1; Rot(i ,i ) = sin(theta); Rot(i ,i2) = -cos(theta); Rot(i2, i) = cos(theta); Rot(i2,i2) = sin(theta); } matrix Qpp = matxmatT(Rot*Qxx, Rot); // ====== second output to logfile (lsq) ====== real8 sigma = sqrt(Omega/redundancy); scratchlogfile << "\nRejected observation pixels: " << iteration << "\nObservation pixels finally used: " << obs.nUsed() << "\nRedundancy: " << redundancy << "\nMaximum test: " << setprecision(2) << abs(Tmax) << "\nCritical value: " << setprecision(2) << estorbitsinput.k_alpha << "\nEstimated phase standard deviation " << setprecision(3) << sigma; // ______ write baseline error parameters and standard deviations ______ scratchlogfile.precision(8); scratchlogfile.width(13); scratchlogfile << "\n\nEstimated coefficients:\n" << "\ndBh_hat \tstd.\n"; for (uint i=0; i<=degree; i++) { if (Bh(i,0) >= 0.) scratchlogfile << " "; scratchlogfile << Bh(i,0) << " \t" << sigma*sqrt(Qxx(i,i)) << endl; } scratchlogfile << "\ndBv_hat \tstd.\n"; for (uint i=0; i<=degree; i++) { uint i2 = i + degree + 1; if (Bv(i,0) >= 0.) scratchlogfile << " "; scratchlogfile << Bv(i,0) << " \t" << sigma*sqrt(Qxx(i2,i2)) << endl; } scratchlogfile << "\ndBpar_hat \tstd.\n"; for (uint i=0; i<=degree; i++) { if (Bpar(i,0) >= 0.) scratchlogfile << " "; scratchlogfile << Bpar(i,0) << " \t" << sigma*sqrt(Qpp(i,i)) << endl; } scratchlogfile << "\ndBperp_hat \tstd.\n"; for (uint i=0; i<=degree; i++) { uint i2 = i + degree + 1; if (Bperp(i,0) >= 0.) scratchlogfile << " "; scratchlogfile << Bperp(i,0) << " \t" << sigma*sqrt(Qpp(i2,i2)) << endl; } // ______ write covariance matrix of baseline error parameters ______ scratchlogfile << "\nCovariance matrix of estimated parameters (h/v):" << "\n------------------------------------------------\n" << setiosflags(ios_base::scientific); real8 sigma2 = sigma*sigma; for (uint i=0; i= 0.) scratchresfile << " "; scratchresfile << Bh(i,0) << endl; } scratchresfile << "\nEstimated_coefficients_vertical:\n"; for (uint i=0; i<=degree; i++) { if (Bv(i,0) >= 0.) scratchresfile << " "; scratchresfile << Bv(i,0) << endl; } scratchresfile << "\nEstimated_coefficients_parallel:\n"; for (uint i=0; i<=degree; i++) { if (Bpar(i,0) >= 0.) scratchresfile << " "; scratchresfile << Bpar(i,0) << endl; } scratchresfile << "\nEstimated_coefficients_perpendicular:\n"; for (uint i=0; i<=degree; i++) { if (Bperp(i,0) >= 0.) scratchresfile << " "; scratchresfile << Bperp(i,0) << endl; } scratchresfile << "*******************************************************************" << "\n* End_" << processcontrol[pr_i_estorbits] << "_NORMAL" << "\n*******************************************************************\n"; scratchresfile.close(); // ====== final output to logfile ====== scratchlogfile << "\nMean look angle [deg]: " << setprecision(4) << rad2deg(theta) << "\nEstimated error in azimuth [fringes]: " << setprecision(1) << Bpar(1,0)/dBparRate_one_fringe*rateConversion << "\nEstimated error in range [fringes]: " << setprecision(1) << Bperp(0,0)/dBperp_one_fringe << "\ndBpar/dt conversion factor to m/s: " << setprecision(8) << rateConversion << "\ndBpar/dt equ. one fringe in azimuth: " << setprecision(5) << dBparRate_one_fringe/rateConversion << "\ndBpar/dt equ. one fringe in az. [m/s]: " << setprecision(5) << dBparRate_one_fringe << "\ndBperp equ. one fringe in range [m]: " << setprecision(3) << dBperp_one_fringe << endl << "\nUse_the_following_cards_to_correct_for_the_estimated_orbit_error___" << "\nPROCESS M_MORBITS"; for (uint i=0; i<=degree; i++) scratchlogfile << "\nM_MO_DBH" << setw(1) << i << " " << setprecision(8) << -Bh(i,0)/2; for (uint i=0; i<=degree; i++) scratchlogfile << "\nM_MO_DBV" << setw(1) << i << " " << setprecision(8) << -Bv(i,0)/2; if (specified(estorbitsinput.reforbitfile)) scratchlogfile << "\nM_MO_REFORBIT " << estorbitsinput.reforbitfile; scratchlogfile << "\nPROCESS S_MORBITS"; for (uint i=0; i<=degree; i++) scratchlogfile << "\nS_MO_DBH" << setw(1) << i << " " << setprecision(8) << Bh(i,0)/2; for (uint i=0; i<=degree; i++) scratchlogfile << "\nS_MO_DBV" << setw(1) << i << " " << setprecision(8) << Bv(i,0)/2; if (specified(estorbitsinput.reforbitfile)) scratchlogfile << "\nS_MO_REFORBIT " << estorbitsinput.reforbitfile; scratchlogfile << "\n*******************************************************************\n"; scratchlogfile.close(); PROGRESS.print("Orbit estimation finished."); // ====== dump data if requested ====== if (specified(estorbitsinput.foobsdata)) { PROGRESS << "Dumping observation data to file: " << estorbitsinput.foobsdata << "."; PROGRESS.print(); ofstream outfile; outfile.open(estorbitsinput.foobsdata, ios::out); bk_assert(outfile,"estorbits: dump data file",__FILE__,__LINE__); outfile.setf(ios::fixed); const uint cen_lin = (master.currentwindow.linelo+master.currentwindow.linehi)/2; const uint cen_pix = (master.currentwindow.pixlo +master.currentwindow.pixhi) /2; outfile << "method " << setprecision(1) << (estorbitsinput.method==eo_lsq ? "LSQ" : "GRIDSEARCH") << "\ndBpar1 " << setprecision(5) << Bpar(1,0) << "\ndBperp0 " << setprecision(4) << Bperp(0,0) << "\nBperp " << setprecision(1) << baseline.get_bperp(cen_lin,cen_pix,0) << "\nBtemp " << setprecision(0) << Btemp(master.utc1,slave.utc1) << "\nwavelength_master " << setprecision(7) << master.wavelength << "\nwavelength_slave " << setprecision(7) << slave.wavelength << "\nrange_bandwidth_master " << setprecision(0) << master.rbw << "\nrange_bandwidth_slave " << setprecision(0) << slave.rbw << "\nmean_range " << setprecision(0) << SOL*master.pix2tr(cen_pix) << "\nmean_incidence_angle " << setprecision(6) << rad2deg(baseline.get_theta_inc(cen_lin,cen_pix,0)) << "\nconv_Bpar1 " << setprecision(8) << rateConversion << "\ndBpar1_onefringe " << setprecision(6) << dBparRate_one_fringe << "\ndBperp_onefringe " << setprecision(4) << dBperp_one_fringe << "\nnumber_of_observations " << setprecision(0) << obs.nUsed() << "\n*******************************************************************" << "****************************************" << "\n__line _pixel ___tAzi__ _____ahm_____ _____avm_____ _____ahs_____" << " _____avs_____ ____weight___ ____phase____"; for (uint i=0; i Ai = obs.lineOfDesignMatrix(i,observationdata::DESIGN_DUMP); outfile << endl << resetiosflags(ios_base::scientific) << setiosflags(ios_base::fixed) << setw( 6) << setprecision(0) << obs.getLine(i)+1 << " " << setw( 6) << setprecision(0) << obs.getPixel(i)+1 << " " << setw( 9) << setprecision(6) << Ai(0,0) << " " << resetiosflags(ios_base::fixed) << setiosflags(ios_base::scientific) << setw(13) << setprecision(6) << Ai(0,1) << " " << setw(13) << setprecision(6) << Ai(0,2) << " " << setw(13) << setprecision(6) << Ai(0,3) << " " << setw(13) << setprecision(6) << Ai(0,4) << " " << setw(13) << setprecision(6) << obs.getWeight(i) << " " << setw(13) << setprecision(6) << obs(i); } } outfile.close(); } // ______ tidy up ______ if (specified(estorbitsinput.reforbitfile)) delete reference, referenceorbit; } // END estorbits /**************************************************************** * modifyOrbits * * * * Modify orbits according to baseline correction coefficients. * * * * Hermann Baehr, 17-Mar-2011 * ****************************************************************/ void modifyOrbits(const input_morbits &morbitsinput, const input_gen &generalinput, const int16 FILEID, const input_ell &ellips, const slcimage &image, const slcimage &masterimage, orbit &thisorbit, orbit &masterorbit) { TRACE_FUNCTION("modifyOrbits (HB 17-Mar-2011)"); // ______ some settings ______ const int precision_time = 8; // decimal places in the resultfile const int precision_coo = 4; // decimal places in the resultfile const int precision_vel = 6; // probably too many digits ??? // ______ choose reference ______ const slcimage *referenceimage; orbit *referenceorbit; if (specified(morbitsinput.reforbitfile)) { slcimage *tempptr = new slcimage(); (*tempptr).fillslcimage(morbitsinput.reforbitfile); referenceimage = tempptr; referenceorbit = new orbit(); (*referenceorbit).set_interp_method(generalinput.orb_interp); (*referenceorbit).initialize(morbitsinput.reforbitfile); INFO << "Using reference orbit from file: " << morbitsinput.reforbitfile; INFO.print(); } else { INFO.print("Using master orbit as reference orbit."); referenceimage = &masterimage; referenceorbit = &masterorbit; } // ______ apply modification to orbit and dump to outfile ______ real8 azoffset = getAzOffset(ellips,*referenceimage,image,*referenceorbit,thisorbit); const real8 tshift = -image.t_azi1 + referenceimage->t_azi1 - azoffset; const real8 tmin = referenceimage->t_azi1; const real8 tmax = referenceimage->t_azi1 + (referenceimage->originalwindow.lines()-1)/referenceimage->prf; matrix datapoints = thisorbit.modify(morbitsinput.coeff,*referenceorbit, tshift,tmin,tmax); // ______ output to file ______ ofstream outfile("scratchdatapoints", ios::out | ios::trunc); // do replace bk_assert(outfile,"modifyOrbits: scratchdatapoints",__FILE__,__LINE__); outfile << "\n\n*******************************************************************" << "\n*_Start_"; if (FILEID==MASTERID) outfile << processcontrol[pr_m_morbits]; else if (FILEID==SLAVEID) outfile << processcontrol[pr_s_morbits]; outfile << "\n*******************************************************************" << "\nt(s)\t\tX(m)\t\tY(m)\t\tZ(m)"; if (datapoints.pixels()==7) outfile << "\t\tX_V(m/s)\t\tY_V(m/s)\t\tZ_V(m/s)"; outfile << "\nNUMBER_OF_DATAPOINTS: \t\t\t" << thisorbit.npoints() << endl; outfile.setf(ios_base::fixed); outfile.setf(ios_base::showpoint); for (uint i=0; i &M) { TRACE_FUNCTION("repairMatrix (HB 17-Mar-2011)"); for (uint i=0; i &Q) { TRACE_FUNCTION("getEigenTheta (HB 17-Mar-2011)"); int16 index1 = 0; int16 index2 = Q.lines()/2; real8 trace = Q(index1,index1) + Q(index2,index2); real8 det = Q(index1,index1) * Q(index2,index2) - Q(index1,index2) * Q(index2,index1); real8 lambda1 = trace/2 + sqrt((trace*trace)/4-det); real8 theta = atan(Q(index1,index2)/(Q(index1,index1)-lambda1)); // ______ if available average theta derived from constant and linear component ______ if (Q.lines()>=4) { index1++; index2++; trace = Q(index1,index1) + Q(index2,index2); det = Q(index1,index1) * Q(index2,index2) - Q(index1,index2) * Q(index2,index1); lambda1 = trace/2 + sqrt((trace*trace)/4-det); theta = 0.5*(theta + atan(Q(index1,index2)/(Q(index1,index1)-lambda1))+PI/2); } return theta; } // END getEigenTheta /**************************************************************** * constrainSolution * * * * apply constraints to estimated orbit error parameters and * * their covariance matrix. * * * * parameters: * * - npar x npar covariance matrix * * - npar x 1 parameter vector (Bh0,Bh1,...,Bv0,Bv1,...) * * - constraints-array (see definition of struct * * input_estorbits in readinput.hh for explanation) * * * * Hermann Baehr, 17-Mar-2011 * ****************************************************************/ void constrainSolution(matrix &Qxx, matrix &rhs, const matrix &constraints) { uint nc = constraints.lines(); uint npar = rhs.lines(); uint degree = npar/2-1; matrix R(nc,npar); // coefficient matrix for constraints matrix Qww(nc,nc); // cofactor matrix of misclosures matrix Proj(npar,npar); // projector applied to solution real8 theta = getEigenTheta(Qxx); // ______ setup coefficient matrix for constraints ______ R = 0; for (uint i=0; i corresponding master line number. * * - slave acquisition starts before master acquisition. * * - the first few slave lines do not overlap with master. * * * * Hermann Baehr, 17-Mar-2011 * ****************************************************************/ real8 getAzOffset(const input_ell &ellips, const slcimage &master, const slcimage &slave, orbit &masterorbit, orbit &slaveorbit) { const uint cen_pix = (slave.currentwindow.pixlo +slave.currentwindow.pixhi)/2; cn P; real8 tAzi, tRg; lp2xyz(1,cen_pix,ellips,slave,slaveorbit,P); xyz2t(tAzi,tRg,master,masterorbit,P); return master.t_azi1-tAzi; } // END getAzOffset /**************************************************************** * observationdata::observationdata * * * * Reads interferometric phases, coherence estimates and * * and heights from file (bufferwise), selects observations, * * computes weights and stores all necessary information in * * private class members. * * * * Hermann Baehr, 17-Mar-2011 * ****************************************************************/ observationdata::observationdata(const input_estorbits &estorbitsinput, const input_gen &generalinput, const input_ell &ellips, const slcimage *master, const slcimage *slave, const slcimage *reference, orbit *masterorbit, orbit *slaveorbit, orbit *referenceorbit, const productinfo &interferogram, const productinfo &coherence) : ellips(ellips), master(master), slave(slave), masterorbit(masterorbit), slaveorbit(slaveorbit), referenceorbit(referenceorbit), useheights(specified(estorbitsinput.fiheightmap)), degree(estorbitsinput.poldegree), interferogram(interferogram), npar(2*(estorbitsinput.poldegree+1)), tmin(reference->t_azi1), tmax(tmin+(reference->originalwindow.lines()-1)/reference->prf) { TRACE_FUNCTION("observationdata::observationdata (HB 17-Mar-2011)"); const uint GRIDBORDER = 50; // define a band of 50 (non-multilooked) pixels at both near // range and far range from where no pixels are used as observations. In ERS-SLC are some- // times processing-artefacts in these regions. Don't know about other sensors, but anyway, // discarding these small borders does not downgrade estimation quality significantly. const uint ifgLines = uint(interferogram.win.lines() /interferogram.multilookL); const uint ifgPixels = uint(interferogram.win.pixels()/interferogram.multilookP); const uint border = ceil(real4(GRIDBORDER)/interferogram.multilookP); // ______ compute azimuth timing offset ______ azoffset = getAzOffset(ellips,*reference,*master,*referenceorbit,*masterorbit); t_start = tmin - azoffset; DEBUG << "Azimuth timing offset w. r. t. reference orbit: " << azoffset; DEBUG.print(); // ______ reading of coherence image required? ______ bool readcoherence = true; if (specified(estorbitsinput.ifpositions) && estorbitsinput.weighting==eo_noweighting && estorbitsinput.threshold==0) readcoherence = false; // ______ determine buffersize, check file format of ifg. ______ uint numberofbigimages = 2; // 1 for ifg, +1 for the small stuff if (interferogram.formatflag == FORMATCR4) numberofbigimages += 2; else if (!(interferogram.formatflag == FORMATR4)) { ERROR << interferogram.file << " must be real4 or complr4."; ERROR.print(); throw(unhandled_case_error); } if (readcoherence) { numberofbigimages++; if (coherence.formatflag == FORMATCR4) numberofbigimages += 2; else if (!(coherence.formatflag == FORMATR4)) { ERROR << coherence.file << " must be real4 or complr4."; ERROR.print(); throw(unhandled_case_error); } } if (useheights) numberofbigimages++; uint bufferlines = generalinput.memory/ifgPixels/4/numberofbigimages; // ______ read positions from file or select from the cells of a grid ______ bool readposfromfile; if (specified(estorbitsinput.ifpositions)) { readposfromfile = true; gridsize = 0; gridlines = 0; gridpixels = 0; maxobs = estorbitsinput.nobs; } else { readposfromfile = false; gridsize = floor(sqrt(ifgLines*ifgPixels/estorbitsinput.nobs)); gridlines = ceil(ifgLines/real4(gridsize)); gridpixels = ceil((ifgPixels-border)/real4(gridsize)); maxobs = gridlines*gridpixels; bufferlines = (bufferlines/gridsize)*gridsize; // integer division! } // ______ check buffersize ______ if (bufferlines>ifgLines) bufferlines = ifgLines; else if (bufferlines<1) { PRINT_ERROR("Please increase memory (MEMORY card) or decrease multiL (INT_MULTILOOK card).") throw(input_error); } const uint nbuffers = ceil(ifgLines/real4(bufferlines)); // ______ initialise storage matrices ______ line = matrix(maxobs,1); pixel = matrix(maxobs,1); phi = matrix(maxobs,1); weight = matrix(maxobs,1); if (useheights) height = matrix(maxobs,1); // ______ read positions from file EO_IN_POS ______ if (readposfromfile) { ifstream ifpos; char dummyline[ONE27]; openfstream(ifpos,estorbitsinput.ifpositions); bk_assert(ifpos,estorbitsinput.ifpositions,__FILE__,__LINE__); PROGRESS << "Reading positions of observations from file: " << estorbitsinput.ifpositions; PROGRESS.print(); uint ll,pp; for (uint i=0; i> ll >> pp; if (ll<1 || pp<1 || ll>ifgLines || pp>ifgPixels) { ERROR << "Pixel location (" << ll << "," << pp << ") is outside the multilooked crop. "; ERROR.print(); throw(unhandled_case_error); } line(i,0) = uint(ll)-1; pixel(i,0) = uint(pp)-1; ifpos.getline(dummyline,ONE27,'\n'); } ifpos.close(); // ______ Check last point ivm.EOL after last position in file ______ if (line(maxobs-1,0) == line(maxobs-2,0) && pixel(maxobs-1,0) == pixel(maxobs-2,0)) { maxobs--; WARNING << "EO: there should be no EOL after last point in file: " << estorbitsinput.ifpositions; WARNING.print(); } DEBUG << maxobs << " positions read from file " << estorbitsinput.ifpositions; DEBUG.print(); } // ______ open files with ifg, coherence and height ______ ifstream ifint, ifcoh, ifheight; openfstream(ifint,interferogram.file); bk_assert(ifint,interferogram.file,__FILE__,__LINE__); if (readcoherence) { openfstream(ifcoh,coherence.file); bk_assert(ifcoh,coherence.file,__FILE__,__LINE__); cerr << coherence.file << endl; } else DEBUG.print("Coherence image will not be read, since values are not required.."); if (useheights) { openfstream(ifheight,estorbitsinput.fiheightmap); bk_assert(ifheight,estorbitsinput.fiheightmap,__FILE__,__LINE__); } else { INFO.print("No DEM specified with EO_IN_DEM_LP."); INFO.print("Assuming flat topography for orbit error estimation."); } // ====== read data bufferwise ====== PROGRESS << "Reading image data in " << nbuffers << " buffer(s)."; PROGRESS.print(); nobs = 0; uint linesdone = 0; uint restlines = ifgLines; for (uint buf=0; buf=bufferlines) linesInThisBuffer=bufferlines; else linesInThisBuffer=restlines; DEBUG << "Reading buffer " << buf+1 << ", (multilooked) lines " << linesdone+1 << " to " << linesdone+linesInThisBuffer+1 << "."; DEBUG.print(); matrix INT, COH, HEIGHT; if (interferogram.formatflag == FORMATR4) { INT = matrix(linesInThisBuffer,ifgPixels); ifint >> INT; } else { matrix CINT(linesInThisBuffer,ifgPixels); ifint >> CINT; INT = angle(CINT); } if (readcoherence) { if (coherence.formatflag == FORMATR4) { COH = matrix(linesInThisBuffer,ifgPixels); ifcoh >> COH; } else { matrix CCOH(linesInThisBuffer,ifgPixels); ifcoh >> CCOH; COH = matrix(linesInThisBuffer,ifgPixels); for (register uint l=0; l(linesInThisBuffer,ifgPixels); ifheight >> HEIGHT; } // ______ either use positions from file ______ if (readposfromfile) { uint lmax = linesdone + bufferlines; for (uint i=0; i=linesdone && line(i,0)maxcoh) { maxcoh = COH(l,p); maxcoh_l = l; maxcoh_p = p; } } if (maxcoh>=estorbitsinput.threshold) { phi(nobs,0) = INT(maxcoh_l,maxcoh_p); weight(nobs,0) = COH(maxcoh_l,maxcoh_p); if (useheights) height(nobs,0) = HEIGHT(maxcoh_l,maxcoh_p); line(nobs,0) = linesdone+maxcoh_l; pixel(nobs,0) = maxcoh_p; nobs++; } } } } linesdone += bufferlines; restlines -= bufferlines; } // END buffer-loop ifint.close(); ifcoh.close(); ifheight.close(); INFO << nobs << " of " << maxobs << " pixel observations have coherence >= " << estorbitsinput.threshold << "."; INFO.print(); if (nobs0) { if (nobs != maxobs) { phi = phi.getdata(window(0,nobs-1,0,0)); weight = weight.getdata(window(0,nobs-1,0,0)); if (useheights) height = height.getdata(window(0,nobs-1,0,0)); line = line.getdata(window(0,nobs-1,0,0)); pixel = pixel.getdata(window(0,nobs-1,0,0)); } use = matrix(nobs,1); use = true; residual = matrix(nobs,1); test = matrix(nobs,1); } } // END observationdata::observationdata /**************************************************************** * observationdata::lineOfDesignMatrix * * * * compute design matrix coefficients for specific observation. * * . * * input: * * - index of the observation * * - output version, defined by one of three constants: * * * * DESIGN_NORMAL: (ah0,ah1,...,av0,av1) * * DESIGN_EXTENDED: (ah0,ah1,...,av0,av1,phi) * * DESIGN_DUMP: (tAzi,-ah0m,-av0m,ah0s,av0s) * * * * tAzi: azimuth time normalised to [-2,2] * * ah0: coefficient for Bh, averaged for master and slave * * ah1: tAzi*ah0 * * av0: coefficient for Bv, averaged for master and slave * * av1: tAzi*av0 * * ah0m: coefficient for Bh, computed for master * * avm0: coefficient for Bv, computed for master * * ah0m: coefficient for Bh, computed for slave * * avm0: coefficient for Bv, computed for slave * * * * Hermann Baehr, 17-Mar-2011 * ****************************************************************/ matrix observationdata::lineOfDesignMatrix(const uint index,int16 version) { TRACE_FUNCTION("observationdata::lineOfDesignMatrix (HB 17-Mar-2011)"); // ______ compute non-multilooked line/pixel and azimuth time ______ cn er, ea, ex; real8 ln = interferogram.win.linelo - .5 + (2.*line(index,0)+1)*interferogram.multilookL/2.; real8 tAzi = t_start + (ln-1)/master->prf; getCoordinateFrame(ea,er,ex,tAzi,*referenceorbit); real8 px = interferogram.win.pixlo -0.5 + (2.*pixel(index,0)+1)*interferogram.multilookP/2.; tAzi = normalize(tAzi,tmin,tmax); // normalise tAzi now for later use // ______ consider terrain height ______ input_ell ELLIPS = ellips; if (useheights) { ELLIPS.a += height(index,0); ELLIPS.b += height(index,0); } // ______ find corresponding pos. on master orbit (M), slave orbit (S) and surface (P) ______ cn M, S, P; M = (*masterorbit).getxyz(master->t_azi1+(ln-1)/master->prf); // compute point on master orbit lp2xyz(ln, px, ELLIPS, *master, *masterorbit, P); // find corresponding surface point xyz2orb(S, *slave, *slaveorbit, P); // find point on slave orbit // ______ initialise Ai ______ matrix Ai; switch (version) { case DESIGN_NORMAL : Ai = matrix(1,npar); break; case DESIGN_EXTENDED: Ai = matrix(1,npar+1); break; case DESIGN_DUMP : Ai = matrix(1,5); break; } // ______ fill Ai ______ switch (version) { case DESIGN_NORMAL: case DESIGN_EXTENDED: { // compute coefficients cn R_scaled = ( (P-M).normalize()/master->wavelength + (P-S).normalize()/slave->wavelength) *2*PI; real8 ah = -R_scaled.in(ex); // coefficient for horizontal baseline component real8 av = -R_scaled.in(er); // coefficient for vertical baseine component // setup line of design matrix for (uint i=0; i<=degree; i++) { Ai(0,i) = ah; Ai(0,degree+1+i) = av; } for (uint i=1; i<=degree; i++) for (uint j=i; j<=degree; j++) { Ai(0,j) *= tAzi; Ai(0,degree+1+j) *= tAzi; } if (version==DESIGN_EXTENDED) Ai(0,npar) = real8(phi(index,0)); } break; case DESIGN_DUMP: cn P_M_norm = (M-P).normalize(); cn P_S_norm = (S-P).normalize(); Ai(0,0) = tAzi; // normalised azimuth time Ai(0,1) = -4*PI/master->wavelength * P_M_norm.in(ex); // across track coefficient for master Ai(0,2) = -4*PI/master->wavelength * P_M_norm.in(er); // radial coefficient for master Ai(0,3) = 4*PI/slave->wavelength * P_S_norm.in(ex); // across track coefficient for slave Ai(0,4) = 4*PI/slave->wavelength * P_S_norm.in(er); // radial coefficient for slave break; } return Ai; } // END observationdata::lineOfDesignMatrix /**************************************************************** * writeResiduals * * * * Write some information on individual observation pixels to * * file. . * * * * Hermann Baehr, 17-Mar-2011 * ****************************************************************/ void writeResiduals(const input_estorbits &estorbitsinput, const observationdata &obs) { ofstream resdata(estorbitsinput.foresiduals, ios::out | ios::trunc); bk_assert(resdata,"estorbits: foresiduals",__FILE__,__LINE__); if (estorbitsinput.method==eo_lsq) resdata << "This file contains residuals from orbit error" << "\nestimation. There are seven columns with: observation" << "\nnumber, line (multilooked), pixel (multilooked)," << "\nphase [rad], weight, residual [rad], test." << "\n number posLm posPm phase weight residual test" << "\n------------------------------------------------------\n"; else if (estorbitsinput.method==eo_gridsearch) resdata << "This file contains residuals from orbit error" << "\nestimation. There are five columns with: observation" << "\nnumber, line (multilooked), pixel (multilooked)," << "\nphase [rad], weight." << "\n number posLm posPm phase weight" << "\n------------------------------------------------------\n"; resdata.close(); FILE *resfile; resfile = fopen(estorbitsinput.foresiduals,"a"); if (estorbitsinput.method==eo_lsq) { for (uint i=0; i line; // multilooked line numbers of observations matrix pixel; // multilooked pixel number os observations matrix phi; // observed interferometric phases matrix weight; matrix height; // interpolated DEM height matrix use; // if false, observation has been rejected by outlier test (LSQ only) matrix residual; matrix test; // outlier test (t-test) uint nobs; // current number of used observations, not counting rejected ones uint maxobs; // theoretical number of observations, ignoring thresholding by EO_THRESHOLD const uint degree; // degree of orbit error polynomial const uint npar; // number of parameters, is: 2*(degree+1) uint gridsize; // size of cells of the grid defined for selection of observagtions uint gridlines; // total number of rows of this grid in azimuth uint gridpixels; // total number of columns of this grid in range const bool useheights; // true if DEM is specified and used, otherwise height is not initialised real8 azoffset; // time offset of master w. r. t. reference acquisition (EO_REFORBIT) const real8 tmin; // acquisition start time of reference acquisition (used for normalisation) const real8 tmax; // acquisition end time of reference acquisition (used for normalisation) real8 t_start; // acquisition start time w. r. t. start time of reference acquisition const input_ell ellips; const slcimage *master; const slcimage *slave; orbit *masterorbit; orbit *slaveorbit; orbit *referenceorbit; const productinfo interferogram; public: observationdata(const input_estorbits &estorbitinput, const input_gen &generalinput, const input_ell &ellips, const slcimage *master, const slcimage *slave, const slcimage *reference, orbit *masterorbit, orbit *slaveorbit, orbit *referenceorbit, const productinfo &interferogram, const productinfo &coherence); // constants needed for lineOfDesignMatrix static const int16 DESIGN_NORMAL=0; static const int16 DESIGN_EXTENDED=1; static const int16 DESIGN_DUMP=2; matrix lineOfDesignMatrix(const uint index, int16 version); uint nRequested() const {return maxobs;}; uint nInit() const {return phi.lines();}; uint nUsed() const {return nobs;}; real8 operator () (const uint i) const {return phi(i,0);}; real8 getWeight(const uint i) const {return weight(i,0);}; // real8 necessary? void reweight(const uint i, const real4 newWeight) {weight(i,0) = newWeight;}; void setRes(const uint i, const real8 v) {residual(i,0) = v;}; real8 getRes(const uint i) const {return residual(i,0);}; uint getLine(const uint i) const {return line(i,0);}; uint getPixel(const uint i) const {return pixel(i,0);}; void reject(const uint i) {use(i,0) = false; nobs--;}; bool isUsed(const uint i) const {return use(i,0);}; void setT(const uint i, const real4 T) {test(i,0) = T;}; real4 getT(const uint i) const {return test(i,0);}; real4 getHeight(const uint i) const {return useheights ? height(i,0) : 0;}; uint getGridSize() const {return gridsize;}; uint getGridLines() const {return gridlines;}; uint getGridPixels() const {return gridpixels;}; }; void repairMatrix(matrix &M); real8 getEigenTheta(const matrix &Q); void constrainSolution(matrix &Qxx, matrix &rhs, const matrix &constraints); void readOrbitDataPoints(const char resfile[], matrix &data); real8 getAzOffset(const input_ell &ellips, const slcimage &master, const slcimage &slave, orbit &masterorbit, orbit &slaveorbit); void writeResiduals(const input_estorbits &estorbitsinput, const observationdata &obs); #endif // ESTORB_H Doris-5.0.3Beta/doris_core/exceptions.cc000077500000000000000000000121631312547014700202250ustar00rootroot00000000000000/* @file excpetions.cc exception handling for Doris InSAR processor @brief exception handling for Doris InSAR processor */ /* * Copyright (c) 1999-2005 Bert Kampes * Copyright (c) 1999-2005 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ #include // function signal() #include // cerr #include // exit [MA] #include "exceptions.hh" // class // ====== Globals to throw everywhere, e.g., throw(some_error) ====== SOME_ERROR some_error;// can be thrown from all programs INPUT_ERROR input_error;// can be thrown from all programs FILE_ERROR file_error;// can be thrown from all programs MEMORY_ERROR memory_error;// can be thrown from all programs UNHANDLED_CASE_ERROR unhandled_case_error;// can be thrown from all programs ARGUMENT_ERROR argument_error;// can be thrown from all programs KEYWORD_ERROR keyword_error;// can be thrown from all programs USAGE_ERROR usage_error;// can be thrown from all programs // TODO: SLiu above not required see end of exceptions.hh /********************************************************************* * @brief exception handler for floating point exception *********************************************************************/ /* function: CatchSignals() * ------------------------ * Traps common signals that by default cause the program to abort. * Sets (pointer to function) Handler as the signal handler for all. * Note that SIGKILL usually cannot be caught. No return value. */ // following is from snaphu: void CatchSignals(void (*SigHandler)(int)){ #ifndef WIN32 signal(SIGHUP,SigHandler);// Hang-up signal signal(SIGQUIT,SigHandler); signal(SIGPIPE,SigHandler); signal(SIGALRM,SigHandler); signal(SIGBUS,SigHandler); #endif signal(SIGINT,SigHandler); signal(SIGILL,SigHandler); signal(SIGABRT,SigHandler); signal(SIGFPE,SigHandler);// floating point exception signal(SIGSEGV,SigHandler);// segmentation fault: introduces when compiled with -O in gcc4? signal(SIGTERM,SigHandler); } // following is based on snaphu code: but needs some work. /* function: SetDump() * ------------------- * Set the global variable dumpresults_global to TRUE if SIGINT or SIGHUP * signals recieved. Also sets requestedstop_global if SIGINT signal * received. This function should only be called via signal() when * a signal is caught. */ void handle_signal(int signum) { switch (signum) { #ifndef WIN32 case SIGHUP: cout << "Caught SIGHUP: Hang-up signal." << endl; cerr << "Caught SIGHUP: Hang-up signal." << endl; break; case SIGQUIT: cout << "Caught SIGQUIT: Quit signal." << endl; cerr << "Caught SIGQUIT: Quit signal." << endl; break; case SIGPIPE: cout << "Caught SIGPIPE: ? signal." << endl; cerr << "Caught SIGPIPE: ? signal." << endl; break; case SIGALRM: cout << "Caught SIGALRM: Alarm signal." << endl; cerr << "Caught SIGALRM: Alarm signal." << endl; break; case SIGBUS: cout << "Caught SIGBUS: Bus error (accessing memory incorrectly)?" << endl; cerr << "Caught SIGBUS: Bus error (accessing memory incorrectly)?" << endl; break; #endif case SIGINT: cout << "Caught SIGINT: User interupt signal." << endl; cerr << "Caught SIGINT: User interupt signal." << endl; exit(1); break; case SIGFPE: cout << "Caught SIGFPE: floating point exception, zero division, etc." << endl; cerr << "Caught SIGFPE: floating point exception, zero division, etc." << endl; break; case SIGILL: cout << "Caught SIGILL: ? signal." << endl; cerr << "Caught SIGILL: ? signal." << endl; break; case SIGABRT: cout << "Caught SIGABRT: Abort signal." << endl; cerr << "Caught SIGABRT: Abort signal." << endl; break; case SIGSEGV: cout << "Caught SIGSEGV: Segmentation fault." << endl; cerr << "Caught SIGSEGV: Segmentation fault." << endl; exit(1); break; case SIGTERM: cout << "Caught SIGTERM: ? signal." << endl; cerr << "Caught SIGTERM: ? signal." << endl; break; default: cout << "Caught an unknown signal. Signum = " << signum << endl; cerr << "Caught an unknown signal. Signum = " << signum << endl; } } Doris-5.0.3Beta/doris_core/exceptions.hh000077500000000000000000000156301312547014700202410ustar00rootroot00000000000000/* @file excpetions.hh exception handling for Doris InSAR processor @brief exception handling for Doris InSAR processor */ /* * Copyright (c) 1999-2005 Bert Kampes * Copyright (c) 1999-2005 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ #ifndef EXCEPTIONS_H #define EXCEPTIONS_H using namespace std; // BK 29-Mar-2003, new compiler? // TODO SLiu see constants.hh // Jia defined this for compilation under windows // Bert Kampes, 24-Aug-2005 #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include // function signal() #include // strcpy /********************************************************************* * @brief exception handler for floating point exception *********************************************************************/ void CatchSignals(void (*SigHandler)(int)); void handle_signal(int signum); /********************************************************************* * @brief exception handler class *********************************************************************/ // #include "exceptions.hh" // this file.. // int main( // int argc, // char* argv[]) // { // // ___ catch math errors ___ // CatchSignals(handle_signal); // // try // --- start trying ----------------- // { // code... // if (error) throw(some_error);// object // if (error) throw("sasas");// string // } // }// --- end of try block; now catch thrown exceptions ------------- // catch(EXCEPTION& error)// catch errors of EXCEPTION class // { // cerr << "i caught an error!" << endl; // cerr << "i think: " << (const char*)error << endl; // exit(1); // } // catch(const char* error_string)// catch handled errors // { // cerr << "i caught an error_string!" << endl; // cerr << "it is: " << error_string << endl; // exit(2); // } // catch(...) // catches other errors // { // cerr << "i caught an unhandled error!" << endl; // exit(3); // } // // cout << "\n\nNormal termination.\nThank you for using Doris.\n\n"; // return int(0); // } // END main // ______ Base class for all error exceptions that can be caught ______ class EXCEPTION { public: EXCEPTION() {}; virtual ~EXCEPTION() {}; operator const char*() const {return(get_error_string());}; // virtual operator const char*() const {return(get_error_string());}; // suggested by SLiu virtual const char* get_error_string() const {return("generic error");}; }; // ______ Now all errors follow ______ // ______ some error ______ class SOME_ERROR : public EXCEPTION { private: char err_str[64]; public: SOME_ERROR() {strcpy(err_str,"specific error");}; virtual ~SOME_ERROR() {}; operator const char*() const {return(get_error_string());}; // overloading, why? virtual const char* get_error_string() const {return(err_str);}; }; // ______ some input error ______ class INPUT_ERROR : public EXCEPTION { private: char err_str[64];// make part of base class? public: INPUT_ERROR() {strcpy(err_str,"input error");}; virtual ~INPUT_ERROR() {}; operator const char*() const {return(get_error_string());}; virtual const char* get_error_string() const {return(err_str);}; }; // ______ some file error ______ class FILE_ERROR : public EXCEPTION { private: char err_str[64];// make part of base class? public: FILE_ERROR() {strcpy(err_str,"file error");}; virtual ~FILE_ERROR() {}; operator const char*() const {return(get_error_string());}; virtual const char* get_error_string() const {return(err_str);}; }; // ______ memory error ______ class MEMORY_ERROR : public EXCEPTION { private: char err_str[64];// make part of base class? public: MEMORY_ERROR() {strcpy(err_str,"memory error");}; virtual ~MEMORY_ERROR() {}; operator const char*() const {return(get_error_string());}; virtual const char* get_error_string() const {return(err_str);}; }; // ______ unhandled case error ______ class UNHANDLED_CASE_ERROR : public EXCEPTION { private: char err_str[64];// make part of base class? public: UNHANDLED_CASE_ERROR() {strcpy(err_str,"unhandled case error");}; virtual ~UNHANDLED_CASE_ERROR() {}; operator const char*() const {return(get_error_string());}; virtual const char* get_error_string() const {return(err_str);}; }; // ______ unhandled case error ______ class ARGUMENT_ERROR : public EXCEPTION { private: char err_str[64];// make part of base class? public: ARGUMENT_ERROR() {strcpy(err_str,"wrong input argument(s) to function");}; virtual ~ARGUMENT_ERROR() {}; operator const char*() const {return(get_error_string());}; virtual const char* get_error_string() const {return(err_str);}; }; // ______ keyword error ______ class KEYWORD_ERROR : public EXCEPTION { private: char err_str[64];// make part of base class? public: KEYWORD_ERROR() {strcpy(err_str,"incorrect keyword");}; virtual ~KEYWORD_ERROR() {}; operator const char*() const {return(get_error_string());}; virtual const char* get_error_string() const {return(err_str);}; }; // ______ usage request error ______ class USAGE_ERROR : public EXCEPTION { private: char err_str[64];// make part of base class? public: USAGE_ERROR() {strcpy(err_str,"done");}; virtual ~USAGE_ERROR() {}; operator const char*() const {return(get_error_string());}; virtual const char* get_error_string() const {return(err_str);}; }; // ====== Globals to throw everywhere, e.g., throw(some_error) ====== extern SOME_ERROR some_error;// can be thrown from all programs extern INPUT_ERROR input_error;// can be thrown from all programs extern FILE_ERROR file_error;// can be thrown from all programs extern MEMORY_ERROR memory_error;// can be thrown from all programs extern UNHANDLED_CASE_ERROR unhandled_case_error;// can be thrown from all programs extern ARGUMENT_ERROR argument_error;// can be thrown from all programs extern KEYWORD_ERROR keyword_error;// can be thrown from all programs extern USAGE_ERROR usage_error;// can be thrown from all programs #endif // EXCEPTIONS_H Doris-5.0.3Beta/doris_core/filtering.cc000077500000000000000000003577071312547014700200470ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/filtering.cc,v $ * * $Revision: 3.19 $ * * $Date: 2005/10/06 11:09:20 $ * * $Author: kampes $ * * * * Implementation of filtering routines: * * -rangefilter (adaptive, after resampling) * * -rangefilter (based on baseline, points on ellips) * * -phasefilter: goldstein * * -phasefilter: spatial convolution * * -phasefilter: spectral method * * -azimuthfilter: based on fDC polynomials * ****************************************************************/ // #define _LIB_VERSION _IEEE_ #include "matrixbk.hh" #include "constants.hh" // global constants #include "filtering.hh" // header file #include "utilities.hh" // myhamming #include "slcimage.hh" // my slc image class #include "productinfo.hh" // my 'products' class #include "orbitbk.hh" // my orbit class #include "exceptions.hh" // my exceptions class #include // for memory stream #include // setp #ifdef WIN32 // Jia defined min/max here, I did it in constants.hh // Bert Kampes, 24-Aug-2005 //#define max _MAX //#define min _MIN #endif /**************************************************************** * rangefilter * * adaptive range filtering. To be performed after resampling. * * peak estimation of local fringe frequency in spectral * * domain of oversampled([2] or 4) complex interferogram. * * then master and slave spectra are filtered, optionally * * de- and re-weight with hamming. * * * * Input: * * - files for master/slave, input options * * Output: * * - filtered files for master/slave * * * * Bert Kampes, 29-Mar-2000 * ****************************************************************/ void rangefilter( const input_gen &generalinput, const slcimage &master, const slcimage &slave, const productinfo &interferogram, const input_filtrange &filtrangeinput) { TRACE_FUNCTION("rangefilter (BK 29-Mar-2000)"); INFO << "RANGEFILT: Master input file: " << master.file; INFO.print(); INFO << "RANGEFILT: Slave input file: " << slave.file; INFO.print(); // ====== Handle input ====== const real8 hamming = filtrangeinput.hammingalpha;// alpha=1: const const int32 nlmean = filtrangeinput.nlmean; // odd number range lines to average const int32 fftlength = filtrangeinput.fftlength; // length of adaptive const int32 OVERLAP = filtrangeinput.overlap; // overlap input blocks const real8 SNRthreshold = filtrangeinput.SNRthreshold;// criterium to filter const bool doweightcorrel= filtrangeinput.doweightcorrel; const int32 oversamplefactor = filtrangeinput.oversample; // RSR,RBW in Hz const real8 RSR = 0.5*master.rsr2x; // range sampling rate fr 18.96MHz const real8 RBW = master.rbw; // range band width fs 15.55MHz // ______ Number of lines on file ______ // ______ Assume resampling has been done and interferowin contains master coord. //const int32 Mfilelines = master.currentwindow.lines(); //const int32 Ifilelines = interferogram.win.lines(); const int32 numpixels = interferogram.win.pixels(); // ______ Memory buffers ______ //const uint BUFFERMEMSIZE = generalinput.memory; const real8 BUFFERMEMSIZE = generalinput.memory; const int32 bytesperline = numpixels * sizeof(complr4); const real4 numbigmatrices = 4.2; // in/out Master/Slave +rest int32 bufferlines = int32(ceil( (BUFFERMEMSIZE/numbigmatrices)/bytesperline )); // numlines in buffer // ====== Open output files ====== ofstream ofilemaster; openfstream(ofilemaster,filtrangeinput.fomaster,generalinput.overwrit); bk_assert(ofilemaster,filtrangeinput.fomaster,__FILE__,__LINE__); ofstream ofileslave; openfstream(ofileslave, filtrangeinput.foslave,generalinput.overwrit); bk_assert(ofileslave, filtrangeinput.foslave, __FILE__,__LINE__); // ====== Compute indices, counters, etc. ====== const int32 numrangeblocks = int32(numpixels/(fftlength-2*OVERLAP)); // approx real8 overallSNR = 0.; // statistics real8 overallnotfiltered = 0.; // statistics // ______ Buffer counters ______ int32 azimuthbuffer = 1; // loop counter bool azimuthdone = false; int32 startlinethisblock = interferogram.win.linelo; window filteredpart (0, bufferlines-uint((nlmean+1)/2), 0, numpixels-1); // output to disk // ______ Give info ______ INFO << "overlap master slave: [" << interferogram.win.linelo << ":" << interferogram.win.linehi << "; " << interferogram.win.pixlo << ":" << interferogram.win.pixhi << "] (master system)"; INFO.print(); // ====== Loop over azimuth buffers over whole width ====== // ______ loop forever, break when finished ______ for (azimuthbuffer=1; azimuthbuffer<1e5; ++azimuthbuffer) { PROGRESS << "azimuthbuffer (" << bufferlines << " lines): " << azimuthbuffer << "."; PROGRESS.print(); // ====== Read data master slave for this block ====== int32 endlinethisblock = startlinethisblock+bufferlines-1; // ______ check slightly larger last block ______ if (endlinethisblock>=int32(interferogram.win.linehi)-nlmean-int32(bufferlines/10)) { azimuthdone = true; // finish this one endlinethisblock = interferogram.win.linehi; // last line on file bufferlines = endlinethisblock-startlinethisblock+1; filteredpart.linehi = bufferlines - 1; // write all at end } // ______ Allocate matrices and read window from file ______ const window winfile(startlinethisblock, endlinethisblock, interferogram.win.pixlo, interferogram.win.pixhi); // ______ Input buffer ______ const matrix MASTER_ORIG = master.readdata(winfile); const matrix SLAVE_ORIG = slave.readdata(winfile); // ______ Output buffer ______ matrix MASTER_FILT(MASTER_ORIG.lines(),MASTER_ORIG.pixels()); matrix SLAVE_FILT (SLAVE_ORIG.lines(), SLAVE_ORIG.pixels()); // ====== Loop over range buffers dividing width ====== // ______ Indices are in inbuffer local coordinates [0:numpixs] ______ int32 startpixel = 0; // valid for first range block int32 filteredpixlo = 0; // valid for first range block int32 partpixlo = 0; // local system in PART int32 partpixhi = fftlength-1-OVERLAP; // local system in PART bool rangedone = false; // not finished yet for (;;)// forever { int32 endpixel = startpixel+fftlength-1; // BUFFER -> PART int32 filteredpixhi = endpixel - OVERLAP; // PART -> BUFFER if (endpixel>=int32(MASTER_ORIG.pixels())-1) // last block back-shifted { rangedone = true; endpixel = MASTER_ORIG.pixels()-1; startpixel = endpixel - fftlength + 1; filteredpixhi = endpixel; // write all for last block partpixhi = fftlength-1; // write all for last block partpixlo = partpixhi - (filteredpixhi-filteredpixlo); } // ______ Some info ______ TRACE << "range block [" << startlinethisblock << ":" << endlinethisblock << "; " << startpixel+interferogram.win.pixlo << ":" << endpixel+interferogram.win.pixlo << "]"; TRACE.print(); // ______ Cut out master/slave for adaptive range filtering ______ const window win(0,MASTER_ORIG.lines()-1,startpixel,endpixel); matrix PARTMASTER(win,MASTER_ORIG); // construct as part matrix PARTSLAVE (win,SLAVE_ORIG); // construct as part // ______ Do the actual range filtering ______ // ______ filtered lines: index[0:L-1]: [(nlmean-1)/2:L-1-(nlmean-1)/2] ______ real8 SNRmean, percentnotfiltered; rfilterblock(PARTMASTER,PARTSLAVE, // returned nlmean,SNRthreshold,RSR,RBW, // parameters hamming,oversamplefactor,doweightcorrel, // control algorithm SNRmean, percentnotfiltered); // statistics returned overallSNR += SNRmean; overallnotfiltered += percentnotfiltered; // ______ Put filtered part in outputbuffer ______ const window winpart(win.linelo,win.linehi, partpixlo,partpixhi); const window wintoset(win.linelo,win.linehi, filteredpixlo,filteredpixhi); MASTER_FILT.setdata(wintoset,PARTMASTER,winpart); SLAVE_FILT.setdata (wintoset,PARTSLAVE, winpart); // ______ Update counters and check if it is already time to go ______ if (rangedone==true) break; partpixlo = OVERLAP; // valid for all next blocks startpixel = endpixel - 2*OVERLAP + 1; // get PART from inputbuffer filteredpixlo = startpixel + OVERLAP; // valid for all blocks except first } // loop over range blocks // ====== Write filtered parts master,slave to output files ====== switch (filtrangeinput.oformatflag) { case FORMATCR4: { writefile(ofilemaster,MASTER_FILT,filteredpart); writefile(ofileslave, SLAVE_FILT, filteredpart); break; } // ______ Convert first to ci2 before writing to file ______ case FORMATCI2: { matrix TMP(MASTER_FILT.lines(),MASTER_FILT.pixels()); for (uint ii=filteredpart.linelo; ii<=filteredpart.linehi; ++ii) for (uint jj=filteredpart.pixlo; jj<=filteredpart.pixhi; ++jj) TMP(ii,jj) = cr4toci2(MASTER_FILT(ii,jj)); writefile(ofilemaster,TMP,filteredpart); for (uint ii=filteredpart.linelo; ii<=filteredpart.linehi; ++ii) for (uint jj=filteredpart.pixlo; jj<=filteredpart.pixhi; ++jj) TMP(ii,jj) = cr4toci2(SLAVE_FILT(ii,jj)); writefile(ofileslave, TMP, filteredpart); break; } default: { PRINT_ERROR("Totally impossible, checked input.") throw(unhandled_case_error); } } // ______ Update counters, check finished ______ if (azimuthdone==true) break; filteredpart.linelo = uint((nlmean-1.)/2.); // same for all buffers except first startlinethisblock = endlinethisblock - nlmean + 2; } // loop over azimuth buffers // _______ Some stats, better dump SUN rasterfile all shifts ______ overallSNR /= (azimuthbuffer*numrangeblocks); overallnotfiltered /= (azimuthbuffer*numrangeblocks); INFO << "Mean SNR for all blocks (approx): " << overallSNR; INFO.print(); INFO << "Filtered (approx): " << setprecision(3) << 100.00-overallnotfiltered << "%"; if (overallnotfiltered<60.) { INFO.print(); } else { WARNING.print(INFO.get_str()); INFO.rewind(); } // ====== Write results to file ====== ofstream scratchlogfile("scratchlogfiltrange", ios::out | ios::trunc); bk_assert(scratchlogfile,"filtrange: scratchlogfiltrange",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* RANGE FILTERING ADAPTIVE FOR MASTER AND SLAVE..." << "\n*******************************************************************" << "\nInput file master (format): \t\t\t" << master.file << " " << master.formatflag << "\nInput file slave (format): \t\t\t" << slave.file << " " << slave.formatflag << "\nOutput file filtered master (format): \t\t\t" << filtrangeinput.fomaster << " "; if (filtrangeinput.oformatflag==FORMATCR4) scratchlogfile << "complex r4"; if (filtrangeinput.oformatflag==FORMATCI2) scratchlogfile << "complex short int"; scratchlogfile << "\nOutput file filtered slave (format): \t\t\t" << filtrangeinput.foslave << " " << FORMATCR4 << "\n..." << "\n*******************************************************************\n"; scratchlogfile.close(); for (int32 fileID=1; fileID<=2; ++fileID) { char oresfile[EIGHTY]; char odatafile[EIGHTY]; char odataformat[EIGHTY]; char processcf[EIGHTY]; if (filtrangeinput.oformatflag==FORMATCR4) strcpy(odataformat,"complex_real4"); else if (filtrangeinput.oformatflag==FORMATCI2) strcpy(odataformat,"complex_short"); else { PRINT_ERROR("case problem.") throw(unhandled_case_error); } switch (fileID) { case 1: // master strcpy(oresfile,"scratchresMfiltrange"); strcpy(odatafile,filtrangeinput.fomaster); strcpy(processcf,processcontrol[pr_m_filtrange]); // control flag break; case 2: // slave strcpy(oresfile,"scratchresSfiltrange"); strcpy(odatafile,filtrangeinput.foslave); strcpy(processcf,processcontrol[pr_s_filtrange]); // control flag break; default: { PRINT_ERROR("panic: ID!={1,2}") throw(unhandled_case_error); } } // ______ updateproductinfo greps info from this file ______ ofstream scratchresfile(oresfile, ios::out | ios::trunc); bk_assert(scratchresfile,oresfile,__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************" << "\n*_Start_" << processcf << "\n*******************************************************************" << "\nMethod_rangefilt: \t" << "adaptive" << "\nData_output_file: \t" << odatafile << "\nData_output_format: \t" << odataformat << "\nFirst_line (w.r.t. original_master): \t" << interferogram.win.linelo << "\nLast_line (w.r.t. original_master): \t" << interferogram.win.linehi << "\nFirst_pixel (w.r.t. original_master): \t" << interferogram.win.pixlo << "\nLast_pixel (w.r.t. original_master): \t" << interferogram.win.pixhi << "\n*******************************************************************" << "\n* End_" << processcf << "_NORMAL" << "\n*******************************************************************\n"; scratchresfile.close(); } // for master and slave // ______Tidy up______ } // END rangefilter /**************************************************************** * rfilterblock * * Computes powerspectrum of complex interferogram. * * (product oversampled master. conj oversampled slave in range)* * A peak in this spectrum corresponds to frequency shift. * * The master and slave are LPF filtered for this shift. * * * * Optionally the oversampling can be turned off, since no use * * if only small baseline, and flat terrain. * * The powerspectrum can be weighted to give more influence to * * higher frequencies (conv. of 2 blocks, should be hamming). * * The peak is detected by taking a mean of nlmean lines (odd). * * Filtering is applied if the SNR (N*power peak / power rest) * * is above a user supplied threshold. * * At LPF filtering of the master/slave a hamming window may * * be applied first to deweight, then to re-weight the spectrum * * * * Should filter based on zero terrain slope if below SNR, * * but this requried knowledge of orbits, pixel,line coordinate * #%// BK 13-Nov-2000 * * * * Input: * * - MASTER: block of master, that will be filtered * * - SLAVE: block of slave, that will be filtered * * Output: * * - MASTER (SLAVE): filtered from indeces[0:numl-1] * * (nlmean-1)/2 to numlines-(nlmean-1)/2-1 * * * * Bert Kampes, 29-Mar-2000 * ****************************************************************/ void rfilterblock( matrix &master, // updated matrix &slave, // updated int32 nlmean, // number of lines to take mean over real8 SNRthreshold, // real8 RSR, // in MHz real8 RBW, // in MHz real8 alphahamming, // parameter hamming filtering [0,1] int32 osfactor, // oversampling factor interf. gen. bool doweightcorrel, // correct correl for #elem. real8 &meanSNR, // returned real8 &percentnotfiltered) // returned { const int32 numlines = master.lines(); const int32 numpixs = master.pixels(); const int32 outputlines = numlines - nlmean + 1; const int32 firstline = int32((nlmean-1)/2); // indices in matrix system const int32 lastline = firstline + outputlines - 1; const bool dohamming = (alphahamming<0.9999) ? true : false; // use oversampling before int. gen. const bool dooversample = (osfactor!=1) ? true : false; int32 notfiltered=0; // counter #ifdef __DEBUG TRACE_FUNCTION("rfilterblock (BK 29-Mar-2000)") // if (!isodd(nlmean)) // MA error check is moved to readinput.cc # rm lines for major release // { // PRINT_ERROR("nlmean has to be odd.") // throw(argument_error); // } if (!ispower2(numpixs)) { PRINT_ERROR("numpixels (FFT) has to be power of 2.") throw(argument_error); } if (!ispower2(osfactor)) { PRINT_ERROR("oversample factor (FFT) has to be power of 2.") throw(argument_error); } if (slave.lines()!=numlines) { PRINT_ERROR("slave not same size as master.") throw(argument_error); } if (slave.pixels()!=numpixs) { PRINT_ERROR("slave not same size as master.") throw(argument_error); } #endif if (outputlines < 1) { WARNING.print("no outputlines, continuing."); return; } // ______ Shift parameters ______ register int32 i,j; const real4 deltaf = RSR/real4(numpixs); const real4 fr = -RSR/2.; matrix freqaxis(1,numpixs); for (i=0; i inversehamming; if (dohamming) { inversehamming = myhamming(freqaxis,RBW,RSR,alphahamming); for (i=0; i power ______ matrix cint; if (dooversample) cint = dotmult(oversample(master,1,osfactor),oversample(conj(slave),1,osfactor)); else cint = dotmult(master,conj(slave)); const int32 fftlength = cint.pixels(); DEBUG.print("is real4 accurate enough?");// seems so fft(cint,2); // cint=fft over rows matrix power = intensity(cint); // power=cint.*conj(cint); // ______ Use weighted correlation due to bias in normal definition ______ // ______ Actually better deweight with autoconvoluted hamming. // ______ No use a triangle for #points used for correlation estimation // ______ not in combination with dooversample... if (doweightcorrel) { INFO.print("De-weighting power spectrum of convolution."); //matrix weighting(1,fftlength); //for (i=0; i nlmeanpower = sum(power(0,nlmean-1, 0,fftlength-1),1); uint shift = 0; // returned by max uint dummy = 0; // returned by max meanSNR = 0.; real8 meanSHIFT = 0.; // ______ Start actual filtering ______ // ______ oline is index in matrix system ______ for (register int32 oline=firstline; oline<=lastline; ++oline) { matrix totalp = sum(nlmeanpower,2); // 1x1 matrix ... const real4 totalpower = totalp(0,0); const real4 maxvalue = max(nlmeanpower,dummy,shift); // shift returned uint lastshift = shift; // use this if current shift not ok. const real8 SNR = fftlength*(maxvalue/(totalpower-maxvalue)); meanSNR += SNR; // ______ Check for negative shift ______ bool negshift = false; if (shift > uint(fftlength/2)) { // ERR: uint! shift = uint(abs(real8(shift-fftlength))); shift = uint(fftlength)-shift; lastshift = shift;// use this if current shift not OK. negshift = true; } // ______ Do actual filtering ______ if (SNR filter; if (dohamming) { // ______ Newhamming is scaled and centered around new mean ______ filter = myhamming(freqaxis-real4(.5*shift*deltaf), RBW-real8(shift*deltaf), RSR,alphahamming); // fftshifted filter *= inversehamming; } else // no weighting of spectra { filter = myrect((freqaxis-real4(.5*shift*deltaf)) / (real4(RBW-shift*deltaf))); // fftshifted } // ______ Use freq. as returned by fft ______ // ______ Note that filter_s = fliplr(filter_m) ______ // ______ and that this is also valid after ifftshift ______ ifftshift(filter); // fftsh works on data! // ====== Actual spectral filtering ====== // ______ Decide which side to filter, may be dependent on ______ // ______ definition of FFT, this is ok for VECLIB ______ // ______ if you have trouble with this step, either check your FFT // ______ (or use uinternal one, or add a card for changing false to true below if (negshift==false) { dotmult(master[oline],filter,1); filter.fliplr(); // works on data! dotmult(slave[oline],filter,1); } else { dotmult(slave[oline],filter,1); filter.fliplr(); // works on data! dotmult(master[oline],filter,1); } // following is removed, we now always filter with last know spectral offset // Bert Kampes, 13-Sep-2004 // } // SNR>threshold // else // { // notfiltered++; // update counter // } // ______ Update 'walking' mean ______ if (oline!=lastline) // then breaks { matrix line1 = power.getrow(oline-firstline); matrix lineN = power.getrow(oline-firstline+nlmean); nlmeanpower += (lineN-line1); } } // loop over outputlines // ______ IFFT of spectrally filtered data, and return these ______ ifft(master,2); // master=ifft over rows ifft(slave,2); // slave=ifft over rows // ______ Return these to main ______ meanSHIFT /= (outputlines-notfiltered); meanSNR /= outputlines; percentnotfiltered = 100. * (real4(notfiltered)/real4(outputlines)); // ______ Some info for this block ______ const real8 meanfrfreq = meanSHIFT*deltaf; // Hz? DEBUG << "mean SHIFT for block" << ": " << meanSHIFT << " = " << meanfrfreq/1e6 << " MHz (fringe freq.)."; DEBUG.print(); DEBUG << "mean SNR for block" << ": " << meanSNR; DEBUG.print(); DEBUG << "filtered for block" << ": " << setprecision(3) << 100.00-percentnotfiltered << "%" << ends; DEBUG.print(); if (percentnotfiltered>60.0) { WARNING.print(DEBUG.get_str()); DEBUG.reset(); } } // END rfilterblock /**************************************************************** * phasefilter * * goldsteins method, see routine goldstein and smooth. * * After Goldstein and Werner, Radar interferogram filtering * * for geophysical applications. GRL 25-21 pp 4035-4038, 1998. * * and: ESA Florence 1997, vol2, pp969-972, Goldstein & Werner * * "Radar ice motion interferometry". * #%// BK 24-Oct-2000 * ****************************************************************/ void phasefilter( const input_gen &generalinput, const productinfo &interferogram, const input_filtphase &filtphaseinput, const productinfo &coherence) { TRACE_FUNCTION("phasefilter (BK 24-Oct-2000)") // ====== Handle input ====== bool doexternalfile = false; if (specified(filtphaseinput.fifiltphase)) doexternalfile = true; char infile[EIGHTY]; // file 2b filtered char cohfile[EIGHTY]; // coherence file for modgoldstein strcpy(infile,interferogram.file); if (filtphaseinput.method == fp_modgoldstein ) strcpy(cohfile,coherence.file); int32 numlinesinput = int32(interferogram.win.lines()/interferogram.multilookL); int32 numpixelsinput = int32(interferogram.win.pixels()/interferogram.multilookP); if (doexternalfile) // overwrite default file { numlinesinput = filtphaseinput.finumlines; strcpy(infile,filtphaseinput.fifiltphase); ifstream ifile; openfstream(ifile,infile); bk_assert(ifile,infile,__FILE__,__LINE__); ifile.seekg(0,ios::end); // pointer to end... const streamoff sizefile = ifile.tellg(); // opened ate, [MA] 64 bit pointer on a 32-bit system ifile.close(); numpixelsinput = sizefile/sizeof(complr4)/numlinesinput;// floor if (streamoff(numlinesinput)*streamoff(numpixelsinput)*streamoff(sizeof(complr4)) != sizefile) WARNING.print("Format infile not CR4, or numlines not correct."); INFO.print("Using input file for phase filtering, not default."); } INFO << "phasefilter: inputfile: (#l,#p): " << infile << " (" << numlinesinput << "," << numpixelsinput << ")"; INFO.print(); // ______ Set variables ______ const real8 ALPHA = filtphaseinput.alpha; // 0 CINT(SIZE,numpixelsinput); // type must be cr4! // if (filtphaseinput.method == fp_modgoldstein ) // { matrix COH(SIZE,numpixelsinput); // type must be r4! // } int32 lineswritten = OVERLAP; // first buffer extra OVERLAP lines const int32 numbuffers = numlinesinput/numout; // approx? int32 tenpercent = int32((numbuffers/10)+.5); // round if (tenpercent==0) tenpercent = 1000; PROGRESS.print("FILTPHASE: 0%"); int32 percent = 10; // ====== Start filter loop buffers of BLOCKSIZE ====== for (int32 buffer=1; buffer<1e6; ++buffer) { // ______ Check if this will be the last buffer ______ if (cintlinehi >= numlinesinput-1) // -1 since in matrix system { lastbuffer = true; cintlinehi = numlinesinput-1; cintlinelo = cintlinehi-SIZE+1; // make sure SIZE lines are read filteredlinehi = SIZE-1; // write upto lastline for last buffer const int32 lines2bwritten = numlinesinput-lineswritten; filteredlinelo = filteredlinehi - lines2bwritten + 1; if (lines2bwritten<1) WARNING.print("PANIC: this will crash, lines2bwritten<1?"); } // ______ Read in buffers of BLOCKSIZE lines complex interferogram ______ const window windummy (0,0,0,0); // no offset in readfile const window wincint (cintlinelo,cintlinehi,0,numpixelsinput-1); readfile(CINT,infile,numlinesinput,wincint,windummy); matrix FILTERED(SIZE,numpixelsinput); if (filtphaseinput.method == fp_goldstein ) { // ______ Filter data in buffer of BLOCKSIZE lines ______ // ______ output has same size, but write only part to disk ______ FILTERED = goldstein(CINT,ALPHA,OVERLAP,filtphaseinput.kernel); } else // filtphaseinput.method == fp_modgoldstein { readfile(COH,cohfile,numlinesinput,wincint,windummy); FILTERED = modgoldstein(CINT,COH,OVERLAP,filtphaseinput.kernel); } // ______ Write filtered data ______ const window winfiltered(filteredlinelo,filteredlinehi,0,numpixelsinput-1); writefile(ofile,FILTERED,winfiltered); // ______ Check if all done ______ if (lastbuffer) break; // ______ Update indexes in matrices, will be corrected for last block ______ lineswritten += numout; // first block overlap added cintlinelo += numout; // next buffer cintlinehi += numout; // next buffer filteredlinelo = OVERLAP; // index in buffer, // valid for all middle buffers, but not last // ______ Give progress message ______ if (buffer%tenpercent==0) { PROGRESS << "FILTPHASE: " << setw(3) << percent << "%"; PROGRESS.print(); percent += 10; } } // end loop buffers ofile.close(); // ______ exit if only external file was desired ______ if (doexternalfile) { cerr << "\n Finished external file phasefilter, Exiting\n"; PROGRESS.print("\n Finished external file phasefilter, Exiting\n"); exit(0); } // ====== Write results to file ====== ofstream scratchlogfile("scratchlogfiltphase", ios::out | ios::trunc); bk_assert(scratchlogfile,"filtphase: scratchlogfiltphase",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* PHASE FILTER COMPLEX INTERFEROGRAM: \t" << "\n*******************************************************************" << infile << "\nOutput file filtered master (format): \t\t\t" << filtphaseinput.fofiltphase << " " << "\n..." << "\n*******************************************************************\n"; scratchlogfile.close(); // ______ updateproductinfo greps info from this file ______ ofstream scratchresfile("scratchresfiltphase", ios::out | ios::trunc); bk_assert(scratchresfile,"scratchresfiltphase",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************" << "\n*_Start_" << processcontrol[pr_i_filtphase] << "\n*******************************************************************"; if (filtphaseinput.method == fp_goldstein ){ scratchresfile << "\nMethod_phasefilt: goldstein: size, alpha, overlap: \t" << SIZE << " " << ALPHA << " " << OVERLAP; } else{ scratchresfile << "\nMethod_phasefilt: modgoldstein: size, overlap: \t" << SIZE << " " << OVERLAP; } scratchresfile << "\n1D Smoothing kernel for |spectrum|: \t"; for (uint ii=0; ii goldstein( const matrix &CINT, const real4 ALPHA, const int32 OVERLAP, const matrix &smoothkernel) // lying down { TRACE_FUNCTION("ROUTINE: goldstein (BK 25-Oct-2000)") //#define CHECKINDICESCALLING #ifdef CHECKINDICESCALLING return CINT; #else // ______ Allocate output matrix ______ const int32 SIZE = CINT.lines(); const int32 NPIX = CINT.pixels(); matrix FILTERED(SIZE,NPIX); // output // ______ Get block from buffer ______ const int32 numout = SIZE-(2*OVERLAP); // number of output pixels int32 cintpixlo = 0; // index in CINT to get 1st block int32 cintpixhi = SIZE-1; // index in CINT to get 1st block int32 outblockpixlo = 0; // index in BLOCK (only 1st block) int32 outblockpixhi = SIZE-1-OVERLAP; // index in BLOCK (except last block) int32 outpixlo = outblockpixlo; // index in FILTERED (1st block) int32 outpixhi = outblockpixhi; // index in FILTERED bool lastblockdone = false; // only just started... // note that int32() floors division const int32 SMOOTH = int32(smoothkernel.pixels())/2; // half block size, odd kernel const bool dosmooth = (SMOOTH==0) ? false : true; DEBUG << "SMOOTH: " << SMOOTH;// problem with uint<0 index in smoothkernel DEBUG.print(); // ______ use FFT's for convolution with smoothkernel ______ // ______ this could also be done static, or in the calling routine ______ // ______ KERNEL2D is FFT2 of even kernel (no imag part after fft!) ______ matrix KERNEL2D; if (dosmooth==true) { matrix kernel(1,SIZE); // init to zeros for (register int32 ii=-SMOOTH; ii<=SMOOTH; ++ii)// 1d kernel function of block { //kernel(0,(ii+SIZE)%SIZE) = smoothkernel(0,ii-SMOOTH); // BK 07-Apr-2003 // Cygwin fails on index very large number, i.e., uint problem somewhere // e.g.: [30,31,0,1,2] <--> [0,1,2,3,4] int32 tmp1 = (ii+SIZE)%SIZE; int32 tmp2 = ii+SMOOTH;// used to be ii-SMOOTH: wrong DEBUG << "tmp1: " << tmp1 << "; tmp2: " << tmp2; DEBUG.print(); kernel(0,tmp1) = complr4(smoothkernel(0,tmp2),real4(0.0)); } KERNEL2D = matTxmat(kernel,kernel); fft2d(KERNEL2D); // should be real sinc } DEBUG.print("kernel created for smoothing spectrum"); // ====== Loop forever, stop after lastblockdone ====== for (;;) //forever { if (cintpixhi>=NPIX-1) // check if we are doing the last block { lastblockdone = true; cintpixhi = NPIX-1; // prevent reading after file cintpixlo = cintpixhi-SIZE+1; // but make sure SIZE pixels are read outpixhi = cintpixhi; // index in FILTERED 2b written outblockpixhi = SIZE-1; // write all to the end outblockpixlo = outblockpixhi - (outpixhi-outpixlo+1) + 1; } const window wincint (0,SIZE-1,cintpixlo,cintpixhi); const window winblock (0,SIZE-1,outblockpixlo,outblockpixhi); const window winfiltered (0,SIZE-1,outpixlo,outpixhi); // ______ Construct BLOCK as part of CINT ______ matrix BLOCK(wincint,CINT); //#define CHECKINDEXONLY #ifndef CHECKINDEXONLY // ______ Get spectrum/amplitude/smooth/filter ______ fft2d(BLOCK); matrix AMPLITUDE = magnitude(BLOCK); // ______ use FFT's for convolution with rect ______ if (dosmooth==true) AMPLITUDE = smooth(AMPLITUDE,KERNEL2D); //dumpasc("A",AMPLITUDE); //AMPLITUDE = smooth(AMPLITUDE,SMOOTH); //dumpasc("As",AMPLITUDE); exit(1); const real4 maxamplitude = max(AMPLITUDE); if (maxamplitude>1e-20) //? { AMPLITUDE /= maxamplitude; AMPLITUDE.mypow(ALPHA); #ifdef WIN32 BLOCK = timesCxR(BLOCK,AMPLITUDE);// weight spectrum #else BLOCK *= AMPLITUDE; // weight spectrum #endif } else { WARNING.print("no filtering, maxamplitude<1e-20, zeros in this block?"); } ifft2d(BLOCK); #endif // check index blocks // ______ Set correct part that is filtered in output matrix ______ FILTERED.setdata(winfiltered,BLOCK,winblock); // ______ Exit if finished ______ if (lastblockdone) return FILTERED; // return // ______ Update indexes in matrices, will be corrected for last block ______ cintpixlo += numout; // next block cintpixhi += numout; // next block outblockpixlo = OVERLAP; // index in block, valid for all middle blocks outpixlo = outpixhi+1; // index in FILTERED, next range line outpixhi = outpixlo+numout-1; // index in FILTERED } // for all blocks in this buffer #endif // check index calling routine } // END goldstein phase filter /**************************************************************** * phasefilter modgoldstein * * Input is matrix of SIZE (e.g. 32) lines, and N range pixels. * * Filtered OUTPUT is same size as input block. * * Because of overlap, only write to disk in calling routine * * part (in matrix coord.) [OVERLAP:SIZE-OVERLAP-1] * * * * Smoothing of the amplitude of the spectrum is performed by * * spatial convolution with a block kernel of size 2*SMOOTH+1. * * (Which is done by FFT's). e.g. a spatial moving average with * * kernel (1d) k=[1 1 1 1 1]/5; kernel2d = transpose(k)*k. * * Blocks in range direction. * * * * After Baran et al. 2003, A Modification to the Goldstein * * Radar Interferogram Filter, IEEE Trans. GRS, v41/9, Sep.2003 * #%// Batu 2011 11 03 * #%// BK 25-Oct-2000 * ****************************************************************/ matrix modgoldstein( const matrix &CINT, const matrix &COH, const int32 OVERLAP, const matrix &smoothkernel) // lying down { TRACE_FUNCTION("ROUTINE: modgoldstein (BK 03-Nov-2011)") //#define CHECKINDICESCALLING #ifdef CHECKINDICESCALLING return CINT; #else // ______ Allocate output matrix ______ const int32 SIZE = CINT.lines(); const int32 NPIX = CINT.pixels(); matrix FILTERED(SIZE,NPIX); // output // ______ Get block from buffer ______ const int32 numout = SIZE-(2*OVERLAP); // number of output pixels int32 cintpixlo = 0; // index in CINT to get 1st block int32 cintpixhi = SIZE-1; // index in CINT to get 1st block int32 outblockpixlo = 0; // index in BLOCK (only 1st block) int32 outblockpixhi = SIZE-1-OVERLAP; // index in BLOCK (except last block) int32 outpixlo = outblockpixlo; // index in FILTERED (1st block) int32 outpixhi = outblockpixhi; // index in FILTERED bool lastblockdone = false; // only just started... // note that int32() floors division const int32 SMOOTH = int32(smoothkernel.pixels())/2; // half block size, odd kernel const bool dosmooth = (SMOOTH==0) ? false : true; DEBUG << "SMOOTH: " << SMOOTH;// problem with uint<0 index in smoothkernel DEBUG.print(); // ______ use FFT's for convolution with smoothkernel ______ // ______ this could also be done static, or in the calling routine ______ // ______ KERNEL2D is FFT2 of even kernel (no imag part after fft!) ______ matrix KERNEL2D; if (dosmooth==true) { matrix kernel(1,SIZE); // init to zeros for (register int32 ii=-SMOOTH; ii<=SMOOTH; ++ii)// 1d kernel function of block { //kernel(0,(ii+SIZE)%SIZE) = smoothkernel(0,ii-SMOOTH); // BK 07-Apr-2003 // Cygwin fails on index very large number, i.e., uint problem somewhere // e.g.: [30,31,0,1,2] <--> [0,1,2,3,4] int32 tmp1 = (ii+SIZE)%SIZE; int32 tmp2 = ii+SMOOTH;// used to be ii-SMOOTH: wrong DEBUG << "tmp1: " << tmp1 << "; tmp2: " << tmp2; DEBUG.print(); kernel(0,tmp1) = complr4(smoothkernel(0,tmp2),real4(0.0)); } KERNEL2D = matTxmat(kernel,kernel); fft2d(KERNEL2D); // should be real sinc } DEBUG.print("kernel created for smoothing spectrum"); // ====== Loop forever, stop after lastblockdone ====== for (;;) //forever { if (cintpixhi>=NPIX-1) // check if we are doing the last block { lastblockdone = true; cintpixhi = NPIX-1; // prevent reading after file cintpixlo = cintpixhi-SIZE+1; // but make sure SIZE pixels are read outpixhi = cintpixhi; // index in FILTERED 2b written outblockpixhi = SIZE-1; // write all to the end outblockpixlo = outblockpixhi - (outpixhi-outpixlo+1) + 1; } const window wincint (0,SIZE-1,cintpixlo,cintpixhi); const window winblock (0,SIZE-1,outblockpixlo,outblockpixhi); const window winfiltered (0,SIZE-1,outpixlo,outpixhi); // ______ Construct BLOCK as part of CINT ______ matrix BLOCK(wincint,CINT); matrix BLKCH(wincint,COH); //#define CHECKINDEXONLY #ifndef CHECKINDEXONLY // ______ Get spectrum/amplitude/smooth/filter ______ fft2d(BLOCK); matrix AMPLITUDE = magnitude(BLOCK); // ______ use FFT's for convolution with rect ______ if (dosmooth==true) AMPLITUDE = smooth(AMPLITUDE,KERNEL2D); //dumpasc("A",AMPLITUDE); //AMPLITUDE = smooth(AMPLITUDE,SMOOTH); //dumpasc("As",AMPLITUDE); exit(1); const real4 maxamplitude = max(AMPLITUDE); if (maxamplitude>1e-20) //? { AMPLITUDE /= maxamplitude; real4 ALPHA=1-mean(BLKCH); // calculate alpha based on 1-coherence AMPLITUDE.mypow(ALPHA); #ifdef WIN32 BLOCK = timesCxR(BLOCK,AMPLITUDE);// weight spectrum #else BLOCK *= AMPLITUDE; // weight spectrum #endif } else { WARNING.print("no filtering, maxamplitude<1e-20, zeros in this block?"); } ifft2d(BLOCK); #endif // check index blocks // ______ Set correct part that is filtered in output matrix ______ FILTERED.setdata(winfiltered,BLOCK,winblock); // ______ Exit if finished ______ if (lastblockdone) return FILTERED; // return // ______ Update indexes in matrices, will be corrected for last block ______ cintpixlo += numout; // next block cintpixhi += numout; // next block outblockpixlo = OVERLAP; // index in block, valid for all middle blocks outpixlo = outpixhi+1; // index in FILTERED, next range line outpixhi = outpixlo+numout-1; // index in FILTERED } // for all blocks in this buffer #endif // check index calling routine } // END goldstein phase filter /**************************************************************** * B = smooth(A,KERNEL) * * (circular) spatial moving average with a (2N+1,2N+1) block. * * See also matlab script smooth.m for some tests. * * implementation as convolution with FFT's * * input: KERNEL is the FFT of the kernel (block) * #%// BK 26-Oct-2000 * ****************************************************************/ matrix smooth( const matrix &A, const matrix &KERNEL2D) { #ifdef __DEBUGMAT2 matDEBUG.print("smooth (BK 26-Oct-2000)"); #endif matrix DATA = mat2cr4(A); // or define fft(R4) fft2d(DATA); // or define fft(R4) // ______ create kernel in calling routine, e.g., like ______ // ______ Kernel has to be even! ______ //const int32 L = A.lines(); //const int32 P = A.pixels(); //matrix kernel(1,L); // init to zeros //for (register int32 ii=-N; ii<=N; ++ii) // 1d kernel function of block // kernel(0,(ii+L)%L) = 1./(2*N+1); //matrix KERNEL2D = matTxmat(kernel,kernel); //fft2d(KERNEL2D); // should be real sinc DATA *= KERNEL2D; // no need for conj. with real fft... ifft2d(DATA); // convolution, but still complex... return real(DATA); // you know it is real only... } // END smooth /**************************************************************** * B = smooth(A,blocksize) * * (circular) spatial moving average with a (2N+1,2N+1) block. * * See also matlab script smooth.m for some tests. * #%// BK 26-Oct-2000 * ****************************************************************/ matrix smooth( const matrix &A, int32 N) { #ifdef __DEBUGMAT2 matDEBUG.print("ROUTINE: smooth (BK 26-Oct-2000)"); #endif // ______ Check if smoothing desired ______ if (N==0) return A; // define one of SPACEDOMAIN and SPECTRALDOMAIN to select algorithm // #define SPACEDOMAIN #define SPECTRALDOMAIN // ====== In space domain ====== #ifdef SPACEDOMAIN const int32 L = A.lines(); const int32 P = A.pixels(); matrix SMOOTH(L,P); // init to zero... register real8 sum = 0.; register int32 indexii; const real8 Nsmooth = (2*N+1)*(2*N+1); for (register int32 i=0; icr4 ______ #ifdef SPECTRALDOMAIN const int32 L = A.lines(); //const int32 P = A.pixels(); matrix DATA = mat2cr4(A); // or define fft(R4) fft2d(DATA); // or define fft(R4) matrix kernel(1,L); // init to zeros for (register int32 ii=-N; ii<=N; ++ii) // 1d kernel function of block kernel(0,(ii+L)%L) = complr4(1.0/(2*N+1),0.0);// BK 07-Apr-2003 matrix KERNEL2D = matTxmat(kernel,kernel); fft2d(KERNEL2D); // should be real sinc DATA *= KERNEL2D; // no need for conj. with real fft... ifft2d(DATA); // convolution, but still complex... return real(DATA); // you know it is real only... #endif } // END smooth /**************************************************************** * spatialphasefilt * * For the first block the part [0:OVERLAP-1] is set to 0. * * For the last block the part [NPIX-1-OVERLAP:NPIX-1] is 0. * #%// BK 30-Oct-2000 * ****************************************************************/ void spatialphasefilt( const input_gen &generalinput, const productinfo &interferogram, const input_filtphase &filtphaseinput) { TRACE_FUNCTION("spatialphasefilt (BK 30-Oct-2000)") // ====== Handle input ====== bool doexternalfile = false; char infile[EIGHTY]; // file 2b filtered strcpy(infile,interferogram.file); int32 numlinesinput = int32(interferogram.win.lines()/interferogram.multilookL); int32 numpixelsinput = int32(interferogram.win.pixels()/interferogram.multilookP); if (specified(filtphaseinput.fifiltphase)) { doexternalfile = true; numlinesinput = filtphaseinput.finumlines; strcpy(infile,filtphaseinput.fifiltphase); ifstream ifile; openfstream(ifile,infile); bk_assert(ifile,infile,__FILE__,__LINE__); ifile.seekg(0,ios::end); // pointer to end... // const int32 sizefile = ifile.tellg(); // opened ate const streamoff sizefile = ifile.tellg(); // opened ate, MA 64 bit pointer ifile.close(); numpixelsinput = sizefile/sizeof(complr4)/numlinesinput;// floor // if (numlinesinput*numpixelsinput*sizeof(complr4) != uint(sizefile)) if (streamoff(numlinesinput)*streamoff(numpixelsinput)*streamoff(sizeof(complr4)) != sizefile) WARNING.print("Format infile not CR4, or numlines not correct."); INFO.print("Using input file for phase filtering, not default."); } INFO << "phasefilter: inputfile: (#l,#p): " << infile << " (" << numlinesinput << "," << numpixelsinput << ")"; INFO.print(); // ______ Set variables ______ // ______ edge of image not filtered ______ //const int32 SIZE = 512; // the larger the better int32 SIZE = 1024; // blocksize power of 2 if (generalinput.memory<100e6) SIZE/=2; // check memory size 512 if (generalinput.memory<20e6) SIZE/=2; // check memory size 256 while (numlinesinput < SIZE ) SIZE/=2; while (numpixelsinput < SIZE ) SIZE/=2; int32 KERNELSIZE_LINES; int32 KERNELSIZE_PIXELS; // ==L for 1D int32 OVERLAP_LINES; int32 OVERLAP_PIXELS; // ==L for 1D // ______ use FFT's for convolution with rect ______ // ______ this could also be done static, or in the calling routine ______ // ______ KERNEL2D is FFT2 of even kernel (no imag part after fft!) ______ // ______ one could also use ascii input file for 2d kernel ______ matrix KERNEL2D; if (!specified(filtphaseinput.fikernel2d)) { KERNELSIZE_LINES = filtphaseinput.kernel.pixels(); KERNELSIZE_PIXELS = KERNELSIZE_LINES; OVERLAP_LINES = int32(floor(KERNELSIZE_LINES/2.)); OVERLAP_PIXELS = OVERLAP_LINES; // ______ 1d kernel function ______ matrix kernel(1,SIZE); // init to zeros for (register int32 ii=-OVERLAP_LINES; ii<=OVERLAP_LINES; ++ii) kernel(0,(ii+SIZE)%SIZE) = complr4(filtphaseinput.kernel(0,ii+OVERLAP_LINES),0.0);// BK 07-Apr-2003 //kernel(0,(ii+SIZE)%SIZE) = filtphaseinput.kernel(0,ii+OVERLAP_LINES); KERNEL2D = matTxmat(kernel,kernel); } else // use filename and blocksize { KERNEL2D.resize(SIZE,SIZE); INFO.print("Reading 2d kernel from file (PF_IN_KERNEL2D card)."); ifstream kernel2d(filtphaseinput.fikernel2d, ios::in); bk_assert(kernel2d,filtphaseinput.fikernel2d,__FILE__,__LINE__); real4 scalefactor; kernel2d >> KERNELSIZE_LINES >> KERNELSIZE_PIXELS >> scalefactor; if (abs(scalefactor)<=EPS) scalefactor=1.; INFO << "kernel2d: file: lines: rows: scale: " << filtphaseinput.fikernel2d << " " << KERNELSIZE_LINES << " " << KERNELSIZE_PIXELS << " " << scalefactor; INFO.print(); if (!isodd(KERNELSIZE_LINES)) { PRINT_ERROR("2D kernel must have odd number of rows!") throw(argument_error); } if (!isodd(KERNELSIZE_PIXELS)) { PRINT_ERROR("2D kernel must have odd number of columns!") throw(argument_error); } if (KERNELSIZE_LINES >SIZE) { PRINT_ERROR("2D kernel has more rows than blocksize") throw(argument_error); } if (KERNELSIZE_PIXELS>SIZE) { PRINT_ERROR("2D kernel has more columns than blocksize") throw(argument_error); } // ______ DO NOT normalize to 1! ______ OVERLAP_LINES = int32((KERNELSIZE_LINES/2));// i.e., int32() floors OVERLAP_PIXELS = int32((KERNELSIZE_PIXELS/2));// i.e., int32() floors // ______ Shift kernel so centered in space domain around pixels ______ for (int32 ii=-OVERLAP_LINES; ii<=OVERLAP_LINES; ++ii) { real4 tmpvalue; char dummyline[10*ONE27]; // take care of very large kernel kernel2d.getline(dummyline,10*ONE27,'\n'); const int32 indexii = (ii+SIZE)%SIZE; for (int32 jj=-OVERLAP_PIXELS; jj<=OVERLAP_PIXELS; ++jj) { const int32 indexjj = (jj+SIZE)%SIZE; kernel2d >> tmpvalue; KERNEL2D(indexii,indexjj) = complr4(scalefactor*tmpvalue); } } } // 2Dkernel // ______ Give some info ______ INFO << "buffersize: (" << SIZE << ", " << SIZE << ")"; INFO.print(); INFO << "kernelsize: (" << KERNELSIZE_LINES << ", " << KERNELSIZE_PIXELS << ")"; INFO.print(); // ______ Prepare kernel for routine convolution ______ fft2d(KERNEL2D); // input to myconv function KERNEL2D.conj(); // input to myconv function, not required here, but correct. // since fft of even function is real only... // ______ Open output file ______ ofstream ofile; openfstream(ofile,filtphaseinput.fofiltphase,generalinput.overwrit); bk_assert(ofile,filtphaseinput.fofiltphase,__FILE__,__LINE__); // ______ initialize indices ______ const int32 numout = SIZE-(2*OVERLAP_LINES);// number of output lines per buffer int32 cintlinelo = 0; // index in CINT to get 1st buffer int32 cintlinehi = SIZE-1; // index in CINT to get 1st buffer int32 filteredlinelo = 0; // index in FILTERED to write (1st) int32 filteredlinehi = SIZE-OVERLAP_LINES-1; // index in FILTERED to write bool lastbuffer = false; // not yet, just starting... if (!doexternalfile) if (interferogram.formatflag!=FORMATCR4) { PRINT_ERROR("Sorry, for phasefilter, format of interferogram must be CR4") throw(argument_error); } matrix CINT(SIZE,numpixelsinput); // type must be cr4! int32 lineswritten = OVERLAP_LINES; // first buffer extra OVERLAP lines const int32 numbuffers = numlinesinput/numout; // approx? int32 tenpercent = int32((numbuffers/10)+.5); // round int32 percent = 10; if (tenpercent==0) tenpercent = 1000; // avoid error x%0; PROGRESS.print("filtphase: 0%"); // ====== Start filter loop buffers of BLOCKSIZE ====== for (int32 buffer=1; buffer<1e6; ++buffer) { // ______ Check if this will be the last buffer ______ if (cintlinehi >= numlinesinput-1) // -1 since in matrix system { lastbuffer = true; cintlinehi = numlinesinput-1; cintlinelo = cintlinehi-SIZE+1; // make sure SIZE lines are read filteredlinehi = SIZE-1; // write 0's OVERLAP lines const int32 lines2bwritten = numlinesinput-lineswritten; filteredlinelo = filteredlinehi - lines2bwritten + 1; if (lines2bwritten<1) WARNING.print("panic, this will crash, lines2bwritten<1?"); } // ______ Read in buffers of BLOCKSIZE lines complex interferogram ______ const window windummy (0,0,0,0); // no offset in readfile const window wincint (cintlinelo,cintlinehi,0,numpixelsinput-1); readfile(CINT,infile,numlinesinput,wincint,windummy); // ______ Filter data in buffer of BLOCKSIZE lines ______ // ______ output has same size, but write only part to disk ______ matrix FILTERED = convbuffer(CINT,KERNEL2D,OVERLAP_PIXELS); // ______ Write filtered data (i.e. part of FILTERED) ______ // ______ Write overlap zero lines for first buffer and lastbuffer (circular) ______ if (filteredlinelo==0) // firstblock for (int ii=0; ii convbuffer( const matrix &CINT, const matrix &KERNEL2D, const int32 OVERLAP) // overlap in column direction { TRACE_FUNCTION("convbuffer (BK 30-Oct-2000)") //#define CHECKINDICESCALLING #ifdef CHECKINDICESCALLING return CINT; #else // ______ Allocate output matrix ______ const int32 SIZE = CINT.lines(); const int32 NPIX = CINT.pixels(); matrix FILTERED(SIZE,NPIX); // allocate output (==0) // ______ Get block from buffer ______ const int32 numout = SIZE-(2*OVERLAP); // number of output pixels per block int32 cintpixlo = 0; // index in CINT to get 1st block int32 cintpixhi = SIZE-1; // index in CINT to get 1st block //int32 outblockpixlo = 0; // index in BLOCK (only 1st block) int32 outblockpixlo = OVERLAP; // index in block int32 outblockpixhi = SIZE-1-OVERLAP; // index in BLOCK (except last block) int32 outpixlo = outblockpixlo; // index in FILTERED (1st block) int32 outpixhi = outblockpixhi; // index in FILTERED bool lastblockdone = false; // only just started... // ====== Loop forever, stop after lastblockdone ====== for (;;) //forever { if (cintpixhi>=NPIX-1) // check if we are doing the last block { lastblockdone = true; cintpixhi = NPIX-1; // prevent reading after file cintpixlo = cintpixhi-SIZE+1; // but make sure SIZE pixels are read // leave last few==0 outpixhi = NPIX-1-OVERLAP; // index in FILTERED 2b written //outblockpixhi = SIZE-1; // write all to the end outblockpixlo = outblockpixhi - (outpixhi-outpixlo+1) + 1; } const window wincint (0,SIZE-1,cintpixlo,cintpixhi); const window winblock (0,SIZE-1,outblockpixlo,outblockpixhi); const window winfiltered (0,SIZE-1,outpixlo,outpixhi); // ______ Construct BLOCK as part of CINT ______ matrix BLOCK(wincint,CINT); //#define CHECKINDEXONLY #ifndef CHECKINDEXONLY // ______ use FFT's for convolution with kernel ______ fft2d(BLOCK); BLOCK *= KERNEL2D; // no need for conj. cause kernel is even? ifft2d(BLOCK); // conv. in space domain #endif // check index blocks // ______ Set correct part that is filtered in output matrix ______ FILTERED.setdata(winfiltered,BLOCK,winblock); // ______ Exit if finished ______ if (lastblockdone) return FILTERED; // return // ______ Update indexes in matrices, will be corrected for last block ______ cintpixlo += numout; // next block cintpixhi += numout; // next block outpixlo = outpixhi+1; // index in FILTERED, next range line outpixhi = outpixlo+numout-1; // index in FILTERED } // for all blocks in this buffer #endif // check index calling routine } // END convbuffer /**************************************************************** * phasefilterspectral * * loop over whole file and multiply spectrum of interferogram * * with kernel specified in input file. * #%// BK 31-Oct-2000 * ****************************************************************/ void phasefilterspectral( const input_gen &generalinput, const productinfo &interferogram, const input_filtphase &filtphaseinput) { TRACE_FUNCTION("phasefilterspectral (BK 31-Oct-2000)") // ====== Handle input ====== bool doexternalfile = false; if (specified(filtphaseinput.fifiltphase)) doexternalfile = true; char infile[EIGHTY]; // file 2b filtered strcpy(infile,interferogram.file); int32 numlinesinput = int32(interferogram.win.lines()/interferogram.multilookL); int32 numpixelsinput = int32(interferogram.win.pixels()/interferogram.multilookP); if (doexternalfile) // overwrite default file { numlinesinput = filtphaseinput.finumlines; strcpy(infile,filtphaseinput.fifiltphase); ifstream ifile; openfstream(ifile,infile); bk_assert(ifile,infile,__FILE__,__LINE__); ifile.seekg(0,ios::end); // pointer to end... // const int32 sizefile = ifile.tellg(); // opened ate const streamoff sizefile = ifile.tellg(); // opened ate, MA 64 bit pointer ifile.close(); numpixelsinput = sizefile/sizeof(complr4)/numlinesinput;// floor //if (numlinesinput*numpixelsinput*sizeof(complr4) != uint(sizefile)) if (streamoff(numlinesinput)*streamoff(numpixelsinput)*streamoff(sizeof(complr4)) != sizefile) WARNING.print("Format infile not CR4, or numlines not correct."); INFO.print("Using input file for phase filtering, not default."); } INFO << "phasefilter: inputfile: (#l,#p): " << infile << " (" << numlinesinput << "," << numpixelsinput << ")"; INFO.print(); // ______ Set variables ______ const int32 SIZE = filtphaseinput.blocksize; // power of 2 const int32 OVERLAP = filtphaseinput.overlap; // half of the overlap // ______ Open output file ______ ofstream ofile; openfstream(ofile,filtphaseinput.fofiltphase,generalinput.overwrit); bk_assert(ofile,filtphaseinput.fofiltphase,__FILE__,__LINE__); if (!doexternalfile) if (interferogram.formatflag!=FORMATCR4) { PRINT_ERROR("Sorry, for phasefilter, format of interferogram must be CR4") throw(argument_error); } matrix CINT(SIZE,numpixelsinput); // type must be cr4! // ====== Obtain KERNEL2D to multiply spectrum by from input file ====== INFO.print("Reading 2d kernel from file (PF_IN_KERNEL2D card)."); ifstream kernel2d(filtphaseinput.fikernel2d, ios::in); bk_assert(kernel2d,filtphaseinput.fikernel2d,__FILE__,__LINE__); // ______ First read header of kernel2d file ______ int32 KERNELSIZE_LINES = 0; int32 KERNELSIZE_PIXELS = 0; real4 scalefactor = 0.; kernel2d >> KERNELSIZE_LINES >> KERNELSIZE_PIXELS >> scalefactor; if (abs(scalefactor)<=EPS) scalefactor=1.; INFO << "kernel2d: file: lines: rows: scale: " << filtphaseinput.fikernel2d << " " << KERNELSIZE_LINES << " " << KERNELSIZE_PIXELS << " " << scalefactor; INFO.print(); // why should it be odd for spectral filter... //if (!isodd(KERNELSIZE_LINES)) PRINT_ERROR("2D kernel must have odd number of rows!") //if (!isodd(KERNELSIZE_PIXELS)) PRINT_ERROR("2D kernel must have odd number of columns!"); if (KERNELSIZE_LINES >SIZE) { PRINT_ERROR("2D kernel has more rows than blocksize"); throw(argument_error); } if (KERNELSIZE_PIXELS>SIZE) { PRINT_ERROR("2D kernel has more columns than blocksize"); throw(argument_error); } // ______ Then read values of kernel2d ______ // ______ Shift kernel so centered in spectral domain around zero freq. ______ // ______ DO NOT normalize to 1 ______ //const int32 HBS_L = int32(floor(KERNELSIZE_LINES/2)); //const int32 HBS_P = int32(floor(KERNELSIZE_PIXELS/2)); const int32 HBS_L = int32((KERNELSIZE_LINES/2)); const int32 HBS_P = int32((KERNELSIZE_PIXELS/2)); const int32 EXTRA_L = (iseven(KERNELSIZE_LINES)) ? 1:0; // 1 less to fill const int32 EXTRA_P = (iseven(KERNELSIZE_PIXELS)) ? 1:0; // 1 less to fill matrix KERNEL2D(SIZE,SIZE); // allocate THE matrix for (int32 ii=-HBS_L+EXTRA_L; ii<=HBS_L; ++ii) { char dummyline[10*ONE27]; // prevent very large kernels kernel2d.getline(dummyline,10*ONE27,'\n'); const int32 indexii = (ii+SIZE)%SIZE; for (int32 jj=-HBS_P+EXTRA_P; jj<=HBS_P; ++jj) { const int32 indexjj = (jj+SIZE)%SIZE; kernel2d >> KERNEL2D(indexii,indexjj); } } if (scalefactor!=1) KERNEL2D *= scalefactor; // ______ Initialize indices ______ const int32 numout = SIZE-(2*OVERLAP); // number of output lines int32 cintlinelo = 0; // index in CINT to get 1st buffer int32 cintlinehi = SIZE-1; // index in CINT to get 1st buffer int32 filteredlinelo = 0; // index in FILTERED to write (1st) int32 filteredlinehi = SIZE-OVERLAP-1; // index in FILTERED to write (1st) bool lastbuffer = false; // not yet, just starting... int32 lineswritten = OVERLAP; // first buffer extra OVERLAP lines // ______ Progress messages ______ int32 percent = 10; //const int32 numbuffers = numlinesinput/numout; // approx? const int32 numbuffers = numlinesinput/SIZE; // approx for large mem? int32 tenpercent = int32((numbuffers/10)+.5); // round if (tenpercent==0) tenpercent = 1000; // avoid error: x%0 PROGRESS.print("filtphase: 0%"); // ====== Start filter loop buffers of BLOCKSIZE ====== for (int32 buffer=1; buffer<1e6; ++buffer) { // ______ Check if this will be the last buffer ______ if (cintlinehi >= numlinesinput-1) // -1 since in matrix system { lastbuffer = true; cintlinehi = numlinesinput-1; cintlinelo = cintlinehi-SIZE+1; // make sure SIZE lines are read filteredlinehi = SIZE-1; // write upto lastline for last buffer const int32 lines2bwritten = numlinesinput-lineswritten; filteredlinelo = filteredlinehi - lines2bwritten + 1; if (lines2bwritten<1) WARNING.print("panic, this will crash, lines2bwritten<1?"); } // ______ Read in buffers of BLOCKSIZE lines complex interferogram ______ const window windummy (0,0,0,0); // no offset in readfile const window wincint (cintlinelo,cintlinehi,0,numpixelsinput-1); readfile(CINT,infile,numlinesinput,wincint,windummy); // ______ Filter data in buffer of BLOCKSIZE lines ______ // ______ output has same size, but write only part to disk ______ const matrix FILTERED = spectralfilt(CINT,KERNEL2D,OVERLAP); // ______ Write filtered data ______ const window winfiltered (filteredlinelo,filteredlinehi,0,numpixelsinput-1); writefile(ofile,FILTERED,winfiltered); // ______ Check if all done ______ if (lastbuffer) break; // ______ Update indexes in matrices, will be corrected for last block ______ lineswritten += numout; // first block overlap added cintlinelo += numout; // next buffer cintlinehi += numout; // next buffer filteredlinelo = OVERLAP; // index in buffer, // valid for all middle buffers, but not last // ______ Give progress message ______ if (buffer%tenpercent==0) { PROGRESS << "FILTPHASE: " << setw(3) << percent << "%"; PROGRESS.print(); percent += 10; } } // end loop buffers ofile.close(); // ______ exit if only external file was desired ______ if (doexternalfile) { cerr << "\n Finished external file phasefilter, Exiting\n"; PROGRESS.print("\n Finished external file phasefilter, Exiting\n"); exit(0); } // ====== Write results to file ====== ofstream scratchlogfile("scratchlogfiltphase", ios::out | ios::trunc); bk_assert(scratchlogfile,"filtphase: scratchlogfiltphase",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* PHASE FILTER COMPLEX INTERFEROGRAM: \t" << "\n*******************************************************************" << infile << "\nOutput file filtered master (format): \t\t\t" << filtphaseinput.fofiltphase << " " // TODO << "\n..." << "\n*******************************************************************\n"; scratchlogfile.close(); // ______ updateproductinfo greps info from this file ______ ofstream scratchresfile("scratchresfiltphase", ios::out | ios::trunc); bk_assert(scratchresfile,"scratchresfiltphase",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************" << "\n*_Start_" << processcontrol[pr_i_filtphase] << "\n*******************************************************************" << "\nMethod_phasefilt: spectral: size, overlap, kernelfile: \t" // TODO << SIZE << " " << OVERLAP << " " << filtphaseinput.fikernel2d << "\nInput_file: \t" << infile << "\nData_output_file: \t" << filtphaseinput.fofiltphase << "\nData_output_format: \t" << "complex_real4" << "\nFirst_line (w.r.t. original_master): \t" << interferogram.win.linelo << "\nLast_line (w.r.t. original_master): \t" << interferogram.win.linehi << "\nFirst_pixel (w.r.t. original_master): \t" << interferogram.win.pixlo << "\nLast_pixel (w.r.t. original_master): \t" << interferogram.win.pixhi << "\nMultilookfactor_azimuth_direction: \t" << interferogram.multilookL << "\nMultilookfactor_range_direction: \t" << interferogram.multilookP << "\nNumber of lines (multilooked): \t" << numlinesinput << "\nNumber of pixels (multilooked): \t" << numpixelsinput << "\n*******************************************************************" << "\n* End_" << processcontrol[pr_i_filtphase] << "_NORMAL" << "\n*******************************************************************\n"; scratchresfile.close(); // ====== Tidy up ====== } // END phasefilterspectral /**************************************************************** * phasefilter spectral * * Input is matrix of SIZE (e.g. 32) lines, and N range pixels. * * Filtered OUTPUT is same size as input block. * * Because of overlap, only write to disk in calling routine * * part (in matrix coord.) [OVERLAP:SIZE-OVERLAP-1] * * * * Filtering is performed by pointwise multiplication of the * * spectrum per block by the KERNEL2D (input). * * Blocks in range direction, * * * #%// BK 31-Oct-2000 * ****************************************************************/ matrix spectralfilt( const matrix &CINT, const matrix &KERNEL2D, const int32 OVERLAP) { TRACE_FUNCTION("spectralfilt (BK 31-Oct-2000)") // ______ Allocate output matrix ______ const int32 SIZE = CINT.lines(); const int32 NPIX = CINT.pixels(); matrix FILTERED(SIZE,NPIX); // output // ______ Get block from buffer ______ const int32 numout = SIZE-(2*OVERLAP); // number of output pixels int32 cintpixlo = 0; // index in CINT to get 1st block int32 cintpixhi = SIZE-1; // index in CINT to get 1st block int32 outblockpixlo = 0; // index in BLOCK (only 1st block) int32 outblockpixhi = SIZE-1-OVERLAP; // index in BLOCK (except last block) int32 outpixlo = outblockpixlo; // index in FILTERED (1st block) int32 outpixhi = outblockpixhi; // index in FILTERED bool lastblockdone = false; // only just started... // ====== Loop forever, stop after lastblockdone ====== for (;;) //forever { if (cintpixhi>=NPIX-1) // check if we are doing the last block { lastblockdone = true; cintpixhi = NPIX-1; // prevent reading after file cintpixlo = cintpixhi-SIZE+1; // but make sure SIZE pixels are read outpixhi = cintpixhi; // index in FILTERED 2b written outblockpixhi = SIZE-1; // write all to the end outblockpixlo = outblockpixhi - (outpixhi-outpixlo+1) + 1; } const window wincint (0,SIZE-1,cintpixlo,cintpixhi); const window winblock (0,SIZE-1,outblockpixlo,outblockpixhi); const window winfiltered (0,SIZE-1,outpixlo,outpixhi); // ______ Construct BLOCK as part of CINT ______ matrix BLOCK(wincint,CINT); // ______ Get spectrum/filter/ifft ______ fft2d(BLOCK); #ifdef WIN32 matrix temp = KERNEL2D;// Jia BLOCK = timesCxR(BLOCK,temp);// Jia #else BLOCK *= KERNEL2D; // the filter... #endif ifft2d(BLOCK); // ______ Set correct part that is filtered in output matrix ______ FILTERED.setdata(winfiltered,BLOCK,winblock); // ______ Exit if finished ______ if (lastblockdone) return FILTERED; // return // ______ Update indexes in matrices, will be corrected for last block ______ cintpixlo += numout; // next block cintpixhi += numout; // next block outblockpixlo = OVERLAP; // index in block, valid for all middle blocks outpixlo = outpixhi+1; // index in FILTERED, next range line outpixhi = outpixlo+numout-1; // index in FILTERED } // for all blocks in this buffer } // END spectralfilt /**************************************************************** * azimuthfilter * * Loop over whole master and slave image and filter out * * part of the spectrum that is not common. * * Only do zero doppler freq. offset. * * do not use a polynomial from header for now. * * (next we will, but assume image are almost coreg. in range, * * so f_dc polynomial can be eval. same) * * Per block in azimuth [1024] use a certain overlap with the * * next block so that same data is partially used for spectrum * * (not sure if this is requried). * * Filter is composed of: DE-hamming, RE-hamming (for correct * * new size and center of the spectrum). * * Trick in processor.c: First call routine as: * * (generalinput,filtaziinput,master,slave) * * in order to process the master, and then as: * * (generalinput,filtaziinput,slave,master) * * to filter the slave slc image. * #%// BK 01-Nov-2000 * ****************************************************************/ void azimuthfilter( const input_gen &generalinput, const input_filtazi &filtaziinput, slcimage &master, // not const, fdc possibly reset here slcimage &slave) // not const, fdc possibly reset here { TRACE_FUNCTION("azimuthfilter (BK 01-Nov-2000)") // ====== Handle input ====== char infile[EIGHTY]; // file 2b filtered strcpy(infile,master.file); int32 numlinesinput = master.currentwindow.lines(); int32 numpixelsinput = master.currentwindow.pixels(); INFO << "azimuthfilter: inputfile: (#l,#p): " << infile << " (" << numlinesinput << "," << numpixelsinput << ")"; INFO.print(); // ______ Set variables ______ const int32 SIZE = filtaziinput.fftlength;// power of 2 const int32 OVERLAP = filtaziinput.overlap; // half of the overlap const real8 HAMMING = filtaziinput.hammingalpha; matrix FILTER; // i.e., THE filter // ====== If master and slave both have almost constant Doppler, ====== // ====== then reset polynomial to easy case ====== // --- Check variation of Doppler for this crop; zeros in spectrum at correct place --- const real8 max_fdc_change = 0.30*abs(master.prf - master.abw);// 100 Hz or so for ERS const real8 master_fdc_p0 = master.pix2fdc(master.currentwindow.pixlo); const real8 master_fdc_p05 = master.pix2fdc((master.currentwindow.pixhi-master.currentwindow.pixlo)/2); const real8 master_fdc_pN = master.pix2fdc(master.currentwindow.pixhi); const real8 slave_fdc_p0 = slave.pix2fdc(slave.currentwindow.pixlo); const real8 slave_fdc_p05 = slave.pix2fdc((slave.currentwindow.pixhi-slave.currentwindow.pixlo)/2); const real8 slave_fdc_pN = slave.pix2fdc(slave.currentwindow.pixhi); const real8 master_max_dfdc = max(abs(master_fdc_p0-master_fdc_p05),abs(master_fdc_p0-master_fdc_pN)); const real8 slave_max_dfdc = max(abs(slave_fdc_p0-slave_fdc_p05),abs(slave_fdc_p0-slave_fdc_pN)); INFO << "Master: fDC Variation [Hz] = " << master_max_dfdc; INFO.print(); INFO << "Slave: fDC Variation [Hz] = " << slave_max_dfdc; INFO.print(); if (master_max_dfdc1.0 INFO << "New Azimuth Bandwidth: " << ABW_new << " [Hz]"; INFO.print(); INFO << "New central frequency: " << fDC_mean << " [Hz]"; INFO.print(); const real4 deltaf = PRF/real4(SIZE); const real4 fr = -PRF/2.0; matrix freqaxis(1,SIZE); for (int32 i=0; i inversehamming = myhamming(freqaxis,ABW,PRF,HAMMING); for (int32 i=0; i SLCIMAGE(SIZE,numpixelsinput); for (int32 buffer=1; buffer<1e6; ++buffer) { // ______ Check if this will be the last buffer ______ if (slclinehi >= numlinesinput-1) // -1 since in matrix system { lastbuffer = true; slclinehi = numlinesinput-1; slclinelo = slclinehi-SIZE+1; // make sure SIZE lines are read filteredlinehi = SIZE-1; // write upto lastline for last buffer // if there is 1 buffer but smaller than size=fftlength, it cannot work //if (slclinelo < 0) slclinelo = 0; //KKM (not OK, BK: have to take fft) if (slclinelo < 0) { WARNING.print("I think fftlength is too big (>size image)."); WARNING.print("...but i will continue and probably crash."); WARNING.print("PLease run again with smaller fftlength."); } const int32 lines2bwritten = numlinesinput-lineswritten; filteredlinelo = filteredlinehi - lines2bwritten + 1; if (lines2bwritten<1) WARNING.print("panic, this will crash, lines2bwritten<1?"); } // ______ Read buffer of BLOCKSIZE lines in SLCIMAGE ______ const window windummy (0,0,0,0); // no offset in readfile const window winslc (slclinelo,slclinehi,0,numpixelsinput-1); switch (master.formatflag) { case FORMATCI2: { fileci2tomatcr4(SLCIMAGE,infile,numlinesinput,winslc,windummy); break; } case FORMATCR4: { readfile(SLCIMAGE,infile,numlinesinput,winslc,windummy); break; } default: { PRINT_ERROR("readdata::not correct format on file.") throw(unhandled_case_error); } } // ______ Filter data in buffer of BLOCKSIZE lines ______ // ______ output has same size, but write only part to disk ______ matrix FILTERED; if (samefd0==true) { // ______ Same filter for all columns ______ fft(SLCIMAGE,1); // fft foreach column FILTERED = diagxmat(FILTER,SLCIMAGE); // filter each column ifft(FILTERED,1); // ifft foreach column } else { // ______ Filter depends on columns number ______ FILTERED = blockazifilt(SLCIMAGE,master,slave,HAMMING); } // ______ Write filtered data ______ const window winfiltered(filteredlinelo,filteredlinehi,0,numpixelsinput-1); switch (filtaziinput.oformatflag) { case FORMATCR4: { writefile(ofile,FILTERED,winfiltered); break; } // ______ Convert first to ci2 before writing to file ______ case FORMATCI2: { matrix TMP(FILTERED.lines(),FILTERED.pixels()); for (uint ii=winfiltered.linelo; ii<=winfiltered.linehi; ++ii) for (uint jj=winfiltered.pixlo; jj<=winfiltered.pixhi; ++jj) TMP(ii,jj) = cr4toci2(FILTERED(ii,jj)); writefile(ofile,TMP,winfiltered); break; } default: { PRINT_ERROR("Totally impossible, checked input.") throw(unhandled_case_error); } } // ______ Check if all done ______ if (lastbuffer) break; // ______ Update indexes in matrices, will be corrected for last block ______ lineswritten += numout; // first block overlap added slclinelo += numout; // next buffer slclinehi += numout; // next buffer filteredlinelo = OVERLAP; // index in buffer, // valid for all middle buffers, but not last // ______ Give progress message ______ if (buffer%tenpercent==0) { PROGRESS << "FILTAZI: " << setw(3) << percent << "%"; PROGRESS.print(); percent += 10; } } // end loop buffers ofile.close(); // ====== Write results to file ====== ofstream scratchlogfile("scratchlogfiltazi", ios::out | ios::trunc); bk_assert(scratchlogfile,"filtazi: scratchlogfiltazi",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* PHASE FILTER COMPLEX INTERFEROGRAM: \t" << "\n*******************************************************************" << infile << "\nOutput file filtered : \t\t\t" << "\n..." << "\n*******************************************************************\n"; scratchlogfile.close(); // ______ updateproductinfo greps info from this file ______ ofstream scratchresfile("scratchresfiltazi", ios::out | ios::trunc); bk_assert(scratchresfile,"scratchresfiltazi",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************" << "\n*_Start_" << processcontrol[pr_m_filtazi] << "\n*******************************************************************" << "\nInput_file: \t" << infile << "\nData_output_file: \t" << filtaziinput.foname << "\nData_output_format: \t"; // ___ report of Mohanty Kamini Kanta i forgot this jun12/03___ if (filtaziinput.oformatflag==FORMATCR4) scratchresfile << "complex_real4"; if (filtaziinput.oformatflag==FORMATCI2) scratchresfile << "complex_short"; scratchresfile << "\nFirst_line (w.r.t. original_image): \t" << master.currentwindow.linelo << "\nLast_line (w.r.t. original_image): \t" << master.currentwindow.linehi << "\nFirst_pixel (w.r.t. original_image): \t" << master.currentwindow.pixlo << "\nLast_pixel (w.r.t. original_image): \t" << master.currentwindow.pixhi << "\n*******************************************************************" << "\n* End_" << processcontrol[pr_m_filtazi] << "_NORMAL" << "\n*******************************************************************\n"; scratchresfile.close(); // ====== Tidy up ====== } // END azimuthfilter /**************************************************************** * azimuth filter per block * * Input is matrix of SIZE (e.g. 1024) lines, and N range pixs. * * Input is SLC of master. slave_info gives fDC polynomial * * for slave + coarse offset. HAMMING is alpha for myhamming f. * * Filtered OUTPUT is same size as input block. * * Because of overlap (azimuth), only write to disk in calling * * routine part (in matrix coord.) [OVERLAP:SIZE-OVERLAP-1] * * = SIZE-(2*OVERLAP); // number of output pixels * * * * Filtering is performed in the spectral domain * * (1DFFT over azimuth for all columns at once) * * Filter is different for each column due to shift in fd_c * * doppler centroid frequency. * * * * ! It should still be studied if real4 matrices are accurate * * enough, but I guess it is (BK). * * * #%// BK 06-Nov-2000 * ****************************************************************/ matrix blockazifilt( const matrix &SLCIMAGE, const slcimage &master, // PRF, BW, fd0 const slcimage &slave, // PRF, BW, fd0 const real8 HAMMING) { TRACE_FUNCTION("blockazifilt (BK 06-Nov-2000)") const uint SIZE = SLCIMAGE.lines(); // fftlength const uint NCOLS = SLCIMAGE.pixels(); // width if (NCOLS != master.currentwindow.pixels()) WARNING.print("this will crash, size input matrix not ok..."); // ______ Compute fDC_master, fDC_slave for all columns ______ // ______ Create axis to evaluate fDC polynomial for master/slave ______ // ______ fDC(column) = fdc_a0 + fDC_a1*(col/RSR) + fDC_a2*(col/RSR)^2 ______ // ______ fDC = y = Ax ______ // ______ Capitals indicate matrices (FDC_M <-> fDC_m) ______ DEBUG.print("Filtering data by evaluated polynomial fDC for each column."); matrix xaxis(1,master.currentwindow.pixels()); // lying for (int32 i=master.currentwindow.pixlo; i<=int32(master.currentwindow.pixhi); ++i) xaxis(0,i-master.currentwindow.pixlo) = real8(i-1.0); xaxis /= (master.rsr2x/2.0); matrix FDC_M = (master.f_DC_a1 * xaxis); FDC_M += master.f_DC_a0; FDC_M += (master.f_DC_a2 * sqr(xaxis));// TODO: better use master.pix2fdc() // Bert Kampes, 20-Apr-2005 // ______ fDC_slave for same(!) columns (coarse offset). ______ // ______ offset defined as: cols=colm+offsetP ______ for (int32 i=master.currentwindow.pixlo; i<=int32(master.currentwindow.pixhi); ++i) xaxis(0,i-master.currentwindow.pixlo) = real8(i-1.0) + real8(slave.coarseoffsetP); xaxis /= (slave.rsr2x/2.0); matrix FDC_S = (slave.f_DC_a1 * xaxis); FDC_S += slave.f_DC_a0; FDC_S += (slave.f_DC_a2 * sqr(xaxis)); #ifdef __DEBUG DEBUG.print("Dumping matrices fDC_m, fDC_s (__DEBUG defined)"); dumpasc("fDC_m",FDC_M); dumpasc("fDC_s",FDC_S); #endif // ______ Axis for filter in frequencies ______ // TODO check, rather shift, test matlab... or wshift,1D over dim1 // use fft properties to shift... const bool dohamming = (HAMMING<0.9999) ? true : false; const real8 PRF = master.prf; // pulse repetition freq. [Hz] const real8 ABW = master.abw; // azimuth band width [Hz] const real4 deltaf = PRF/real4(SIZE); const real4 fr = -PRF/2.0; matrix freqaxis(1,SIZE); for (uint i=0; i FILTER; // i.e., the filter per column matrix FILTERMAT(SIZE,NCOLS); // i.e., THE filter for (uint i=0; i 1.0 if (dohamming) { // ______ NOT a good implementation for per col., cause wshift AND fftshift. // ______ DE-weight spectrum at centered at fDC_m ______ // ______ spectrum should be periodic! (use wshift) ______ matrix inversehamming = myhamming(freqaxis,ABW,PRF,HAMMING); for (uint ii=0; ii FILTERED = SLCIMAGE; fft(FILTERED,1); // fft foreach column #ifdef WIN32 FILTERED = timesCxR(FILTERED,FILTERMAT);// Jia #else FILTERED *= FILTERMAT; // filter each column #endif ifft(FILTERED,1); // ifft foreach column return FILTERED; } // END blockazifilt /**************************************************************** * rangefiltporbits * * -getoverlap approx between master/slave. * * -get next line master/slave. * * -compute freq. shift due to different incidence angle. * * -filter master and slave. * * -write output. * #%// BK 13-Nov-2000 * * BUG detected by Rens Swart (26-Apr-2001): * * if fftlength < width/2 then output consists of replicas * * number of replicas = int(width/fftlength) - 1 * ****************************************************************/ void rangefiltporbits( const input_gen &generalinput, const input_filtrange &filtrangeinput, const input_ell &ellips, const slcimage &master, const slcimage &slave, orbit &masterorbit, orbit &slaveorbit) { TRACE_FUNCTION("rangefiltporbits (BK 13-Nov-2000)") // ______ RSR,RBW in Hz, SI ______ const real8 HAMMINGA = filtrangeinput.hammingalpha; const bool dohamming = (HAMMINGA<0.9999) ? true : false; const real8 RSR = 0.5*master.rsr2x; // range sampling rate fr 18.96MHz const real8 RBW = master.rbw; // range band width fs 15.55MHz // ______ Use approximate overlap master slave ______ // ______ s=m+offset --> m=s-offset ______ // ______ prevent a-b uint (< 0) == very large ______ window wintmp; int32 tmp = slave.currentwindow.linelo - slave.coarseoffsetL; wintmp.linelo = (tmp<1) ? 1 : tmp; tmp = slave.currentwindow.linehi - slave.coarseoffsetL; wintmp.linehi = (tmp<1) ? 1 : tmp; tmp = slave.currentwindow.pixlo - slave.coarseoffsetP; wintmp.pixlo = (tmp<1) ? 1 : tmp; tmp = slave.currentwindow.pixhi - slave.coarseoffsetP; wintmp.pixhi = (tmp<1) ? 1 : tmp; // ______ master.currentwin and wintmp are now in same system ______ window overlap = getoverlap(master.currentwindow,wintmp); TRACE << "overlap window: " << overlap.linelo << " " << overlap.linehi << " " << overlap.pixlo << " " << overlap.pixhi; TRACE.print(); // ______ Initialize loop parameters etc. ______ int32 FFTLENGTH = filtrangeinput.fftlength; const int32 NCOLS = overlap.pixels(); // width 2b processed while (FFTLENGTH>NCOLS) { WARNING << "FFTLENGTH>overlap: New length: " << FFTLENGTH << " --> " << FFTLENGTH/2; WARNING.print(); FFTLENGTH /= 2; } const int32 NBLOCKS = int32((NCOLS/FFTLENGTH)); const int32 EXTRA = ((NCOLS%FFTLENGTH)==0) ? 0:1; // last overlaps previous cn M; // master position cn S; // slave position cn P; // P on ellipsoid, perpendicular to orbits; const int32 MAXITER = 10; const real8 CRITERPOS = 1e-6; const real8 CRITERTIM = 1e-10; INFO << "rangefiltporbits: MAXITER: " << MAXITER << "; " << "CRITERPOS: " << CRITERPOS << " m; " << "CRITERTIM: " << CRITERTIM << " s"; INFO.print(); // ====== Open output files ====== ofstream of_m; openfstream(of_m,filtrangeinput.fomaster,generalinput.overwrit); bk_assert(of_m,filtrangeinput.fomaster,__FILE__,__LINE__); ofstream of_s; openfstream(of_s,filtrangeinput.foslave,generalinput.overwrit); bk_assert(of_s,filtrangeinput.foslave, __FILE__,__LINE__); // ______ Shift parameters ______ //register int32 i; const real4 df = RSR/real4(FFTLENGTH); const real4 fr = -RSR/2.; matrix freqaxis(1,FFTLENGTH); for (uint i=0; i inversehamming; if (dohamming) { inversehamming = myhamming(freqaxis,RBW,RSR,HAMMINGA); for (uint i=0; i MASTER = master.readdata(win_m); matrix SLAVE = slave.readdata(win_s); fft(MASTER,2); fft(SLAVE,2); // ______ Compose filter for master and slave, and filter both ______ matrix FILTER; // for master, slave=fliplr(m) if (dohamming) { // ______ Newhamming is scaled and centered around new mean ______ // Plus or min?, master or slave? FILTER = myhamming(freqaxis-real4(.5*deltaf),// new center RBW-deltaf, // new width RSR,HAMMINGA); // fftshifted FILTER *= inversehamming; // rect f. included } else // no weighting of spectra { FILTER = myrect((freqaxis-real4(.5*deltaf)) / real4(RBW-deltaf)); // fftshifted } ifftshift(FILTER); // fftsh works on data! // ______ Note that filter_s = fliplr(filter_m) ______ // ______ and that this is also valid after ifftshift ______ // ______ I tested what side had to be filtered: master first ______ // ______ or slave first. Now it should always work. ______ // ______ But comment out define if you think wrong side is filtered ______ #define THISside #ifdef THISside #ifdef WIN32 MASTER = timesCxR(MASTER,FILTER);// Jia FILTER.fliplr(); SLAVE = timesCxR(SLAVE,FILTER);// Jia #else MASTER *= FILTER; // filtered master range spectral domain FILTER.fliplr(); SLAVE *= FILTER; // filtered slave range spectral domain #endif #else WARNING.print("This is not as theory, sign Bperp defined otherwise?"); SLAVE *= FILTER; // filtered slave range spectral domain FILTER.fliplr(); MASTER *= FILTER; // filtered master range spectral domain #endif ifft(MASTER,2); // back to space domain ifft(SLAVE,2); // back to space domain // ______ Write to new output file for master and slave ______ if (lastblock==false) { switch (filtrangeinput.oformatflag) { case FORMATCR4: { of_m << MASTER; of_s << SLAVE; break; } // ______ Convert first to ci2 before writing to file ______ case FORMATCI2: { matrix TMP(1,MASTER.pixels()); for (uint ii=0; ii TMP_M(wintmp,MASTER); // construct as part matrix TMP_S(wintmp,SLAVE); // construct as part switch (filtrangeinput.oformatflag) { case FORMATCR4: { of_m << TMP_M; of_s << TMP_S; break; } // ______ Convert first to ci2 before writing to file ______ case FORMATCI2: { matrix TMP(1,TMP_M.pixels()); for (uint ii=0; ii m=s-offset ______ // ______ still in own system! ______ << "\nFirst_line (w.r.t. original_image): \t" << overlap.linelo + offsetL << "\nLast_line (w.r.t. original_image): \t" << overlap.linehi + offsetL << "\nFirst_pixel (w.r.t. original_image): \t" << overlap.pixlo + offsetP << "\nLast_pixel (w.r.t. original_image): \t" << overlap.pixhi + offsetP << "\n*******************************************************************" << "\n* End_" << processcf << "_NORMAL" << "\n*******************************************************************\n"; scratchresfile.close(); } // for master and slave } // END rangefiltporbits Doris-5.0.3Beta/doris_core/filtering.hh000077500000000000000000000127531312547014700200460ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/filtering.hh,v $ * $Revision: 3.9 $ * $Date: 2005/08/24 10:03:18 $ * $Author: kampes $ * * Declaration of routines for filtering ****************************************************************/ #ifndef FILTERING_H // guard #define FILTERING_H using namespace std; // BK 29-Mar-2003, new compiler? // Jia defined this for compilation under windows // Bert Kampes, 24-Aug-2005 #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "constants.hh" // typedefs #include "readinput.hh" // input structs #include "matrixbk.hh" // my matrix class #include "slcimage.hh" // my slc image class #include "orbitbk.hh" // my orbit class #include "productinfo.hh" // my 'products' class // ______ Adaptive range filtering, estimate local fringe frequency _____ void rangefilter( const input_gen &generalinput, const slcimage &master, const slcimage &slave, const productinfo &interferogram, const input_filtrange &filtrangeinput); // ______ Iteratively called by rangefilter ______ void rfilterblock( matrix &MASTER, // updated matrix &SLAVE, // updated int32 nlmean, real8 SNRthreshold, real8 RSR, // in MHz? real8 RBW, // in MHz? real8 hammingalpha, int32 oversamplefactor, // pow2 bool docorrectcorrel, real8 &meanSNR, // returned real8 &percentnotfiltered);// returned // ______ Range filtering based on orbit _____ void rangefiltporbits( const input_gen &generalinput, const input_filtrange &filtrangeinput, const input_ell &ellips, const slcimage &master, const slcimage &slave, orbit &masterorbit, orbit &slaveorbit ); // ====== Adaptive phase filtering, weight spectrum, goldstein ====== void phasefilter( const input_gen &generalinput, const productinfo &interferogram, const input_filtphase &filtphaseinput, const productinfo &coherence); // ______ goldstein filter per buffer ______ matrix goldstein( const matrix &CINT, const real4 ALPHA, const int32 OVERLAP, const matrix &smoothkernel); // ______ modified goldstein filter per buffer ______ matrix modgoldstein( const matrix &CINT, const matrix &COH, const int32 OVERLAP, const matrix &smoothkernel); // ______ Smooth by spatial circular averaging over 2N+1 box ______ matrix smooth( const matrix &A, int32 halblocksize); // ______ Smooth by FFT's, KERNEL2D once computed for ______ // ______ recursive calls to smooth routine, save time ______ matrix smooth( const matrix &A, const matrix &KERNEL2D); // ====== Spatial convolution filter per buffer ====== void spatialphasefilt( const input_gen &generalinput, const productinfo &interferogram, const input_filtphase &filtphaseinput); // ______ Spatial convolution filter per block _____ matrix convbuffer( const matrix &CINT, const matrix &KERNEL2D, const int32 OVERLAP); // ====== phase filtering, spectral ====== void phasefilterspectral( const input_gen &generalinput, const productinfo &interferogram, const input_filtphase &filtphaseinput); // ______ spectral filter per buffer ______ matrix spectralfilt( const matrix &CINT, const matrix &KERNEL2D, const int32 OVERLAP); // ====== azimuth filter ====== void azimuthfilter( const input_gen &generalinput, const input_filtazi &filtaziinput, slcimage &master, slcimage &slave); matrix blockazifilt( const matrix &SLCIMAGE, const slcimage &master, // PRF, BW, fd0 const slcimage &slave, // PRF, BW, fd0 const real8 HAMMING); #endif // FILTERING_H Doris-5.0.3Beta/doris_core/geocode.cc000077500000000000000000001722411312547014700174550ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/geocode.cc,v $ * * $Revision: 3.16 $ * * $Date: 2005/10/06 11:09:20 $ * * $Author: kampes $ * * * * implementation of computation of endproducts (DEM, defo.map) * * -slant range 2 height (schwabisch) * * -slant range 2 height (rodriguez, exact, some problems) * * -slant range 2 height (ambiguity) * * -geocode heightmatrix to phi,lambda * ****************************************************************/ #include "constants.hh" // global constants #include "matrixbk.hh" // my matrix class #include "slcimage.hh" // my slc image class #include "productinfo.hh" // my 'products' class #include "geocode.hh" // header file #include "utilities.hh" // utils #include "ioroutines.hh" // error messages #include "coregistration.hh" // distributepoints #include "exceptions.hh" // my exceptions class #include // for memory stream #include // isspace #include // max /**************************************************************** * slant2h eight (schwabisch) * * * * compute height in radar coded system (master): * * * * Input: * * - * * Output: * * - * * * * See thesis swabisch for method * * 1. compute reference phase for h=0,2000,4000 in Npoints * * 2. solve system: h(phi) = a_0 + a_1*phi + a_2*phi*phi * * (2nd degree 1D polynomial) for all Npoints * * 3. compute a_i (l,p) = DEGREE2D 2D polynomial * * 4.0 set offset to the one of first pixel , add this to all * * this step is skipped, phase is w.r.t. h=0, ref. is subtracted * * 4.1 evaluate polynomial of 3. for all points (l,p) of * * (multilooked) unwrapped interferogram * * solution to system for betas seems not very stable? * * * * Bert Kampes, 02-Jun-1999 * ****************************************************************/ void slant2hschwabisch( const input_gen &generalinput, const input_slant2h &slant2hinput, const input_ell &ellips, const slcimage &master, const slcimage &slave, const productinfo &unwrappedinterf, orbit &masterorbit, orbit &slaveorbit) { TRACE_FUNCTION("slant2hschwabisch (BK 02-Jun-1999)") const int32 MAXITER = 10; const real8 CRITERPOS = 1e-6; const real8 CRITERTIM = 1e-10; const real8 m_minpi4cdivlambda = (-4.*PI*SOL)/master.wavelength; const real8 s_minpi4cdivlambda = (-4.*PI*SOL)/slave.wavelength; const int32 Npoints = slant2hinput.Npoints; // where ref.phase is evaluated const int32 DEGREE1D = slant2hinput.degree1d; // only possible now. const int32 DEGREE2D = slant2hinput.degree2d; const int32 Nheights = slant2hinput.Nheights; const int32 MAXHEIGHT = 5000; // max hei for ref.phase const int32 TEN = 10; // used in pointer if (DEGREE1D - 1 > TEN) { PRINT_ERROR("panic, programmers problem: increase TEN.") throw(some_error); } const int32 HEIGHTSTEP = MAXHEIGHT / (Nheights - 1); // heights to eval ref.phase // ______ Matrices for storing phase for all ref. ellipsoids ______ // ______ PHASE(i,0) phase for height 0 // ______ PHASE(i,1) phase for height Heigthsep * 1 // ______ PHASE(i,Nh) phase for height 4000 matrix PHASE(Npoints,Nheights); // pseudo-observation // ______ Distribute points in original master system (not multilooked) ______ // ______ (i,0): line, (i,1): pixel, (i,2) flagfromdisk (not used here) ______ //matrix Position = distributepoints(Npoints,unwrappedinterf.win); // [FvL] for correct folding of points outside overlap window when inserted by file matrix Position = distributepoints(Npoints,unwrappedinterf.win); // ====== STEP 1 ====== // ====== Compute reference phase in N points for height (numheight) ====== PROGRESS.print("S2H: schwabisch: STEP1: compute reference phase for Nheights."); register int32 numheight; register int32 i,j,k,l,index; register int32 alfa; for (numheight=0; numheight phi[0,1] ______ matrix DESIGN(Nheights,DEGREE1D+1); // design matrix matrix ALPHAS(Npoints,DEGREE1D+1); // pseudo-observation matrix HEI(Nheights,1); for (i=0; i N = matTxmat(DESIGN,DESIGN); matrix rhs = matTxmat(DESIGN,HEI); matrix Qx_hat = N; choles(Qx_hat); // Cholesky factorisation normalmatrix solvechol(Qx_hat,rhs); // Estimate of unknowns (alphas) in rhs // ______ Test inverse ______ invertchol(Qx_hat); // Covariance matrix (lower) for (uint k=0; k A(Npoints,Nunk); // designmatrix // ______ Set up system of equations ______ // ______ Order unknowns: B00 B10 B01 B20 B11 B02 B30 B21 B12 B03 for degree=3 ______ const real8 minL = min(Position.getcolumn(0)); const real8 maxL = max(Position.getcolumn(0)); const real8 minP = min(Position.getcolumn(1)); const real8 maxP = max(Position.getcolumn(1)); for (i=0; i N = matTxmat(A,A); matrix rhs = matTxmat(A,ALPHAS); matrix Qx_hat = N; choles(Qx_hat); // Cholesky factorisation normalmatrix ///// solvechol(Qx_hat,rhs); // Estimate of unknowns (betas) in rhs, NOT OK! // ______ Solve the normal equations for all alpha_i ______ // ______ Simultaneous solution doesn't work somehow ______ for (uint i=0; i rhs_alphai = rhs.getcolumn(i); solvechol(Qx_hat,rhs_alphai); // Solution in rhs_alphai rhs.setcolumn(i,rhs_alphai); // place solution back } // ______ Test solution by inverse ______ invertchol(Qx_hat); // Covariance matrix (lower) for (uint i=0; i 0.01"; WARNING.print(); } // ====== STEP 4 ====== PROGRESS.print("S2H: schwabisch: STEP4: compute height for all pixels."); // ====== Evaluate for all points interferogram h=f(l,p,phase) ====== // ______ recon with multilook, degree1D, degree2D free // ______ Multilook factors ______ const real8 multiL = unwrappedinterf.multilookL; const real8 multiP = unwrappedinterf.multilookP; // ______ Number of lines/pixels of multilooked unwrapped interferogram ______ const int32 mllines = int32(floor(real8( unwrappedinterf.win.linehi-unwrappedinterf.win.linelo+1) / multiL)); const int32 mlpixels = int32(floor(real8( unwrappedinterf.win.pixhi-unwrappedinterf.win.pixlo+1) / multiP)); // ______ Line/pixel of first point in original master coordinates ______ const real8 veryfirstline = real8(unwrappedinterf.win.linelo) + (real8(multiL) - 1.) / 2.; const real8 firstpixel = real8(unwrappedinterf.win.pixlo) + (real8(multiP) - 1.) / 2.; // ______ Constant axis of pixel coordinates ______ matrix p_axis(mlpixels,1); for (i=0; i mllines) // whole image fits in BUFFER bufferlines = mllines; const int32 FULLBUFFERS = mllines / bufferlines; const int32 RESTLINES = mllines % bufferlines; const int32 EXTRABUFFER = RESTLINES ? 1 : 0; // ______ Window to be read into BUFFER from file in multilooked system ______ const uint dummy = 999999; // large to force error if not ok window bufferwin(1, bufferlines, 1, mlpixels); // initial window offsetbuffer(1,dummy,1,dummy); // dummy not used in readfile, no offset // ______ Open output file ______ ofstream ofile; openfstream(ofile,slant2hinput.fohei,generalinput.overwrit); bk_assert(ofile,slant2hinput.fohei,__FILE__,__LINE__); // ====== Process BUFFERS ====== for (register int32 buffer=1; buffer<=FULLBUFFERS+EXTRABUFFER; buffer++) { // ______ Give progress ______ PROGRESS << "SLANT2H: " << 100*(buffer-1)/(FULLBUFFERS+EXTRABUFFER) << "%"; PROGRESS.print(); // ______ In original master coordinate sytem ______ const real8 firstline = veryfirstline + (buffer-1) * bufferlines * multiL; // ______ Set indices for loading / check last buffer ______ bufferwin.linelo = 1 + (buffer-1) * bufferlines; // Update window to be read from file if (buffer == FULLBUFFERS+1) { bufferlines = RESTLINES; //BUFFER.resize(bufferlines,mlpixels); } bufferwin.linehi = bufferwin.linelo + bufferlines - 1; // window 2b read from file // ______ Read in phase buffer of unwrapped interferogram ______ matrix BUFFER = unwrappedinterf.readphase(bufferwin); // ______ Evaluate polynomial coefficients for these points ______ // ______ Compute first line of current buffer in master coordinates ______ matrix l_axis(bufferlines,1); for (k=0; kshowdata(); // (*pntALPHA[0][0]).showdata(); // containing a grid of 1D coefficients matrix *pntALPHA[TEN]; for (k=0; k<=DEGREE1D; k++) { matrix beta(Ncoeffs(DEGREE2D),1); for (l=0; l (l_axis.lines(),p_axis.lines()); (*pntALPHA[k]) = polyval(l_axis, p_axis, beta, DEGREE2D); // [MA] } // ______ Evaluate h=f(l,p,phi) for all points in grid in BUFFER ______ matrix coeff_thispoint(DEGREE1D+1,1); for (uint line=0; line mllines) // whole image fits in BUFFER bufferlines = mllines; const int32 FULLBUFFERS = mllines / bufferlines; const int32 RESTLINES = mllines % bufferlines; const int32 EXTRABUFFER = RESTLINES ? 1 : 0; // ______ Window to be read into BUFFER from file in multilooked system ______ // matrix BUFFER(bufferlines,mlpixels); // unwrapped phase and height // matrix PHI(BUFFER.lines(),BUFFER.pixels()); // geocoded // matrix LAMBDA(BUFFER.lines(),BUFFER.pixels()); // geocoded window bufferwin(1, bufferlines, 1, mlpixels); // initial // ______ Open output file ______ ofstream fohei; openfstream(fohei,slant2hinput.fohei,generalinput.overwrit); bk_assert(fohei,slant2hinput.fohei,__FILE__,__LINE__); ofstream fophi; openfstream(fophi,slant2hinput.fophi,generalinput.overwrit); bk_assert(fophi,slant2hinput.fophi,__FILE__,__LINE__); ofstream folambda; openfstream(folambda,slant2hinput.folam,generalinput.overwrit); bk_assert(folambda,slant2hinput.folam,__FILE__,__LINE__); // ______ Local variables ______ cn M; // coordinates of master in orbit cn Mdot; // velocity of master in orbit cn S; // coordinates of slave in orbit cn P; // coordinates of point on earth real8 sintheta = 0.0; // sine looking angle real8 costheta = 0.0; // cosine looking angle real8 inc_angle = 0.0; // incidence angle by KKM matrix observations(3,1); // setofeq matrix partials(3,3); // partial derivatives matrix solution(3,1); // solution of setofeq. // ====== Process BUFFERS ====== for (register int32 buffer=1; buffer<=FULLBUFFERS+EXTRABUFFER; ++buffer) { // ______ Give progress ______ PROGRESS << "SLANT2H: " << 100*(buffer-1)/(FULLBUFFERS+EXTRABUFFER) << "%"; PROGRESS.print(); // ====== First read in data ====== // ______ firstline of this buffer in master coordinate system ______ real8 firstline = veryfirstline + real8((buffer-1) * bufferlines * multiL); // ______ Set indices to be read from file / check if last buffer ______ bufferwin.linelo = 1 + (buffer-1) * bufferlines; if (buffer == FULLBUFFERS+1) { bufferlines = RESTLINES; } bufferwin.linehi = bufferwin.linelo + bufferlines - 1; // ______ Read in buffer of unwrapped interferogram ______ matrix BUFFER = unwrappedinterf.readphase(bufferwin); matrix PHI(BUFFER.lines(),BUFFER.pixels()); // geocoded matrix LAMBDA(BUFFER.lines(),BUFFER.pixels()); // geocoded // ====== Actually compute h for all points ====== // ====== (better use inverse function in baseline, ie., schwabisch method.) input_ell ELLIPS = ellips; // to put P at height above ellips register real8 line = firstline - multiL; // in master coordinate system for (uint i=0; i0 if (MP>SP) then S is to the right of slant line costheta = ((-(P.norm2()) + norm2M + // cosine law sqr(master.pix2range(temppixel))) / (2*sqrt(norm2M)*master.pix2range(temppixel))); sintheta = sqrt(1-sqr(costheta)); // cos^2 + sin^2 = 1 const cn r2 = S.min(P); // vector; to find sign const real8 costheta2 = M.in(r2) / (M.norm()*r2.norm()); Bperp = (costheta < costheta2) ? // sign ok sqrt(sqr(B)-sqr(Bpar)) : -sqrt(sqr(B)-sqr(Bpar)); } else { // --- New method with BASELINE class and incidence angle --- Bpar = baseline.get_bpar(line,temppixel,currentheight); Bperp = baseline.get_bperp(line,temppixel,currentheight); costheta = cos(baseline.get_theta_inc(line,temppixel,currentheight)); sintheta = sqrt(1.0-sqr(costheta)); inc_angle = baseline.get_theta_inc(line,temppixel,currentheight);//KKM } // --- Update height --- lastheight = currentheight; const real8 m_tr = master.pix2tr(temppixel); const real8 tempr1 = SOL*m_tr; currentheight = (-master.wavelength*tempr1*sin(inc_angle)*tempphase)/ (4.*PI*Bperp);//KKM added this // ______ Check convergence ______ if (abs(currentheight-lastheight) < CRITERHERE) break; // iterate to get h } // loop iterations (j) // ______ Check number of iterations ______ if (j >= MAXITERHERE) { WARNING << "slant2hambiguity: maxiter reached. " << "MAXITER: " << MAXITERHERE << "CRITER: " << CRITERHERE << "m " << "last correction: " << currentheight-lastheight; WARNING.print(); } } // check lineokunwrapped (all NaNs) // ______ The baseline parameters that are used foreach pixel ______ // this is not correct, Bhor not same for each pixel? // BK 09-Aug-2000 const real8 Bhor = Bperp*costheta + Bpar*sintheta; const real8 Bver = Bperp*sintheta - Bpar*costheta; currentheight = 0.0; // this iteration lastheight = 0.0; // last iteration // ====== Start loop over pixels ====== for (uint j=0; j= MAXITERHERE) { WARNING << "slant2hambiguity: maxiter reached. " << "MAXITER: " << MAXITERHERE << "CRITER: " << CRITERHERE << "m " << "last correction: " << currentheight-lastheight; WARNING.print(); } // ______ Put computed height in buffer ______ BUFFER(i,j) = currentheight; // ______ Geocode P(x,y,z) --> lat/lon/hei (h already known) ______ real8 tmp_phi, tmp_lambda; ellips.xyz2ell(P, tmp_phi, tmp_lambda);// WGS84 coordinates PHI(i,j) = rad2deg(tmp_phi); LAMBDA(i,j) = rad2deg(tmp_lambda); } // unwrapped ok } // loop over pixels } // loop over lines fohei << BUFFER; // write output fophi << PHI; // write output folambda << LAMBDA; // write output } // loop over buffers // ====== Write to result files ====== ofstream scratchlogfile("scratchlogslant2h", ios::out | ios::trunc); bk_assert(scratchlogfile,"slant2h: scratchlogslant2h",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* " << processcontrol[pr_i_slant2h] << "\n*******************************************************************" << "\nMethod: \t\t\tambiguity" << "\nData_output_file: \t\t" << slant2hinput.fohei << "\nData_output_format: \t\t" << "real4" << "\nData_output_file_phi: \t\t" << slant2hinput.fophi << "\nData_output_format: \t\t" << "real4" << "\nData_output_file_lam: \t\t" << slant2hinput.folam << "\nData_output_format: \t\t" << "real4" << "\nEllipsoid (name,a,b): \t\t" << ellips.name << " " << ellips.a << " " << ellips.b << endl; scratchlogfile.close(); ofstream scratchresfile("scratchresslant2h", ios::out | ios::trunc); bk_assert(scratchresfile,"slant2h: scratchresslant2h",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************" << "\n*_Start_" << processcontrol[pr_i_slant2h] << "\n*******************************************************************" << "\nMethod: \t" << "ambiguity" << "\nData_output_file: \t" << slant2hinput.fohei << "\nData_output_format: \t" << "real4" << "\nData_output_file_phi: \t" << slant2hinput.fophi << "\nData_output_format: \t" << "real4" << "\nData_output_file_lam: \t" << slant2hinput.folam << "\nData_output_format: \t" << "real4" << "\nFirst_line (w.r.t. original_master): \t" << unwrappedinterf.win.linelo << "\nLast_line (w.r.t. original_master): \t" << unwrappedinterf.win.linehi << "\nFirst_pixel (w.r.t. original_master): \t" << unwrappedinterf.win.pixlo << "\nLast_pixel (w.r.t. original_master): \t" << unwrappedinterf.win.pixhi << "\nMultilookfactor_azimuth_direction: \t" << unwrappedinterf.multilookL << "\nMultilookfactor_range_direction: \t" << unwrappedinterf.multilookP << "\nEllipsoid (name,a,b): \t" << ellips.name << " " << ellips.a << " " << ellips.b << "\n*******************************************************************" //<< "\n* End_slant2h:_NORMAL" << "\n* End_" << processcontrol[pr_i_slant2h] << "_NORMAL" << "\n*******************************************************************\n"; // ====== Tidy up ====== scratchresfile.close(); PROGRESS.print("finished slant2hambiguity."); } // END slant2hambiguity /**************************************************************** * slant2h rodriguez92 method * * * * compute height in radar coded system (master): * * use own derivations, check carefully * * * * Input: * * - * * Output: * * - * * * * Bert Kampes, 30-Sep-1999 * ****************************************************************/ void slant2hrodriguez( const input_gen &generalinput, const input_slant2h &slant2hinput, const input_ell &ellips, const slcimage &master, const slcimage &slave, const productinfo &unwrappedinterf, const matrix &coeff_flatearth, orbit &masterorbit, orbit &slaveorbit, const BASELINE &baseline) { TRACE_FUNCTION("slant2hrodriguez (BK 30-Sep-1999)") WARNING.print("this method is based on wrong approximations. (?)"); const int32 MAXITER = 10; // iterations for lp2xyz const real8 CRITERPOS = 1e-6; // stop criterium for lp2xyz const real8 CRITERTIM = 1e-10; // stop criterium for lp2xyz const int32 degreecfe = degree(coeff_flatearth.size()); // ______ Normalize data for polynomial ______ const real8 minL = master.originalwindow.linelo; const real8 maxL = master.originalwindow.linehi; const real8 minP = master.originalwindow.pixlo; const real8 maxP = master.originalwindow.pixhi; // ______ Multilook factors ______ const real8 multiL = unwrappedinterf.multilookL; const real8 multiP = unwrappedinterf.multilookP; const real8 m_pi4divlambda = (4.*PI)/master.wavelength; // ______ Number of lines/pixels of multilooked unwrapped interferogram ______ const int32 mllines = int32(floor(real8( unwrappedinterf.win.linehi-unwrappedinterf.win.linelo+1) / multiL)); const int32 mlpixels = int32(floor(real8( unwrappedinterf.win.pixhi-unwrappedinterf.win.pixlo+1) / multiP)); // ______ Line/pixel of first point in original master coordinates ______ const real8 veryfirstline = real8(unwrappedinterf.win.linelo) + (real8(multiL) - 1.) / 2.; const real8 firstpixel = real8(unwrappedinterf.win.pixlo) + (real8(multiP) - 1.) / 2.; // ====== Compute number of buffers required ====== const int32 NUMMAT = 1; // number of large matrices to determine size of matrices //int32 bufferlines = generalinput.memory / (NUMMAT * (mlpixels * sizeof(real4))); int32 bufferlines = int32(ceil( real8( generalinput.memory / (NUMMAT * (mlpixels * sizeof(real4)) )) )); if (bufferlines > mllines) // whole image fits in BUFFER bufferlines = mllines; const int32 FULLBUFFERS = mllines / bufferlines; const int32 RESTLINES = mllines % bufferlines; const int32 EXTRABUFFER = RESTLINES ? 1 : 0; // ______ Window to be read into BUFFER from file in multilooked system ______ const uint dummy = 999999; // large to force error if not ok window bufferwin(1, bufferlines, 1, mlpixels); // initial window offsetbuffer(1,dummy,1,dummy); // dummy not used in readfile, no offset // ______ Open output file ______ ofstream fohei; openfstream(fohei,slant2hinput.fohei,generalinput.overwrit); bk_assert(fohei,slant2hinput.fohei,__FILE__,__LINE__); // ====== Process BUFFERS ====== for (register int32 buffer=1; buffer<=FULLBUFFERS+EXTRABUFFER; ++buffer) { // ______ Give progress ______ PROGRESS << "SLANT2H: " << 100*(buffer-1)/(FULLBUFFERS+EXTRABUFFER) << "%"; PROGRESS.print(); // ====== First read in data ====== // ______ firstline of this buffer in master coordinate system ______ real8 firstline = veryfirstline + real8((buffer-1) * bufferlines * multiL); // ______ Set indices to be read from file / check if last buffer ______ bufferwin.linelo = 1 + (buffer-1) * bufferlines; if (buffer == FULLBUFFERS+1) { bufferlines = RESTLINES; //BUFFER.resize(bufferlines,mlpixels); } bufferwin.linehi = bufferwin.linelo + bufferlines - 1; // ______ Read in buffer of unwrapped interferogram ______ matrix BUFFER = unwrappedinterf.readphase(bufferwin); // ====== Actually compute h for all points ====== //register int32 i,j; register real8 line = firstline - multiL; // in master coordinate system for (uint i=0; i P(h0) -> S -> B -> h1 = H - r costheta; // -> P(h1) -> S -> B -> h2 // -> P(h2) -> S -> B -> h3 etc. // ====== The baseline parameters, derived from the positions (x,y,z) ====== // ====== Compute B and alpha (contant per line) ====== // ______ theta is angle (M,M-P) ______ const real8 B = M.dist(S); // abs. value const real8 Bpartemp = P.dist(M) - P.dist(S); // sign ok // ______ if (MP>SP) then S is to the right of slant line, then B perp is positive. const real8 rho1sqr = M.norm2(); // (sqr) constant per line const real8 costhetatemp = ((-(P.norm2()) + rho1sqr + // cosine law sqr(master.pix2range(middlepixel))) / (2*sqrt(rho1sqr)*master.pix2range(middlepixel))); //sintheta = sqrt(1-sqr(costhetatemp)); // cos^2 + sin^2 = 1 const cn r2 = S.min(P); // vector; to find out sign const real8 Bperp = (acos(costhetatemp) > M.angle(r2)) ? // sign ok sqrt(sqr(B)-sqr(Bpartemp)) : -sqrt(sqr(B)-sqr(Bpartemp)); const real8 alpha = acos(costhetatemp) - atan2(Bpartemp,Bperp); // ______ not used here ______ // const real8 Bhor = Bperp*costhetatemp + Bpartemp*sintheta; // const real8 Bver = Bperp*sintheta - Bpartemp*costhetatemp; // const real8 Bhor = B * cos(alfa); // const real8 Bver = B * sin(alfa); // ______ Find out height of satellite ______ // ______ assume radius to P is equal to this Radius. ______ const real8 rho1 = sqrt(rho1sqr); real8 satphi,satlambda,satheight; ellips.xyz2ell(M, satphi,satlambda,satheight); const real8 Radius = rho1 - satheight; // ====== Compute per pixel: phi->Bpar, r, ->theta,p,mu,H,h ====== for (uint j=0; j1.0) theta = PI-asin(sinthetaminalpha)+alpha; const real8 costheta = cos(theta); const real8 psqr = rho1sqr+r1sqr - 2*rho1*r1*costheta; // cosine law const real8 p = sqrt(psqr); const real8 cosmu = ((-r1sqr+psqr+rho1sqr) / (2*p*rho1)); // cosine law const real8 H = rho1 - Radius*cosmu; // ______ Put computed height in buffer ______ BUFFER(i,j) = H - r1*costheta; } // unwrapped ok } // loop over pixels } // loop over lines fohei << BUFFER; // write output } // loop over buffers // ====== Write to result files ====== ofstream scratchlogfile("scratchlogslant2h", ios::out | ios::trunc); bk_assert(scratchlogfile,"slant2h: scratchlogslant2h",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* " << processcontrol[pr_i_slant2h] << "\n*******************************************************************" << "\nMethod: \t\t\trodriguez" << "\nData_output_file: \t\t" << slant2hinput.fohei << "\nData_output_format: \t\t" << "real4" << "\nEllipsoid (name,a,b): \t\t" << ellips.name << " " << ellips.a << " " << ellips.b << endl; scratchlogfile.close(); ofstream scratchresfile("scratchresslant2h", ios::out | ios::trunc); bk_assert(scratchresfile,"slant2h: scratchresslant2h",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************" << "\n*_Start_" << processcontrol[pr_i_slant2h] << "\n*******************************************************************" << "\nMethod: \t" << "rodriguez" << "\nData_output_file: \t" << slant2hinput.fohei << "\nData_output_format: \t" << "real4" << "\nFirst_line (w.r.t. original_master): \t" << unwrappedinterf.win.linelo << "\nLast_line (w.r.t. original_master): \t" << unwrappedinterf.win.linehi << "\nFirst_pixel (w.r.t. original_master): \t" << unwrappedinterf.win.pixlo << "\nLast_pixel (w.r.t. original_master): \t" << unwrappedinterf.win.pixhi << "\nMultilookfactor_azimuth_direction: \t" << unwrappedinterf.multilookL << "\nMultilookfactor_range_direction: \t" << unwrappedinterf.multilookP << "\nEllipsoid (name,a,b): \t" << ellips.name << " " << ellips.a << " " << ellips.b << "\n*******************************************************************" //<< "\n* End_slant2h:_NORMAL" << "\n* End_" << processcontrol[pr_i_slant2h] << "_NORMAL" << "\n*******************************************************************\n"; // ====== Tidy up ====== scratchresfile.close(); PROGRESS.print("finished slant2hrodriguez."); } // END slant2rodriguez /**************************************************************** * geocode * * * * compute phi, lambda, (height is input) * * * * Input: * * - slant2h done, h filename in interferogram struct * * Output: * * - geocoded image * * * * See thesis swabisch for method 3eq. * * ellips is added known height, * * point(x,y,z) is evaluated at that ellips. * * This is converted to ell. coord. (bowrings method) * * * * Bert Kampes, 02-Jun-1999 * ****************************************************************/ void geocode( const input_gen &generalinput, const input_geocode &geocodeinput, const input_ell &ellips, const slcimage &master, const productinfo &heightinradarsystem, orbit &masterorbit) { TRACE_FUNCTION("geocode (BK 02-Jun-1999)") const int32 MAXITER = 10; const real8 CRITERPOS = 1e-6; //const real8 CRITERTIM = 1e-10; // ====== Evaluate for all points interferogram pos=f(l,p,height) ====== // ______ recon with multilook, buffers // ______ Multilook factors ______ const real8 multiL = heightinradarsystem.multilookL; const real8 multiP = heightinradarsystem.multilookP; // ______ Number of lines/pixels of multilooked unwrapped interferogram ______ const int32 mllines = int32(floor(real8( heightinradarsystem.win.linehi-heightinradarsystem.win.linelo+1) / multiL)); const int32 mlpixels = int32(floor(real8( heightinradarsystem.win.pixhi-heightinradarsystem.win.pixlo+1) / multiP)); // ______ Line/pixel of first point in original master coordinates ______ const real8 veryfirstline = real8(heightinradarsystem.win.linelo) + (multiL - 1.) / 2.; const real8 firstpixel = real8(heightinradarsystem.win.pixlo) + (multiP - 1.) / 2.; // ====== Compute number of buffers required ====== const int32 NUMMAT = 3; // number of large matrices to determine size of matrices //int32 bufferlines = generalinput.memory / (NUMMAT * (mlpixels * sizeof(real4))); int32 bufferlines = int32(ceil( real8( generalinput.memory / (NUMMAT * (mlpixels * sizeof(real4)) )) )); if (bufferlines > mllines) // whole image fits in BUFFER bufferlines = mllines; const int32 FULLBUFFERS = mllines / bufferlines; const int32 RESTLINES = mllines % bufferlines; const int32 EXTRABUFFER = RESTLINES ? 1 : 0; // ______ Window to be read into BUFFER from file in multilooked system ______ matrix PHI(bufferlines,mlpixels); // matrix LAMBDA(bufferlines,mlpixels); // matrix HEIGHT(bufferlines,mlpixels); // also output const uint dummy = 999999; // large to force error if not ok window bufferwin(1, bufferlines, 1, mlpixels); // initial window offsetbuffer(1,dummy,1,dummy); // dummy not used in readfile, no offset // ______ Open output files ______ ofstream fophi; openfstream(fophi,geocodeinput.fophi,generalinput.overwrit); bk_assert(fophi,geocodeinput.fophi,__FILE__,__LINE__); ofstream folam; openfstream(folam,geocodeinput.folam,generalinput.overwrit); bk_assert(folam,geocodeinput.folam,__FILE__,__LINE__); // ====== Process BUFFERS ====== for (register int32 buffer=1; buffer<=FULLBUFFERS+EXTRABUFFER; buffer++) { // ______ Give progress ______ PROGRESS << "GEOCODE: " << 100*(buffer-1)/(FULLBUFFERS+EXTRABUFFER) << "%"; PROGRESS.print(); // ______ firstline of this buffer in master coordinate system ______ real8 firstline = veryfirstline + (buffer-1) * bufferlines * multiL; // ______ Set indices to be read from file / check if last buffer ______ bufferwin.linelo = 1 + (buffer-1) * bufferlines; if (buffer == FULLBUFFERS+1) { bufferlines = RESTLINES; PHI.resize(bufferlines,mlpixels); LAMBDA.resize(bufferlines,mlpixels); HEIGHT.resize(bufferlines,mlpixels); } bufferwin.linehi = bufferwin.linelo + bufferlines - 1; // ______ Read in buffer of s2h ______ switch (heightinradarsystem.formatflag) { case FORMATR4: readfile (HEIGHT, heightinradarsystem.file, mllines, bufferwin, offsetbuffer); break; default: PRINT_ERROR("geocode format flag on file heights (s2h output) only real4 possible."); throw(unhandled_case_error); } // switch formatflag // ====== Compute xyz for all points on their height ====== register real8 line = firstline - multiL; // in master coordinate system cn pospoint; // returned by lp2xyz input_ell ELLIPS = ellips; // to correct height of ellips real8 r; // for conversion xyz2philambda real8 nu; // for conversion xyz2philambda real8 sin3; // for conversion xyz2philambda real8 cos3; // for conversion xyz2philambda for (uint i=0; i 1000 #pragma once #endif // _MSC_VER > 1000 #include "constants.hh" // typedefs #include "readinput.hh" // input structs #include "orbitbk.hh" // my orbit class #include "slcimage.hh" // my slc image class #include "productinfo.hh" // my 'products' class #include "bk_baseline.hh" // my 'baseline' class // ______ Use schwabisch approx. method ______ void slant2hschwabisch( const input_gen &generalinput, const input_slant2h &slant2hinput, const input_ell &ellips, const slcimage &master, const slcimage &slave, const productinfo &interferogram, orbit &masterorbit, orbit &slaveorbit); // ______ Use method ramon, derivative ______ void slant2hambiguity( const input_gen &generalinput, const input_slant2h &slant2hinput, const input_ell &ellips, const slcimage &master, const slcimage &slave, const productinfo &interferogram, orbit &masterorbit, orbit &slaveorbit, const BASELINE &baseline); // ______ Use standard method? ______ void slant2hrodriguez( const input_gen &generalinput, const input_slant2h &slant2hinput, const input_ell &ellips, const slcimage &master, const slcimage &slave, const productinfo &interferogram, const matrix &coeff_flatearth, orbit &masterorbit, orbit &slaveorbit, const BASELINE &baseline); // ______ Geocode after s2h ______ void geocode( const input_gen &generalinput, const input_geocode &geocodeinput, const input_ell &ellips, const slcimage &master, const productinfo &interferogram, orbit &masterorbit); #endif // GEOCODE_H Doris-5.0.3Beta/doris_core/ioroutines.cc000077500000000000000000003272111312547014700202470ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/ioroutines.cc,v $ * $Revision: 3.25 $ * $Date: 2005/10/06 11:09:20 $ * $Author: kampes $ * * implementation of io routines. ****************************************************************/ #include "constants.hh" // global constants #include "ioroutines.hh" // header of this file #include "utilities.hh" // ispower2 #include "slcimage.hh" // my slc image class #include "productinfo.hh" // my 'products' class #include "exceptions.hh" // my exceptions class #include // for file streams #include // for memory stream #include // for strcmp etc. #include // for setprecision etc. #include // exit #include // isspace() #include // for ellipses in functions #include // generic max #include // some compilers, remove function #include // some compilers, clock functions #include // int2str [MA] char *strptime(const char *s, const char *format, struct tm *tm); /**************************************************************** * printcpu * * * * Prints cpu and wallclock to screen as DEBUG * * Printcpu(true) should be called at start main. * * * * input: * * - bool init: first time true, default false * * output: * * - screen: cpu and wallclock time * * * * Bert Kampes, 11-Dec-1998 * ****************************************************************/ void printcpu( bool init) { TRACE_FUNCTION("printcpu (BK 11-Dec-1998)") time_t nseconds = time(NULL); char *tijd = ctime(&nseconds); // includes newline INFO << "Current time: " << tijd; INFO.print(); //static int32 cput_last = clock(); //static real4 cput_total = 0.; //int32 cput_process = clock() - cput_last; //static int32 wct_total = 0; // wallclock, init at first call //static int32 wct_last = time(NULL); // wallclock, init at first call //int32 wct_process = time(NULL) - wct_last; static clock_t cput_last = clock();// init only first call clock_t cput_process = clock() - cput_last; static real4 cput_total = 0.0;// init only first call static time_t wct_last = time(NULL); // wallclock, init at first call time_t wct_process = time(NULL) - wct_last; static int32 wct_total = 0; // wallclock, init at first call if (init) // return if only initialization return; cput_total += (real4(cput_process))/real4(CLOCKS_PER_SEC); cput_last = clock(); //wct_total += wct_process; wct_total += int32(wct_process); wct_last = time(NULL); const int32 cputmin = int32(floor(cput_total/60)); const real4 cputsec = cput_total - cputmin*60; DEBUG << " cputime used for process: \t" << setw(6) << real4(cput_process)/real4(CLOCKS_PER_SEC) << " sec (total: " << setw(4) << cputmin << " min " << setw(3) << cputsec << " sec)\n" << "\t wallclock: \t\t\t" << setw(6) << wct_process << " sec (total: " << setw(4) << wct_total/60 << " min " << setw(3) << wct_total%60 << " sec)"; DEBUG.print(); cerr << "total cpu: \t" << setw(4) << cputmin << " min " << setw(3) << cputsec << " sec\n"; } // END printcpu /**************************************************************** * inittest * * * * Some initial tests and info for portability. * * * * input: * * - void * * output: * * - void, exits if trouble * * * * Bert Kampes, 11-Dec-1998 * ****************************************************************/ void inittest() { TRACE_FUNCTION("inittest (BK 11-Dec-1998)") // ______ Some info ______ #ifdef __DEBUG DEBUG.print("\"__DEBUG\" defined (extra verbose)"); #else DEBUG.print("\"__DEBUG\" not defined (extra verbose)"); #endif #ifdef __DEBUGMAT1 DEBUG.print("\"__DEBUGMAT1\" defined (range checking matrix class)"); #else DEBUG.print("\"__DEBUGMAT1\" not defined (range checking matrix class)"); #endif #ifdef __DEBUGMAT2 DEBUG.print("\"__DEBUGMAT2\" defined (verbose matrix class)"); #else DEBUG.print("\"__DEBUGMAT2\" not defined (verbose matrix class)"); #endif #ifdef __USE_FFTW_LIBRARY__ DEBUG.print("\"__USE_FFTW_LIBRARY__\" defined (using fftw routines)"); #else DEBUG.print("\"__USE_FFTW_LIBRARY__\" not defined (not using fftw routines)"); #endif #ifdef __USE_VECLIB_LIBRARY__ DEBUG.print("\"__USE_VECLIB_LIBRARY__\" defined (using library routines)"); #else DEBUG.print("\"__USE_VECLIB_LIBRARY__\" not defined (using internal routines)"); #endif #ifdef __USE_LAPACK_LIBRARY__ DEBUG.print("\"__USE_LAPACK_LIBRARY__\" defined (using library routines)"); #else DEBUG.print("\"__USE_LAPACK_LIBRARY__\" not defined (using internal routines)"); #endif #ifdef __GplusplusCOMPILER__ DEBUG.print("\"__GplusplusCOMPILER__\" defined (GNU c++ compiler)"); WARNING.print("NOT USED ANYMORE. since v3.8"); #else DEBUG.print("\"__GplusplusCOMPILER__\" not defined (no GNU c++ compiler)"); #endif #ifdef __GNUC__ DEBUG << "\"__GNUC__\": " << __GNUC__; DEBUG.print(); #endif #ifdef __GNUC_MINOR__ DEBUG << "\"__GNUC_MINOR__\": " << __GNUC_MINOR__; DEBUG.print(); #endif // ___ Testing endianness ___ DEBUG.print("Testing endianness."); int i; int littleendian=0;// thus big assumed char test[64]={0}; for (i=0;i<32;i++) test[i]=0; test[0]=0x01; if (0x0001==*(int *)(&test[0])) littleendian=1; #ifdef __X86PROCESSOR__ DEBUG.print("\"__X86PROCESSOR__\" defined (little Endian machine)"); if (littleendian == 1) INFO.print("Little Endian machine defined and this is correct."); else WARNING.print("Little Endian machine defined and this is NOT correct."); #else DEBUG.print("\"__X86PROCESSOR__\" not defined (big Endian machine)"); if (littleendian == 0) INFO.print("Big Endian machine defined and this is correct."); else WARNING.print("Big Endian machine defined and this is NOT correct."); #endif #ifdef __NO_STRPTIME DEBUG.print("\"__NO_STRPTIME\" defined (using internal routine)"); #else DEBUG.print("\"__NO_STRPTIME\" not defined (using library routine)"); #endif // ___ Testing strptime function ___ DEBUG.print("Testing strptime function."); struct tm tm_ref; char utc_ref[100] = "05-JAN-1985 01:02:03.000"; strptime(utc_ref,"%d-%b-%Y %T",&tm_ref); int status = 0; if (tm_ref.tm_mday != 5) status=1; if (tm_ref.tm_mon != 0) status=1; if (tm_ref.tm_year != 85) status=1; if (tm_ref.tm_hour != 1) status=1; if (tm_ref.tm_min != 2) status=1; if (tm_ref.tm_sec != 3) status=1; if (status == 0) INFO.print("strptime function works fine."); else WARNING.print("strptime function seems NOT TO BE OK."); // ______ Some info ______ if (sizeof(int16) != 2) { PRINT_ERROR("code: 900: sizeof int16(short) != 2: see typedefs in constants.h") throw(some_error); } if (sizeof(int32) != 4) { PRINT_ERROR("code: 900: sizeof int32(int) != 4: see typedefs in constants.h") throw(some_error); } if (sizeof(uint) != 4) { PRINT_ERROR("code: 900: sizeof uint(unsigned int) != 4: see typedefs in constants.h") throw(some_error); } if (sizeof(real8) != 8) { PRINT_ERROR("code: 900: sizeof real8(double) != 8: see typedefs in constants.h") throw(some_error); } if (sizeof(real4) != 4) { PRINT_ERROR("code: 900: sizeof real4(float) != 4: see typedefs in constants.h") throw(some_error); } if (sizeof(compli16) != 4) { PRINT_ERROR("code: 900: sizeof compli16(complex short) != 4: see typedefs in constants.h") throw(some_error); } if (sizeof(compli32) != 8) { PRINT_ERROR("code: 900: sizeof compli32(complex int) != 8: see typedefs in constants.h") throw(some_error); } if (sizeof(complr4) != 8) { PRINT_ERROR("code: 900: sizeof complr4(complex float) != 8: see typedefs in constants.h") throw(some_error); } if (sizeof(complr8) != 16) { PRINT_ERROR("code: 900: sizeof complr16(complex double) != 16: see typedefs in constants.h") throw(some_error); } if (int32(7.5) != 7) { PRINT_ERROR("code: 900: it is assumed that int(7.5)==7") throw(some_error); } if (complr4(1.1) != complr4(1.1,0)) { PRINT_ERROR("code: ???: it is assumed that complr4(7.5) == 7.5 + 0.0i") throw(some_error); } DEBUG.print("test somewhere also memory,diskspace."); #ifdef __DEBUG // ___ Testing cn class ___ DEBUG.print("Testing coordinate class:"); cn P; P.test(); // ___ Testing window class ___ DEBUG.print("Testing window class:"); window W; W.test(); // ___ Testing ellips class ___ DEBUG.print("Testing ellips class:"); input_ell E; E.test(); #endif } // END inittest /**************************************************************** * doinitwrite * * * * Decides to call initwrite or not * * necessary because no call for image (slave or master). * * if something will be processed then true * * input: * * - input processes * * - imageid: =2 master, =3 slave * * output: * * - bool true or false * * future: THIS ROUTINE SHOULD BE UPDATED AS WE GO ALONG * * * * Bert Kampes, 15-Dec-1998 * * * * Mahmut: make slc result files equivalent * ****************************************************************/ bool doinitwrite( input_gen &generalinput, int16 imageid) { TRACE_FUNCTION("doinitwrite (BK 15-Dec-1998)") // ______Check input and decide (normally true)______ if (imageid == MASTERID) { if (!(generalinput.process[pr_m_readfiles] || generalinput.process[pr_m_crop] || generalinput.process[pr_m_oversample] || generalinput.process[pr_m_porbits] || generalinput.process[pr_m_morbits] || //[HB] generalinput.process[pr_m_simamp] || //[MA] 2008 generalinput.process[pr_m_mtiming] || //[MA] 2008 generalinput.process[pr_m_resample] || //[MA] 200903, fake entry to make slc.res files equivalent. Note: no dependency defined in check routine. generalinput.process[pr_m_filtazi] || generalinput.process[pr_m_filtrange] || generalinput.process[pr_m_EXTRA] )) return false; } else if (imageid == SLAVEID) { if (!(generalinput.process[pr_s_readfiles] || generalinput.process[pr_s_crop] || generalinput.process[pr_s_oversample] || generalinput.process[pr_s_porbits] || generalinput.process[pr_s_morbits] || //[HB] generalinput.process[pr_s_simamp] || //[MA] 200903. fake entry generalinput.process[pr_s_mtiming] || //[MA] 200903. fake entry generalinput.process[pr_s_resample] || generalinput.process[pr_s_filtazi] || generalinput.process[pr_s_filtrange] || generalinput.process[pr_s_EXTRA] )) return false; } else if (imageid == INTERFID) { if (!(generalinput.process[pr_i_coarse] || generalinput.process[pr_i_coarse2] || generalinput.process[pr_i_fine] || generalinput.process[pr_i_timing] || //[FvL] generalinput.process[pr_i_demassist] || //[FvL] generalinput.process[pr_i_coregpm] || generalinput.process[pr_i_comprefpha] || generalinput.process[pr_i_subtrrefpha] || generalinput.process[pr_i_comprefdem] || generalinput.process[pr_i_subtrrefdem] || generalinput.process[pr_i_interfero] || generalinput.process[pr_i_coherence] || generalinput.process[pr_i_filtphase] || generalinput.process[pr_i_unwrap] || generalinput.process[pr_i_estorbits] || //[HB] generalinput.process[pr_i_slant2h] || generalinput.process[pr_i_geocoding] || generalinput.process[pr_i_dinsar] || generalinput.process[pr_i_EXTRA2] )) return false; } else { PRINT_ERROR("code 901: wrong input.") throw(some_error); } return true; } // END doinitwrite /**************************************************************** * initwrite * * * * Writes some general info to logfile and resultfile * * * * input: * * - file: name of file * * - fileid: * * 1:logfile, 2:masterres, 3:slaveres, 4:interferogram * * output: * * - void, file is updated * * * * Bert Kampes, 11-Dec-1998 * ****************************************************************/ void initwrite( const char* file, int16 fileid) { TRACE_FUNCTION("initwrite (BK 11-Dec-1998)") #ifndef SWNAME DEBUG.print("SWNAME NOT DEFINED."); #endif #ifndef SWVERSION DEBUG.print("SWVERSION NOT DEFINED."); #endif // ______Initialize time______ // #ifdef __GplusplusCOMPILER__ // g++ 2.7.2.2 wants int, though long is exactly same // use __GNUC__ = 2, __GNUC_MINOR__ = 7, __GNUG__ = 2 // can be seen with g++ -v dummy.c //#if __GNUC_MINOR__ == 7 // int32 nseconds = time(NULL); //#else // at least version 2.95.2 and HP aCC // long nseconds = time(NULL); //#endif time_t nseconds = time(NULL); char *tijd = ctime(&nseconds); // includes newline // ______Write logfile if not exists______ bool ofilenew = true; if (existed(file)) ofilenew = false; // [MA] TODO [hi]: fix a potential bug when ifg.res file is missing, it is regenerated partially. ofstream ofile; ofile.open(file, ios::out | ios::app); bk_assert(ofile,file,__FILE__,__LINE__); DEBUG.print("Writing (updating) of file (initwrite)."); if (ofilenew) { ofile << "====================================================="; switch (fileid) { case LOGID: ofile << "\n LOGFILE: " << file; break; case MASTERID: ofile << "\n MASTER RESULTFILE: " << file; break; case SLAVEID: ofile << "\n SLAVE RESULTFILE: " << file; break; case INTERFID: ofile << "\n INTERFEROGRAM RESULTFILE: " << file; break; default: PRINT_ERROR("panic: code 901:initwrite, internal fileid not ok!") throw(unhandled_case_error); } ofile << "\n\nCreated by: " // << getlogin() // screen caused trouble with this // [MA] try getUserName() on Windows << "\nInSAR Processor: " << SWNAME << "\nVersion: " << SWVERSION #if defined (__DEBUG) || defined (__DEBUGMAT1) || defined (__DEBUGMAT2) << " (debug)" #else << " (optimal)" #endif #ifdef __USE_FFTW_LIBRARY__ << "\nFFTW library: " << "used" #else << "\nFFTW library: " << "not used" #endif #ifdef __USE_VECLIB_LIBRARY__ << "\nVECLIB library: " << "used" #else << "\nVECLIB library: " << "not used" #endif #ifdef __USE_LAPACK_LIBRARY__ << "\nLAPACK library: " << "used" #else << "\nLAPACK library: " << "not used" #endif << "\nCompiled at: " << __DATE__ << " " << __TIME__; #ifdef __GNUC__ ofile << "\nBy GNU gcc: " << __GNUC__; #ifdef __GNUC_MINOR__ ofile << "." << __GNUC_MINOR__; #ifdef __GNUG__ ofile << "." << __GNUG__; #endif #endif #endif ofile << "\nFile creation at: " << tijd << "\n -------------------------------------------------------" << "\n| Delft Institute of Earth Observation & Space Systems |" << "\n| Delft University of Technology |" << "\n| http://doris.tudelft.nl |" << "\n| |" << "\n| Author: (c) TUDelft - DEOS Radar Group |" << "\n -------------------------------------------------------\n\n"; // ======Write process control in result file====== switch (fileid) { // ______These may not be changed without changing check process control______ case MASTERID: ofile << "\nStart_process_control\n" << processcontrol[pr_m_readfiles] << " \t\t0\n" << processcontrol[pr_m_porbits] << " \t0\n" << processcontrol[pr_m_morbits] << " \t\t0\n" //[HB] << processcontrol[pr_m_crop] << " \t\t\t0\n" << processcontrol[pr_m_simamp] << " \t\t0\n" //[MA] 2008 << processcontrol[pr_m_mtiming] << " \t\t0\n" //[MA] 2008 << processcontrol[pr_m_oversample] << " \t\t0\n" << processcontrol[pr_m_resample] << " \t\t0\n" //[MA] 2009. fake entry to make slc.res files equivalent << processcontrol[pr_m_filtazi] << " \t\t0\n" << processcontrol[pr_m_filtrange] << " \t\t0\n" << processcontrol[pr_m_EXTRA] << " \t\t0\n" << "End_process_control\n"; break; // ______These may not be changed without changing check process control______ case SLAVEID: ofile << "\nStart_process_control\n" << processcontrol[pr_s_readfiles] << " \t\t0\n" << processcontrol[pr_s_porbits] << " \t0\n" << processcontrol[pr_s_morbits] << " \t\t0\n" //[HB] << processcontrol[pr_s_crop] << " \t\t\t0\n" << processcontrol[pr_s_simamp] << " \t\t0\n" //[MA] 2009. fake entry << processcontrol[pr_s_mtiming] << " \t\t0\n" //[MA] 2009. fake entry no processing is defined << processcontrol[pr_s_oversample] << " \t\t0\n" << processcontrol[pr_s_resample] << " \t\t0\n" << processcontrol[pr_s_filtazi] << " \t\t0\n" << processcontrol[pr_s_filtrange] << " \t\t0\n" << processcontrol[pr_s_EXTRA] << " \t\t0\n" << "End_process_control\n"; break; // ______These may not be changed without changing check process control______ case INTERFID: ofile << "\nStart_process_control\n" << processcontrol[pr_i_coarse] << " \t\t0\n" << processcontrol[pr_i_coarse2] << " \t\t0\n" << processcontrol[pr_i_fine] << " \t\t0\n" << processcontrol[pr_i_timing] << " \t\t0\n" //[FvL] << processcontrol[pr_i_demassist] << " \t\t0\n" //[FvL] << processcontrol[pr_i_coregpm] << " \t\t0\n" << processcontrol[pr_i_interfero] << " \t\t0\n" << processcontrol[pr_i_coherence] << " \t0\n" << processcontrol[pr_i_comprefpha] << " \t\t0\n" << processcontrol[pr_i_subtrrefpha] << " \t\t0\n" << processcontrol[pr_i_comprefdem] << " \t\t0\n" << processcontrol[pr_i_subtrrefdem] << " \t\t0\n" << processcontrol[pr_i_filtphase] << " \t\t0\n" << processcontrol[pr_i_unwrap] << " \t\t0\n" << processcontrol[pr_i_estorbits] << " \t\t0\n" //[HB] << processcontrol[pr_i_slant2h] << " \t\t0\n" << processcontrol[pr_i_geocoding] << " \t\t0\n" << processcontrol[pr_i_dinsar] << " \t\t\t0\n" << processcontrol[pr_i_EXTRA2] << " \t\t0\n" << "End_process_control\n"; break; default: ; //do nothing } // switch fileid } else // file already existed { ofile << endl << endl << " *====================================================================*\n" << " | |\n" << " Following part is appended at: " << tijd // \n included in tijd... << " Using Doris " << SWVERSION << " \n" << " | |\n" << " *--------------------------------------------------------------------*\n\n"; } //if else file existence // ______Tidy up______ ofile.close(); } // END initwrite /**************************************************************** * updatefile * * * * A scratchfile is appended to a logfile. * * The scratchfile is deleted after copying. * * * * input: * * - scratchfile * * - logfile * * output: * * - void, updated logfile, scratchfile is deleted * * * * Bert Kampes, 11-Dec-1998 * * changed to 4*127 after problem. #%// BK 07-Mar-2001 ****************************************************************/ void updatefile( const char* sfile, const char* lfile) { TRACE_FUNCTION("updatefile (BK 11-Dec-1998)") char dummyline[4*ONE27]; //ifstream scratchfile(sfile, ios::in | ios::nocreate); ifstream scratchfile(sfile, ios::in); bk_assert(scratchfile,sfile,__FILE__,__LINE__); ofstream logfile(lfile, ios::out | ios::app); bk_assert(logfile,lfile,__FILE__,__LINE__); // ______Start writing______ scratchfile.getline(dummyline,4*ONE27,'\n'); // to prevent twice last line while (scratchfile) { logfile << dummyline << endl; scratchfile.getline(dummyline,4*ONE27,'\n'); } // ______ Add current time ______ time_t nseconds = time(NULL); char *tijd = ctime(&nseconds); // includes newline logfile << "\n Current time: " << tijd; // \n included in tijd... // ______Tidy up______ logfile.close(); scratchfile.close(); if (remove(sfile)) // remove file WARNING.print("Could not remove file."); DEBUG << "File: " << lfile << " has been updated by file: " << sfile << " (removed.)"; DEBUG.print(); } // END updatefile /**************************************************************** * getanswer * * * * Waits for user to press a key. * * (Mainly) used in interactive mode. * * should not wait for enter but getch() doesnt work !! * * (dos only?) * * * future: no enter required * * * * Bert Kampes, 11-Dec-1998 * ****************************************************************/ void getanswer( ) { TRACE_FUNCTION("getanswer (BK 11-Dec-1998)") char dummychar; cerr << "\n Press to continue."; cin.unsetf(ios::skipws); // ignore ws (just enter) cin >> dummychar; cerr << " continuing...\n"; } // END getanswer /**************************************************************** * readres * * * * Pattern is searched in file (1st word), * * next (skipwords) words are ignored (default=0) * * the following word is returned as returnword, * * sizeofrw includes '\0' * * * * eg: in main c8[9] as readres(c8,sizeof(c8),file,pat) * * * * input: * * - pointer to returnword * * - size of returnword (including '\0') * * - file name to search * * - pattern to search for * * - number of words to skip before desired returnword (0=def * * output: * * - true if found, returnword is filled * * * * future: should include identifier as well * * better?: file.readsome(pattern) * * * * Bert Kampes, 11-Dec-1998 * * Mahmut Arikan, 17-Apr-2009 skip matching lines * ****************************************************************/ bool readres( char* returnword, const int16 sizeofrw, const char* file, const char* pattern, const int16 skipwords, //=0 default int16 skiplines) //=0 default { TRACE_FUNCTION("readres (BK 11-Dec-1998)") char dummyline[4*ONE27]; char word[4*ONE27]; bool foundword = false; ifstream infile(file, ios::in); bk_assert(infile,file,__FILE__,__LINE__); // ======Search infile====== returnword[0] = '\0'; // garanty word is empty char ch = '\t'; while (infile) { infile >> word; if (strcmp(pattern,word)) // no pattern match. { infile.getline(dummyline,4*ONE27,'\n'); // goto next line. } else // pattern match. { if ( skiplines == 0) { for (register int32 i=0; i> word; // goto correct position: word int32 tin; while (isspace(tin=ch)) // goto correct position: trailing blanks { infile.get(ch); if (ch == '\n') // no argument after key { WARNING.print("Found identifier, but not so desired word!, exiting routine..."); break; } } } else { skiplines -= 1 ; // [MA] continue; } // ______ Actual read word ______ foundword = true; //infile.putback(ch); //infile.read(returnword,sizeofrw-1); // read desired word including blanks //returnword[sizeofrw]='\0'; ? // ______ Test bert ______ for (int ii=0; ii> word; resfile2 << word; tmpfile2.getline(dummyline,4*ONE27,'\n'); // go to next line if (!strcmp(word,"End_process_control")) { resfile2 << endl; break; } switch (fileid) { case MASTERID: if (!strcmp(word,processcontrol[pr_m_readfiles])) (checkprocess[pr_m_readfiles]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_m_porbits])) (checkprocess[pr_m_porbits]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_m_morbits])) (checkprocess[pr_m_morbits]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; //[HB] else if (!strcmp(word,processcontrol[pr_m_crop])) (checkprocess[pr_m_crop]) ? resfile2 << "\t\t\t1\n" : resfile2 << "\t\t\t0\n"; else if (!strcmp(word,processcontrol[pr_m_simamp])) (checkprocess[pr_m_simamp]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; //[MA] 2008 else if (!strcmp(word,processcontrol[pr_m_mtiming])) (checkprocess[pr_m_mtiming]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; //[MA] 2008 else if (!strcmp(word,processcontrol[pr_m_oversample])) (checkprocess[pr_m_oversample]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_m_resample])) //[MA] 2009, fake entry no processing is defined (checkprocess[pr_m_resample]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_m_filtazi])) (checkprocess[pr_m_filtazi]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_m_filtrange])) (checkprocess[pr_m_filtrange]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_m_EXTRA])) (checkprocess[pr_m_EXTRA]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else { ERROR << "PANIC: forgotten to update routine? " << word << " not recognized in master resultfile."; PRINT_ERROR(ERROR.get_str()) throw(unhandled_case_error); } break; // switch case SLAVEID: if (!strcmp(word,processcontrol[pr_s_readfiles])) (checkprocess[pr_s_readfiles]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_s_porbits])) (checkprocess[pr_s_porbits]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_s_morbits])) (checkprocess[pr_s_morbits]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; //[HB] else if (!strcmp(word,processcontrol[pr_s_crop])) (checkprocess[pr_s_crop]) ? resfile2 << "\t\t\t1\n" : resfile2 << "\t\t\t0\n"; else if (!strcmp(word,processcontrol[pr_s_simamp])) (checkprocess[pr_s_simamp]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; //[MA] 2009, fake entry no processing is defined else if (!strcmp(word,processcontrol[pr_s_mtiming])) (checkprocess[pr_s_mtiming]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; //[MA] 2009, fake entry no processing is defined else if (!strcmp(word,processcontrol[pr_s_oversample])) (checkprocess[pr_s_oversample]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_s_resample])) (checkprocess[pr_s_resample]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_s_filtazi])) (checkprocess[pr_s_filtazi]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_s_filtrange])) (checkprocess[pr_s_filtrange]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_s_EXTRA])) (checkprocess[pr_s_EXTRA]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else { ERROR << "PANIC: forgotten to update routine? " << word << " not recognized in slave resultfile."; PRINT_ERROR(ERROR.get_str()) throw(unhandled_case_error); } break; // switch case INTERFID: if (!strcmp(word,processcontrol[pr_i_coarse])) (checkprocess[pr_i_coarse]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_i_coarse2])) (checkprocess[pr_i_coarse2]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_i_fine])) (checkprocess[pr_i_fine]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_i_timing])) (checkprocess[pr_i_timing]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; //[FvL] else if (!strcmp(word,processcontrol[pr_i_demassist])) (checkprocess[pr_i_demassist]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; //[FvL] else if (!strcmp(word,processcontrol[pr_i_coregpm])) (checkprocess[pr_i_coregpm]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_i_interfero])) (checkprocess[pr_i_interfero]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_i_coherence])) (checkprocess[pr_i_coherence]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_i_comprefpha])) (checkprocess[pr_i_comprefpha]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_i_subtrrefpha])) (checkprocess[pr_i_subtrrefpha]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_i_comprefdem])) (checkprocess[pr_i_comprefdem]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_i_subtrrefdem])) (checkprocess[pr_i_subtrrefdem]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_i_filtphase])) (checkprocess[pr_i_filtphase]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_i_unwrap])) (checkprocess[pr_i_unwrap]) ? resfile2 << "\t\t\t1\n" : resfile2 << "\t\t\t0\n"; else if (!strcmp(word,processcontrol[pr_i_estorbits])) (checkprocess[pr_i_estorbits]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; //[HB] else if (!strcmp(word,processcontrol[pr_i_slant2h])) (checkprocess[pr_i_slant2h]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_i_geocoding])) (checkprocess[pr_i_geocoding]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else if (!strcmp(word,processcontrol[pr_i_dinsar])) (checkprocess[pr_i_dinsar]) ? resfile2 << "\t\t\t1\n" : resfile2 << "\t\t\t0\n"; else if (!strcmp(word,processcontrol[pr_i_EXTRA2])) (checkprocess[pr_i_EXTRA2]) ? resfile2 << "\t\t1\n" : resfile2 << "\t\t0\n"; else { ERROR << "PANIC: forgotten to update routine? " << word << " not recognized in interferogram resultfile."; PRINT_ERROR(ERROR.get_str()) throw(unhandled_case_error); } break; // switch default: PRINT_ERROR("PANIC, impossible wrong.") throw(unhandled_case_error); } // switch } // forever // ======Copy rest of file====== tmpfile2.getline(dummyline,4*ONE27,'\n'); // get line while(tmpfile2) { resfile2 << dummyline << endl; tmpfile2.getline(dummyline,4*ONE27,'\n'); } resfile2.close(); tmpfile2.close(); // ______Tidy up______ // if (processerror) // ERROR(__FILE__,__LINE__,"updateprocesscontrols: resfile some problem."); if (remove("scratchcopy")) // remove file WARNING.print("Could not remove file: scratchcopy."); } // END updateprocesscontrols /**************************************************************** * checkprocessing * * * * Checks if requested processing is possible. * * checkprocess[i] contains already processed * * (master index is mis-used to indicate) * * inputgeneral.process[i] contains requests * * requirements for processing can be found in software folder * * general if step is requested: * * 0) check already * * 1) check requirements (other steps/files) * * 2) set checkprocessed true * * * * input: * * output: * * - void (no exit hopefully) * * - checkprocess is filled with what is already processed * * * *BUG: filled with what will be processed as well... * *BUG??: not correctly passed back ??? * * * * Bert Kampes, 14-Dec-1998 * ****************************************************************/ void checkprocessing( const input_gen &generalinput, int16 checkprocess[NUMPROCESSES]) { TRACE_FUNCTION("checkprocessing (BK 14-Dec-1998)") char dummyline[4*ONE27] = " "; //char word[EIGHTY] = " "; const char* file; int16 checkprocess2[NUMPROCESSES+1]; // check with filecontent checkprocess2[NUMPROCESSES]=0; register int32 i; for (i=0;i stop condition } // try to repair } // existed(file) } // for fileid // ______ Keep checkprocess like this (only what is actually in resultfile) ______ // ______ and update a new array ______ int16 checkprocesstmp[NUMPROCESSES]; for (i=0; i readfiles if (generalinput.process[pr_i_coarse2]) // requested coarse correlation checkrequest(pr_i_coarse2,checkprocesstmp, 2,pr_m_crop,pr_s_crop); // required // orbits... if (generalinput.process[pr_m_filtrange]) // requested checkrequest(pr_m_filtrange,checkprocesstmp, 2,pr_m_crop,pr_i_coarse2); // adviced // adaptive... //if (generalinput.process[pr_m_filtrange]) // requested // checkrequest(pr_m_filtrange,checkprocesstmp, // 2,pr_m_crop,pr_s_resample); // required //if (generalinput.process[pr_s_filtrange]) // requested // checkrequest(pr_s_filtrange,checkprocesstmp, // 1,pr_s_crop); // required if (generalinput.process[pr_i_fine]) // requested checkrequest(pr_i_fine,checkprocesstmp, 2,pr_m_crop,pr_s_crop); if (generalinput.process[pr_i_timing]) // requested checkrequest(pr_i_timing,checkprocesstmp, 2,pr_i_coarse,pr_i_fine); //[FvL] if (generalinput.process[pr_i_demassist]) // requested checkrequest(pr_i_demassist,checkprocesstmp, 3,pr_m_crop,pr_s_crop,pr_i_fine); //[FvL] if (generalinput.process[pr_i_coregpm]) // requested checkrequest(pr_i_coregpm,checkprocesstmp, 1,pr_i_fine); // this should go here... // BK 24-Aug-2000 if (generalinput.process[pr_s_resample]) // requested checkrequest(pr_s_resample,checkprocesstmp, 1,pr_i_coregpm); // required if (generalinput.process[pr_i_interfero]) // requested checkrequest(pr_i_interfero,checkprocesstmp, 1,pr_s_resample); if (generalinput.process[pr_i_coherence]) // requested checkrequest(pr_i_coherence,checkprocesstmp, 1,pr_s_resample); if (generalinput.process[pr_i_comprefpha]) // requested checkrequest(pr_i_comprefpha,checkprocesstmp, 2,pr_m_readfiles,pr_s_readfiles); // orbits required if (generalinput.process[pr_i_subtrrefpha]) // requested checkrequest(pr_i_subtrrefpha,checkprocesstmp, 1,pr_i_interfero); // required // 2,pr_i_comprefpha,pr_i_interfero); // required if (generalinput.process[pr_i_comprefdem]) // requested checkrequest(pr_i_comprefdem,checkprocesstmp, 2,pr_m_readfiles,pr_s_readfiles); // orbits required if (generalinput.process[pr_i_subtrrefdem]) // requested checkrequest(pr_i_subtrrefdem,checkprocesstmp, 2,pr_i_comprefdem,pr_i_interfero); // required if (generalinput.process[pr_i_filtphase]) // requested checkrequest(pr_i_filtphase,checkprocesstmp, 1,pr_i_interfero); // required if (generalinput.process[pr_i_unwrap]) // requested checkrequest(pr_i_unwrap,checkprocesstmp, 1,pr_i_interfero); // required if (generalinput.process[pr_i_estorbits]) // requested [HB] checkrequest(pr_i_estorbits,checkprocesstmp, // required 1,pr_i_subtrrefpha); if (generalinput.process[pr_i_slant2h]) // requested checkrequest(pr_i_slant2h,checkprocesstmp, 1,pr_i_unwrap); // required if (generalinput.process[pr_i_geocoding]) // requested checkrequest(pr_i_geocoding,checkprocesstmp, 1,pr_i_slant2h); // required if (generalinput.process[pr_i_dinsar]) // requested checkrequest(pr_i_dinsar,checkprocesstmp, 1,pr_i_interfero); // required if (generalinput.process[pr_i_EXTRA2]) // requested checkrequest(pr_i_EXTRA2,checkprocesstmp,0); // no requirements // ______Tidy up______ } // END checkprocessing /**************************************************************** * checkrequest * * * * Checks if requested processing step can be processed. * * * * input: * * - step to be processed * * - array of already processed steps * * - optional: Number of req, and, * * steps that are required for this step * * output: * * - (updated) alreadyprocess[] * * * * * * Bert Kampes, 16-Dec-1998 * ****************************************************************/ void checkrequest( int16 step, int16 alreadyprocess[NUMPROCESSES], ...) { TRACE_FUNCTION("checkrequest (BK 16-Dec-1998)") // ______Check if step is already processed and update already______ if (alreadyprocess[step]) { ERROR << "Results of step: " << step << " (" << processcontrol[step] << ") already in result file."; ERROR << "\n TIP : use \'doris.rmstep.sh\' to cleanup " << processcontrol[step] << " entries in result file." ; // [MA] TODO report result filename file or general.? PRINT_ERROR(ERROR.get_str()) throw(input_error); } alreadyprocess[step]=1; // set to processed // ______Check with requirements______ // ______ It seemed this has to be int instea of int16 on redhat 7.0 linux? ______ // but why? BK 21-Nov-2000 va_list arglist; // use ellipses va_start(arglist,alreadyprocess); /* *** SOME compiler required the second form, though it seems wrong, *** in order to compile doris comment out the second, and put a comment before *** the first form. */ // seems that while passing '...' type is converted to int, so use that here... //int16 N = va_arg(arglist, int16); // number of arguments=first ellipses int16 N = va_arg(arglist, int); int16 requiredstep; for (register int32 i=0; i 30) return; char word[4*ONE27]; // should be enough // ______ Disect line ______ for (register int32 i=0;ioverlap.linelo) overlap.linelo=master.linelo; if (master.linehioverlap.pixlo) overlap.pixlo =master.pixlo; if (master.pixhi &cpmL, const matrix &cpmP) { TRACE_FUNCTION("getoverlap (BK 10-Mar-1999)") // ______ Normalize data for polynomial ______ const real8 minL = master.originalwindow.linelo; const real8 maxL = master.originalwindow.linehi; const real8 minP = master.originalwindow.pixlo; const real8 maxP = master.originalwindow.pixhi; INFO << "getoverlap: polynomial normalized by factors: " << minL << " " << maxL << " " << minP << " " << maxP << " to [-2,2]"; INFO.print(); // ______offset = A(slave system) - A(master system)______ // ______Corners of slave in master system______ // ______Offsets for slave corners (approx.)______ // ______ approx: defined as offset = f(l,p)_M in master system not slave. real8 approxoffL = cpmL(0,0); // zero order term; real8 approxoffP = cpmP(0,0); // zero order term; // real8 sL00 = slave.currentwindow.linelo - // polyval(slave.currentwindow.linelo - approxoffL, // slave.currentwindow.pixlo - approxoffP, cpmL); // ______ Use normalized polynomial ______ const real8 sL00 = slave.currentwindow.linelo - polyval(normalize(real8(slave.currentwindow.linelo)-approxoffL,minL,maxL), normalize(real8(slave.currentwindow.pixlo) -approxoffP,minP,maxP), cpmL); const real8 sP00 = slave.currentwindow.pixlo - polyval(normalize(real8(slave.currentwindow.linelo)-approxoffL,minL,maxL), normalize(real8(slave.currentwindow.pixlo) -approxoffP,minP,maxP), cpmP); const real8 sL0N = slave.currentwindow.linelo - polyval(normalize(real8(slave.currentwindow.linelo)-approxoffL,minL,maxL), normalize(real8(slave.currentwindow.pixhi) -approxoffP,minP,maxP), cpmL); const real8 sP0N = slave.currentwindow.pixhi - polyval(normalize(real8(slave.currentwindow.linelo)-approxoffL,minL,maxL), normalize(real8(slave.currentwindow.pixhi) -approxoffP,minP,maxP), cpmP); const real8 sLN0 = slave.currentwindow.linehi - polyval(normalize(real8(slave.currentwindow.linehi)-approxoffL,minL,maxL), normalize(real8(slave.currentwindow.pixlo) -approxoffP,minP,maxP), cpmL); const real8 sPN0 = slave.currentwindow.pixlo - polyval(normalize(real8(slave.currentwindow.linehi)-approxoffL,minL,maxL), normalize(real8(slave.currentwindow.pixlo) -approxoffP,minP,maxP), cpmP); const real8 sLNN = slave.currentwindow.linehi - polyval(normalize(real8(slave.currentwindow.linehi)-approxoffL,minL,maxL), normalize(real8(slave.currentwindow.pixhi) -approxoffP,minP,maxP), cpmL); const real8 sPNN = slave.currentwindow.pixhi - polyval(normalize(real8(slave.currentwindow.linehi)-approxoffL,minL,maxL), normalize(real8(slave.currentwindow.pixhi) -approxoffP,minP,maxP), cpmP); // // ______make window rectangular + int______ // // ______window is uint type______ // if (sL00 < 0.) sL00 = 0.; // if (sP00 < 0.) sP00 = 0.; // window slaveinmaster = {ceil(max(sL00,sL0N)), // floor(min(sLN0,sLNN)), // ceil(max(sP00,sPN0)), // floor(min(sP0N,sPNN))}; // ______Corners of overlap master,slave in master system______ window win; win.linelo = max(int32(master.currentwindow.linelo), int32(ceil(max(sL00,sL0N)))); win.linehi = min(int32(master.currentwindow.linehi), int32(floor(min(sLN0,sLNN)))); win.pixlo = max(int32(master.currentwindow.pixlo), int32(ceil(max(sP00,sPN0)))); win.pixhi = min(int32(master.currentwindow.pixhi), int32(floor(min(sP0N,sPNN)))); #ifdef __DEBUG DEBUG.print("Finished getoverlap"); DEBUG.print("Approximate overlap master/slave window:"); win.disp(); #endif return win; } // END getoverlap /**************************************************************** * getoverlap * * * * compute rectangular overlap between master and slave * * (master coordinate system) * * Freek van Leijen, 22-SEP-2007 * ****************************************************************/ window getoverlap( const slcimage &master, const slcimage &slave, const real8 &Npointsd2, const real8 &timing_L, const real8 &timing_P) { TRACE_FUNCTION("getoverlap (FvL 22-SEP-07)") real8 ml0 = master.currentwindow.linelo; real8 mlN = master.currentwindow.linehi; real8 mp0 = master.currentwindow.pixlo; real8 mpN = master.currentwindow.pixhi; real8 sl00 = slave.currentwindow.linelo+slave.slavemasteroffsets.l00+Npointsd2-timing_L; real8 sp00 = slave.currentwindow.pixlo+slave.slavemasteroffsets.p00+Npointsd2-timing_P; real8 sl0N = slave.currentwindow.linelo+slave.slavemasteroffsets.l0N+Npointsd2-timing_L; real8 sp0N = slave.currentwindow.pixhi+slave.slavemasteroffsets.p0N-Npointsd2-timing_P; real8 slN0 = slave.currentwindow.linehi+slave.slavemasteroffsets.lN0-Npointsd2-timing_L; real8 spN0 = slave.currentwindow.pixlo+slave.slavemasteroffsets.pN0+Npointsd2-timing_P; real8 slNN = slave.currentwindow.linehi+slave.slavemasteroffsets.lNN-Npointsd2-timing_L; real8 spNN = slave.currentwindow.pixhi+slave.slavemasteroffsets.pNN-Npointsd2-timing_P; matrix mh1sv1(2,1), mh1sv2(2,1), mh2sv1(2,1), mh2sv2(2,1), mv1sh1(2,1), mv1sh2(2,1), mv2sh1(2,1), mv2sh2(2,1); lineintersect(ml0,mp0,ml0,mpN,sl00,sp00,slN0,spN0,mh1sv1); lineintersect(ml0,mp0,ml0,mpN,sl0N,sp0N,slNN,spNN,mh1sv2); lineintersect(mlN,mp0,mlN,mpN,sl00,sp00,slN0,spN0,mh2sv1); lineintersect(mlN,mp0,mlN,mpN,sl0N,sp0N,slNN,spNN,mh2sv2); lineintersect(ml0,mp0,mlN,mp0,sl00,sp00,sl0N,sp0N,mv1sh1); lineintersect(ml0,mp0,mlN,mp0,slN0,spN0,slNN,spNN,mv1sh2); lineintersect(ml0,mpN,mlN,mpN,sl00,sp00,sl0N,sp0N,mv2sh1); lineintersect(ml0,mpN,mlN,mpN,slN0,spN0,slNN,spNN,mv2sh2); real8 overlap_l0 = max(max(max(max(max(max(ml0,sl00),sl0N),mh1sv1(0,0)),mh1sv2(0,0)),mv1sh1(0,0)),mv2sh1(0,0)); real8 overlap_p0 = max(max(max(max(max(max(mp0,sp00),spN0),mh1sv1(1,0)),mh2sv1(1,0)),mv1sh1(1,0)),mv1sh2(1,0)); real8 overlap_lN = min(min(min(min(min(min(mlN,slN0),slNN),mh2sv1(0,0)),mh2sv2(0,0)),mv1sh2(0,0)),mv2sh2(0,0)); real8 overlap_pN = min(min(min(min(min(min(mpN,sp0N),spNN),mh1sv2(1,0)),mh2sv2(1,0)),mv2sh1(1,0)),mv2sh2(1,0)); // ______Corners of overlap master,slave in master system______ window overlap; overlap.linelo = int32(ceil(overlap_l0)); overlap.linehi = int32(floor(overlap_lN)); overlap.pixlo = int32(ceil(overlap_p0)); overlap.pixhi = int32(floor(overlap_pN)); return overlap; } // END getoverlap /**************************************************************** * lineintersect * * * * compute intersection point of two line segments * * (master coordinate system) * * Freek van Leijen, 22-SEP-2007 * ****************************************************************/ void lineintersect( const real8 &ax, const real8 &ay, const real8 &bx, const real8 &by, const real8 &cx, const real8 &cy, const real8 &dx, const real8 &dy, matrix &exy) { TRACE_FUNCTION("lineintersect (FvL 22-SEP-2007)") real8 u1 = bx-ax; real8 u2 = by-ay; real8 v1 = dx-cx; real8 v2 = dy-cy; real8 w1 = ax-cx; real8 w2 = ay-cy; real8 s = (v2*w1-v1*w2)/(v1*u2-v2*u1); exy(0,0) = ax+s*u1; exy(1,0) = ay+s*u2; } // END lineintersect /**************************************************************** * readcoeff * * * * Pattern is searched in file (1st word), * * After Pattern the Ncoeffs must follow * * next (Ncoeff) lines are assumed to contain the coefficients * * * * e.g.: readcoeff(resfile,"Degree_flat:",9) * * * * input: * * - file name to search * * - pattern to search for * * * * output: * * - matrix coefficients(Nc , 1) * * * * Bert Kampes, 12-Mar-1999 * ****************************************************************/ matrix readcoeff( const char* file, const char* pattern, const int16 Ncoeff) { TRACE_FUNCTION("readcoeff (BK 12-Mar-1999)") char dummyline[ONE27]; char word[EIGHTY]; bool foundword = false; matrix coeffs(Ncoeff,1); // store coefficients ifstream infile(file, ios::in); bk_assert(infile,file,__FILE__,__LINE__); // ====== Search infile ====== while (infile) { infile >> word; if (strcmp(pattern,word)) // no pattern match. { infile.getline(dummyline,4*ONE27,'\n'); // goto next line. } else // pattern match. { infile.getline(dummyline,ONE27,'\n'); // start data foundword = true; for (register int32 i=0;i> coeffs(i,0); infile.getline(dummyline,ONE27,'\n'); // goto next line. } break; // file } // else } // file infile.close(); if (!foundword) { ERROR << "readcoeff: file: " << file << ": could not find string \"" << pattern << "\"."; PRINT_ERROR(ERROR.get_str()); throw(file_error); } else { INFO << "read: " << Ncoeff << " coefficients after: \"" << pattern << "\""; INFO.print(); } return coeffs; } // END readcoeff /**************************************************************** * readcoeff * * * * Pattern is searched in file (1st word), * * After Pattern the Ncoeffs must follow * * next (Ncoeff) lines are assumed to contain the coefficients * * * * e.g.: readcoeff(resfile,"Degree_flat:",9) * * * * input: * * - file name to search * * - pattern to search for * * * * output: * * - matrix coefficients(Nc , 1) * * * * Bert Kampes, 12-Mar-1999 * ****************************************************************/ matrix readnormcoeff( const char* file, const char* pattern) { TRACE_FUNCTION("readcoeff (BK 12-Mar-1999)") char dummyline[ONE27]; char word[EIGHTY]; bool foundword = false; matrix coeffs(2,1); // store coefficients ifstream infile(file, ios::in); bk_assert(infile,file,__FILE__,__LINE__); // ====== Search infile ====== while (infile) { infile >> word; if (strcmp(pattern,word)) // no pattern match. { infile.getline(dummyline,4*ONE27,'\n'); // goto next line. } else // pattern match. { foundword = true; infile >> coeffs(0,0)>>coeffs(1,0); break; break; // file } // else } // file infile.close(); if (!foundword) { ERROR << "readcoeff: file: " << file << ": could not find string \"" << pattern << "\"."; PRINT_ERROR(ERROR.get_str()); throw(file_error); } else { INFO << "read: " << 2 << " coefficients after: \"" << pattern << "\""; INFO.print(); } return coeffs; } // END readcoeff /**************************************************************** * openfstream * * * * Open an input file stream by name * * input: * * - fstream * * - filename * * output: * * - opened file, check yourself with assert * * * * Bert Kampes, 11-Sep-2004 * ****************************************************************/ void openfstream( ifstream &stream, const char* ifilename) { TRACE_FUNCTION("openfstream (BK 11-Sep-2004)") INFO << "Opening input file: " << ifilename; INFO.print(); DEBUG << "Opening input file: " << ifilename; DEBUG.print(); #ifdef __NO_IOS_BINARY__ stream.open(ifilename, ios::in); #else stream.open(ifilename, ios::in | ios::binary); #endif } // END openfstream /**************************************************************** * openfstream * * * * Open an output file stream by name * * input: * * - ofstream * * - filename * * - overwrite bool * * output: * * - opened file, check yourself with assert * * * * Bert Kampes, 11-Sep-2004 * ****************************************************************/ void openfstream( ofstream &stream, const char* ofilename, const bool overwrite) { TRACE_FUNCTION("openfstream (BK 11-Sep-2004)") DEBUG << "Opening output file: " << ofilename; DEBUG.print(); if (overwrite == true) { #ifdef __NO_IOS_BINARY__ stream.open(ofilename, ios::out | ios::trunc); #else stream.open(ofilename, ios::out | ios::binary | ios::trunc); #endif } else { if (existed(ofilename) == true) { ERROR << "output file \": " << ofilename << "\" exists, use OVERWRITE ON"; PRINT_ERROR(ERROR.get_str()) throw(file_error); } else { #ifdef __NO_IOS_BINARY__ stream.open(ofilename, ios::out); #else stream.open(ofilename, ios::out | ios::binary); #endif } } } // END openfstream /**************************************************************** * bk_assert * * * * Check opened input fstream * * input: * * - fstream * * - filedescription * * - __FILE__ * * - __LINE__ * * output: * * - exit or ok * * * * Bert Kampes, 04-Jun-1999 * ****************************************************************/ void bk_assert( const ifstream &stream, const char* ofilename, const char* callingfile, int32 linenumber) { TRACE_FUNCTION("bk_assert (BK 04-Jun-1999)") DEBUG << "Opened input file: " << ofilename; DEBUG.print(); if (!stream) { ERROR << "Unable to open input file: " << ofilename << " in source file: " << callingfile << " at line: " << linenumber; PRINT_ERROR(ERROR.get_str()); ERROR << "Missing a required file: " << ofilename; // [MA] 201004 PRINT_ERROR(ERROR.get_str()); throw(file_error); } } // END bk_assert /**************************************************************** * bk_assert * * * * Check opened output fstream * * input: * * - fstream * * - filedescription * * - __FILE__ * * - __LINE__ * * output: * * - exit or ok * * * * Bert Kampes, 04-Jun-1999 * ****************************************************************/ void bk_assert( const ofstream &stream, const char* ofilename, const char* callingfile, int32 linenumber) { TRACE_FUNCTION("bk_assert (BK 04-Jun-1999)") DEBUG << "Opened output file: " << ofilename; DEBUG.print(); if (!stream) { ERROR << "Unable to open output file: " << ofilename << " in source file: " << callingfile << " at line: " << linenumber << " (OVERWRIT OFF/non existing directory?)"; PRINT_ERROR(ERROR.get_str()); throw(file_error); } } // END bk_assert /**************************************************************** * tolower * * * * Convert string to lower case * * input: * * - __LINE__ * * output: * * - converted lowercase string * * * * Bert Kampes, 06-Sep-1999 * ****************************************************************/ void tolower(char *s) { TRACE_FUNCTION("tolower (BK 06-Sep-1999)") #ifdef WIN32 s = _strlwr(s);// Jia #else while (*s != '\0') *s++ = tolower(*s);// cctype #endif } /**************************************************************** * toupper * * * * Convert string to upper case * * input: * * - __LINE__ * * output: * * - converted uppercase string * * * * Bert Kampes, 06-Sep-1999 * ****************************************************************/ void toupper(char *s) { TRACE_FUNCTION("toupper (BK 06-Sep-1999)") #ifdef WIN32 s = _strupr(s);// Jia #else while (*s != '\0') { //*s++ = toupper(*s); // [AV] do not works correctly with g++ 4.8 *s = std::toupper(*s); // cctype ++s; } #endif } /**************************************************************** * int2str * * * * Convert integer to string * * input: * * - integer * * output: * * - converted to string * * * * Mahmut Arikan, 23-Oct-2008 * ****************************************************************/ string int2str(const int &integer) { TRACE_FUNCTION("int2str (MA 23-Oct-2008)") ostringstream datastream; datastream << integer << flush; return (datastream.str()); } // End of int2str Doris-5.0.3Beta/doris_core/ioroutines.hh000077500000000000000000000162121312547014700202550ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/ioroutines.hh,v $ * $Revision: 3.9 $ * $Date: 2005/08/24 10:03:18 $ * $Author: kampes $ * * Definitions of general input/output routines. ****************************************************************/ /**************************************************************** * Note that the strstream class using a buffer and stream output memory * can be replaced by the following construction (BK, april 2003): * ----------------------------------------------------- * static ostringstream message; * message << "Hi Bert. " << 1.1 << ends; * cout << "message.str(): " << message.str() << "\n"; * message.str(string());// empty buffer * ----------------------------------------------------- ****************************************************************/ #ifndef IOROUTINES_H #define IOROUTINES_H using namespace std; // BK 29-Mar-2003, new compiler? // Jia defined this for compilation under windows // Bert Kampes, 24-Aug-2005 #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "constants.hh" // global ONE27, inputstructs etc. #include "readinput.hh" // input structs #include "matrixbk.hh" // my matrix class #include "slcimage.hh" // my slc image class #include "productinfo.hh" // my 'products' class #include // exit // // ====== Prototypes and inlined functions ====== // ______ Screenoutput ______ void printcpu(bool init=false); // prototype // ====== Prototypes ====== // ______ Initialization ______ void inittest(); // Some initial tests // ______ Find out if initwrite is necessary ______ bool doinitwrite( input_gen &generalinput, int16 imageid); // ______ Write initial data to files ______ // ______ id=1: logfile, 2:master result, 3: slaveresult ______ void initwrite( const char* file, int16 fileid); // ______ Append filein to fileout and remove in ______ void updatefile( const char* filein, const char* fileout); // ______ Search file for result and return that ______ bool readres( char* returnword, const int16 sizeofreturnword, const char* file, const char* patern, const int16 napatern=0, int16 skiplines=0); // ______ Read coefficients from resultfile ______ matrix readcoeff( const char* file, const char* pattern, const int16 Ncoefficients); // ______ Read normalization coefficients from ifgs result file________ matrix readnormcoeff( const char* file, const char* pattern); // ______ Updates process_control in resultfiles ______ void updateprocesscontrol( const char* filein, int16 fileid); // ______ Check if only ones results per step ______ void checkprocessing( const input_gen &generalinput, int16 alreadyprocessed[NUMPROCESSES]); // ______ Check if requested processing is logical ______ void checkrequest( int16 step, int16 alreadyprocess[NUMPROCESSES], ...); // ______ Check if process control flags are written correctly _____ void fillcheckprocess( const char *line, int16 checkprocess[NUMPROCESSES], int16 fileid); // ______ Fill array what is already processed ______ void fillprocessed( const char *line, int16 checkprocess[NUMPROCESSES], int16 fileid); // ______ Removes data section from resultfile ______ void removedatleader( const char *file); // ______ True if file existed ______ bool existed( const char *file); // ______ Returns filesize ______ uint filesize( const char *file); // ______ Count number of eols ______ int32 filelines( const char *file); // ______ Pause for interactive processing ______ void getanswer( ); // ______ Open an input file stream ______ void openfstream( ifstream &str, const char* ifilename); // ______ Open an output file stream ______ void openfstream( ofstream &str, const char* ofilename, const bool overwrit); // ______ Check if file is opened correctly ______ void bk_assert( const ifstream &str, const char* ifilename, const char* callingfilename = "?", int32 linenumber = 0); // ______ Check if file is opened correctly ______ void bk_assert( const ofstream &str, const char* ofilename, const char* callingfilename = "?", int32 linenumber = 0); // _____ Convert a string to lower/upper case ______ void tolower(char *s); void toupper(char *s); // _____ Convert an integer to string ______ string int2str(const int &integer); // [MA] // // ______ (partially) Fills struct image/inter-info ______ // void fillslcimage( // slcimage &image, // const char *file); // // ______ Struct slcimage: update it after certain step ______ // void updateslcimage( // slcimage &image, // const char *file, // const char *iden); // ______ Fill struct interferogram info ______ //void fillproductinfo( // productinfo &interferogram, // ______ compute overlap in same system ______ window getoverlap( const window &master, const window &slave); // compute overlap approx with transf. polynomial between slave2master coord.system window getoverlap( const slcimage &master, const slcimage &slave, const matrix &cpmL, const matrix &cpmP); window getoverlap( const slcimage &master, const slcimage &slave, const real8 &Npointsd2, const real8 &timing_L, const real8 &timing_P); //[FvL] void lineintersect( const real8 &ax, const real8 &ay, const real8 &bx, const real8 &by, const real8 &cx, const real8 &cy, const real8 &dx, const real8 &dy, matrix &exy); //[FvL] // // ______ Struct productinfo: fill info after certain step ______ // void fillproductinfo( // productinfo &interferogram, // const char *file, // const char *iden); #endif // IOROUTINES_H Doris-5.0.3Beta/doris_core/matrix_test.cc000077500000000000000000000203331312547014700204050ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/matrixbk_test.cc,v $ * * $Revision: 3.11 $ * * $Date: 2005/10/18 13:46:51 $ * * $Author: kampes $ * * * * Test program for matrix class. * * Compile with Doris Makefile. * #%// BK 17-Aug-2000 * ****************************************************************/ #include "constants.hh" // typedefs #include "matrixbk.hh" // matrix functions bk_messages TRACE; bk_messages DEBUG; bk_messages INFO; bk_messages PROGRESS; bk_messages WARNING; bk_messages ERROR; bk_messages matDEBUG; bk_messages matERROR; // ______ used in matrix_bk.cc to keep track of total allocated ______ uint totalallocated=0; // [B] matrixdebuging /**************************************************************** * main * #%// BK 17-Aug-2000 * ****************************************************************/ int main( int argc, char* argv[]) { const int L = 4; // numlines A const int P = 2; // numcols A int i,j; matrix A(L,P); matrix B(P,L+1); for (i=0; i C = A*B; cout << "matrix C(" << C.lines() << "," << C.pixels() << ") = A*B\n"; C.showdata(); cout << "\n\n---------------------\n\n"; // ______ Test matTxmat ______ matrix C1 = matTxmat(transpose(A),B); cout << "matrix C(" << C1.lines() << "," << C1.pixels() << ") = A*B (using matTxmat)\n"; C1.showdata(); cout << "\n\n---------------------\n\n"; // ______ Test matTxmat ______ matrix C2 = matxmatT(A,transpose(B)); cout << "matrix C(" << C2.lines() << "," << C2.pixels() << ") = A*B (using matxmatT)\n"; C2.showdata(); cout << "\n\n---------------------\n\n"; // --- check result --- cout << "checksum1 = " << max(magnitude(C-C1)) << endl; cout << "checksum2 = " << max(magnitude(C-C2)) << endl; // --- Conjugated --- matrix Bconj = conj(B); cout << "conjugated:\n"; Bconj.showdata(); cout << "\n\n---------------------\n\n"; // ______ Test 1d fft ______ fft(A,1); cout << "1d fft over columns of matrix A(" << A.lines() << "," << A.pixels() << "):\n"; A.showdata(); cout << "\n\n---------------------\n\n"; // // ______ Test operator = ______ // for (i=0; i<10; ++i) // { // cout << i << ": A=B\n"; // A=B; // cout << i << ": B=B\n"; // B=B; // cout << i << ": C=A\n"; // matrix C=A; // cout << "\n"; // } // ______ Test find function ______ // matrix indexNaN = A.find(2); // ______ Test mypow function ______ matrix R(L,P); for (i=0; i Q(L,P); for (i=0; i Q2 = conj(Q); Q2.showdata(); return 0; // ______ Test smooth function ______ // R.smooth(1); // ______ Test pow ^ operator ______ // R = R^2.0; // ______ Test wshift function ______ cout << "\n\n- WSHIFT -\n\n"; matrix AA(1,7); for (i=0; i QQ(7,7); for (i=0; i BB = diagxmat(AA,QQ); cout << "BB=diagxmat(AA,QQ)\n"; BB.showdata(); // ______ Test cos/sin complr4 operator ______ cout << "VVVVVVVVVVVVVVVVVVVVVVVVVVVVV\n"; matrix r8A(3,5); r8A = 5.3; cout << "r8A=5.3:\n"; r8A.showdata(); for (i=0; i cosr8A = cos(r8A); cout << "\ncosr8A:\n"; cosr8A.showdata(); // matrix r8B = r8A+0.2; matrix sinr8B = sin(r8B); cout << "\nsinr8B:\n"; sinr8B.showdata(); // matrix cr4AB = mat2cr4(r8A,r8B); cout << "\ncomplr4(r8A,r8B):\n"; cr4AB.showdata(); // ______ Test mysort rows on first col ______ cout << "\n\nmysort(real4) matrix ascending on rows\n"; matrix SS(5,3); SS(0,0)=2.1; SS(0,1)=10.1; SS(0,2)=500.1; SS(1,0)=1.1; SS(1,1)=20.1; SS(1,2)=400.1; SS(2,0)=3.1; SS(2,1)=30.1; SS(2,2)=300.1; SS(3,0)=5.1; SS(3,1)=40.1; SS(3,2)=200.1; SS(4,0)=1.1; SS(4,1)=50.1; SS(4,2)=100.1; cout << "original data (SS)\n"; SS.showdata(); cout << "mysort2(SS)\n"; mysort2(SS); SS.showdata(); matrix SSi(5,3); SSi(0,0)=2; SSi(0,1)=10; SSi(0,2)=500; SSi(1,0)=1; SSi(1,1)=20; SSi(1,2)=400; SSi(2,0)=3; SSi(2,1)=30; SSi(2,2)=300; SSi(3,0)=5; SSi(3,1)=40; SSi(3,2)=200; SSi(4,0)=1; SSi(4,1)=50; SSi(4,2)=100; cout << "original data (SSi)\n"; SSi.showdata(); cout << "mysort2(SSi)\n"; mysort2(SSi); SSi.showdata(); // ______ Test oversample ______ cout << "\n\nmysort(real4) matrix ascending on rows\n"; matrix OVS(4,4); OVS(0,0)=2.1; OVS(0,1)=10.1; OVS(0,2)=500.1; OVS(1,0)=1.1; OVS(1,1)=20.1; OVS(1,2)=400.1; OVS(2,0)=3.1; OVS(2,1)=30.1; OVS(2,2)=300.1; OVS(3,0)=5.1; OVS(3,1)=40.1; OVS(3,2)=200.1; cout << "original data (OVS)\n"; OVS.showdata(); cout << "mysort2(SS)\n"; matrix OVS_ = oversample(OVS,2,2); OVS_.showdata(); // ______ Test fliplr/flipud ______ cout << "\n\nOVS.showdata()\n"; OVS.showdata(); cout << "OVS.flipud()\n"; OVS.flipud(); OVS.showdata(); cout << "OVS.fliplr() (ie both up and lr)\n"; OVS.fliplr(); OVS.showdata(); cout << "\n\nNormal termination.\n\n"; return 0; } // END main Doris-5.0.3Beta/doris_core/matrixbk.cc000077500000000000000000002057371312547014700177000ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /************************************************************************ * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/matrixbk.cc,v $ * * $Revision: 3.14 $ * * $Date: 2005/10/18 14:16:32 $ * * $Author: kampes $ * * * * template (base) class for matrices. * * * * ====== Defines (compiler -D option) ====== * * __USE_VECLIB_LIBRARY__ for using VECLIB library * * __USE_LAPACK_LIBRARY__ for using LAPACK library * * __USE_FFTW_LIBRARY__ for using FFTW library * * __DEBUGMAT1 index checking, dimensions etc. * * __DEBUGMAT2 info, can savely be un-defined * * * * Note that data is continuously in memory, because * * VECLIB/FFTW assumes this (and me as well...) so a vector of vectors * * cannot be used. * ************************************************************************/ #include "constants.hh" // typedefs, window #include // cout etc. #include // ofstream type #include // memory stream #include // setw etc. #include // max #include // memset according to g++ (?) #include #ifdef __DEBUGMAT1 // use index checking, alloc #include // bad_alloc #endif // ______ Keep track of total allocated memory ______ // ______ This will work upto 2^31 bytes (2GB) ______ // ______ there is a problem here, but how to declare a global? ______ // ______ if called from different files, not correct bookkeeping ______ // ______ therefor we define it above main in processor.cc ______ #ifdef __DEBUGMAT2 // use index checking, alloc extern uint totalallocated; // [B] #endif // ______ message objects, global, set in main ______ extern bk_messages matERROR; extern bk_messages matDEBUG; // ====== Start of class definition ====== // ====== Private functions ====== /**************************************************************** * allocate * * allocate 2d array in major row order, continuously in * * memory (required by VECLIB/FFTW). consider rewriting to vector * * of vectors of stl, but may not be cont. in mem. * * g++ w/o exception handling, ... * * Bert Kampes, 01-Feb-1999 * ****************************************************************/ template void matrix::allocate(uint numlines, uint numpixels) // allocator { #ifdef __DEBUGMAT1 if (numlines==0 || numpixels==0) { matERROR << "Allocation impossible: size (l,p): " << numlines << ", " << numpixels; matERROR.print(); } #endif nrows = numlines; ncols = numpixels; nsize = numlines*numpixels; // Bert Kampes, 07-Apr-2005: try/catch should work by now... try { data = new Type*[numlines];// get memory : make linear array of pointers } catch (bad_alloc) { matERROR << "code 502: first allocation failed, size: " << numlines << ", " << numpixels; matERROR.print(); } try { data[0] = new Type[nsize];// get memory : get the first pointer for the memory block, later we'll fill in all the address } catch(bad_alloc) { matERROR << "code 502: second allocation failed: size: " << numlines << ", " << numpixels; matERROR.print(); } for (register uint i=1; i void matrix::initialize(uint numlines, uint numpixels) { #ifdef __DEBUGMAT2 matDEBUG.print("initialization matrix."); #endif allocate(numlines,numpixels); clean(); } // END initialize #ifdef __DEBUGMAT1 /**************************************************************** * checkindex (l,p) * * Bert Kampes, 01-Feb-1999 * ****************************************************************/ template void matrix::checkindex(uint line, uint pixel) const { if (int32(line) > int32(nrows)-1 || int32(pixel) > int32(ncols)-1) { matERROR << "Wrong index (l,p)=(" << line << "," << pixel << "); Matrix(" << nrows << "," << ncols << ") at " << &data[0][0]; matERROR.print(); } } // END checkindex #endif // ====== Public functions ====== // ====== Constructors ====== /**************************************************************** \\ * matrix A; * \\ * Bert Kampes, 11-Dec-1998 * \\ ****************************************************************/ template matrix::matrix() // constructor (0 arg) { nrows = 0; ncols = 0; nsize = 0; data = 0; // address of pointer array is set to null } // END constructor /**************************************************************** * matrix A(3,3); * * Bert Kampes, 11-Dec-1998 * ****************************************************************/ template matrix::matrix(uint lines, uint pixels) { initialize(lines,pixels); // set to 0 } // END constructor /**************************************************************** * matrix A=B; * * copy constructor; avoids default for dynamical memory: * * bitwise copy. * * Bert Kampes, 11-Dec-1998 * ****************************************************************/ template matrix::matrix(const matrix& A) { #ifdef __DEBUGMAT2 matDEBUG.print("copy constructor."); // [MA] ex: copy constructor is called when operator << is used. #endif if (A.nsize) { allocate(A.nrows,A.ncols); memcpy(data[0],A.data[0],nsize*sizeof(Type)); } else { // [MA] allow for NULL matrix returns when dynamic memory nsize =0 allocate(A.nrows,A.ncols); #ifdef __DEBUGMAT2 // [MA] delete this set in future matDEBUG << "new mtx nsize: " << nsize << " datasize: " << nsize*sizeof(Type) << " dataaddress: " << &data << " vs inputadd: " << &A << " addressNULLmemblock: " << data[0]; matDEBUG.print(); #endif //memcpy(data[0],0,nsize*sizeof(Type)); // clean() // when nsize=0 and A.data[0] doesn't exist (data=0), such as a null mtx, thus memcpy crashes with "Caught SIGSEGV: Segmentation fault." // this is necessary otherwise it points to a memory block data[0]=0; } } // END constructor /**************************************************************** * matrix A(win,B) * * Constructor (part) * * Bert Kampes, 01-Feb-1999 * * Bert Kampes, 31-Mar-1999 memcpy ipv. for_j * * window starts at 0 (matrix index) * #%// BK 25-Oct-2000 * ****************************************************************/ template matrix::matrix (window win, const matrix& A) { #ifdef __DEBUGMAT2 matDEBUG.print("constructor as part."); #endif // ______ Check arguments ______ #ifdef __DEBUGMAT1 if (win.linehi matrix::~matrix() { if (data==0) return; #ifdef __DEBUGMAT2 uint deallocated = sizeof(Type)*nsize; // [B] totalallocated -= deallocated; // [B] matDEBUG << "deallocated matrix(" << nrows << "," << ncols << ") at: " << data[0] << " (" << setw(10) << deallocated << "B; total: " << setw(10) << totalallocated << "B)"; matDEBUG.print(); #endif delete [] data[0]; // deallocate delete [] data; // deallocate data=0; // set to null pointer } // END destructor // ======Data functions====== /**************************************************************** * A.setdata(w) * * Bert Kampes, 01-Feb-1999 * ****************************************************************/ template void matrix::setdata(Type w) // sets matrix to constant { #ifdef __DEBUGMAT2 matDEBUG.print("A.setdata(w)"); #endif Type *pnt = data[0]; for (register uint i=0;i void matrix::setdata(uint l1, uint p1, const matrix& A) { #ifdef __DEBUGMAT1 checkindex(l1+A.nrows-1,p1+A.ncols-1);// check far most corner #endif const uint sizelin = A.ncols*sizeof(Type); for (register uint i=0;i void matrix::setdata(window winin, const matrix &A, window winA) { #ifdef __DEBUGMAT2 matDEBUG.print("setdata (win,A,win)"); #endif // ______Check default request______ if (winin.linehi == 0 && winin.pixhi == 0) {winin.linehi = nrows -1; winin.pixhi = ncols -1;} if (winA.linehi == 0 && winA.pixhi == 0) {winA.linehi = A.lines() -1; winA.pixhi = A.pixels() -1;} #ifdef __DEBUGMAT1 if (((winin.linehi - winin.linelo) != (winA.linehi - winA.linelo)) || ((winin.pixhi - winin.pixlo) != (winA.pixhi - winA.pixlo)) ) matERROR.print("code 901: wrong input."); if (winin.linehi nrows -1) || (winin.pixhi > ncols -1) ) matERROR.print("code 901: wrong input.2"); if ((winA.linehi > A.lines() -1) || (winA.pixhi > A.pixels() -1) ) matERROR.print("code 901: wrong input.3"); #endif // ______ Fill data ______ const uint sizelin = (winA.pixhi - winA.pixlo + 1)*sizeof(Type); for(register uint i=winin.linelo; i<=winin.linehi;i++) memcpy(data[i]+winin.pixlo,A[i-winin.linelo+winA.linelo]+winA.pixlo,sizelin); } // END setdata /**************************************************************** * B.setdata(A, winA): * * set total of B to winA of A * * Bert Kampes, 17-Mar-1999 * ****************************************************************/ template void matrix::setdata(const matrix &A, window winA) { #ifdef __DEBUGMAT2 matDEBUG.print("setdata (A,win)"); #endif #ifdef __DEBUGMAT1 if (((nrows -1) != (winA.linehi - winA.linelo)) || ((ncols -1) != (winA.pixhi - winA.pixlo)) ) matERROR.print("code 901: wrong input."); if ((winA.linehi > A.lines() -1) || (winA.pixhi > A.pixels() -1) ) matERROR.print("code 901: wrong input.3"); #endif // ______ Fill data ______ const uint sizelin = ncols*sizeof(Type); for(register uint i=0; i matrix matrix::getdata(window win) const { #ifdef __DEBUGMAT2 matDEBUG.print("getdata."); #endif #ifdef __DEBUGMAT1 if (win.linehi Result(numlin,numpix); // =data(; for(register uint i=0; i matrix matrix::getrow(uint line) const { #ifdef __DEBUGMAT1 checkindex(line,0); #endif matrix Result(1,ncols); memcpy(Result[0],data[line],ncols*sizeof(Type)); return Result; } // END getrow /**************************************************************** * A=B.getcolumn(col) * * cols: 0 1 2 .. * * Bert Kampes, 01-Feb-1999 * ****************************************************************/ template matrix matrix::getcolumn(uint pixel) const { #ifdef __DEBUGMAT1 checkindex(0,pixel); #endif matrix Result(nrows,1); Type *pntA = data[0]+pixel; Type *pntR = Result[0]; for (register uint i=0; i void matrix::showdata() const // show all data in matrix { #ifdef __DEBUGMAT1 matDEBUG.print("showdata."); #endif #ifdef __DEBUGMAT2 if (nrows>100 || ncols>15) { matDEBUG << "matrix (" << nrows << "," << ncols << "); only showing data (0:99,0:9)."; matDEBUG.print(); } #endif const uint L = (nrows<=100) ? nrows : 100; const uint P = (ncols<=10) ? ncols : 10; matDEBUG.precision(11); // [MA] 9 --> 11 matDEBUG.width(12); // 10 --> 12 //matDEBUG.setf(ios::left, ios::adjustfield); // [MA] this failed by 4.01 version of messages.hh for (register uint i=0; i inline bool matrix::isvector() const { return (nrows==1 || ncols==1) ? true : false; } // END isvector /**************************************************************** * uint l = A.lines() * * Bert Kampes, 01-Feb-1999 * ****************************************************************/ template inline uint matrix::lines() const // return number of lines { return nrows; } // END lines /**************************************************************** * uint p = A.pixels() * * Bert Kampes, 01-Feb-1999 * ****************************************************************/ template inline uint matrix::pixels() const // return number of pixels { return ncols; } // END pixels /**************************************************************** * uint s = A.size() * * Bert Kampes, 01-Feb-1999 * ****************************************************************/ template inline uint matrix::size() const // return nsize { return nsize; } // END size /**************************************************************** * A.resize(l,p) * * Bert Kampes, 01-Feb-1999 * ****************************************************************/ template void matrix::resize(uint l1, uint p1) { #ifdef __DEBUGMAT2 matDEBUG.print("resize."); #endif if (l1 == nrows && p1 == ncols) return; else if (data!=0) // check for allocated memory { #ifdef __DEBUGMAT2 uint deallocated = sizeof(Type)*nsize; // [B] totalallocated -= deallocated; // [B] matDEBUG << "deallocated matrix(" << nrows << "," << ncols << ") at: " << data[0] << " (" << setw(10) << deallocated << "B; total: " << setw(10) << totalallocated << "B)"; matDEBUG.print(); #endif delete [] data[0]; delete [] data; data=0; } initialize(l1,p1); // set to 0 } // END resize /**************************************************************** * A.clean() * * Bert Kampes, 01-Feb-1999 * ****************************************************************/ template void matrix::clean() // sets 2 zero { #ifdef __DEBUGMAT2 matDEBUG.print("mtx clean."); #endif memset(data[0],0,nsize*sizeof(Type)); } // END clean /**************************************************************** * B.setrow(row, data) * * rows: 0 1 2 .., should fit exactly * * orientation of vector is disregarded. * * Bert Kampes, 12-Oct-1999 * ****************************************************************/ template void matrix::setrow(uint line, const matrix &LINE) { #ifdef __DEBUGMAT1 checkindex(line,0); if (!(LINE.nrows == 1 || LINE.ncols == 1)) matERROR.print("setrow: only vector input."); if (LINE.nsize != ncols) matERROR.print("setrow: sizeofvector should be same as matrix."); #endif memcpy(data[line],LINE[0],ncols*sizeof(Type)); } // END setrow /**************************************************************** * B.setrow(row, scalar) * * rows: 0 1 2 .., should fit exactly * * orientation of vector is disregarded. * * Bert Kampes, 12-Oct-1999 * ****************************************************************/ template void matrix::setrow(uint line, Type scalar) { #ifdef __DEBUGMAT1 checkindex(line,0); #endif for (register Type *pntB =&data[line][0]; pntB<=&data[line][ncols-1]; pntB++) *pntB = scalar; } // END setrow /**************************************************************** * B.setcolumn(col, COL) * * cols: 0 1 2 .. * * orientation of vector is disregarded. * * Bert Kampes, 12-Oct-1999 * ****************************************************************/ template void matrix::setcolumn(uint pixel, const matrix &COLUMN) { #ifdef __DEBUGMAT1 checkindex(0,pixel); if (!(COLUMN.nrows == 1 || COLUMN.ncols == 1)) matERROR.print("setcolumn: only vector input."); if (COLUMN.nsize != nrows) matERROR.print("setcolumn: sizeofvector should be same as matrix."); #endif Type *pntCOL = COLUMN[0]; for (register Type *pntB =&data[0][pixel]; pntB<=&data[nrows-1][pixel]; pntB+=ncols) *pntB = *pntCOL++; } // END setcolumn /**************************************************************** * B.setcolumn(col, scalar) * * cols: 0 1 2 .. * #%// BK 25-Sep-2000 * ****************************************************************/ template void matrix::setcolumn(uint pixel, Type scalar) { #ifdef __DEBUGMAT1 checkindex(0,pixel); #endif for (register Type *pntB =&data[0][pixel]; pntB<=&data[nrows-1][pixel]; pntB+=ncols) *pntB = scalar; } // END setcolumn /**************************************************************** * B.fliplr() * * Mirror in center vertical (flip left right). * * Bert Kampes, 23-Mar-2000 * ****************************************************************/ template void matrix::fliplr() { #ifdef __DEBUGMAT2 matDEBUG.print("fliplr."); #endif if (nrows==1) { Type *pnt1 = data[0]; // first one Type *pnt2 = data[0]+ncols-1; // last one Type tmp = *pnt1; for (register int32 i=0; i tmp1 = getcolumn(i); matrix tmp2 = getcolumn(ncols-i-1); setcolumn(i,tmp2); setcolumn(ncols-i-1,tmp1); } } } // END fliplr /**************************************************************** * B.flipud() * * Mirror in center vertical (flip left right). * * Actually move data around, not pointers, to be sure * * veclib works ok, data is cont. in memory. * * Bert Kampes, 23-Mar-2000 * ****************************************************************/ template void matrix::flipud() { #ifdef __DEBUGMAT2 matDEBUG.print("flipud."); #endif if (ncols==1) { Type *pnt1 = data[0]; // first one Type *pnt2 = data[0]+nrows-1; // last one Type tmp = *pnt1; for (register int32 i=0; i tmp1 = getrow(i); matrix tmp2 = getrow(nrows-i-1); setrow(i,tmp2); setrow(nrows-i-1,tmp1); } } } // END flipud /**************************************************************** **************************************************************** * OVERLOADED OPS * **************************************************************** ****************************************************************/ /**************************************************************** * a = A[5][2]; * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ template inline Type* matrix::operator [] (uint line) const { #ifdef __DEBUGMAT1 checkindex(line,0); #endif return data[line]; } // END [] /**************************************************************** * a = A(i,j); * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ template inline Type& matrix::operator () (uint line, uint pixel) const { #ifdef __DEBUGMAT1 checkindex(line,pixel); #endif return data[line][pixel]; } // END () /**************************************************************** * matrix B = A(window); * * may not be to efficient cause twice allocation? * * Bert Kampes, 31-Mar-2000 * ****************************************************************/ template matrix matrix::operator () (const window &win) const { matrix Res(win,*this); return Res; } // END (win) /**************************************************************** * matrix B = A(uint,uint,uint,uint); * * Bert Kampes, 31-Mar-2000 * ****************************************************************/ template matrix matrix::operator () ( const uint &l0, const uint &lN, const uint &p0, const uint &pN) const { const window win(l0,lN,p0,pN); matrix Res(win,*this); return Res; } // END (4 uint) /**************************************************************** * = * * Bert Kampes, 14-Jan-1999 * * Mahmut Arikan, 19-May-2009 Null matrix assignment * ****************************************************************/ template matrix& matrix::operator = (const matrix& A) { #ifdef __DEBUGMAT2 matDEBUG.print("operator ="); #endif //cerr << "operator =\n"; if (this != &A) // prevent copy to itself { if (A.nsize) // if allocated : disable this to return null matrix { if (data != 0) // if allocated { #ifdef __DEBUGMAT2 uint deallocated = sizeof(Type)*nsize; // [B] totalallocated -= deallocated; // [B] matDEBUG << "deallocated matrix(" << nrows << "," << ncols << ") at: " << data[0] << " (" << setw(10) << deallocated << "B; total: " << setw(10) << totalallocated << "B)"; matDEBUG.print(); #endif delete [] data[0]; delete [] data; data = 0; } allocate(A.nrows,A.ncols); memcpy(data[0],A.data[0],nsize*sizeof(Type)); } else { // [MA] allow for NULL matrix returns when dynamic memory nsize =0 cerr << "op = : NULL matrix is assigned."; allocate(A.nrows,A.ncols); data[0]=0; // point to no memory block } } return *this; } // END = /**************************************************************** * = * #%// BK 09-Nov-2000 * ****************************************************************/ template matrix& matrix::operator = (const Type scalar) { #ifdef __DEBUGMAT2 matDEBUG.print("operator = (scalar)"); #endif setdata(scalar); return *this; } // END = (scalar) /**************************************************************** * C *= 5.0; * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ template matrix& matrix::operator *= (Type scalar) { #ifdef __DEBUGMAT2 matDEBUG.print("*="); #endif #ifdef __DEBUGMAT1 if (!nsize) matERROR.print("matrix:: *= with empty matrix."); #endif Type *pntmat = data[0]; for (register uint i=0; i matrix& matrix::operator *= (const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("*= pointwise"); #endif #ifdef __DEBUGMAT1 if (nrows != A.lines() || ncols != A.pixels()) matERROR.print("matrix:: *= matrices must be same size."); #endif Type *pntmat = data[0]; Type *pntA = A[0]; //for (register uint i=0; i 4.0): for (register uint i=0; i matrix& matrix::operator /= (Type scalar) { #ifdef __DEBUGMAT2 matDEBUG.print("/= scalar"); #endif #ifdef __DEBUGMAT1 if (!nsize) matERROR.print("matrix:: /= with empty matrix."); #endif Type *pntmat = data[0]; for (register uint i=0; i matrix& matrix::operator /= (const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("/="); #endif #ifdef __DEBUGMAT1 if (nrows != A.lines() || ncols != A.pixels()) matERROR.print("matrix:: /= matrices must be same size."); #endif Type *pntmat = data[0]; Type *pntA = A[0]; //for (register uint i=0; i 4.0): for (register uint i=0; i matrix& matrix::operator -= (const matrix& A) { #ifdef __DEBUGMAT2 matDEBUG.print("-= mat"); #endif #ifdef __DEBUGMAT1 if (nrows != A.nrows || ncols != A.ncols) matERROR.print("error dimensions."); if (!A.nsize) matERROR.print("matrix:: -= with empty matrices."); #endif Type *pntmat = data[0]; Type *pntA = A.data[0]; //for (register uint i=0; i 4.0): for (register uint i=0; i matrix& matrix::operator -= (Type scalar) { #ifdef __DEBUGMAT2 matDEBUG.print("-= scalar"); #endif #ifdef __DEBUGMAT1 if (!nsize) matERROR.print("matrix:: -= with empty matrix."); #endif Type *pntmat = data[0]; for (register uint i=0; i matrix& matrix::operator += (const matrix& A) { #ifdef __DEBUGMAT2 matDEBUG.print("+="); #endif #ifdef __DEBUGMAT1 if (nrows != A.nrows || ncols != A.ncols) matERROR.print("error dimensions."); if (!A.nsize) matERROR.print("matrix:: += with empty matrices."); #endif Type *pntmat = data[0]; Type *pntA = A.data[0]; //for (register uint i=0; i 4.0): for (register uint i=0; i matrix& matrix::operator += (Type scalar) { #ifdef __DEBUGMAT2 matDEBUG.print("+= scalar"); #endif #ifdef __DEBUGMAT1 if (!nsize) matERROR.print("matrix:: += with empty matrix."); #endif Type *pntmat = data[0]; for (register uint i=0; i void matrix::conj() { #ifdef __DEBUGMAT2 matDEBUG.print("conj"); #endif Type *pntmat = data[0]; for (register uint i=0; i bool matrix::operator == (Type scalar) const { #ifdef __DEBUGMAT2 matDEBUG.print("== (scalar)"); #endif if (nsize == 0) return false; bool same = true; Type *pnt = data[0]; for (register int32 i=0; i bool matrix::operator == (const matrix &A) const { #ifdef __DEBUGMAT2 matDEBUG.print("=="); #endif if ((A.lines() != nrows) || (A.pixels() != ncols)) return false; bool same = true; Type *pnt = data[0]; Type *pntA = A[0]; for (register uint i=0; i bool matrix::operator != (Type scalar) const { #ifdef __DEBUGMAT2 matDEBUG.print("!= (scalar)"); #endif if (*this == scalar) return false; else return true; } // END != /**************************************************************** * if (A!=B) * * Bert Kampes, 08-Oct-1999 * ****************************************************************/ template bool matrix::operator != (const matrix &A) const { #ifdef __DEBUGMAT2 matDEBUG.print("!="); #endif if (*this == A) return false; else return true; } // END != // ++++++++++++++++++++++++++ // template functions, stupid place, but else not found? // specializations in matrixspecs.cc are NOT used before these? // BK 16-Aug-2000 // ++++++++++++++++++++++++++ /**************************************************************** * C = A * B; * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ template matrix operator * (const matrix& A, const matrix& B) { #ifdef __DEBUGMAT2 matDEBUG.print("matrices * (no veclib)"); #endif #ifdef __DEBUGMAT1 if (A.pixels() != B.lines()) matERROR.print("matrix::operator *: multiplication not possible"); if (!A.size()) matERROR.print("matrix:: operator * with empty matrices."); #endif // ______ Straightforward, no veclib _____ // ______ it is probably worth to make this faster, e.g., // ______ using pointers (using A[i][j] is same speed) // ______ and not initializing Result matrix Result(A.lines(),B.pixels()); register Type sum = Type(0.0); // --- use straightforward notation for slow matrix access -------- #define NO_POINTERS // this is likely a bit slower #ifdef NO_POINTERS // straightforward notation for (register uint i=0; i 4.0): sum += (*pntA) * (*pntB); // pointer over row A *pntA++; pntB += B.pixels();// point to next element in this column of B } (*pntR++) = sum;// matrix is linear in memory, major-row sum = Type(0.0);// complex requires this } } #endif return Result; } // END * /**************************************************************** * C = 5.0 * B; * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ template matrix operator * (const matrix& A, Type scalar) { #ifdef __DEBUGMAT2 matDEBUG.print("scalar *"); #endif // ______Perform multiplication______ matrix Result=A; return Result *= scalar; // checks in *= } // END * scalar /**************************************************************** * C = B * 5.0; * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ template matrix operator * (Type scalar, const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("* scalar."); #endif return A*scalar; // checks in *= } // END scalar * /**************************************************************** * C = A / 5; * * Bert Kampes, 04-Apr-2000 * ****************************************************************/ template matrix operator / (const matrix& A, Type scalar) { #ifdef __DEBUGMAT2 matDEBUG.print("/"); #endif matrix Result = A; return Result /= scalar; // checks are performed here. } // END / /**************************************************************** * C = A / B; * * Bert Kampes, 04-Apr-2000 * ****************************************************************/ template matrix operator / (const matrix& A, const matrix& B) { #ifdef __DEBUGMAT2 matDEBUG.print("/"); #endif matrix Result = A; return Result /= B; // checks are performed here. } // END / /**************************************************************** * C = A - B; * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ template matrix operator - (const matrix& A, const matrix& B) { #ifdef __DEBUGMAT2 matDEBUG.print("-"); #endif matrix Result = A; return Result -= B; // checks are performed here. } // END - (binary) /**************************************************************** * C = A - 5; * * Bert Kampes, 04-Apr-2000 * ****************************************************************/ template matrix operator - (const matrix& A, Type scalar) { #ifdef __DEBUGMAT2 matDEBUG.print("-"); #endif matrix Result = A; return Result -= scalar; // checks are performed here. } // END - (binary) /**************************************************************** * C = A + B; * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ template matrix operator + (const matrix& A, const matrix& B) { #ifdef __DEBUGMAT2 matDEBUG.print("+"); #endif matrix Result = B; return Result += A; // checks are in += } // END + (binary) /**************************************************************** * C = A + 5; * * Bert Kampes, 04-Apr-2000 * ****************************************************************/ template matrix operator + (const matrix& A, Type scalar) { #ifdef __DEBUGMAT2 matDEBUG.print("+"); #endif matrix Result = A; return Result += scalar; // checks are performed here. } // END + (binary) /**************************************************************** * a = max(A) * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ template Type max(const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("max"); #endif Type m=A(0,0); for (register uint i=0; im) m=A(i,j); return m; } // END max /**************************************************************** * a = max(A,linemax,pixelmax) * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ template Type max(const matrix &A, uint& line, uint& pixel) { #ifdef __DEBUGMAT2 matDEBUG.print("max"); #endif Type m=A(0,0); for (register uint i=0; i=m) { m = A(i,j); line = i; pixel = j; } return m; } // END max /**************************************************************** * a = min(A) * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ template Type min(const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("min"); #endif Type m=A(0,0); for (register uint i=0; i Type min(const matrix &A, uint& line, uint& pixel) { #ifdef __DEBUGMAT2 matDEBUG.print("min"); #endif Type m=A(0,0); for (register int32 i=0; i matrix matTxmat(const matrix &A, const matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("matTxmat: no veclib"); #endif #ifdef __DEBUGMAT1 if (A.lines() != B.lines()) matERROR.print("matTxmat: size A,B: input is A,B; computed is trans(A)*B."); #endif matrix Result(A.pixels(),B.pixels()); register Type sum = Type(0.0); // --- use straightforward notation for slow matrix access -------- #define NO_POINTERS // this is likely a bit slower #ifdef NO_POINTERS // straightforward notation for (register uint i=0; i matrix matxmatT(const matrix &A, const matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("matxmatT: no veclib"); #endif #ifdef __DEBUGMAT1 if (A.pixels() != B.pixels()) matERROR.print("matxmatT: size A,B: input is A,B; computed is A*trans(B)."); #endif register Type sum = Type(0.0); matrix Result(A.lines(),B.lines()); // --- use straightforward notation for slow matrix access -------- #define NO_POINTERS // this is likely a bit slower #ifdef NO_POINTERS // straightforward notation for (register uint i=0; i 4.0): sum += (*pntA) * (*pntB); // pointer over row A *pntA++; *pntB++; } (*pntR++) = sum;// matrix is linear in memory, major-row sum = Type(0.0);// complex requires this } } #endif return Result; } // END matxmatT /**************************************************************** * dumpasc(file,A); * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ template void dumpasc(const char *file, const matrix& A) { #ifdef __DEBUGMAT2 matDEBUG.print("dumpasc to file"); #endif ofstream fo(file,ios::out | ios::trunc); matassert(fo,file,__FILE__,__LINE__); fo.precision(3); fo.width(11); fo.setf(ios::fixed); for (register int32 i=0; i matrix dotmult (const matrix &A, const matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("dotmult"); #endif matrix Result = A; Result *= B; // checks are here return Result; } // END dotmult /**************************************************************** * C = dotdiv(A,B) = A/B * * Bert Kampes, 26-Jan-1999 * ****************************************************************/ template matrix dotdiv (const matrix &A, const matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("dotdiv"); #endif matrix Result = A; Result /= B; // checks are here return Result; } // END dotdiv /**************************************************************** * A = sqr(B) * * Bert Kampes, 16-Feb-1999 * ****************************************************************/ template matrix sqr (const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("sqr"); #endif matrix Result = dotmult(A,A); return Result; } // END sqr /**************************************************************** * B = conj(A) * * Bert Kampes, 02-Mar-1999 * ****************************************************************/ template matrix conj (const matrix &A) { matrix Result = A; Result.conj(); return Result; } // END conj /**************************************************************** * C=diagxmat(vec,B) C=diag(vec) * B; * * Bert Kampes, 22-Feb-1999 * ****************************************************************/ template matrix diagxmat (const matrix &diag, const matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("diagxmat"); #endif #ifdef __DEBUGMAT1 if (min(diag.lines(),diag.pixels()) != 1) matERROR.print("diagxmat: sizes A,B: diag is vector."); if (diag.size() != B.lines()) matERROR.print("diagxmat: sizes A,B: input is vector, matrix."); #endif matrix Result=B; if (diag.lines() != 1) // standing { for (register int32 i=0; i matrix multilook (const matrix &A, uint factorL, uint factorP) { #ifdef __DEBUGMAT2 matDEBUG.print("multilook."); if (A.lines()%factorL) // [MA] we can handle this //matERROR.print("lines A must be multiple of factorL."); matDEBUG.print("For this buffer, lines A is not multiple of factorL."); #endif if (factorL==1 && factorP==1) { //matrix R=A; //return R; return A; // [MA]: fastest solution } #ifdef __DEBUGMAT2 matDEBUG << "multilook input [A] size: " << A.size() << " lines: " << A.lines() << " pixels: " << A.pixels() << " address: " << &A ; // A.[0] can't be printed if 0 matDEBUG.print(); #endif if ( A.lines()/factorL == 0 || A.pixels()/factorP == 0 ) // [MA] fix for extra buffer when lines < mlfactor or ... { DEBUG.print("Multilooking was not necessary for this buffer: buffer.lines() < mlL or buffer.pixels < mlP"); matrix R; //=A; // see initialize() //R.resize(1,1); // fill with 0 #ifdef __DEBUGMAT2 matDEBUG << "multilook return [R] size: " << R.size() << " lines: " << R.lines() << " pixels: " << R.pixels() << " address: " << &R << endl; matDEBUG.print(); #endif return R; // NULL } Type sum; Type factorLP = Type(factorL * factorP); //cerr << "multilook: "<< A.lines()/factorL << " " << A.pixels()/factorP << endl; matrix Result(A.lines()/factorL,A.pixels()/factorP); for (register uint i=0; i matrix correlate (const matrix &A, matrix Mask) { #ifdef __DEBUGMAT2 matDEBUG.print("Correlate."); matDEBUG.print("not yet correct for complex?: returns real4"); if (Mask.lines()<2 || Mask.pixels()<2) matERROR.print("very small mask."); #endif #ifdef __DEBUGMAT1 if (A.lines() 4.0): for (register uint ii=0; ii Result(A.lines(),A.pixels()); // init to 0 // ______First window of A, updated at end of loop______ window winA (0, Mask.lines()-1, 0, Mask.pixels()-1); window windef (0,0,0,0);// defaults to total Am // ______Correlate part of Result______ matrix Am(Mask.lines(),Mask.pixels()); for (register uint i=beginl; i 4.0): covAM += ((*pntM) * (*pntAm)); // wait for move pnt varA += sqr(*pntAm); // pnt ++ *pntM++; *pntAm++; } // Result(i,j) = covAM / sqrt(varM*varA); Result(i,j) = real4(covAM / sqrt(varM*varA)); // [BO] winA.pixlo++; winA.pixhi++; } winA.linelo++; winA.linehi++; winA.pixlo = 0; winA.pixhi = winA.pixlo + Mask.pixels() - 1; } return Result; } // END correlate /**************************************************************** * C = -A; * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ template matrix operator - (const matrix& A) { #ifdef __DEBUGMAT2 matDEBUG.print("operator -"); #endif #ifdef __DEBUGMAT1 if (!A.size()) matERROR.print("matrix:: unary minus with empty matrix"); #endif matrix Result(A.lines(),A.pixels()); Type *pntA = A[0]; Type *pntR = Result[0]; //for (register uint i=0; i 4.0): for (register uint i=0; i real8 mean (const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("mean"); #endif real8 sum=0.; // ______Ensure stride one memory______ Type *pntA = A[0]; //for (register uint i=0; i 4.0): for (register uint i=0; i S = sum(A,dim) * * return sum over dim of A. dim=1 by default. * * always returns a matrix, not very handy... * * A=[1 2 3] then: sum(A,1) = [5 7 9]; sum(A,2)=[6] * * [4 5 6] [15] * * Bert Kampes, 28-Mar-2000 * ****************************************************************/ template matrix sum (const matrix &A, int32 dim) { #ifdef __DEBUGMAT2 matDEBUG.print("sum"); #endif Type sum = Type(0); matrix Res; // may be 1x1 ... if (A.isvector()) { Res.resize(1,1); Type *pntA = A[0]; //for (uint i=0; i 4.0): for (uint i=0; i S = pow(A,scalar) * * return pointwize power. * * always returns a matrix, not very handy... * #%// BK 26-Oct-2000 ****************************************************************/ template void matrix::mypow(Type s) { for (register uint i=0; i void convert_type (const matrix &A, const matrix &B) { TRACE_FUNCTION("convert_type(matrixA-->matrixB) (MA 07-Jun-2009)") // #ifdef __DEBUGMAT2 // matDEBUG.print("convert_type(A-->B)."); // #endif Type *pntA = A[0]; Type2 *pntB = B[0]; if ( A.lines()!=B.lines() || A.pixels()!=B.pixels() ) { DEBUG.print("convert_type aborted since the number of lines or/and pixels of the matrices are not equal."); return; } else if ( A.lines()==0 || A.pixels() == 0 ) { DEBUG.print("convert_type aborted since the number of lines or/and pixels of the input matrix is 0."); return; } //if ( sizeof(Type) == sizeof(Type2) ) if ( getformat(*pntA) == getformat(*pntB) ) { cerr << "==| convert_type input and output types are the same types" << "==| " << getformat(*pntA) << " to " << getformat(*pntB) << endl; DEBUG.print("convert_type was not necessary since both input and output types are the same."); memcpy(pntB,pntA,A.size()*sizeof(Type)); return; } for (register uint32 i=0; i 1000 #pragma once #endif // _MSC_VER > 1000 #include "constants.hh" // typedefs, window #include // ofstream type //#ifdef __USE_FFTW_LIBRARY__ // #include // fftw types //#endif // ______ message objects, global, set in main ______ extern bk_messages matERROR; extern bk_messages matDEBUG; #ifdef __USE_LAPACK_LIBRARY__ #define ilaver ilaver_ extern "C" { int32 ilaver ( int32*, int32*, int32* ) ; } // [MA] get lapack version, used in processor.cc #endif /************************************************************************ friend functions are defined inside the class, since if they are declared here, and defined in matrixbk.cc then gcc gives errors like (for friend functions): In file included from processor.c:23: matrixbk.h:162: warning: friend declaration `void myswap(matrix &, matrix &)' matrixbk.h:162: warning: declares a non-template function matrixbk.h:162: warning: (if this is not what you intended, make sure matrixbk.h:162: warning: the function template has already been declared, matrixbk.h:162: warning: and add <> after the function name here) matrixbk.h:162: warning: -Wno-non-template-friend disables this warning. Adding <> only makes the code less readable, cause other compilers don't want it. BK 17-Aug-2000 *************************************************************************/ /************************************************************************ Compiler g++-4.0 seems to require that for overloaded template operators of the template matrix class the following syntax: template<> template matrix& matrix::operator += (const matrix &A) {code;} this function has to be in the same file as the class, below it. unfortunately, g++2.95.2 does crash if this is done. it does not understand the "template<> template" syntax, but more importantly, it crashes if these functions are put below the class, saying they are defined more than once! There does not seem to be an easy solution to this problem. What seems to work is to keep them in matrixspecs.cc and to use a dummy call to all specialized functions. this guarantees that they are instantiated. in short, this compiles with gcc version 4.0.0 20050301 (prerelease) (Debian 4.0-0pre6ubuntu7) #%// Bert Kampes, 07-Oct-2005 *************************************************************************/ // ====== Define template functions (no member no friend) ====== // ______ (matrix class is declared way below) ______ template class matrix; #ifdef __USE_VECLIB_LIBRARY__ // ______ See: matrixspecs.c ______ // ______ Compiler uses specialization if declared here ______ // ______ and not the template definition in matrixbk.cc ______ matrix operator * (const matrix& A, const matrix& B); matrix operator * (const matrix& A, const matrix& B); matrix operator * (const matrix& A, const matrix& B); matrix operator * (const matrix& A, const matrix& B); matrix matTxmat (const matrix &A, const matrix &B); matrix matTxmat (const matrix &A, const matrix &B); matrix matTxmat (const matrix &A, const matrix &B); matrix matTxmat (const matrix &A, const matrix &B); matrix matxmatT (const matrix &A, const matrix &B); matrix matxmatT (const matrix &A, const matrix &B); matrix matxmatT (const matrix &A, const matrix &B); matrix matxmatT (const matrix &A, const matrix &B); #endif // ______ File: matrixspecs.c ______ //#if defined (__DEBUGMAT2) || defined (__DEBUGMAT1) // extra checking //void matDEBUG(char ch[ONE27]); //#endif //void matERROR(char ch[ONE27]); void matassert( const ofstream &str, const char* ofilename, const char* callingfilename = "?", int32 linenumber = 0); void matassert( const ifstream &str, const char* ifilename, const char* callingfilename = "?", int32 linenumber = 0); // ====== Without VECLIB these are also implemented (slower) ====== // ______ NOW used is www.fftw.org routines ______ // ______ matrixspecs.c: VECLIB [cz]1dfft or internal routine ______ // ______ matrixspecs.c: FFTW is used since 16-sep-2003 ______ void fft (matrix &A, int32 dimension); void ifft (matrix &A, int32 dimension); void fft2d (matrix &A); void ifft2d (matrix &A); //void fft2d (matrix &A, matrix &B); //void ifft2d (matrix &A, matrix &B); matrix oversample (const matrix &A,// new 8/05: by ref. uint frow, uint fcol); matrix oversample (const matrix &A, uint frow, uint fcol); // ______ LAPACK_LIBRARY ______ // ______ Without LAPACK, internal routines can be used (slower, inaccurate?) ______ void choles (matrix &A); void invertchol (matrix &A); void solvechol (const matrix &A, matrix &B); void choles (matrix &A); void invertchol (matrix &A); void solvechol (const matrix &A, matrix &B); matrix intensity (const matrix &A); matrix magnitude (const matrix &A); matrix real (const matrix &A); matrix imag (const matrix &A); real4 norm2 (const matrix &A); real4 norm2 (const matrix &A); matrix norm (const matrix &A); matrix abs (const matrix &A); matrix abs (const matrix &A); // ______ Read file complex into matrix complex ______ void fileci2tomatcr4( matrix &Result, const char *file, uint filelines, window win, window winoffset); // ______ Casts ______ // operator complr4 (matrix) seems better... (but how?) // matrix mat2cr4( // const matrix &A); matrix mat2cr4( const matrix &A); matrix mat2cr4( const matrix &A, const matrix &B); matrix mat2cr4( const matrix &A, const matrix &B); // ______ phase ______ matrix angle( const matrix &A); // phase matrix angle2cmplx( const matrix &A); // phasor, a=1 void dotmultconjphase( matrix &complexinterferogram,// by ref. const matrix &refphase); // phasor, a=1 // --- Using lookup table --- matrix fast_angle( const matrix &A); // phase matrix fast_angle2cmplx( const matrix &A); // phasor, a=1 matrix fast_angle2cmplx( // MA const matrix &A); // phasor, a=1 void fast_dotmultconjphase( matrix &complexinterferogram,// by ref. const matrix &refphase); // phasor, a=1 void fast_dotmultconjphase( matrix &complexinterferogram,// by ref. const matrix &refphase); // phasor, a=1 // ______ complex coherence ______ matrix coherence( const matrix &complex_interferogram, const matrix &norm_image1_and_2, uint estimatorwinsizeL, uint estimatorwinsizeP); // ______ complex coherence ______ matrix coherence2( const matrix &complex_interferogram, const matrix &norm_image1_and_2, uint estimatorwinsizeL, uint estimatorwinsizeP); // should be in matrix class? // ______ sort rows of matrix on some column; uses qsort ______ // void mysort1(matrix &A); // sort matrix based on col. number; // ______ (ascending) sort rows of matrix on first col, then second; uses qsort ______ void mysort2(matrix &A); // mysort(A); void mysort2(matrix &A); // mysort(A); void mysort231(matrix &A); // mysort(A); void mysort2selcol(matrix &A, int32 selcol); void mysort2selcol(matrix &A, int32 selcol); // ______ multiply strike x memory with values in B ______ // ______ to multiply a column of A by vector B use: // ______ complr4 pntA=&A[0][c], strike=numpixels(A), length(B)=numrows. void dotmult (complr4 *startaddress, const matrix &B, int32 strike); //void dotmultrow (matrix &, row, matrix &B); //void dotmultcol (matrix &, col, const matrix &B); //matrix dotmult(const matrix &B, const matrix &A); //matrix dotmult(const matrix &A, const matrix &B); // ______ Some trigonometric functions #%// BK 09-Nov-2000 ______ // add lookup table for fast trig! (someday..) // Bert Kampes, 10-Apr-2005 matrix cos (const matrix &A); matrix fast_cos (const matrix &A);// lookup table matrix cos (const matrix &A); matrix sin (const matrix &A); matrix fast_sin (const matrix &A);// lookup table matrix sin (const matrix &A); // ______ Some casts for complex (Re,Im) ______ HOW? //matrix operator complr4 (const matrix& A); //matrix operator complr4 (const matrix& A, const matrix& B); //matrix operator complr8 (const matrix& A, const matrix& B); // ______ See: matrixbk.cc for definition (bottom) ______ // ______ functions are no friends no members ______ template matrix operator * (const matrix& A, const matrix& B); template matrix operator * (const matrix& A, Type scalar); template matrix operator * (Type scalar, const matrix &A); template matrix operator / (const matrix& A, Type B); template matrix operator / (const matrix& A, const matrix& B); template matrix operator - (const matrix& A, const matrix& B); template matrix operator - (const matrix& A, Type scalar); template matrix operator + (const matrix& A, const matrix& B); template matrix operator + (const matrix& A, Type B); template Type max(const matrix &A); template Type max(const matrix &A, uint& line, uint& pixel); template Type min(const matrix &A); template Type min(const matrix &A, uint& line, uint& pixel); template matrix matTxmat(const matrix &A, const matrix &B); template matrix matxmatT(const matrix &A, const matrix &B); template void dumpasc(const char *file, const matrix& A); template matrix dotmult (const matrix &A, const matrix &B); template matrix dotdiv (const matrix &A, const matrix &B); template matrix sqr (const matrix &A); template matrix conj (const matrix &A); template matrix diagxmat (const matrix &diag, const matrix &B); // ______ Specialisation R4*CR4 ______ // for windows it seems this is not supported. Jia defined a new function // I hope. // Bert Kampes, 24-Aug-2005 #ifndef WIN32 matrix diagxmat (const matrix &diag, const matrix &B); #endif template matrix multilook (const matrix &A, uint factorL, uint factorP); template void converttype (const matrix &A, matrix &B); template matrix correlate (const matrix &A, matrix Mask); template matrix operator - (const matrix& A); template real8 mean (const matrix &A); template matrix sum (const matrix &A, int32 dim); //template // matrix operator ^ (const matrix& A); //template // matrix operator ^ (Type scalar); // ====== ====== ====== ====== ====== ====== // ====== Start of class declaration: ====== // ====== ====== ====== ====== ====== ====== template // class template class matrix { private: // ______ Private data ______ Type **data; // two dimensional array uint nrows; // number of rows (lines) uint ncols; // number of rows (pixels) uint nsize; // lines*pixels // ______ Private functions ______ void allocate (uint l, uint p); void initialize (uint l, uint p); #ifdef __DEBUGMAT1 void checkindex (uint l, uint p) const; #endif public: // ______ Constructors ______ matrix (); matrix (uint l, uint p); matrix (const matrix& A); matrix (window w, const matrix& A); // ______ Destructor ______ ~matrix (); // ______ Data functions ______ void setdata (Type w); void setdata (uint l, uint p, const matrix& A); void setdata (window winin, const matrix &A, window winA); void setdata (const matrix &A, window winA); matrix getdata (window w) const; matrix getrow (uint l) const; matrix getcolumn (uint p) const; // later... index matrix, mask, ... functies findlt findgt, etc. // later,,, void operator () (indexmatrix, mask, or whatever) // BK 23-Oct-2000 //matrix find (Type w) const; void showdata () const; inline bool isvector () const; inline uint lines () const; inline uint pixels () const; inline uint size () const; void resize (uint l, uint p); void clean (); void setrow (uint l, const matrix &L); void setrow (uint l, Type scalar); void setcolumn (uint p, const matrix &C); void setcolumn (uint p, Type scalar); void fliplr (); void flipud (); inline Type* operator [] (uint l) const; inline Type& operator () (uint l, uint p) const; matrix operator () (const window &win) const; matrix operator () (const uint &l0, const uint &lN, const uint &p0, const uint &pN) const; matrix& operator = (const matrix& A); matrix& operator = (const Type scalar); matrix& operator -= (Type scalar); matrix& operator -= (const matrix& A); matrix& operator += (Type scalar); matrix& operator += (const matrix& A); matrix& operator *= (Type scalar); matrix& operator *= (const matrix &A); matrix& operator /= (Type scalar); matrix& operator /= (const matrix &A); bool operator == (Type scalar) const; bool operator == (const matrix &A) const; bool operator != (Type scalar) const; bool operator != (const matrix &A) const; void conj (); void mypow (Type s); // better use operator ^ // for MS-Windows it seems this is not supported. Jia defined a new function // timesCxR instead of "*=" with complex and real input // Bert Kampes, 24-Aug-2005 #ifdef WIN32 // maybe this function needs to be moved out of class for compiler matrix timesCxR (matrix &B, matrix &A); #else // ______ Functions to, e.g., multiply a CR4 by a R4 matrix ______ // ______ Declare for all, but only define for a few in matrixspecs.cc ______ // ______ for g++-4.0 this required some additions in matrixspecs.cc ______ template matrix& operator *= (const matrix &A); template matrix& operator /= (const matrix &A); template matrix& operator += (const matrix &A); template matrix& operator -= (const matrix &A); #endif // ================ // Template friend functions have to be defined within class // (where they are declared) to satisfy with g++ preference (why??) // ================ /**************************************************************** * file << A; * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ friend ostream& operator << (ostream& file, const matrix& A) { // uses copy constructor #ifdef __DEBUGMAT2 matDEBUG.print("operator <<"); matDEBUG << "outfile << [A] size: " << A.size() << " lines: " << A.lines() << " pixels: " << A.pixels() << " address: " << &A; matDEBUG.print(); #endif if ( A.nsize == 0) // [MA] fix for empty matrices due to multilooking ... etc. { cout << "op << : Buffer was empty, nothing done.\n" ; // TEMP DEBUG.print("input matrix buffer was empty, nothing is dumped to file."); return file; // do nothing } const uint sizeofType = sizeof(Type); for (register uint i=0;i> A; * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ //friend istream& operator >> (istream& file, const matrix& A) // BK 25-Sep-2000 friend istream& operator >> (istream& file, matrix& A) { #ifdef __DEBUGMAT2 matDEBUG.print("operator >>"); #endif const uint sizeofType = sizeof(Type); for (register uint i=0;i> /**************************************************************** * myswap(A,B) * * interchange matrices of same size * * somehow g++ does not like name swap, so myswap * * Bert Kampes, 14-Apr-1999 * ****************************************************************/ friend void myswap (matrix &A, matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("myswap."); #endif #ifdef __DEBUGMAT1 if (A.nrows != B.nrows || A.ncols != B.ncols ) matERROR.print("swap: matrices must be same size (for now)."); #endif Type **pntA = A.data; Type **pntB = B.data; A.data = pntB; B.data = pntA; } // END myswap /**************************************************************** * A = sqrt(B) * * Bert Kampes, 16-Feb-1999 * ****************************************************************/ friend matrix sqrt (const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("sqrt"); #endif matrix Result(A.lines(),A.pixels()); // ______Ensure stride one memory______ Type *pntA = A.data[0]; Type *pntR = Result.data[0]; //for (register uint i=0; i 4.0): for (register uint i=0; i transpose (const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("transpose (Bert Kampes, 16-Oct-2005)"); #endif matrix Result(A.pixels(),A.lines()); // not very fast implementation; better use pointer for (register uint i=0; i &Result, const char *file, uint filelines, window win, window winoffset) { #ifdef __DEBUGMAT2 matDEBUG.print("readfile (window)."); #endif // ______First account for possible offsets of file______ // BK 18/1/00: winoffset starts at line 1? win.linelo = win.linelo - winoffset.linelo + 1; win.linehi = win.linehi - winoffset.linelo + 1; win.pixlo = win.pixlo - winoffset.pixlo + 1; win.pixhi = win.pixhi - winoffset.pixlo + 1; //win.pixhi -= (winoffset.pixlo - 1); // ______ Check input ______ // ifstream ifile(file, ios::in | ios::ate | ios::binary); // g++ seems to have a prob. with this... BK 130700 // ifstream ifile(file, ios::in | ios::app | ios::binary); //ifstream ifile(file, ios::in | ios::binary | ios::nocreate); // new compiler v3.2 handles nocreate automatically fine #ifdef __NO_IOS_BINARY__ ifstream ifile(file, ios::in); #else ifstream ifile(file, ios::in | ios::binary); #endif matassert(ifile,file,__FILE__,__LINE__); ifile.seekg(0,ios::end); // pointer to end... //const uint sizefile = ifile.tellg(); // opened ate const streamoff &sizefile = ifile.tellg(); // opened ate, [MA] 64-bit pointer const uint pixelsxbytes = sizefile/filelines; const uint filepixels = pixelsxbytes/sizeof(Type); // Type on disk. const uint sizepixel = pixelsxbytes/filepixels; #ifdef __DEBUGMAT2 if (win.linelo<=0 || win.pixlo<=0) matERROR.print("minimum line(pixel) is 0, (should be 1?)."); if (win.linelo>win.linehi || win.pixlo>win.pixhi) matERROR.print("minimum line(pixel) is larger than max."); if (win.linehi>filelines || win.pixhi>filepixels) matERROR.print("max. line (pixel) is larger then on file."); if (sizeof(Type)!=sizepixel) matERROR.print("Type on disk is different than type of matrix."); if (sizefile==0) matERROR.print("filesize==0..."); #endif const uint lines = win.lines(); const uint pixels = win.pixels(); //INFO << "lines " << lines <<" " << pixels; //INFO.print(); //const uint start = ((win.linelo-1)*filepixels+win.pixlo-1)*sizepixel; [MA] const uint64 start = (uint64)((win.linelo-1)*filepixels+win.pixlo-1)*sizepixel; // both sides should have the same type to // detect/eliminate integer overflow [MA] #ifdef __DEBUGMAT1 if (Result.lines() < lines || Result.pixels() < pixels) matERROR.print("readfile: matrix too small to contain window from file."); if (Result.lines() != lines || Result.pixels() != pixels) matDEBUG.print("debug info: readfile: matrix is not fully filled."); #endif for (register uint lin=0; lin &tobwritten, window win) { #ifdef __DEBUGMAT2 matDEBUG.print("writefile."); #endif #ifdef __DEBUGMAT1 if (win.linelo>win.linehi || win.pixlo>win.pixhi) matERROR.print("minimum line(pixel) is larger than max."); if (win.linehi>=tobwritten.lines() || win.pixhi>=tobwritten.pixels()) matERROR.print("window not ok with matrix."); #endif matassert(file,"writefile: file unknown",__FILE__,__LINE__); const uint pixels = win.pixels(); const uint size = pixels*sizeof(Type); for (uint line=win.linelo; line<=win.linehi; ++line) file.write((char*)&tobwritten.data[line][win.pixlo],size); } // END writefile /**************************************************************** * fftshift(A) * * fftshift of vector A is returned in A by reference * * shift DC term to middle. p=ceil(m/2); A=A[p:m-1 0:p-1]; * * Bert Kampes, 24-Mar-2000 * ****************************************************************/ friend void fftshift (matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("fftshift"); #endif #ifdef __DEBUGMAT1 if (!A.isvector()) matERROR.print("fftshift: only vectors"); #endif matrix Res(A.nrows,A.ncols); const int32 start = int32(ceil(real8(A.nsize)/2)); memcpy(Res.data[0],A.data[0]+start,sizeof(Type)*(A.nsize-start)); memcpy(Res.data[0]+A.nsize-start,A.data[0],sizeof(Type)*start); myswap(A,Res); // prevent copy } // END fftshift /**************************************************************** * ifftshift(A) * * ifftshift of vector A is returned in A by reference * * undo effect of fftshift. ?p=floor(m/2); A=A[p:m-1 0:p-1]; * * Bert Kampes, 24-Mar-2000 * ****************************************************************/ friend void ifftshift (matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("ifftshift"); #endif #ifdef __DEBUGMAT1 if (!A.isvector()) matERROR.print("ifftshift: only vectors"); #endif matrix Res(A.nrows,A.ncols); const int32 start = int32(floor(real8(A.nsize)/2)); memcpy(Res.data[0],A.data[0]+start,sizeof(Type)*(A.nsize-start)); memcpy(Res.data[0]+A.nsize-start,A.data[0],sizeof(Type)*start); myswap(A,Res); } // END ifftshift /**************************************************************** * wshift(A,n) * * circular shift of vector A by n pixels. positive n for * * right to left shift. * * implementation: WSHIFT(A,n) == WSHIFT(A,n-sizeA); * * A is changed itself! * * Bert Kampes, 02-Nov-2000 * ****************************************************************/ friend void wshift (matrix &A, int32 n) { #ifdef __DEBUGMAT2 matDEBUG.print("wshift"); #endif #ifdef __DEBUGMAT1 if (abs(n)>=A.nsize) matERROR.print("wshift: shift larger than matrix not implemented."); if (!A.isvector()) matERROR.print("wshift: only vectors"); #endif // positive only, use rem! n = n%A.nsize; if (n==0) return; if (n<0) n += A.nsize; matrix Res(A.nrows,A.ncols); // ______ n always >0 here ______ memcpy(Res.data[0],A.data[0]+n,sizeof(Type)*(A.nsize-n)); memcpy(Res.data[0]+A.nsize-n,A.data[0],sizeof(Type)*n); myswap(A,Res); // prevent copy } // END wshift }; // END matrix class // ______ Compilation with g++ seems impossible any other way? ______ #include "matrixbk.cc" #endif // MATRIXBK_H guard Doris-5.0.3Beta/doris_core/matrixspecs.cc000077500000000000000000003410131312547014700204050ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/matrixspecs.cc,v $ * $Revision: 3.23 $ * $Date: 2005/10/07 15:17:21 $ * $Author: kampes $ * * definition of routines for matrices (helpers) ****************************************************************/ #include "matrixbk.hh" #include "utilities.hh" // fast_sin() #include // #include // max #ifdef __DEBUGMAT1 #include // type ofstream #endif //#if defined (__DEBUGMAT2) || defined (__DEBUGMAT1) #include // exit //#endif // ______ message objects, global, set in main ______ extern bk_messages matERROR; extern bk_messages matDEBUG; // ______ Prototype 1d fft in this file ______ // ______ Only change this routine for other library for fft _____ // ______ At the moment one can select VECLIB/FFTW/INTERNAL (slow?) // ______ VECLIB/FFTW call optimized routines for 2dfft's void four1( complr4 data[], int32 fftlength, int32 isign); // ______ Prototype veclib functions ______ // ====== File matrixspecialization.c ====== #ifdef __USE_VECLIB_LIBRARY__ extern "C" { int32 sgemm (char* , char*, int32*, int32*, int32*, real4*, real4*, int32*, real4*, int32*, real4*, real4*, int32*, int32, int32); } extern "C" { int32 dgemm (char* , char*, int32*, int32*, int32*, real8*, real8*, int32*, real8*, int32*, real8*, real8*, int32*, int32, int32); } extern "C" { int32 cgemm (char* , char*, int32*, int32*, int32*, complr4*, complr4*, int32*, complr4*, int32*, complr4*, complr4*, int32*, int32, int32); } extern "C" { int32 zgemm (char* , char*, int32*, int32*, int32*, complr8*, complr8*, int32*, complr8*, int32*, complr8*, complr8*, int32*, int32, int32); } #endif #ifdef __USE_VECLIB_LIBRARY__ extern "C" { int32 c1dfft (complr4*, int32*, real4*, int32*, int32*); } extern "C" { int32 c2dfft (complr4*, int32*, int32*, int32*, int32*, int32*); } //extern "C" { int32 s2dfft (real4*, real4*, int32*, int32*, int32*, int32*, int32*); } #endif // ______ USE FFTW IF AVAILABLE ______ // first include complex then this to have complex type known? #ifdef __USE_FFTW_LIBRARY__ #include // fftw types and functions v3.0.1 #endif #ifdef __USE_LAPACK_LIBRARY__ // ___ FORTRAN version on SUN solaris (appends an underscore) ___ #ifdef __DEBUGMAT2 //matDEBUG.print("Using LAPACK library fortran version."); // MA this won't work here [DEL] #warning "Using LAPACK library fortran version." #endif #define spotrf spotrf_ #define spotri spotri_ #define spotrs spotrs_ #define dpotrf dpotrf_ #define dpotri dpotri_ #define dpotrs dpotrs_ #ifdef WIN32 // ___ Windows version, Jia defined this ___ // Bert Kampes, 24-Aug-2005 #define spotrf SPOTRF #define spotri SPOTRI #define spotrs SPOTRS #define dpotrf DPOTRF #define dpotri DPOTRI #define dpotrs DPOTRS #endif // ___ C version on HP uses names "as is" ___ extern "C" { int32 spotrf (const char*, int32*, real4*, int32*, int32*, int32); } // [MA] fixed: deprecated conversion from string constant to char* extern "C" { int32 spotri (const char*, int32*, real4*, int32*, int32*, int32); } extern "C" { int32 spotrs (const char*, int32*, int32*, real4*, int32*, real4*, int32*, int32*, int32); } extern "C" { int32 dpotrf (const char*, int32*, real8*, int32*, int32*, int32); } extern "C" { int32 dpotri (const char*, int32*, real8*, int32*, int32*, int32); } extern "C" { int32 dpotrs (const char*, int32*, int32*, real8*, int32*, real8*, int32*, int32*, int32); } #endif /**************************************************************** * myispower2 * * Bert Kampes, 22-Mar-2000 * ****************************************************************/ inline bool myispower2(uint w) {if (w==2 || w==4 || w==8 || w==16 || w==32 || w==64 || w==128 || w==256 || w==512 || w==1024 || w==2048 || w==4096 || w==8192 || w==16384 || w==32768 ) return true; return false;} /**************************************************************** * matassert * * check if file is opened ok * * Bert Kampes, 16-Jun-1999 * ****************************************************************/ void matassert( const ifstream &str, const char* ifilename, const char* callingfile, int32 linenumber) { if (!str) { matERROR << "Cannot open file: \"" << ifilename << "\" (input). Source: \"" << callingfile << "\", line: " << linenumber; matERROR.print(); } #ifdef __DEBUGMAT2 matDEBUG << "OK input stream associated with file: \"" << ifilename << "\""; matDEBUG.print(); #endif } // END matassert /**************************************************************** * matassert * * check if file is opened ok * * Bert Kampes, 16-Jun-1999 * ****************************************************************/ void matassert( const ofstream &str, const char* ofilename, const char* callingfile, int32 linenumber) { if (!str) { matERROR << "Cannot open file: \"" << ofilename << "\" (output). Source: \"" << callingfile << "\", line: " << linenumber << "; OVERWRIT OFF/non existing directory?"; matERROR.print(); } #ifdef __DEBUGMAT2 matDEBUG << "OK output stream associated with file: \"" << ofilename << "\""; matDEBUG.print(); #endif } // END matassert /**************************************************************** * fileci2tomatcr4 * * reads file format complex short (or 2*short) * * fills matrix complex real4 * * window specified in system of file. win(10:20) means * * start at 10th line after 1st Byte on file. * * currentwindow should be passed to account for any offset * * between what is linenumber of first line in file and byte = 1* * Bert Kampes, 14-Jan-1999 * ****************************************************************/ void fileci2tomatcr4( matrix &Result, const char *file, uint filelines, window win, window winoffset) { #ifdef __DEBUGMAT2 matDEBUG.print("ROUTINE: fileci2tomatcr4."); #endif // ______First account for possible offsets of file______ win.linelo = win.linelo - winoffset.linelo + 1; win.linehi = win.linehi - winoffset.linelo + 1; win.pixlo = win.pixlo - winoffset.pixlo + 1; win.pixhi = win.pixhi - winoffset.pixlo + 1; // ifstream ifile(file, ios::in | ios::ate | ios::binary); // g++ seems to haeve a prob. with this... BK 130700 // ifstream ifile(file, ios::in | ios::app | ios::binary); //ifstream ifile(file, ios::in | ios::binary | ios::nocreate); #ifdef __NO_IOS_BINARY__ ifstream ifile(file, ios::in); #else ifstream ifile(file, ios::in | ios::binary); #endif // ifstream ifile; // openfstream(ifile,file); ifile.seekg(0,ios::end); // pointer to end... matassert(ifile,file,__FILE__,__LINE__); // const uint sizefile = ifile.tellg(); // opened ate const streamoff &sizefile = ifile.tellg(); // opened ate, [MA] if (sizefile==0) matERROR.print("filesize==0..."); // ______Check input______ const uint pixelsxbytes = sizefile/filelines; const uint SIZE = sizeof(compli16); // size per element on disk (=4) const uint filepixels = pixelsxbytes/SIZE; const uint sizepixel = pixelsxbytes/filepixels; const uint lines = win.lines(); const uint pixels = win.pixels(); //const uint lines = win.linehi - win.linelo + 1; //const uint pixels = win.pixhi - win.pixlo + 1; //const uint start = ((win.linelo-1)*filepixels+win.pixlo-1)*sizepixel; const uint64 start = (uint64)((win.linelo-1)*filepixels+win.pixlo-1)*sizepixel; //[MA], see matrixbk.hh for details on this line #ifdef __DEBUGMAT2 if (win.linelo<=0) matERROR.print("minimum line <= 0, (should be 1?)."); if (win.pixlo<=0) matERROR.print("minimum pixel <= 0, (should be 1?)."); if (win.linelo>win.linehi) matERROR.print("minimum line > max line."); if (win.pixlo>win.pixhi) matERROR.print("minimum pixel > max pixel."); if (win.linehi>filelines) matERROR.print("max. line is larger than on file."); if (win.pixhi>filepixels) matERROR.print("max. pixel is larger than on file."); if (SIZE != sizepixel) matERROR.print("Formatflag not consistent with file."); #endif #ifdef __DEBUGMAT2 if (Result.lines() < lines || Result.pixels() < pixels) matERROR.print("code ?::fileci2tomatcr4: Result matrix not ok."); if (Result.lines() != lines || Result.pixels() != pixels) matDEBUG.print("debug info: fileci2tomatcr4: matrix not fully filled."); #endif int16 el[2]; // pseudo complex type // ______Convert io_____ for (int32 lin=0; lin magnitude( const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("magnitude."); #endif // _____Ensure stride one in memory______ matrix Result(A.lines(),A.pixels()); complr4 *pntA = A[0]; real4 *pntR = Result[0]; //for (register int32 i=0; i 4.0): for (register int32 i=0; i intensity( const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("intensity."); #endif // _____Ensure stride one in memory______ matrix Result(A.lines(),A.pixels()); complr4 *pntA = A[0]; real4 *pntR = Result[0]; //for (register int32 i=0; i 4.0): for (register int32 i=0; i &A) { #ifdef __DEBUGMAT2 matDEBUG.print("choles: LAPACK"); #endif #ifdef __DEBUGMAT1 if (A.lines() != A.pixels()) matERROR.print("only symmetrical matrixes for cholesky."); #endif int32 lda = A.pixels(); // leading dimension int32 n = lda; // order of A int32 ierr; // spotrf("U",&n,A[0],&lda,&ierr,1); // Upper remains unchanged #ifdef __DEBUGMAT1 if (ierr == 0) matDEBUG.print("choles: ok. lower contains factorisation."); else if (ierr < 0) matERROR.print("choles: the kth element is not ok."); else matERROR.print("choles: not positive definite."); #endif } // END choles // ______ Else use simple intern algorithm ______ // #elif defined (INTERNAL) #else /**************************************************************** * choles(A); cholesky factorisation internal implementation * * lower triangle of A is changed on output * * upper reamins un referenced * * this one is a lot slower then veclib and there may be more * * efficient implementations. * * Bert Kampes, 11-Oct-1999 * ****************************************************************/ void choles(matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("choles: internal"); #endif const int32 N = A.lines(); register real4 sum; for (register int32 i=0; i=0; --k) { sum -= A[i][k] * A[j][k]; } if (i == j) { if (sum <= 0.) {matERROR.print("choles: internal: A not pos. def.");} A[i][i] = sqrt(sum); } else { A[j][i] = sum/A[i][i]; } } } } // END choles internal, self bk #endif #ifdef __USE_LAPACK_LIBRARY__ /**************************************************************** * choles(A); cholesky factorisation lapack * * lower triangle of A is changed on output * * upper reamins un referenced * * Bert Kampes, 22-Feb-1999 * ****************************************************************/ void choles( matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("choles: LAPACK"); #endif #ifdef __DEBUGMAT1 if (A.lines() != A.pixels()) matERROR.print("only symmetrical matrixes for cholesky."); #endif int32 lda= A.pixels(); // leading dimension int32 n = lda; // order of A int32 ierr; // dpotrf("U",&n,A[0],&lda,&ierr,1); // Upper remains unchanged #ifdef __DEBUGMAT1 if (ierr == 0) matDEBUG.print("choles: ok. lower contains factorisation."); else if (ierr < 0) matERROR.print("choles: the kth element is not ok."); else matERROR.print("choles: not positive definite."); #endif } // END choles // ______ Else use simple intern algorithm ______ // #elif defined (INTERNAL) #else /**************************************************************** * choles(A); cholesky factorisation internal implementation * * lower triangle of A is changed on output * * upper reamins un referenced * * this one is a lot slower then veclib and there may be more * * efficient implementations. * * Bert Kampes, 11-Oct-1999 * ****************************************************************/ void choles(matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("choles: internal"); #endif const int32 N = A.lines(); register real8 sum; for (register int32 i=0; i=0; --k) { sum -= A[i][k] * A[j][k]; } if (i == j) { if (sum <= 0.) {matERROR.print("choles: internal: A not pos. def.");} A[i][i] = sqrt(sum); } else { A[j][i] = sum/A[i][i]; } } } } // END choles internal, self bk #endif #ifdef __USE_LAPACK_LIBRARY__ /**************************************************************** * solvechol(A,rhs); solution of AX=rhs * * cholesky factorisation lapack * * A contains cholesky factorisation of A * * rhs contains estimated X on output * * * * known BUG: niet mogelijk meer dan 1 rechterlid simultaan op * * te lossen, waarschijnlijk door fortran <> c tegenstelling * * Bert Kampes, 22-Feb-1999 * ****************************************************************/ void solvechol( const matrix &A, matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("solvechol::LAPACK"); #endif #ifdef __DEBUGMAT1 if (A.lines() != A.pixels()) matERROR.print("only symmetrical matrices for cholesky."); if (A.lines() != B.lines()) matERROR.print("solvechol: must same size a,b."); if (B.pixels() != 1) matERROR.print("solvechol: NOT possible simultaneous solution in this way."); #endif int32 lda= A.pixels(); // leading dimension int32 ldb= B.lines(); // leading dimension int32 nrhs= B.pixels(); // number of righthandsides int32 n = lda; // order of A int32 ierr; // spotrs("U",&n,&nrhs,A[0],&lda,B[0],&ldb,&ierr,1); // factorisation stored in lower #ifdef __DEBUGMAT1 if (ierr == 0) matDEBUG.print("solvechol: ok, rhs contains solution."); else if (ierr < 0) matERROR.print("solvechol: the kth element is not ok."); else matERROR.print("solvechol: impossible ierr."); #endif } // END solvechol // ______ Else use simple (inaccurate, slow?) internal algorithm ______ // #elif defined (INTERNAL) #else /**************************************************************** * solvechol(A,rhs); solution of AX=rhs * * cholesky factorisation internal implemetnation * * A contains cholesky factorisation of A * * rhs contains estimated X on output * * there may be more efficient implementations. * * Bert Kampes, 11-Oct-1999 * ****************************************************************/ void solvechol( const matrix &A, matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("solvechol::INTERNAL"); #endif #ifdef __DEBUGMAT1 if (A.lines() != A.pixels()) matERROR.print("solvechol: INTERNAL: symmetrical matrices for cholesky."); if (A.lines() != B.lines()) matERROR.print("solvechol: must same size a,b."); if (B.pixels() != 1) matERROR.print("solvechol: NOT possible simultaneous solution in this way."); #endif const int32 N = A.lines(); register real4 sum; register int32 i,j; // ______ Solve Ly=b, use B to store y ______ for (i=0; i=0; --j) { sum -= A[i][j]*B[j][0]; } B[i][0] = sum/A[i][i]; } // ______ Solve Ux=y, use B to store unknowns ______ for (i=N-1; i>=0; --i) { sum = B[i][0]; for (j=i+1; j c tegenstelling * * Bert Kampes, 22-Feb-1999 * ****************************************************************/ void solvechol( const matrix &A, matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("solvechol: LAPACK: there was problem here, ldb,nrhs."); #endif #ifdef __DEBUGMAT1 if (A.lines() != A.pixels()) matERROR.print("only symmetrical matrixes for cholesky."); if (A.lines() != B.lines()) matERROR.print("solvechol: must same size A,B."); if (B.pixels() != 1) matERROR.print("solvechol: NOT possible simultaneous solution in this way."); #endif int32 lda = A.pixels(); // leading dimension int32 ldb = B.lines(); // leading dimension int32 nrhs = B.pixels(); // number of righthandsides int32 n = lda; // order of A int32 ierr; // dpotrs("U",&n,&nrhs,A[0],&lda,B[0],&ldb,&ierr,1); // factorisation stored in lower #ifdef __DEBUGMAT1 if (ierr == 0) matDEBUG.print("solvechol: ok, rhs contains solution."); else if (ierr < 0) matERROR.print("solvechol: the kth element is not ok."); else matERROR.print("solvechol: impossible ierr."); #endif } // END solvechol // ______ Else use simple (inaccurate, slow?) internal algorithm ______ // #elif defined (INTERNAL) #else /**************************************************************** * solvechol(A,rhs); solution of AX=rhs * * cholesky factorisation internal implemetnation * * A contains cholesky factorisation of A * * rhs contains estimated X on output * * there may be more efficient implementations. * * Bert Kampes, 11-Oct-1999 * ****************************************************************/ void solvechol( const matrix &A, matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("solvechol::INTERNAL"); #endif #ifdef __DEBUGMAT1 if (A.lines() != A.pixels()) matERROR.print("solvechol: INTERNAL: symmetrical matrices for cholesky."); if (A.lines() != B.lines()) matERROR.print("solvechol: must same size a,b."); if (B.pixels() != 1) matERROR.print("solvechol: NOT possible simultaneous solution in this way."); #endif const int32 N = A.lines(); register real8 sum; register int32 i,j; // ______ Solve Ly=b, use B to store y ______ for (i=0; i=0; --j) { sum -= A[i][j]*B[j][0]; } B[i][0] = sum/A[i][i]; } // ______ Solve Ux=y, use B to store unknowns ______ for (i=N-1; i>=0; --i) { sum = B[i][0]; for (j=i+1; j &A) { #ifdef __DEBUGMAT2 matDEBUG.print("invertchol: LAPACK"); #endif #ifdef __DEBUGMAT1 if (A.lines() != A.pixels()) matERROR.print("only symmetrical matrixes for cholesky."); #endif int32 lda= A.pixels(); // leading dimension int32 n = lda; // order of A int32 ierr; // spotri("U",&n,A[0],&lda,&ierr,1); // Upper remains unchanged #ifdef __DEBUGMAT1 if (ierr == 0) matDEBUG.print("invertcholes: ok, lower contains inverse."); else if (ierr < 0) matERROR.print("invertcholes: the kth element is not ok."); else matERROR.print("invertcholes: singular."); #endif } // END invertchol // ______ Else use simple (inaccurate? slow?) internal algorithm ______ // #elif defined (INTERNAL) #else /**************************************************************** * invertchol(A); inversion by cholesky factorisation internal * * lower triangle of A is changed on output * * upper remains un referenced * * implementation with double loop probably can be improved easy* * Bert Kampes, 11-Oct-1999 * ****************************************************************/ void invertchol( matrix &A) { const int32 N = A.lines(); register real4 sum; register int32 i,j,k; // ______ Compute inv(L) store in lower of A ______ for (i=0; i &A) { #ifdef __DEBUGMAT2 matDEBUG.print("invertchol: LAPACK"); #endif #ifdef __DEBUGMAT1 if (A.lines() != A.pixels()) matERROR.print("only symmetrical matrixes for cholesky."); #endif int32 lda= A.pixels(); // leading dimension int32 n = lda; // order of A int32 ierr; // dpotri("U",&n,A[0],&lda,&ierr,1); // Upper remains unchanged #ifdef __DEBUGMAT1 if (ierr == 0) matDEBUG.print("invertcholes: ok, lower contains inverse."); else if (ierr < 0) matERROR.print("invertcholes: the kth element is not ok."); else matERROR.print("invertcholes: singular."); #endif } // END invertchol // ______ Else use simple (inaccurate? slow?) internal algorithm ______ // #elif defined (INTERNAL) #else /**************************************************************** * invertchol(A); inversion by cholesky factorisation internal * * lower triangle of A is changed on output * * upper remains un referenced * * implementation with double loop probably can be improved easy* * Bert Kampes, 11-Oct-1999 * ****************************************************************/ void invertchol( matrix &A) { const int32 N = A.lines(); register real8 sum; register int32 i,j,k; // ______ Compute inv(L) store in lower of A ______ for (i=0; i norm( const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("norm"); #endif // ______Ensure stride one memory______ matrix Result(A.lines(),A.pixels()); complr4 *pntA = A[0]; complr4 *pntR = Result[0]; //for (register int32 i=0; i 4.0): for (register int32 i=0; i &A) { #ifdef __DEBUGMAT2 matDEBUG.print("norm2"); #endif // ______Ensure stride one memory______ real4 n=0.; complr4 *pntA = A[0]; //for (register int32 i=0; i 4.0): for (register int32 i=0; i &A) { #ifdef __DEBUGMAT2 matDEBUG.print("norm2"); #endif // ______Ensure stride one memory______ real4 n=0.; real4 *pntA = A[0]; //for (register int32 i=0; i 4.0): for (register int32 i=0; i abs( const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("abs"); // TODO define #endif matrix Result(A.lines(),A.pixels()); // ______Ensure stride one memory______ real4 *pntA = A[0]; real4 *pntR = Result[0]; //for (register int32 i=0; i 4.0): for (register int32 i=0; i abs( const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("abs"); #endif matrix Result(A.lines(),A.pixels()); // ______Ensure stride one memory______ real8 *pntA = A[0]; real8 *pntR = Result[0]; //for (register int32 i=0; i 4.0): for (register int32 i=0; i real( const matrix &A) { matrix Result(A.lines(),A.pixels()); real4 *pntR = Result[0]; complr4 *pntA = A[0]; #ifdef __DEBUGMAT2 matDEBUG.print("real. do not initialize memory (no alloc&and init)."); #endif // ______Ensure stride one memory______ //for (register int32 i=0; i 4.0): for (register int32 i=0; i imag( const matrix &A) { matrix Result(A.lines(),A.pixels()); real4 *pntR = Result[0]; complr4 *pntA = A[0]; #ifdef __DEBUGMAT2 matDEBUG.print("imag. do not initialize memory (no alloc)."); #endif // ______Ensure stride one memory______ //for (register int32 i=0; i 4.0): for (register int32 i=0; i angle( const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("angle(complex) Bert Kampes, 13-Apr-1999."); #endif matrix Result(A.lines(),A.pixels());// faster not to initialize real4 *pntR = Result[0]; complr4 *pntA = A[0]; // ______Ensure stride one memory______ //for (register int32 i=0; i 4.0): for (register int32 i=0; i fast_angle( const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("angle(complex) Bert Kampes, 06-Oct-2005."); #endif matrix Result(A.lines(),A.pixels());// faster not to initialize real4 *pntR = Result[0]; complr4 *pntA = A[0]; // ______Ensure stride one memory______ //for (register int32 i=0; i 4.0): for (register int32 i=0; i angle2cmplx( const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("angle2cmplx() Bert Kampes, 06-Oct-1999"); #endif matrix Result(A.lines(),A.pixels());// faster not initialize matrix complr4 *pntR = Result[0]; real4 *pntA = A[0]; // ______Ensure stride one memory______ //for (register int32 i=0; i 4.0): for (register int32 i=0; i fast_angle2cmplx( const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("fast_angle2cmplx() Bert Kampes, 06-Oct-2005"); #endif matrix Result(A.lines(),A.pixels()); // faster not initialize matrix complr4 *pntR = Result[0]; real4 *pntA = A[0]; // ______Ensure stride one memory______ //for (register int32 i=0; i 4.0): for (register int32 i=0; i fast_angle2cmplx( const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("fast_angle2cmplx() Bert Kampes, 06-Oct-2005"); #endif matrix Result(A.lines(),A.pixels()); // faster not initialize matrix complr8 *pntR = Result[0]; real8 *pntA = A[0]; // ______Ensure stride one memory______ //for (register int32 i=0; i 4.0): for (register int32 i=0; i &cint, const matrix &refpha) { complr4 *pntC = cint[0]; real4 *pntA = refpha[0]; #ifdef __DEBUGMAT2 matDEBUG.print("dotmultconjphase."); #endif #if defined (__DEBUGMAT1) || defined (__DEBUGMAT2) if (cint.lines() != refpha.lines()) matERROR.print("dotmultconjphase: not same number of lines."); if (cint.pixels() != refpha.pixels()) matERROR.print("dotmultconjphase: not same number of pixels."); #endif // ______ Ensure stride one memory ______ // --- looks a bit fishy: is pntA first increased from right to left, // --- or as i thought after sin is taken? // --- better would be to increase pntA in the for, together with i++ // --- if we ever see a problem, it may be due to this? //for (register int32 i=0; i &cint, const matrix &refpha) { complr4 *pntC = cint[0]; real4 *pntA = refpha[0]; #ifdef __DEBUGMAT2 matDEBUG.print("fast_dotmultconjphase."); #endif #if defined (__DEBUGMAT1) || defined (__DEBUGMAT2) if (cint.lines() != refpha.lines()) matERROR.print("dotmultconjphase: not same number of lines."); if (cint.pixels() != refpha.pixels()) matERROR.print("dotmultconjphase: not same number of pixels."); #endif // ______ Ensure stride one memory ______ // --- looks a bit fishy: is pntA first increased from right to left, // --- or as i thought after sin is taken? // --- better would be to increase pntA in the for, together with i++ // --- if we ever see a problem, it may be due to this? //for (register int32 i=0; i pntA++ previously: 1. addr++ then 2. * is evaluated } } // END fast_dotmultconjphase /**************************************************************** // see template in matrix.cc * fast_dotmultconjphase(B,A) * * subtract phase in real4 matrix A of complexr4 matrix B * * by reference. (B .* conj(complr4(cos(phi,sin(phi)))) * * Bert Kampes, 06-Oct-2005 * * Mahmut Arikan 2009 real8 ****************************************************************/ void fast_dotmultconjphase( matrix &cint, const matrix &refpha) { complr4 *pntC = cint[0]; real8 *pntA = refpha[0]; #ifdef __DEBUGMAT2 matDEBUG.print("fast_dotmultconjphase."); #endif #if defined (__DEBUGMAT1) || defined (__DEBUGMAT2) if (cint.lines() != refpha.lines()) matERROR.print("dotmultconjphase: not same number of lines."); if (cint.pixels() != refpha.pixels()) matERROR.print("dotmultconjphase: not same number of pixels."); #endif // ______ Ensure stride one memory ______ // --- looks a bit fishy: is pntA first increased from right to left, // --- or as i thought after sin is taken? // --- better would be to increase pntA in the for, together with i++ // --- if we ever see a problem, it may be due to this? //for (register int32 i=0; i pntA++ previously: 1. addr++ then 2. * is evaluated } } // END fast_dotmultconjphase /**************************************************************** * A=coherence(complexinterferogram,norms,estwindowsizel,p) * * returned is matrix size=(orig-winsizel,orig.pixels) * * This routine is time consuming so no subroutines are called. * * a fft version is tried but does not speed up * * Bert Kampes, 19-Apr-1999 * ****************************************************************/ matrix coherence( const matrix &CINT, const matrix &NORMS, uint winL, uint winP) { // #define PLACE // #define FFTS #define PLACE2 // fastest #ifdef __DEBUGMAT2 matDEBUG.print("coherence"); if (!winL>=winP) matDEBUG.print("coherence: estimator window size L

Result(CINT.lines()-winL+1,CINT.pixels()); int32 leadingzeros = (winP-1)/2; // number of pixels=0 floor... int32 trailingzeros = (winP)/2; // floor... // --- METHOD 1: --------------------------------------------- // #ifdef PLACE complr4 sum = 0.; complr4 power = 0.; for (register int32 i=0; i 0.0) ? sum/sqrt(p) : 0.0; sum = 0.; power = 0.; } } #undef PLACE #endif // --- end METHOD 1: ----------------------------------------- // // --- METHOD 2: --------------------------------------------- // #ifdef PLACE2 register int32 i,j,k,l; register complr4 sum; register complr4 power; for (j=leadingzeros; j 0.0) ? sum/sqrt(p) : 0.0; // ______ Compute sum over rest of blocks ______ for (i=0; i 0.0) ? sum/sqrt(p) : 0.0; } } #undef PLACE2 #endif // --- end METHOD 2: ----------------------------------------- // // --- METHOD 3: --------------------------------------------- // // ====== Compute coherence by fft's ====== #ifdef FFTS matDEBUG.print("THIS SEEMS TO GO WRONG SOMEWHERE, writes all zeros, computes ok?"); bool newline = false; bool nonewline = false; int32 SIZEBLOCKL = 256; // power2, must be larger than winL int32 SIZEBLOCKP = 1024; // power2, must be larger than winP int32 sizeL = SIZEBLOCKL; int32 sizeP = SIZEBLOCKP; if (CINT.lines() < SIZEBLOCKL) { SIZEBLOCKL = nextpow2(CINT.lines()); sizeL = CINT.lines(); nonewline = true; } if (CINT.pixels() < SIZEBLOCKP) { SIZEBLOCKP = nextpow2(CINT.pixels()); sizeP = CINT.pixels(); } const int32 twoL = 2*SIZEBLOCKL; const int32 twoP = 2*SIZEBLOCKP; const complr4 cr4one = complr4(1.,0); matrix CINT2(twoL, twoP); matrix NORMS2(twoL, twoP); matrix BLOCK(twoL, twoP); register int32 i,j; for (i=0; i0.0) ? CINT2(i,j)/sqrt(p) : 0.0; } } #ifdef __DEBUGMAT2 cout << "time for coherence.:\n"; printcpu(); #endif // ______ Update window ______ j2 += (SIZEBLOCKP - winP + 1); win.pixlo = win.pixhi + 1 - leadingzeros - trailingzeros; win.pixhi = win.pixlo + sizeP - 1; if (win.pixhi > CINT.pixels() - 1) { cout << "BERT: win.pixhi > CINT.pixels() - 1\n"; if (win.pixlo+leadingzeros > Result.pixels()-trailingzeros-1) newline = true; if (newline) { cout << "BERT: newline==true\n"; if (nonewline) break; // break loop newline = false; sizeP = SIZEBLOCKP; win.linelo = win.linehi + 1 - (winL-1)/2; win.linehi = win.linelo + sizeL - 1; win.pixlo = 0; win.pixhi = win.pixlo + sizeP - 1; i2 += (SIZEBLOCKL - winL + 1); j2 = leadingzeros; if (win.linehi > CINT.lines() - 1) { nonewline = true; // this is last block win.linehi = CINT.lines() - 1; // no resizing for now sizeL = win.linehi - win.linelo + 1; } } else // last block of line { cout << "BERT: newline==false\n"; newline = true; win.pixhi = CINT.pixels() - 1; // no resizing for now sizeP = win.pixhi - win.pixlo + 1; } win2.linehi = sizeL - 1; win2.pixhi = sizeP - 1; } } #undef FFTS #endif // --- end METHOD 2: ----------------------------------------- // //cout << "Mean coherence: " << mean(Result); return Result; } // END coherence /**************************************************************** * A=coherence(complexinterferogram,norms,estwindowsizel,p) * * returned is matrix size=(orig-winsizel,orig.pixels) * * real4 coherence * * This routine is time consuming so no subroutines are called. * * Bert Kampes, 19-Apr-1999 * ****************************************************************/ matrix coherence2( const matrix &CINT, const matrix &NORMS, uint winL, uint winP) { #ifdef __DEBUGMAT2 matDEBUG.print("coherence2"); if (!winL>=winP) matDEBUG.print("coherence: estimator window size L

Result(CINT.lines()-winL+1,CINT.pixels()); int32 leadingzeros = (winP-1)/2; // number of pixels=0 floor... int32 trailingzeros = (winP)/2; // floor... register int32 i,j,k,l; register complr4 sum; register complr4 power; for (j=leadingzeros; j0.0) ? sqrt(norm(sum)/p) : 0.0; // ______ Compute (relatively) sum over rest of blocks ______ for (i=0; i0.0) ? sqrt(norm(sum)/p) : 0.0; } } return Result; } // END coherence2 /**************************************************************** * mysort2(A) * * sorts matrix first on column1, then on col2 * * used to sort l,p,value matrices. * * calls to std c lib qsort, should better be c++ sort function?* * sorts in ascending order. * * Bert Kampes, 10-Jan-2000 * ****************************************************************/ int32 mycomp2 (const void *x1, const void *x2) { // float *pntf = (float*) x1; // cout << " BB : " << *pntf << " " << *(pntf+1) << endl; // cout << " BB : " << *(float*)x1 << " " << *((float*)x1+1) << endl; int ret = 0; if (*(float*)x1 < *(float*)x2 ) ret = -1; // first field smaller else if (*(float*)x1 > *(float*)x2 ) ret = 1; else if (*((float*)x1+1) < *((float*)x2+1) ) ret = -1; // x1=x2 else if (*((float*)x1+1) > *((float*)x2+1) ) ret = 1; // x1=x2 // else ret=0; // same x1,x2 and x1+1,x2+1 return ret; } int32 mycomp231 (const void *x1, const void *x2) // [MA] compare last 2 cols for getmodeoffset { // float *pntf = (float*) x1; // cout << " BB : " << *pntf << " " << *(pntf+1) << endl; // cout << " BB : " << *(float*)x1 << " " << *((float*)x1+1) << endl; int ret = 0; if (*((float*)x1+1) < *((float*)x2+1) ) ret = -1; // second field smaller else if (*((float*)x1+1) > *((float*)x2+1) ) ret = 1; // else if (*((float*)x1+2) < *((float*)x2+2) ) ret = -1; // x2=x3 // third field smaller else if (*((float*)x1+2) > *((float*)x2+2) ) ret = 1; // x2=x3 else if (*(float*)x1 < *(float*)x2 ) ret = -1; // first field smaller else if (*(float*)x1 > *(float*)x2 ) ret = 1; // else ret=0; // same x1,x2 and x1+1,x2+1 and x1+2,x2+2 // else ret=0; // same x1,x2 and x1+1,x2+1 return ret; } // /**************************************************************** void mysort2 (matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("mysort2 (real4)"); #endif #ifdef __DEBUGMAT1 if (A.pixels() < 2) matERROR.print("mysort sorts only min. 2 cols."); #endif qsort(&A[0][0],A.lines(),A.pixels()*sizeof(real4),mycomp2); } // END mysort2 // /**************************************************************** void mysort2 (matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("mysort2 (int)"); #endif #ifdef __DEBUGMAT1 if (A.pixels() < 2) matERROR.print("mysort sorts only min. 2 cols."); #endif qsort(&A[0][0],A.lines(),A.pixels()*sizeof(int32),mycomp2); } // END mysort2 // /**************************************************************** void mysort231 (matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("mysort23 (real4) [MA]"); #endif #ifdef __DEBUGMAT1 if (A.pixels() < 3) matERROR.print("mysort sorts on 2nd, 3rd and 1st cols respectively."); #endif qsort(&A[0][0],A.lines(),A.pixels()*sizeof(real4),mycomp231); } // END mysort23 /**************************************************************** * mysort2selcol(A,selcol) * * first col=0, second col=1 and so on... * * sorts matrix on the selected col * * used to sort l,p,value matrices. * * Sorts using simple BubleSort, not very efficient: O(N^2) * * sorts in ascending order. * * Bert Kampes, 10-Jan-2000 (original mysort2) * * Batuhan Osmanoglu, Aug 2007 * ****************************************************************/ void mysort2selcol (matrix &A, int32 selcol) { #ifdef __DEBUGMAT2 matDEBUG.print("mysort2selcol (real4)"); #endif #ifdef __DEBUGMAT1 if (A.pixels() < 2) matERROR.print("mysort2selcol sorts only min. 2 cols."); #endif //qsort(&A[0][0],A.lines()+col*sizeof(real4),A.pixels()*sizeof(real4),mycomp2); for (int32 i=0; i A(r+1,selcol)) { //DEBUG << "Swapping Row " << r << " with " << r+1; //DEBUG.print(); for (int32 c=0; c &A, int32 selcol) { #ifdef __DEBUGMAT2 matDEBUG.print("mysort2 (int)"); #endif #ifdef __DEBUGMAT1 if (A.pixels() < 2) matERROR.print("mysort sorts only min. 2 cols."); #endif //qsort(&A[0][0],A.lines(),A.pixels()*sizeof(int32),mycomp2); for (int32 i=0; i A(r+1,selcol)) { //DEBUG << "Swapping Row " << r << " with " << r+1; //DEBUG.print(); for (int32 c=0; c *(float*)x2 ) ret = 1; // else if (*((float*)x1+columnnumber...) < *((float*)x2+columnnumber...) ) ret = -1; // x1=x2 // else if (*((float*)x1+columnnumber...) > *((float*)x2+columnnumber...) ) ret = 1; // x1=x2 // // else ret=0; // same x1,x2 and x1+1,x2+1 // return ret; // } // void mysort1 (matrix &A, column) // { // #ifdef __DEBUGMAT2 // matDEBUG.print("mysort2."); // #endif // #ifdef __DEBUGMAT1 // if (A.pixels() < 2) // matERROR.print("mysort sorts only min. 2 cols."); // #endif // qsort(&A[0][0],A.lines(),A.pixels()*sizeof(real4),mycompare); // } // END mysort1 /**************************************************************** * four1(complr4 *, length, isign) * * four1(&A[0][0], 128, 1) * * either based on numerical recipes or veclib * * helper function for other fft routines, if no veclib * * cooley-turkey, power 2, replaces input, * * isign=1: fft , isign=-1: ifft * * handling vectors should be simpler (lying, standing) * * note that this is not a good implementation, only to get * * doris software working without veclib. * * * * define SAMEASVECIB if you want the order of the coefficients * * of the fft the same as veclib. it seems this is not required * * for a good version of Doris, but in case of problems this * * may be the solution. * * * * VECLIB defines the FT same as matlab: * * N-1 * * X(k) = sum x(n)*exp(-j*2*pi*k*n/N), 0 <= k <= N-1. * * n=0 * * * * FFTW defines the same as Matlab, but inv. not normalized. * * I don't know if the matrix must be allocated somehow, so for * * now we try only 1d ffts to build 2d too. * #%// BK 17-Sep-2003 * * * * Bert Kampes, 12-Oct-1999 * ****************************************************************/ #ifndef __USE_VECLIB_LIBRARY__ #ifndef __USE_FFTW_LIBRARY__ #define SWAP(a,b) bert=(a);(a)=(b);(b)=bert #endif #endif // --- common part to four1 for veclib,fftw, and internal --- void four1( complr4 data[], int32 fftlength, int32 isign) { // ______ Repair original routine ______ //#ifdef __DEBUGMAT2 // called very often... //matDEBUG.print("four1: fft internal"); //#endif #ifdef __DEBUGMAT1 if (!myispower2(fftlength)) matERROR.print("four1: length fft must be power of 2");// not really... if (abs(isign) != 1) matERROR.print("four1: isign should be (-)1."); #endif // ====== FFTW LIBRARY ROUTINE ====== #ifdef __USE_FFTW_LIBRARY__ // if no plan yet, create it depending on direction. // use guru interface for created plan on different data. // first check if dimension of old plan is still valid, or that the size of data changed, // and we thus have to create a new plan? // FFTW_ESTIMATE does not overwrite data during planning. // the plan can be stored in matrixclass as I do now, or as a static here... // that would mean only one plan, and no changes to matrixbk.h, but... // #define __NO_GURU_YET__ #ifdef __NO_GURU_YET__ fftwf_plan fftwf_tmp_plan = (isign==1) ? fftwf_plan_dft_1d(fftlength, reinterpret_cast(data), reinterpret_cast(data), FFTW_FORWARD, FFTW_ESTIMATE | FFTW_DESTROY_INPUT) : fftwf_plan_dft_1d(fftlength, r reinterpret_cast(data), reinterpret_cast(data), FFTW_BACKWARD, FFTW_ESTIMATE | FFTW_DESTROY_INPUT) : fftwf_execute(fftwf_tmp_plan); if (isign==-1) for (int32 i=0; i(data), reinterpret_cast(data), FFTW_FORWARD, FFTW_ESTIMATE | FFTW_DESTROY_INPUT); #ifdef __DEBUGMAT2 fftwf_print_plan(fftwf_fwd_plan);// nerd-readable plan output matDEBUG.print(" "); #endif } // ___ Execute plan (guru interface) ___ #ifdef __DEBUGMAT2 matDEBUG << "BK: FFTW: executing plan..." << "last_length_fwd: " << last_length_fwd; matDEBUG.print(); #endif fftwf_execute_dft(fftwf_fwd_plan, reinterpret_cast(data), reinterpret_cast(data)); } // ___ Inverse transform ___ else { static int32 last_length_inv = 0; static fftwf_plan fftwf_inv_plan;// for inverse fft if (fftlength != last_length_inv) { #ifdef __DEBUGMAT2 matDEBUG.print("BK: FFTW: creating guru plan..."); matDEBUG << "BK: FFTW: fftlength: " << fftlength << "; last_length_inv: " << last_length_inv; matDEBUG.print(); #endif last_length_inv = fftlength; fftwf_inv_plan = fftwf_plan_dft_1d(fftlength, reinterpret_cast(data), reinterpret_cast(data), FFTW_BACKWARD, FFTW_ESTIMATE | FFTW_DESTROY_INPUT); #ifdef __DEBUGMAT2 fftwf_print_plan(fftwf_inv_plan);// nerd-readable plan output matDEBUG.print(" "); #endif } // ___ Execute plan (guru interface) ___ #ifdef __DEBUGMAT2 matDEBUG << "BK: FFTW: executing plan..." << "last_length_inv: " << last_length_inv; matDEBUG.print(); #endif fftwf_execute_dft(fftwf_inv_plan, reinterpret_cast(data), reinterpret_cast(data)); // ___ Inverse transform, normalization is not performed by fftw ___ for (int32 i=0; i j/2 (floor) to correct for complex and first element // this should be repaired, made better later... within loop counter // define order differently for (i=1; i i) { SWAP(data[j/2],data[i/2]); } m = n >> 1; while (m>=2 && j>m) { j -= m; m >>= 1; } j += m; } mmax=2; while (n > mmax) { istep = mmax << 1; theta = isign*(6.28318530717959/mmax); wp = complr8(-2.0*sqr(sin(0.5*theta)),sin(theta)); w = complr8(1.0,0.0); for (m=1; m work; // vector best lying if (int32(2.5*fftlength) != work.size()) // new size or first time?? { work.resize(1,int32(2.5*fftlength)); // ______ call initial work: iopt:=-3 ______ int32 iopt = -3; // initialize work c1dfft(data,&fftlength,work[0],&iopt,&ierr); #ifdef __DEBUGMAT1 switch (ierr) { case 0: matDEBUG.print("c1dfft ok."); break; case -1: matERROR.print("length < 0"); break; case -2: matERROR.print("l not of required form"); break; case -3: matERROR.print("invalid value of iopt"); break; case -4: matERROR.print("insufficient dynamical memory available in work"); break; default: matERROR.print("four1: unrecognized ierr."); } #endif } // ______ Do actual 1d transform ____ c1dfft(data,&fftlength,work[0],&isign,&ierr); if (ierr != 0) {cerr << "veclib: c1dfft: ierr = " << ierr << endl; exit(-1);} } // END four1 #endif // either internal or veclib complex 1d fft or fftw #endif // either internal or veclib complex 1d fft or fftw /**************************************************************** * fft(A,dim) * * forward 1dfft over dim of A is returned in A by reference * * if dim=1 fft is over all columns of A, if 2 over rows. * * data is stored major row order in memory, so dim=2 is * * probably much faster. * * fftlength should be power of 2 * * Bert Kampes, 22-Mar-2000 * ****************************************************************/ void fft(matrix &A, int32 dimension) { register int32 i; const int32 iopt = 1; // forward FFT switch (dimension) { case 1: { #ifdef __DEBUGMAT2 matDEBUG.print("1d fft over columns"); #endif const int32 fftlength = A.lines(); for (i=0; i VECTOR = A.getcolumn(i);// tmp copy, not very efficient maybe four1(&VECTOR[0][0],fftlength,iopt);// but generic. A.setcolumn(i,VECTOR); } break; } case 2: #ifdef __DEBUGMAT2 matDEBUG.print("1d fft over rows"); #endif { const int32 fftlength = A.pixels(); for (i=0; i &A, int32 dimension) { register int32 i; const int32 iopt = -1; // inverse FFT (scaled) switch (dimension) { case 1: { #ifdef __DEBUGMAT2 matDEBUG.print("1d ifft over columns"); #endif const int32 fftlength = A.lines(); for (i=0; i VECTOR = A.getcolumn(i); four1(&VECTOR[0][0],fftlength,iopt); A.setcolumn(i,VECTOR); } break; } case 2: #ifdef __DEBUGMAT2 matDEBUG.print("1d ifft over rows"); #endif { const int32 fftlength = A.pixels(); for (i=0; i &A) { #ifndef __USE_FFTW_LIBRARY__ // prefer FFTW #ifdef __USE_VECLIB_LIBRARY__ // use VECLIB #ifdef __DEBUGMAT2 matDEBUG.print("fft2d: veclib"); #endif int32 l2 = A.lines(); int32 l1 = A.pixels(); int32 ldz= l1; // leading dimension int32 iopt = 1; // forward transform if >= 0 int32 ierr; // c2dfft(A[0],&l1,&l2,&ldz,&iopt,&ierr); #ifdef __DEBUGMAT1 switch (ierr) { case 0: matDEBUG.print("fft2d: ok"); break; case -1: matERROR.print("fft2d: l1 not of the required form"); break; case -2: matERROR.print("fft2d: l2 not of the required form"); break; case -3: matERROR.print("fft2d: ldz not of the required form"); break; case -4: matERROR.print("fft2d: probable error in ldz or dimension of z"); break; default: matERROR.print("fft2d: unrecognized error."); } #endif } // END fft2d #endif #endif #ifdef __USE_FFTW_LIBRARY__ // prefer FFTW /************************************************************** * fft2d(A) * * 2dfft internal slow implementation, * * four1 should be improved * * optionally now fftw for 2d directly #%// BK 17-Sep-2003 * * Bert Kampes, 12-Oct-1999 * **************************************************************/ // ______ fftw implementation 2d fft ______ #ifdef __DEBUGMAT2 matDEBUG.print("fft2d: fftw"); #endif int32 nx = A.pixels(); int32 ny = A.lines(); fftwf_plan fftwf_tmp_plan;// plan created each time, stupid. test. #ifdef __DEBUGMAT2 matDEBUG.print("BK: FFTW: creating tmp fwd 2d plan."); #endif fftwf_tmp_plan = fftwf_plan_dft_2d( nx, ny, reinterpret_cast(A[0]), reinterpret_cast(A[0]), FFTW_FORWARD, FFTW_ESTIMATE | FFTW_DESTROY_INPUT); #ifdef __DEBUGMAT2 fftwf_print_plan(fftwf_tmp_plan);// nerd-readable plan output matDEBUG.print(" "); #endif // ___ execute plan ___ #ifdef __DEBUGMAT2 matDEBUG.print("BK: FFTW: executing tmp fwd 2d plan."); #endif fftwf_execute(fftwf_tmp_plan); #ifdef __DEBUGMAT2 matDEBUG.print("BK: FFTW: destroying tmp fwd 2d plan."); #endif fftwf_destroy_plan(fftwf_tmp_plan);// also associated data? } // END fft2d #endif // select FFTW // ====== Internal implementation using series of 1d fft-s ====== #ifndef __USE_FFTW_LIBRARY__ #ifndef __USE_VECLIB_LIBRARY__ #ifdef __DEBUGMAT2 matDEBUG.print("fft2d: internal (using multiple 1d ffts)"); #endif fft(A,2); // forward transform over rows fft(A,1); // forward transform over columns } // END fft2d #endif // select internal #endif // select internal // common part to ifft2d for veclib, fftw, internal. /**************************************************************** * ifft2d(A); 2dfft veclib * * Bert Kampes, 01-Feb-1999 * ****************************************************************/ void ifft2d( matrix &A) { #ifndef __USE_FFTW_LIBRARY__ // prefer fftw #ifdef __USE_VECLIB_LIBRARY__ // but use veclib before internal implementation. #ifdef __DEBUGMAT2 matDEBUG.print("ifft2d: veclib"); #endif int32 l2 = A.lines(); int32 l1 = A.pixels(); int32 ldz= l1; // leading dimension int32 iopt = -1; // invers transform if < 0 int32 ierr; // c2dfft(A[0],&l1,&l2,&ldz,&iopt,&ierr); #ifdef __DEBUGMAT1 switch (ierr) { case 0: matDEBUG.print("ifft2d: ok"); break; case -1: matERROR.print("ifft2d: l1 not of the required form"); break; case -2: matERROR.print("ifft2d: l2 not of the required form"); break; case -3: matERROR.print("ifft2d: ldz not of the required form"); break; case -4: matERROR.print("ifft2d: probable error in ldz or dimension of z"); break; default: matERROR.print("ifft2d: unrecognized error."); } #endif } // END ifft2d #endif #endif #ifdef __USE_FFTW_LIBRARY__ // prefer fftw // ====== use internal slow implementation ====== /**************************************************************** * ifft2d(A); 2dfft internal slow implementation, * * should be improved * * Bert Kampes, 12-Oct-1999 * ****************************************************************/ // ______ fftw implementation 2d fft ______ #ifdef __DEBUGMAT2 matDEBUG.print("ifft2d: fftw"); #endif int32 nx = A.pixels(); int32 ny = A.lines(); fftwf_plan fftwf_tmp_plan;// plan created each time, stupid. test. #ifdef __DEBUGMAT2 matDEBUG.print("BK: FFTW: creating tmp inv 2d plan."); #endif fftwf_tmp_plan = fftwf_plan_dft_2d( nx, ny, reinterpret_cast(A[0]), reinterpret_cast(A[0]), FFTW_BACKWARD, FFTW_ESTIMATE | FFTW_DESTROY_INPUT); #ifdef __DEBUGMAT2 fftwf_print_plan(fftwf_tmp_plan);// nerd-readable plan output matDEBUG.print(" "); #endif // ___ execute plan ___ #ifdef __DEBUGMAT2 matDEBUG.print("BK: FFTW: executing tmp inv 2d plan."); #endif fftwf_execute(fftwf_tmp_plan); #ifdef __DEBUGMAT2 matDEBUG.print("BK: FFTW: destroying tmp inv 2d plan."); #endif fftwf_destroy_plan(fftwf_tmp_plan);// also associated data? // ___ normalize inverse transform, not done by fftw ___ #ifdef __DEBUGMAT2 matDEBUG.print("BK: FFTW: normalizing inverse transform."); #endif A /= complr4(nx*ny); //for (int32 i=0; i oversample( const matrix &AA,// not by reference, changed by fft uint factorrow, uint factorcol) { #ifdef __DEBUGMAT2 matDEBUG.print("oversample"); #endif matrix A = AA;// copy, AA is changed by in-place fft; const uint l = A.lines(); const uint p = A.pixels(); const uint halfl = l/2; const uint halfp = p/2; const uint L2 = factorrow*l; // numrows of output matrix const uint P2 = factorcol*p; // columns of output matrix #ifdef __DEBUGMAT1 if (A.isvector()) matERROR.print("OVERSAMPLE: only 2d matrices."); if (!myispower2(l) && factorrow != 1) matERROR.print("OVERSAMPLE: numlines != 2^n."); if (!myispower2(p) && factorcol != 1) matERROR.print("OVERSAMPLE: numcols != 2^n."); #endif #ifdef __GNUC__ const real4 half = 0.5; #else const complr4 half = complr4(0.5); #endif matrix Res(L2,P2); register int32 i,j; if (factorrow==1) { fft(A,2); // 1d fourier transform per row for (i=0; i oversample( const matrix &A, uint factorrow, uint factorcol) { // not efficient, mat2cr4 allocates new, and oversample copies this. matrix TMP = oversample(mat2cr4(A),factorrow,factorcol); return real(TMP); // imag == 0 } /**************************************************************** * dotmult(complr4* pnt, const matrix&B, stride) * * multiply memory pointed to by content of B, with mem. stride * * Bert Kampes, 04-Apr-2000 * ****************************************************************/ void dotmult( complr4 *pntR, const matrix &B, int32 stride) { #ifdef __DEBUGMAT2 matDEBUG.print("dotmult, no range checking"); #endif real4 *pntB = B[0]; for (register int32 i=0; i 4.0): { (*pntR) *= (*pntB); *pntB++; } #else //(*pntR) *= complr4(*pntB++); // changed by FvL (for g++/gcc > 4.0): { (*pntR) *= complr4(*pntB); *pntB++; } #endif pntR += stride; } } // dotmult // ====== First declare (define?) specialized function ====== // ______ Before template function ______ #ifdef __USE_VECLIB_LIBRARY__ /**************************************************************** * C = A * B; real4 * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ matrix operator * (const matrix& A, const matrix& B) { #ifdef __DEBUGMAT2 matDEBUG.print("matrices * (veclib)"); #endif #ifdef __DEBUGMAT1 if (A.pixels() != B.lines()) matERROR.print("matrix::operator *: multiplication not possible"); if (!A.size()) matERROR.print("matrix:: operator * with empty matrices."); #endif matrix Result(A.lines(),B.pixels()); int32 n = B.pixels(); int32 m = A.lines(); int32 k = A.pixels(); real4 r4alpha = 1.; real4 r4beta = 0.; sgemm("N","N",&n,&m,&k,&r4alpha,B[0],&n,A[0],&k,&r4beta,Result[0],&n,1,1); return Result; } // END * #endif #ifdef __USE_VECLIB_LIBRARY__ /**************************************************************** * C = A * B; real8 * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ matrix operator * (const matrix& A, const matrix& B) { #ifdef __DEBUGMAT2 matDEBUG.print("matrices * (veclib)"); #endif #ifdef __DEBUGMAT1 if (A.pixels() != B.lines()) matERROR.print("matrix::operator *: multiplication not possible"); if (!A.size()) matERROR.print("matrix:: operator * with empty matrices."); #endif matrix Result(A.lines(),B.pixels()); int32 n = B.pixels(); int32 m = A.lines(); int32 k = A.pixels(); real8 r8alpha =1.; real8 r8beta = 0.; dgemm("N","N",&n,&m,&k,&r8alpha,B[0],&n,A[0],&k,&r8beta,Result[0],&n,1,1); return Result; } // END * #endif #ifdef __USE_VECLIB_LIBRARY__ /**************************************************************** * C = A * B; complex real4 * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ matrix operator * (const matrix& A, const matrix& B) { #ifdef __DEBUGMAT2 matDEBUG.print("matrices * (veclib)"); #endif #ifdef __DEBUGMAT1 if (A.pixels() != B.lines()) matERROR.print("matrix::operator *: multiplication not possible"); if (!A.size()) matERROR.print("matrix:: operator * with empty matrices."); #endif matrix Result(A.lines(),B.pixels()); int32 n = B.pixels(); int32 m = A.lines(); int32 k = A.pixels(); complr4 c4alpha(1.,0.); complr4 c4beta(0.,0.); cgemm("N","N",&n,&m,&k,&c4alpha,B[0],&n,A[0],&k,&c4beta,Result[0],&n,1,1); return Result; } // END * #endif #ifdef __USE_VECLIB_LIBRARY__ /**************************************************************** * C = A * B; complex real8 * * Bert Kampes, 14-Jan-1999 * ****************************************************************/ matrix operator * (const matrix& A, const matrix& B) { #ifdef __DEBUGMAT2 matDEBUG.print("matrices * (veclib)"); #endif #ifdef __DEBUGMAT1 if (A.pixels() != B.lines()) matERROR.print("matrix::operator *: multiplication not possible"); if (!A.size()) matERROR.print("matrix:: operator * with empty matrices."); #endif matrix Result(A.lines(),B.pixels()); int32 n = B.pixels(); int32 m = A.lines(); int32 k = A.pixels(); complr8 c8alpha = 1.; complr8 c8beta = 0.; zgemm("N","N",&n,&m,&k,&c8alpha,B[0],&n,A[0],&k,&c8beta,Result[0],&n,1,1); return Result; } // END * #endif #ifdef __USE_VECLIB_LIBRARY__ /**************************************************************** * C=matTxmat(A,B) C=trans(A)*B; specialized for veclib * * Bert Kampes, 22-Feb-1999 * ****************************************************************/ matrix matTxmat(const matrix &A, const matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("matTxmat, veclib::sgemm"); #endif #ifdef __DEBUGMAT1 if (A.lines() != B.lines()) matERROR.print("matTxmat: size A,B: input is A,B; computed is trans(A)*B."); #endif matrix Result(A.pixels(),B.pixels()); int32 m = A.pixels(); int32 n = B.pixels(); int32 k = B.lines(); real4 r4alpha =1.; real4 r4beta = 0.; sgemm("N","T",&n,&m,&k,&r4alpha,B[0],&n,A[0],&m,&r4beta,Result[0],&n,1,1); return Result; } // END matTxmat #endif #ifdef __USE_VECLIB_LIBRARY__ /**************************************************************** * C=matTxmat(A,B) C=trans(A)*B; specialized for veclib * * Bert Kampes, 22-Feb-1999 * ****************************************************************/ matrix matTxmat(const matrix &A, const matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("matTxmat, veclib::dgemm"); #endif #ifdef __DEBUGMAT1 if (A.lines() != B.lines()) matERROR.print("matTxmat: size A,B: input is A,B; computed is trans(A)*B."); #endif matrix Result(A.pixels(),B.pixels()); int32 m = A.pixels(); int32 n = B.pixels(); int32 k = B.lines(); real8 r8alpha = 1.; real8 r8beta = 0.; dgemm("N","T",&n,&m,&k,&r8alpha,B[0],&n,A[0],&m,&r8beta,Result[0],&n,1,1); return Result; } // END matTxmat #endif #ifdef __USE_VECLIB_LIBRARY__ /**************************************************************** * C=matTxmat(A,B) C=trans(A)*B; specialized for veclib * * Bert Kampes, 22-Feb-1999 * ****************************************************************/ matrix matTxmat(const matrix &A, const matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("matTxmat, veclib::cgemm"); #endif #ifdef __DEBUGMAT1 if (A.lines() != B.lines()) matERROR.print("matTxmat: size A,B: input is A,B; computed is trans(A)*B."); #endif matrix Result(A.pixels(),B.pixels()); int32 m = A.pixels(); int32 n = B.pixels(); int32 k = B.lines(); complr4 c4alpha(1.,0.); complr4 c4beta(0.,0.); cgemm("N","T",&n,&m,&k,&c4alpha,B[0],&n,A[0],&m,&c4beta,Result[0],&n,1,1); return Result; } // END matTxmat #endif #ifdef __USE_VECLIB_LIBRARY__ /**************************************************************** * C=matTxmat(A,B) C=trans(A)*B; specialized for veclib * * Bert Kampes, 22-Feb-1999 * ****************************************************************/ matrix matTxmat(const matrix &A, const matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("matTxmat, veclib::zgemm"); #endif #ifdef __DEBUGMAT1 if (A.lines() != B.lines()) matERROR.print("matTxmat: size A,B: input is A,B; computed is trans(A)*B."); #endif matrix Result(A.pixels(),B.pixels()); int32 m = A.pixels(); int32 n = B.pixels(); int32 k = B.lines(); complr8 c8alpha = 1.; complr8 c8beta = 0.; zgemm("N","T",&n,&m,&k,&c8alpha,B[0],&n,A[0],&m,&c8beta,Result[0],&n,1,1); return Result; } // END matTxmat #endif #ifdef __USE_VECLIB_LIBRARY__ /**************************************************************** * C=matxmatT(A,B) C=A*trans(B); specialized for veclib * * Bert Kampes, 22-Feb-1999 * ****************************************************************/ matrix matxmatT(const matrix &A, const matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("matxmatT, veclib::sgemm"); #endif #ifdef __DEBUGMAT1 if (A.pixels() != B.pixels()) matERROR.print("matxmatT: size A,B: input is A,B; computed is A*trans(B)."); #endif matrix Result(A.lines(),B.lines()); int32 m = A.lines(); int32 n = B.lines(); int32 k = B.pixels(); real4 r4alpha =1.; real4 r4beta = 0.; sgemm("T","N",&n,&m,&k,&r4alpha,B[0],&k,A[0],&k,&r4beta,Result[0],&n,1,1); return Result; } // END matxmatT #endif #ifdef __USE_VECLIB_LIBRARY__ /**************************************************************** * C=matxmatT(A,B) C=A*trans(B); specialized for veclib * * Bert Kampes, 22-Feb-1999 * ****************************************************************/ matrix matxmatT(const matrix &A, const matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("matxmatT, veclib::dgemm"); #endif #ifdef __DEBUGMAT1 if (A.pixels() != B.pixels()) matERROR.print("matxmatT: size A,B: input is A,B; computed is A*trans(B)."); #endif matrix Result(A.lines(),B.lines()); int32 m = A.lines(); int32 n = B.lines(); int32 k = B.pixels(); real8 r8alpha =1.; real8 r8beta = 0.; dgemm("T","N",&n,&m,&k,&r8alpha,B[0],&k,A[0],&k,&r8beta,Result[0],&n,1,1); return Result; } // END matxmatT #endif #ifdef __USE_VECLIB_LIBRARY__ /**************************************************************** * C=matxmatT(A,B) C=A*trans(B); specialized for veclib * * Bert Kampes, 22-Feb-1999 * ****************************************************************/ matrix matxmatT(const matrix &A, const matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("matxmatT, veclib::cgemm"); #endif #ifdef __DEBUGMAT1 if (A.pixels() != B.pixels()) matERROR.print("matxmatT: size A,B: input is A,B; computed is A*trans(B)."); #endif matrix Result(A.lines(),B.lines()); int32 m = A.lines(); int32 n = B.lines(); int32 k = B.pixels(); complr4 c4alpha(1.,0.); complr4 c4beta(0.,0.); cgemm("T","N",&n,&m,&k,&c4alpha,B[0],&k,A[0],&k,&c4beta,Result[0],&n,1,1); return Result; } // END matxmatT #endif #ifdef __USE_VECLIB_LIBRARY__ /**************************************************************** * C=matxmatT(A,B) C=A*trans(B); specialized for veclib * * Bert Kampes, 22-Feb-1999 * ****************************************************************/ matrix matxmatT(const matrix &A, const matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("matxmatT, veclib::zgemm"); #endif #ifdef __DEBUGMAT1 if (A.pixels() != B.pixels()) matERROR.print("matxmatT: size A,B: input is A,B; computed is A*trans(B)."); #endif matrix Result(A.lines(),B.lines()); int32 m = A.lines(); int32 n = B.lines(); int32 k = B.pixels(); complr8 c8alpha = 1.; complr8 c8beta = 0.; zgemm("T","N",&n,&m,&k,&c8alpha,B[0],&k,A[0],&k,&c8beta,Result[0],&n,1,1); return Result; } // END matxmatT #endif //#ifdef WIN32 // Jia defined a function which I think is identical. // maybe it did not compile under windows. // but, then it should be placed in matrixspecs.cc and // a prototype below the class in matrixbk.hh // Bert Kampes, 24-Aug-2005 // /**************************************************************** * C=diagxmat(vec,B) C=diag(vec) * B; (diag R4, mat CR4) * * Bert Kampes, 22-Feb-1999 * ****************************************************************/ matrix diagxmat (const matrix &diag, const matrix &B) { #ifdef __DEBUGMAT2 matDEBUG.print("diagxmat: R4*CR4"); #endif #ifdef __DEBUGMAT1 if (min(diag.lines(),diag.pixels()) != 1) matERROR.print("diagxmat: sizes A,B: diag is vector."); if (diag.size() != B.lines()) matERROR.print("diagxmat: sizes A,B: input is vector, matrix."); #endif matrix Result=B; if (diag.lines() != 1) // standing { for (register uint i=0; i cos( const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("cos"); #endif matrix Result(A.lines(),A.pixels()); real4 *pntR = Result[0]; real4 *pntA = A[0]; // ______Ensure stride one memory______ //for (register uint i=0; i 4.0): for (register uint i=0; i fast_cos( const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("fast_cos"); #endif matrix Result(A.lines(),A.pixels()); real4 *pntR = Result[0]; real4 *pntA = A[0]; // ______Ensure stride one memory______ //for (register uint i=0; i 4.0): for (register uint i=0; i cos( const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("cos"); #endif matrix Result(A.lines(),A.pixels()); real8 *pntR = Result[0]; real8 *pntA = A[0]; // ______Ensure stride one memory______ //for (register uint i=0; i 4.0): for (register uint i=0; i sin( const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("sin"); #endif matrix Result(A.lines(),A.pixels()); real4 *pntR = Result[0]; real4 *pntA = A[0]; // ______Ensure stride one memory______ //for (register uint i=0; i 4.0): for (register uint i=0; i fast_sin( const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("fast_sin"); #endif matrix Result(A.lines(),A.pixels()); real4 *pntR = Result[0]; real4 *pntA = A[0]; // ______Ensure stride one memory______ //for (register uint i=0; i 4.0): for (register uint i=0; i sin( const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("sin"); #endif matrix Result(A.lines(),A.pixels()); real8 *pntR = Result[0]; real8 *pntA = A[0]; // ______Ensure stride one memory______ //for (register uint i=0; i 4.0): for (register uint i=0; i * * Bert Kampes, 01-Feb-1999 * ****************************************************************/ matrix mat2cr4( const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("mat2cr4. (real4)"); #endif matrix Result(A.lines(),A.pixels()); real4 *pntA = A[0]; complr4 *pntR = Result[0]; //for (register uint i=0; i 4.0): for (register uint i=0; i mat2cr4( const matrix& A, const matrix& B) { #ifdef __DEBUGMAT1 if (A.lines()!=B.lines() || A.lines()!=B.lines()) matERROR.print("operator complr4, input matrices not same size"); #endif #ifdef __DEBUGMAT2 matDEBUG.print("operator complr4(r4,r4)"); #endif matrix Result(A.lines(),A.pixels()); real4 *pntA = A[0]; real4 *pntB = B[0]; complr4 *pntR = Result[0]; //for (register uint i=0; i 4.0): for (register uint i=0; i mat2cr4( const matrix& A, const matrix& B) { #ifdef __DEBUGMAT1 if (A.lines()!=B.lines() || A.lines()!=B.lines()) matERROR.print("operator complr4, input matrices not same size"); #endif #ifdef __DEBUGMAT2 matDEBUG.print("operator complr4(r8,r8)"); #endif matrix Result(A.lines(),A.pixels()); real8 *pntA = A[0]; real8 *pntB = B[0]; complr4 *pntR = Result[0]; //for (register uint i=0; i 4.0): for (register uint i=0; i timesCxR (matrix &B, matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("*="); #endif #ifdef __DEBUGMAT1 if (B.nrows != A.lines() || B.ncols != A.pixels()) matERROR.print("matrix:: *= matrices must be same size."); #endif complr4 *pntmat = B[0]; real4 *pntA = A[0]; //for (register uint i=0; i 4.0): for (register uint i=0; i is required to specialize this. I guess this means it should be added everywhere, also for Veclib. // Bert Kampes, 06-Oct-2005 ****************************************************************/ /**************************************************************** * C *= A; pointwise multiplication, CR4 R4 * #%// BK 26-Oct-2000 ****************************************************************/ #if __GNUC__ < 4 //template<> // essential for specialization //template // seems not allowed for g++2.95 //#if __GNUC_MINOR__ < 95 //#endif // #else #if __GNUC_MINOR__ > 0 template<> // essential for specialization template<> // seems required for specialization g++-4.0 upwards #else template<> // essential for specialization template // seems required for specialization g++-4.0 upwards #endif #endif // **************************************************************** matrix& matrix::operator *= (const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("*="); #endif #ifdef __DEBUGMAT1 if (nrows != A.lines() || ncols != A.pixels()) matERROR.print("matrix:: *= matrices must be same size."); #endif complr4 *pntmat = data[0]; real4 *pntA = A[0]; //for (register uint i=0; i 4.0): for (register uint i=0; i // essential for specialization //template // seems not allowed for g++2.95 //#if __GNUC_MINOR__ < 95 //#endif // #else /* g++-4.0 upwards */ #if __GNUC_MINOR__ > 0 template<> // essential for specialization template<> // seems required for specialization g++-4.0 upwards #else template<> // essential for specialization template // seems required for specialization g++-4.0 upwards #endif #endif matrix& matrix::operator /= (const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("/="); #endif #ifdef __DEBUGMAT1 if (nrows != A.lines() || ncols != A.pixels()) matERROR.print("matrix:: *= matrices must be same size."); #endif complr4 *pntmat = data[0]; real4 *pntA = A[0]; //for (register uint i=0; i 4.0): for (register uint i=0; i // essential for specialization //template // seems not allowed for g++2.95 //#if __GNUC_MINOR__ < 95 //#endif // #else /* g++-4.0 upwards */ #if __GNUC_MINOR__ > 0 template<> // essential for specialization template<> // seems required for specialization g++-4.0 upwards #else template<> // essential for specialization template // seems required for specialization g++-4.0 upwards #endif #endif matrix& matrix::operator += (const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("+="); #endif #ifdef __DEBUGMAT1 if (nrows != A.lines() || ncols != A.pixels()) matERROR.print("matrix:: += matrices must be same size."); #endif complr4 *pntmat = data[0]; real4 *pntA = A[0]; //for (register uint i=0; i 4.0): for (register uint i=0; i // essential for specialization //template // seems not allowed for g++2.95 //#if __GNUC_MINOR__ < 95 //#endif // #else /* g++-4.0 upwards */ #if __GNUC_MINOR__ > 0 template<> // essential for specialization template<> // seems required for specialization g++-4.0 upwards #else template<> // essential for specialization template // seems required for specialization g++-4.0 upwards #endif #endif matrix& matrix::operator -= (const matrix &A) { #ifdef __DEBUGMAT2 matDEBUG.print("-="); #endif #ifdef __DEBUGMAT1 if (nrows != A.lines() || ncols != A.pixels()) matERROR.print("matrix:: -= matrices must be same size."); #endif complr4 *pntmat = data[0]; real4 *pntA = A[0]; //for (register uint i=0; i 4.0): for (register uint i=0; i A(1,1); matrix B(1,1); A*=B; A+=B; A-=B; A/=B;// impossible divide zero, but not executed } // dummy_calls_to_specs #endif Doris-5.0.3Beta/doris_core/newsincev2.4000077500000000000000000000455141312547014700177130ustar00rootroot00000000000000new since release 2.4 --------------------- added some include files for compilation on Linux x86 card: FE_IN_POS module: SRP_METHOD exact card: M_ORB_DUMP removed: calls to script untar and getodr. assumed is that the ODR files are untarred in ORBDIR. #%// BK 04-Jul-2000 step1routines: added function ntohl to ensure proper byte order interpretation, step readfiles. this is important if type is B4 in slc format description orbit bugfix if dt != 1 routine splintvel card M_ORB_INTERVAL added card M_ORB_ESTRATIME added card M_ORB_DUMP added card S_ORB_DUMP added changed way orbit interpolation is called. #%// BK 06-Jul-2000 card DUMPBASELINE added #%// BK 07-Jul-2000 bugfix: linuxx86, version? ifile.open(ios::ate) not ok, fixed to seekg(0,ios::end) in routines filesize, readfile, fileci2tomatcr4 bugfix: linux86, reading slc data file: htons for byteswap added define __X86PROCESSOR__ #%// BK 13-Jul-2000 added verbose output of input file with 'writearg' function #%// BK 14-Jul-2000 orbit class created readleader: some changes for reading ESA.RAW instead of ESA.SLC format. #%// BK 18-Jul-2000 resample: changed resample routine to write 0 lines if DBOW is specified. #%// BK 21-Aug-2000 v3.0 because of new filter steps. FILTAZI FILTRANGE + orbit FILTPHASE debuged RESAMPLE v3.0.2 added more output to resfile step readfiles. added covariance matrices output to log file. changed implementation va_arg function to compile under redhat7.0 g++ distr. (repaired/added to run/plotcpm/etc) 22-mar-2001 Added output modelling bperp to ref. ellipsoid. Added output modelling theta to ref. ellipsoid. Added output modelling range to ref. ellipsoid. Changed use of real4 -> real8 matrices coreg. estimates. Warning summary added 26-mar-2001 bugfix: processing structure after range filtering: Processing order should be either i) filter based on orbits -> resample -> interf; or ii) resample -> filter based on fr.freq. -> interf; The bug was that when filtering based on orbits was requested, the input for the interferogram generation was the filtered image, NOT the resampled one. thanks to Rens Swart. #%// BK 19-Apr-2001 changed install_doris.csh -> configure and included test for endianness. #%// BK 20-Apr-2001 added scalebar -b option in cpxfiddle #%// BK 26-Apr-2001 bugfix line 2416 filtering.c fftlength #%// BK 04-May-2001 changed input format of dem to short/real4/real8. (not tested properly) #%// BK 07-Feb-2002 installation on Cygwin under Windows XP. changed shell for run script, helpdoris changed configure script added PREVIEW card added BEEP card #%// BK 13-Apr-2002 added verbose output for step COMPREFDEM checked code, documentation step COMPREFDEM #%// BK 16-Apr-2002 bug report from Bruno: nextpow2 function was wrong. (not used in Doris) #%// BK 26-Oct-2002 bug report Raffaele: spectrum strange with shift aziumth spectrum resampling. changed it to shift kernel in azimuth. #%// BK 01-Nov-2002 Added snaphu method system call for unwrapping. changed source code filenames to .cc instead of .c for clarity. changed source code system include filenames for new compiler gcc3.2 (?): iostream.h ---> iostream strstream.h ---> strstream fstream.h ---> fstream iomanip.h ---> iomanip time.h ---> ctime string.h ---> cstring stdio.h ---> cstdio stdlib.h ---> cstdlib ctype.h ---> cctype #%// BK 03-Apr-2003 1) For new compiler, it seems ios::nocreate and ios::noreplace are not supported. Therefore, this has been removed from the code. Mainly used to check if files were opened OK, and to prevent files from being overwritten (OVERWRITE OFF) It seems the new version handles nocreate correctly, i.e., it does not create an input file if it does not exist. 2) strandard namespace used 3) assert renamed to bk_assert, since it gave problems as a known function. 4) floor(int/int) is considered illegal, so i removed that, since int division is already a floor. (but less readable in my opinion) #%// BK 08-Apr-2003 added define __NO_IOS_BINARY__ for SGI old compiler not very nice code, probably change this one day to a define IOSBIN "| ios::binary" so it can be easily replaced in file open constructions. #%// BK 11-Apr-2003 Added a new class for messages, since new compiler seems to have some problem with static old global definition. see bk_messages.h Added a new level: "TRACE" #%// BK 13-Apr-2003 SARtools added cpxfiddle option for real files added preview for unwrapped ifg hgt and real4 format added preview for slant2h real4 format added extensive debugging options for matrixclass/general tracing fixed bug in matrixclass allocated bytes tracing with static totalallocated added debug option in configure script #%// BK 16-Jun-2003 Added envisat processing capability. step READFILES with card method=ASAR now performs a system call to program envisat_dump_header2doris.csh that relies on envisat_dump_header.c program i wrote. The only input file for this method is the asar IMS file, use card M_IN_DAT to specify filename. step CROP recognizes it was ASAR automatically. Improved azimuth filter: percentage counter and output format description. small bugfix if RS_DBOW and format CI2, and required to write zero lines at start. Added orbit interpolation/approximation with polynomial (LS) fit. ----release v3.6------------------------------------------------------- bugfix: plotoffsets: line counting in awk somehow disappeared. #%// BK 09-Jul-2003 bugfix: readinput.cc::checkcomprefdem: added check for big endian short format after report of Daniel. #%// BK 14-Aug-2003 fixed cpxfiddle a bit after report flip in X for r4 data added JERS format as input method. i think it is ceos? the method thus simply thus the exact same as for ERS, for read_files and crop steps slcimage.cc recognizes ERS, ASAR, RSAT, JERS as substrings in product type specifier. added check in coherence if master or slave amplitude > 0.0 automated coregistration. remove outlier windows if wtests is rejected, until done or max_iter is reached. #%// BK 28-Aug-2003 run script added -s9 -e9 quicklook processing. unfortunately, step1 will crash due to cdrom name in batch, but user will understand. #%// BK 12-Sep-2003 cpxfiddle: skip header bytes and added more real input formats. doris: added format checks somewhere. doris: GPL release prepared by adding copyright notice to each file. #%// BK 17-Oct-2003 added ./ to path for preview generation to prevent errors if "." is not in path of inexperienced user and preview scritp cannot be executed without it. Note that this si a unix separator. Also, changed in coregistration.cc the automated selection of outlier window to be the sq.sum of the wtests. #%// BK 21-Oct-2003 Added check for RBW, RSR if they are ginven in MHZ in leaderfile for atlantis processed data. #%// BK 28-Oct-2003 Added some checks for configure to use strptime function Added debug info for getorb strptime function. #%// BK 21-Nov-2003 Added example programs for envisat alternating pol. data extraction. Z.Perski tested this. One program with input handling may have been nicer, but I don;t know the format well enough to do this, and lack of time. But they work. #%// BK 24-Nov-2003 added check in ioroutines for strptime and endianness on the fly. they still need to be defined via the configure script. #%// BK 28-Nov-2003 bug report Mark Warren: outer product definition (was not used in doris) new input card CROP_GEO with geograph. lat/lon cropping. #%// BK 15-Dec-2003 bugfix coregistration automated outlier detection. tested doris with JERS, seems to work. see www. only bandwidths could not be found in CEOS product, and orbit is terrible. Added logging of leader file by B.Cassee for calibration purposes. (incidence angle of first pix. in next version this may be written to resultfile and used as parameter) // BK 16-Dec-2003 added knab interpolator kernels for bandlimited signal interpolation see ieee 41 (5) pp1105-1110 Migliaccio RS_METHOD KNAB4P KNAB6P KNAB8P KNAB10P KNAB16P // BK 22-Dec-2003 Raffaele Nutricato offered his oversampling routines. Doris now can perform an extra step oversampling (in range only for now) // BK 20-Jan-2004 Added HEIGHT card for average terrain height used in crop geo. Bugfix envisat tools, several improvements with them for CROP data. Have to add still range_timing_error, azimuth_timing_error one day. INCREASE/DECREASE problem signalled, not fixed. UNWRAP TIEPOINT card for integration constant. #%// Bert Kampes, 13-May-2004 Introduced range timing error and azimuth timing error general cards. M_RG_T_ERROR t [s] M_AZ_T_ERROR t [s] S_RG_T_ERROR t [s] S_AZ_T_ERROR t [s] In future, we may want to set the generalinput.rg_t_error to a value based on e.g., processor version, PAF, etc. We can then do this in step1routines, changing this variable, and not via user input. #%// Bert Kampes, 27-May-2004 Method RADARSAT for readfiles step implemented: Added radarsat support: reading leader/volume file in CEOS, reading info in dat file for timing. Still unclear is how to convert the orbit state vectors from inertial to earth centered earth fixed, and also how to interpolate the orbit with doris, ie., they are given as an arc of 15*8 minutes, which is much too long for interpolation with say a polynomial. This is ignored for now. Also implemented is the cropping routine for the datafile. All this must be tested however, ie. regarding the DECREASE time indicator. It should be the case that when readfiles is run, the product identifier signifies that it is radarsat, and then automatically in the cropping step this is recognized and used. #%// Bert Kampes, 04-Aug-2004 matrixspecs.cc: added DEBUGMAT2 around FFTW execute plan statement to prevent lots of output, e.g., in rangefilt. seems that was forgotten. ioroutines.cc: changed ctime argument to a time_t type, see man ctime. #%// Bert Kampes, 03-Sep-2004 bugfix coherence2 routine, check zero division to avoid NaN in coherence image bugfix goldstein routine: seemed kernel was not placed correctly update adaptive range filter: use last know shift of spectra if a clear peak cannot be detected fleefix adaptive range filter: verbose output reduced if not in debug mode update compcoherence: strange zero starting lines removed. i am sure I placed it there to fix some other situation, but the code as it was did not create the correct size image if the coherence window was larger than the multilook window. added a function openfstream to have a singel function handling opening in/out binary files to avoid duplicate code. #%// Bert Kampes, 13-Sep-2004 updated viewanddel script to use gv first. On cygwin this works fine now. #%// Bert Kampes, 20-Sep-2004 fixed small bug in configure if byte order was incorrectly detected reported by Mladen Zivcic #%// Bert Kampes, 23-Jan-2005 Fixed bug in fDC computation cubic term for shifting kernel when interpolation. new function: real8 fDC=pix2fdc(pixel,image); #%// Bert Kampes, 02-Mar-2005 .Added conversion functions like line2ta to slcimage.h class members because this is more logical. Should still change it to private members with access over public functions. Also, the products class or orbit class should have a function that computes Bperp, etc. because then it would be easy to change things like using a polynomial for modeling, or baseline improvement based on residual fringes. .changed names of include files from .h to .hh (c++ standard) #%// Bert Kampes, 05-Mar-2005 added a try block to catch math errors in processor.cc started class BASELINE in bk_baseline.hh to avoid multiple implementation of same functionality and improve speed in future by modeling the baseline, etc. This could also lead to easier correction of residual reference phase due to bad orbit data. #%// Bert Kampes, 31-Mar-2005 checked Atlantis processed data read correctly added constructor to slcimage class added trilinear interpolation to be used with comprefdem added is_initialized() for orbits changed try.catch memory allocation to be default also for GNU compiler. #%// Bert Kampes, 08-Apr-2005 debugged trilinear new COMPREFDEM, using extradense = 0.25, ca 44 MB for 1000x1000; reasonably fast. #%// Bert Kampes, 08-Apr-2005 added fasttrig.cc fasttrig.hh to be used in matrix class etc. for complex mulitplication. to be tested gain in speed of time, acc. is <0.1degree added key SAR_PROCESSOR ATLANTIS | VMP | TUD written in readvolume(); read by fill_slc_image(); used in crop() #%// Bert Kampes, 13-Apr-2005 added CRD_OUT_DEM_LP card to dump external DEM height in meters in radar coordinates. Request of Zbigniew Perski, goal is to geocode these heights again, so lat/lon of a displacement interferogram is obtained. Option needs to be documented still by someone. #%// Bert Kampes, 16-Apr-2005 Changed exceptions.cc to be more precise about the signal caught Improved filtazi to check if constant Doppler can be assumed for the image. #%// Bert Kampes, 20-Apr-2005 removed warnings from snaphu coherence window size, should be ok. #%// Bert Kampes, 22-Apr-2005 added heightamb utility to bin dir added raised cosine interpolation kernel for interpolation. (new argument "RC_6" and "RC_12" for card RS_KERNEL) see paper cho05; needs to be tested better, but is now default method in run script; added DEBUG output of kernel. Normalized kernel for resampling. added [deg] for check for stepsize of DEM to be more verbose. removed function updateslcimageML and integrated reading oversampling factor for slc in the default function updateslcimage; getoffset: changed to use the average of the most coherent windows in COARSE CORR; #%// Bert Kampes, 28-Jul-2005 added azimuth oversampling method. #%// Bert Kampes, 01-Aug-2005 added kernel az and rg for resampling. since e.g., rc kernel has oversampling ratio, which can be different for az and rg. Moreover, it would be faster to have the lookup table in range, since that does not change. -ovs step: normalized kernel in range (sinc); i think it would be better to use a 6 point rc kernel in range too, but I left the original code. #%// Bert Kampes, 12-Aug-2005 -added method for fine coreg "OVERSAMPLE" that first oversamples the complex data by a factor two before cross-correlating the magnitude patches. -in fine coreg first performed a local peak search, then oversample locally; this allows to handle images with different prf etc. in principle. -speed improvement using new routine crosscorrelate. this routine uses ffts smartly to get correlation for shifted matrices. #%// Bert Kampes, 13-Aug-2005 changed name of file "step1routines" to readdata.cc #%// Bert Kampes, 19-Aug-2005 Added a delete after new matrix in resample routine; this may be incorrect. #%// Bert Kampes, 24-Aug-2005 Added WIN32 define so Doris compiles under windows. I do not support compilation problems. And do not advice Doris to be run under windows (gmt, getorb, snaphu, etc. interfaces). However, people seem to want this, and there are only a few defines. -DWIN32 In processor.cc there also is -DWINDOWS and in the .hh files there is a check for -DMSC_VER > 1000 I dont know why. #%// Bert Kampes, 24-Aug-2005 Added #define spotrf spotrf_ in matrixspecs.hh ie., from now on the fortran version of the lapack lib is used by default (most users seem to use this). #%// Bert Kampes, 24-Aug-2005 normalized BASELINE class polynomial computation after report of some strange error. I cannot explain the report, but it definitely is more stable now. #%// Bert Kampes, 25-Aug-2005 Bugfix interp_trilinear: type-->incorrect formula used (comprefdem outliers)! #%// Bert Kampes, 25-Aug-2005 Added range time error for ERS as -1.9325e-7 sec to two-way time based on radarcoding of precise corner reflector positions using TIEPOINT card. #%// Bert Kampes, 20-Sep-2005 added fast_sin(); fast_cos(); fast_atan(); fast_atan2(); fast_arg() using look-up tables also for matrix class + fast_angle(); fast_angle2cmplx; fast_dotmultconjphase(). fast_min_sin(); these functions are used in products.cc for complex subtraction of ref.phase, etc. and in coregistration::resample() for kernel spectrum centering around fdc. error max. 1/1000 or max 0.003 rad for angles. it seems LUT is factor 5 to 20 faster for fast machines than std::sin() #%// Bert Kampes, 04-Oct-2005 change size of lut of coregistration to power of two 128, could be more memory suitable (from 101). #%// Bert Kampes, 04-Oct-2005 removed refsystems.hh conversion.hh conversion.cc and put some routines in ellips class, others in utilities. #%// Bert Kampes, 05-Oct-2005 improved geocoding, for large heights there likely was an offset in lat/lon geocoded coordinates. #%// Bert Kampes, 06-Oct-2005 added pointer for faster operator *, matTxmat, matxmatT in matrix class added transpose to matrix class added tests for these functions in matrixbk_test.cc still unclear why in class some are friends, like transpose, sqrt, some are not; i think sqrt and transpose shoudl be moved to matrixbk.cc as template function #%// Bert Kampes, 13-Oct-2005 tested new template<> template for g++-4.0 compilers. the code now compiles using this compiler. Use -O max. optimization. #%// Bert Kampes, 13-Oct-2005 ----released v3.17------------------------------------------------------- New features: 1) Handling of file sizes larger than 4GB on both 32-bit and 64-bit platforms. 2) Processing for TerraSAR-X data. See Appendix B.1.4 for installation guidelines. 3) Improvement of the master-slave overlap calculation. The new algorithm should prevent segmentation faults as sometimes experienced in the past. 4) Improvement and speed-up of COMPREFDEM based on a two-step approach. First, the complete DEM is radarcoded and written to a file. Second, the radarcoded DEM is interpolated to the master image geometry using Delaunay triangulation. The overlapping buffers, as in previous versions of Doris, are prevented. 5) Simulation of master amplitude image based on DEM (M_SIMAMP). 6) Estimation of master timing error based on correlation between master amplitude and simulated master amplitude (M_TIMING). 7) Estimation of relative timing error between master and slave image (RELTIMING). 8) DEM assisted coregistration (DEMASSIST). For optimal performance, apply after M_SIMAMP, M_TIMING and RELTIMING. 9) Coherence estimation after DEM subtraction (default). 10) Utility construct_dem.sh to download, merge and fill voids of SRTM data. 11) Utility doris.process-reset.sh to reset and clean up the processing entries in Doris result files allowing to easily re-run a step or multiple steps. 12) Option to output height-to-phase conversion factors (H2PH) based on flat earth (SUBTRREFPHA) or DEM (COMPREFDEM). 13) During COARSECORR and FINE coregistration NaN (not-a-number) correlation values, which are mainly due to no data regions at the border of the scene, are eliminated automatically, but the whole list of windows are kept in the doris.log file. 14) Coherence output is properly scaled between 0 to 1 range with new option -r of cpxfiddle. #%// TUDelft DEOS Radar, 15-April-2009 ----released v4.01------------------------------------------------------- Doris-5.0.3Beta/doris_core/orbitbk.cc000077500000000000000000001451451312547014700175070ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/orbitbk.cc,v $ * * $Revision: 3.20 $ * * $Date: 2005/10/06 11:09:20 $ * * $Author: kampes $ * * * * implementation of orbit class. * * - orbit interpolation (spline and polynomial). * * - baseline estimation. * * - utility dumping etc. * * * * Compilation with: make testorbit * * g++ -D__TESTMAIN__ orbit.cc -o testorbit * * creates a standalone executable for testing of the functions * * of the orbit class. Please see below: "main program". * ****************************************************************/ #include "orbitbk.hh" // declarations, matrix class #include "constants.hh" // global constants #include "ioroutines.hh" // error messages #include "utilities.hh" // solve33 #include "exceptions.hh" // my exceptions class #include "estorbit.hh" // probably only temporary [HB] #include // some compilers, remove function #include // for memory stream #include // setw // ====== Global variables, declared extern in constants.h ====== // === Declared extern in constants.h, set in main to be able to use them === // === in readinput.cc they are set via the input file ====================== // [MA] copied from processor.cc to build orbit as a standalone binary #ifdef __TESTMAIN__ bk_messages TRACE; bk_messages DEBUG; bk_messages INFO; bk_messages PROGRESS; bk_messages WARNING; bk_messages ERROR; bk_messages matDEBUG; bk_messages matERROR; #endif // ====== Prototypes in this file ====== matrix splineinterpol( const matrix &time, const matrix &data); matrix polyfit( const matrix &time, const matrix &y, const int32 DEGREE); /**************************************************************** * orbit::initialize * * Fills data vectors, computes coefficients for interpolation * * Expects time sorted data in file after string: * * "NUMBER_OF_DATAPOINTS: 3" * * t1.xxx x1.xxx y1.xxx z1.xxx * * t2.xxx x2.xxx y2.xxx z2.xxx * * t3.xxx x3.xxx y3.xxx z3.xxx * * * * Bert Kampes, 11-Dec-1998 * #%// BK 17-Jul-2000: changed to class * ****************************************************************/ void orbit::initialize(const char* file) { TRACE_FUNCTION("orbit::initialize (BK 17-Jul-2000)") char dummyline[4*ONE27]; char word[EIGHTY]; bool foundsection = false; register int32 i; // ______ Open file ______ ifstream infile(file, ios::in); bk_assert(infile,file,__FILE__,__LINE__); numberofpoints = 0; // ====== Search file for data section ====== while (infile) { infile >> word; if (strcmp("NUMBER_OF_DATAPOINTS:",word)) // no pattern match. { infile.getline(dummyline,4*ONE27,'\n'); // goto next line. } else // in data section { foundsection=true; infile >> numberofpoints; klo=0; // initial guess khi=1; // initial guess, place in constructor time.resize(numberofpoints,1); // data_x.resize(numberofpoints,1); // data_y.resize(numberofpoints,1); // data_z.resize(numberofpoints,1); // data_xv.resize(numberofpoints,1); // data_yv.resize(numberofpoints,1); // data_zv.resize(numberofpoints,1); // cerr << "[orbit.cc] " << "orbvector_type: " << orbvector_type << " vs velo prm fixed: " << ORB_PRM_VEL << endl; // ______ Actually read data ______ for (i=0;i> time(i,0) >> data_x(i,0) >> data_y(i,0) >> data_z(i,0); } } // else not foundsection } // file // ______ Tidy up ______ infile.close(); if (!foundsection) { WARNING << "string: \"NUMBER_OF_DATAPOINTS:\" not found (i.e., orbit) in file: " << file << "."; WARNING.print(); } INFO << numberofpoints << " datapoints (t,x,y,z) read from: \"" << file << "\""; INFO.print(); // ______ Compute interpolation coefficients ______ DEBUG << "value of interp_method: " << interp_method; DEBUG.print(); if (foundsection) { // ______ Check if time sorted data ______ for (i=0; i6) ? 5 : numberofpoints-2;// 1 redundant for testing! // for radarsat however, do use interpolation, seems to work // even when there are warnings? //if (numberofpoints==15 && (time(1,0)-time(0,0))>479.9)// RSAT? if ((time(1,0)-time(0,0))>479.9 && (time(1,0)-time(0,0))<481.1)// RSAT? { WARNING.print("Assuming RADARSAT: use highest polyfit recommended."); interp_method = numberofpoints-1;// even polyfit(14) seems to work.. } } // ___ call function that computes coefficients ___ computecoefficients(); // cubic spline or polynomial PROGRESS.print("Orbit: interpolation coefficients computed."); } #ifdef __DEBUG showdata(); const real8 t_tmp = time(0,0); DEBUG.width(22); DEBUG.precision(20); DEBUG.rewind(); DEBUG << "check: computing orbit for t between t0 and t1 = " << t_tmp; DEBUG.print(); cn pos_tmp = getxyz(t_tmp); cn vel_tmp = getxyzdot(t_tmp); cn acc_tmp = getxyzddot(t_tmp); DEBUG << "interp. pos: " << pos_tmp.x << " " << pos_tmp.y << " " << pos_tmp.z; DEBUG.print(); DEBUG << "interp. vel: " << vel_tmp.x << " " << vel_tmp.y << " " << vel_tmp.z; DEBUG.print(); DEBUG << "interp. acc: " << acc_tmp.x << " " << acc_tmp.y << " " << acc_tmp.z; DEBUG.print(); #endif } // END initialize /**************************************************************** * Compute coefficients for piecewise polynomial. * * time axis and x,y,z should be filled already. * * call splineinterpol routine. * #%// BK 18-Jul-2000 * ****************************************************************/ void orbit::computecoefficients() { TRACE_FUNCTION("orbit::computecoefficients (BK 18-Jul-2000)") DEBUG << "value of interp_method: " << interp_method; DEBUG.print(); switch (interp_method)// either spline method or degree of polynomial { case ORB_SPLINE: INFO.print("Computing coefficients for orbit spline interpolation"); coef_x = splineinterpol(time,data_x); coef_y = splineinterpol(time,data_y); coef_z = splineinterpol(time,data_z); break; default: INFO << "Computing coefficients for orbit polyfit degree: " << interp_method; INFO.print(); if (interp_method < 0) { PRINT_ERROR("degree of polynomial < 0") throw(input_error); } coef_x = polyfit(time,data_x,interp_method);// method==degree coef_y = polyfit(time,data_y,interp_method);// method==degree coef_z = polyfit(time,data_z,interp_method);// method==degree } } // END computecoefficients /**************************************************************** * private getklokhi * * * * Returns klo/khi for spline interpolation routines. * * klo is index in time axis before point t, khi is index after * * old values are checked first because lot of successive * * interpolation between same t0 t1 is expected. * * * * Bert Kampes, 11-Dec-1998 * #%// BK 18-Jul-2000: orbit class * ****************************************************************/ void orbit::getklokhi(real8 t) { #ifdef __DEBUG // ___ Called a lot, within debug ___ TRACE_FUNCTION("orbit::getinterval (BK 18-Jul-2000)") #endif // ______ Check if last interval still applies, init. to [0;1] ______ if (time(klo,0) <= t && time(khi,0) >= t) return; // _____ Else compute correct interval ______ int32 k; klo = 0; khi = numberofpoints - 1; while(khi-klo>1) { k = (khi+klo) >> 1; // bisection, divide by two if (time(k,0) > t) khi = k; else klo = k; } } // END getinterval /**************************************************************** * public getxyz * * * * Returns (natural) cubic spline interpolant. * * based on numerical recipes routine: splint pp.113 * * input: * * - matrix time and position info * * - matrix from splineinterpol * * - t to be evaluated * * output: * * - interpolated value at t * * * * use routine getsatpos, later we will make an orbit class... * * * * Bert Kampes, 11-Dec-1998 * * Bert Kampes, 02-Jun-1999 streamlined, const variables etc.* ****************************************************************/ cn orbit::getxyz( real8 t) // const // not, klo,khi { #ifdef __DEBUG TRACE_FUNCTION("orbit::getxyz (BK 02-Jun-1999)") if (t < time(0,0) || t > time(numberofpoints-1,0)) { WARNING << "interpolation at: " << t << " is outside interval time axis: (" << time(0,0) << ", " << time(numberofpoints-1,0) << ")."; WARNING.print(); } #endif cn satpos; if (interp_method==ORB_SPLINE) { // ______ Compute correct interval ______ getklokhi(t); // return correct interval const real8 h = time(khi,0) - time(klo,0); // delta_t, might not be const. const real8 a = (time(khi,0) - t) / h; const real8 b = 1. - a; // ______ Evaluate function in x,y,z ______ satpos.x = a*data_x(klo,0)+b*data_x(khi,0) + (((sqr(a)*a-a)*coef_x(klo,0)+(sqr(b)*b-b)*coef_x(khi,0))*sqr(h))/6.; satpos.y = a*data_y(klo,0)+b*data_y(khi,0) + (((sqr(a)*a-a)*coef_y(klo,0)+(sqr(b)*b-b)*coef_y(khi,0))*sqr(h))/6.; satpos.z = a*data_z(klo,0)+b*data_z(khi,0) + (((sqr(a)*a-a)*coef_z(klo,0)+(sqr(b)*b-b)*coef_z(khi,0))*sqr(h))/6.; } // ______ Orbit interpolator is simple polynomial ______ // ______ unfortunately, i normalize data here each time. // ______ we could normalize input t, but then also t_azi1 // ______ and maybe more consequences for code. see howlong this takes // ______ we normalize here only by a shift to avoid rescaling xdot and xddot // ______ (it seems else vdot=vdot*.5(min+max) for some reason) else { const real8 t_tmp = (t-time(numberofpoints/2,0))/real8(10.0); satpos.x = polyval1d(t_tmp, coef_x); satpos.y = polyval1d(t_tmp, coef_y); satpos.z = polyval1d(t_tmp, coef_z); } return satpos; } // END getxyz /**************************************************************** * getxyzdot * * * * Returns 1st derivative natural cubic spline interpolant. * * Numerical recipes splint pp113 * * input: * * - t to be evaluated * * output: * * - interpolated value at t for x,y,z * * * * Bert Kampes, 11-Dec-1998 * * Bert Kampes, 02-Jun-1999 streamlined, const variables etc.* * Bert Kampes, 06-Jul-2000 bugfix dt!=1 * ****************************************************************/ cn orbit::getxyzdot( real8 t) { #ifdef __DEBUG TRACE_FUNCTION("orbit::getxyzddot (BK 06-Jul-2000)") if (t < time(0,0) || t > time(numberofpoints-1,0)) { WARNING << "interpolation at: " << t << " is outside interval time axis: (" << time(0,0) << ", " << time(numberofpoints-1,0) << ")."; WARNING.print(); } #endif cn satvel; // ______ Orbit interpolator is splines piecewise polynomial ______ if (interp_method==ORB_SPLINE) { // ______ Compute correct interval ______ getklokhi(t); // return correct interval const real8 h = time(khi,0) - time(klo,0); // delta_t, might not be const. const real8 a = (time(khi,0) - t) / h; const real8 b = 1. - a; // ______ Evaluate 1st derivative of function in x,y,z ______ satvel.x = ((data_x(khi,0)-data_x(klo,0)) / h) + (h * (((1-(3*sqr(a)))*coef_x(klo,0)) + (((3*sqr(b))-1)*coef_x(khi,0)))) / 6.; satvel.y = ((data_y(khi,0)-data_y(klo,0)) / h) + (h * (((1-(3*sqr(a)))*coef_y(klo,0)) + (((3*sqr(b))-1)*coef_y(khi,0)))) / 6.; satvel.z = ((data_z(khi,0)-data_z(klo,0)) / h) + (h * (((1-(3*sqr(a)))*coef_z(klo,0)) + (((3*sqr(b))-1)*coef_z(khi,0)))) / 6.; } // ______ Orbit interpolator is simple polynomial ______ else { const int32 DEGREE = coef_x.lines()-1; satvel.x = coef_x(1,0);// a_1*t^0 + 2a_2*t^1 + 3a_3*t^2 + ... satvel.y = coef_y(1,0); satvel.z = coef_z(1,0); const real8 t_tmp = (t-time(numberofpoints/2,0))/real8(10.0); for (int32 i=2; i<=DEGREE; ++i) { real8 powt = real8(i)*pow(t_tmp,real8(i-1)); satvel.x += coef_x(i,0)*powt; satvel.y += coef_y(i,0)*powt; satvel.z += coef_z(i,0)*powt; } satvel.x /= real8(10.0);// normalization satvel.y /= real8(10.0);// normalization satvel.z /= real8(10.0);// normalization } return satvel; } // END getxyzdot /**************************************************************** * getxyzddot * * * * Returns 2nd derivative natural cubic spline interpolant. * * Numerical recipes splint pp113 * * input: * * - t to be evaluated * * output: * * - interpolated value at t for x,y,z * * * * Bert Kampes, 11-Dec-1998 * * Bert Kampes, 02-Jun-1999 streamlined, const variables etc.* * Bert Kampes, 06-Jul-2000 bugfix dt!=1 * ****************************************************************/ cn orbit::getxyzddot( real8 t) { #ifdef __DEBUG TRACE_FUNCTION("orbit::getxyzddot (BK 06-Jul-2000)") if (t < time(0,0) || t > time(numberofpoints-1,0)) { WARNING << "interpolation at: " << t << " is outside interval time axis: (" << time(0,0) << ", " << time(numberofpoints-1,0) << ")."; WARNING.print(); } #endif cn satacc; // ______ Orbit interpolator is splines piecewise polynomial ______ if (interp_method==ORB_SPLINE) { // ______ Compute correct interval ______ getklokhi(t); // return correct interval const real8 h = time(khi,0) - time(klo,0); // delta_t, might not be const. const real8 a = (time(khi,0) - t) / h; const real8 b = 1. - a; // ______ Evaluate 2nd derivative of function in x,y,z ______ satacc.x = a*coef_x(klo,0) + b*coef_x(khi,0); satacc.y = a*coef_y(klo,0) + b*coef_y(khi,0); satacc.z = a*coef_z(klo,0) + b*coef_z(khi,0); } // ______ Orbit interpolator is simple polynomial ______ else { // 2a_2 + 2*3a_3*t^1 + 3*4a_4*t^2... const int32 DEGREE = coef_x.lines()-1; satacc.x = 0.0; satacc.y = 0.0; satacc.z = 0.0; const real8 t_tmp = (t-time(numberofpoints/2,0))/real8(10.0); for (int32 i=2; i<=DEGREE; ++i) { real8 powt = real8((i-1)*i)*pow(t_tmp,real8(i-2)); satacc.x += coef_x(i,0)*powt; satacc.y += coef_y(i,0)*powt; satacc.z += coef_z(i,0)*powt; } satacc.x /= real8(100.0);//normalization satacc.y /= real8(100.0);//normalization satacc.z /= real8(100.0);//normalization } return satacc; } // END getxyzddot // ====== Friends ====== /**************************************************************** * lp2xyz * * * * converts line,pixels to x,y,z on (which) ellipsoid? * * * * input: * * - MAXITER (default = 10) * * - CRITER (default ~ 10-6 m ?) * * output: * * - cn (x,y,z) (returnpos is filled) * * - number of iterations is returned * * * * Bert Kampes, 04-Jan-1999 * ****************************************************************/ int32 lp2xyz( real8 line, real8 pixel, const input_ell &ell, const slcimage &image, orbit &orb, cn &returnpos, int32 MAXITER, real8 CRITERPOS) { TRACE_FUNCTION("lp2xyz (BK 04-Jan-1999)") // ______ Convert lp to time ______ const real8 aztime = image.line2ta(line); const real8 ratime = image.pix2tr(pixel); const cn possat = orb.getxyz(aztime); const cn velsat = orb.getxyzdot(aztime); // ______ Set up system of equations and iterate ______ returnpos.x = image.approxcentreoriginal.x; // iteration 0 returnpos.y = image.approxcentreoriginal.y; // iteration 0 returnpos.z = image.approxcentreoriginal.z; // iteration 0 // ______ Save some alloc, init and dealloc time by declaring static (15%?) ______ static matrix solxyz(3,1); // solution of system static matrix equationset(3,1); // observations static matrix partialsxyz(3,3); // partials to position due to nonlinear register int32 iter; for (iter=0; iter<=MAXITER; ++iter) { // ______ Update equations + solve system ______ const cn dsat_P = returnpos.min(possat); // vector satellite, P on ellipsoid equationset(0,0) = -eq1_doppler(velsat, dsat_P); equationset(1,0) = -eq2_range(dsat_P, ratime); equationset(2,0) = -eq3_ellipsoid(returnpos,ell.a,ell.b); partialsxyz(0,0) = velsat.x; partialsxyz(0,1) = velsat.y; partialsxyz(0,2) = velsat.z; partialsxyz(1,0) = 2*dsat_P.x; partialsxyz(1,1) = 2*dsat_P.y; partialsxyz(1,2) = 2*dsat_P.z; partialsxyz(2,0) = (2*returnpos.x)/sqr(ell.a); partialsxyz(2,1) = (2*returnpos.y)/sqr(ell.a); partialsxyz(2,2) = (2*returnpos.z)/sqr(ell.b); // ______ Solve system ______ solve33(solxyz, equationset,partialsxyz); // ______Update solution______ returnpos.x += solxyz(0,0); // update approx. value returnpos.y += solxyz(1,0); // update approx. value returnpos.z += solxyz(2,0); // update approx. value // ______Check convergence______ if (abs(solxyz(0,0)) < CRITERPOS && // dx abs(solxyz(1,0)) < CRITERPOS && // dy abs(solxyz(2,0)) < CRITERPOS ) // dz break; // converged } // ______ Check number of iterations ______ if (iter >= MAXITER) { WARNING << "line, pix -> x,y,z: maximum iterations (" << MAXITER << ") reached. " << "Criterium (m): "<< CRITERPOS << "dx,dy,dz=" << solxyz(0,0) << ", " << solxyz(1,0) << ", " << solxyz(2,0); WARNING.print(); } // ______ (Converged) Result is in returnpos ______ return iter; } // END lp2xyz /**************************************************************** * xyz2orb * * * * converts xyz (which) ellipsoid? to orbital coordinates * * ellips, xyz is in system of orbit ephemerides * * * * input: * * - MAXITER (default = 10) * * - CRITER (default = 10-15s) * * output: * * - x,y,z * * - number of iterations * * * #%// BK 22-Sep-2000 * ****************************************************************/ int32 xyz2orb( cn &possat, const slcimage &image, orbit &orb, // non const, khi/klo const cn &pointonellips, int32 MAXITER, // defaults real8 CRITERTIM) // seconds { TRACE_FUNCTION("xyz2orb (BK 22-Sep-2000)"); // ______ Initial value azimuth time ______ real8 sol = 0.0; register int32 iter; real8 tazi = image.line2ta(.5*(image.currentwindow.linehi-image.currentwindow.linelo)); for(iter=0 ;iter<=MAXITER; ++iter) // break at convergence { // ______ Update equations ______ possat = orb.getxyz(tazi); const cn velsat = orb.getxyzdot(tazi); const cn accsat = orb.getxyzddot(tazi); const cn delta = pointonellips.min(possat); // ______ Update solution ______ sol = -eq1_doppler(velsat, delta) / eq1_doppler_dt(delta, velsat, accsat); tazi += sol; // ______ Check convergence ______ if (abs(sol) < CRITERTIM) // dta break; } // ______ Check number of iterations _____ if (iter >= MAXITER) { WARNING << "x,y,z -> line, pix: maximum iterations (" << MAXITER << ") reached. " << "Criterium (s):" << CRITERTIM << "dta (s)=" << sol; WARNING.print(); } // ====== Compute range time ====== // ______ Update equations ______ possat = orb.getxyz(tazi); return iter; } // END xyz2orb /**************************************************************** * xyz2t * * * * converts xyz (which) ellipsoid? to azimuth time with * * zero doppler equation, use slant range eq. for range time * #%// BK 18-Jul-2000 * * ellips, xyz is in system of orbit ephemerides * * * * input: * * - MAXITER (default = 10) * * - CRITER (default = 10-15s) * * output: * * - (updated tazi,tran) * * - number of iterations * * * * Bert Kampes, 04-Jan-1999 * ****************************************************************/ int32 xyz2t( real8 &tazi, // azimuth real8 &tran, // and range time const slcimage &image, orbit &orb, // non const, khi/klo const cn &pos, int32 MAXITER, // defaults real8 CRITERTIM) // seconds { TRACE_FUNCTION("xyz2t (BK 04-Jan-1999)") // ______ Compute initial value ______ tazi = image.line2ta(0.5*(image.currentwindow.linehi-image.currentwindow.linelo)); // _____ Start _______ real8 sol = 0.0; register int32 iter; for(iter=0 ;iter<=MAXITER; ++iter) // break at convergence { // ______ Update equations ______ const cn possat = orb.getxyz(tazi); const cn velsat = orb.getxyzdot(tazi); const cn accsat = orb.getxyzddot(tazi); const cn delta = pos.min(possat); // ______ Update solution ______ sol = -eq1_doppler(velsat, delta) / eq1_doppler_dt(delta, velsat, accsat); tazi += sol; // ______ Check convergence ______ if (abs(sol) < CRITERTIM) // dta break; } // ______ Check number of iterations _____ if (iter >= MAXITER) { WARNING << "x,y,z -> line, pix: maximum iterations (" << MAXITER << ") reached. " << "Criterium (s):" << CRITERTIM << "dta (s)=" << sol; WARNING.print(); } // ====== Compute range time ====== // ______ Update equations ______ const cn possat = orb.getxyz(tazi); const cn delta = pos.min(possat); tran = delta.norm() / SOL; return iter; } // END xyz2t /**************************************************************** * xyz2lp * * * * converts xyz (which) ellipsoid? to line,pixels * * * * input: * * - MAXITER (default = 10) * * - CRITER (default ~ 10-15s) * * output: * * - cn (x,y,z) (returnpos is filled) * * - number of iterations * * * * Bert Kampes, 04-Jan-1999 * ****************************************************************/ int32 xyz2lp( real8 &returnline, real8 &returnpixel, const slcimage &image, orbit &orb, const cn &pos, // point at ground int32 MAXITER, real8 CRITERTIM) { TRACE_FUNCTION("xyz2lp (BK 04-Jan-1999)"); real8 tazi; real8 tran; // ______ Compute tazi, tran ______ int32 iter = xyz2t(tazi,tran,image,orb,pos,MAXITER,CRITERTIM); // ______ Convert time to pixel ______ // ______ (Converged) Result is in returnline/pixel ______ returnline = image.ta2line(tazi); returnpixel = image.tr2pix (tran); return iter; } // END xyz2lp /**************************************************************** * ell2lp * * * * converts ell to x,y,z, to l,p * * * * input: * * - ?? * * - MAXITER (default = 10) * * - CRITER (default ~ 10-6 m ?) * * output: * * - phi,lambda,height (updated) * * - number of iterations * * * * Bert Kampes, 27-Jan-1999 * ****************************************************************/ int32 ell2lp( real8 &returnline, real8 &returnpixel, const input_ell &ellips, const slcimage &image, orbit &orb, real8 phi, real8 lambda, real8 height, int32 MAXITER, real8 CRITERTIM) { TRACE_FUNCTION("ell2lp (BK 27-Jan-1999)") // ______ Transform ell2xyz ______ cn returnpos = ellips.ell2xyz(phi, lambda, height); DEBUG << "tmp result phi,lambda,h --> x,y,z: " << phi << ", " << lambda << ", " << height << " --> " << returnpos.x << " " << returnpos.y << " " << returnpos.z; DEBUG.print(); // ______ Transform xyz2lp ______ int32 n_iter = xyz2lp(returnline, returnpixel, image, orb, returnpos, MAXITER, CRITERTIM); return n_iter; // number of iterations } // END ell2lp /**************************************************************** * lp2ell * * * * converts line,pixels to x,y,z to geodetic coordinates ell * * * * input: * * - line,pixel, etc. * * - MAXITER (default = 10) * * - CRITER (default ~ 10-6 m ?) * * output: * * - phi,lambda,height (updated) * * - number of iterations * * * * Bert Kampes, 27-Jan-1999 * ****************************************************************/ int32 lp2ell( real8 line, real8 pixel, const input_ell &ellips, const slcimage &image, orbit &orb, real8 &returnphi, real8 &returnlambda, real8 &returnheight, int32 MAXITER, real8 CRITERPOS) { TRACE_FUNCTION("lp2ell (BK: 27-Jan-1999)"); // ______ Transform lp2xyz ______ cn returnpos; int32 iter = lp2xyz(line, pixel, ellips, image, orb, returnpos, MAXITER, CRITERPOS); // ______ Transform xyz2ell, compute phi,lambda,h ______ ellips.xyz2ell(returnpos, returnphi, returnlambda, returnheight); return iter; } // END lp2ell /**************************************************************** * dumporbit * * * * rescale data to interval [-1,1] * * data -> X(data-min)/(max-min) ; data+SS * * X=1--1==EE-SS; SS=-1, EE=1 * * * * input: * * output: * * Bert Kampes, 03-Jul-2000 * ****************************************************************/ void orbit::dumporbit( const input_pr_orbits &inputorb, const int16 ID) { TRACE_FUNCTION("orbit::dumporbit (BK 03-Jul-2000)") // ___ prevent error if called after readfiles, but no orbit section ___ if (numberofpoints==0) { INFO.print("Exiting dumporbit, no orbit data available."); return; } // ====== Compute positions for center pixel ====== // ______ *dumporbit initialized to -1.0 in readinput.c ______ real8 dt=0.; char ofile[EIGHTY]; if (ID==MASTERID) { if (inputorb.dumpmasterorbit<0) return; dt = inputorb.dumpmasterorbit; strcpy(ofile,"masterorbit.dat"); PROGRESS.print("Dumping master orbit."); } else if (ID==SLAVEID) { dt = inputorb.dumpslaveorbit; if (inputorb.dumpslaveorbit<0) return; strcpy(ofile,"slaveorbit.dat"); PROGRESS.print("Dumping slave orbit."); } else { PRINT_ERROR("Panic: not possible.") throw(unhandled_case_error); } const int32 MAXITER = 10; const real8 CRITERPOS = 1e-6; const real8 CRITERTIM = 1e-10; INFO << "dumporbits: MAXITER: " << MAXITER << "; " << "CRITERPOS: " << CRITERPOS << " m; " << "CRITERTIM: " << CRITERTIM << " s"; INFO.print(); // ______ Evaluate polynomial orbit for t1:dt:tN ______ int32 outputlines = 1 + int32((time(numberofpoints-1,0)-time(0,0)) / dt); real8 tazi = time(0,0); ofstream fo(ofile,ios::out | ios::trunc); matassert(fo,ofile,__FILE__,__LINE__); fo.precision(3); fo.width(11); // this is ok, but test if not: fo.setf(ios::left); fo.setf(ios::fixed); fo.setf(ios::showpoint); for (register int32 i=0; i x * * data <-> y * * pp <-> y2 * * rhs <-> u * * * * Compute coefficients of piecewize polynomials for * * cubic splines. Use natural ones if __NATURALSPLINE__ is * * defined (by default internal in this routine.) * * Else use boundary condition from nrc pp113. * * (fix first derivative.) * * There does not seem to be a big difference between both * * boundary conditions, particularly for middle segment. * * A pp = rhs; L Lt pp = rhs; (?) * * pptmp=Lt pp); L pptmp = rhs; Lt pp = pptmp; (?) * * input: * * - matrix by getdata with time and position info * * output: * * - matrix with 2nd order derivatives * * (input for interp. routines) * * * * Bert Kampes, 11-Dec-1998 * #%// BK 17-Jul-2000: added nonnatural * ****************************************************************/ matrix splineinterpol( const matrix &time, const matrix &data) { TRACE_FUNCTION("splineinterpol (BK 17-Jul-2000)") if (time.pixels() != 1 || data.pixels() != 1) { PRINT_ERROR("code 901: splineinterpol: wrong input."); throw(input_error); } if (time.lines() != data.lines()) // number of points { PRINT_ERROR("code 901: splineinterpol: require same size vectors."); throw(input_error); } const int32 N = time.lines(); // number of points matrix rhs(N-1,1); matrix pp(N,1); // init to 0. // #define __NATURALSPLINE__ // in Makefile or here if so desired. #define __NATURALSPLINE__ // ====== Set boundary condition first datapoint ====== #ifdef __NATURALSPLINE__ pp(0,0) = 0.0; // natural spline boundary condition #else // ______ yp1 is first der. at point 0 ______ // estimate it by dy/dx: nearly linear for sat. orbit... const real8 yp1 = (data(1,0)-data(0,0)) / (time(1,0)-time(0,0)); pp(0,0) = -0.5; rhs(0,0) = (3.0 / (time(1,0)-time(0,0))) * ((data(1,0)-data(0,0)) / (time(1,0)-time(0,0)) - yp1); #endif // ====== Decomposition loop ====== register int32 i; for (i=1; i<=N-2; ++i) { const int32 ip1 = i + 1; const int32 im1 = i - 1; const real8 sig = (time(i,0)-time(im1,0)) / (time(ip1,0)-time(im1,0)); const real8 p = sig*pp(im1,0) + 2.0; // pp(i,0) = (sig-1.0) / p; rhs(i,0) = (data(ip1,0)-data(i,0)) / (time(ip1,0)-time(i,0)) - (data(i,0)-data(im1,0)) / (time(i,0)-time(im1,0)); rhs(i,0) = (6.*rhs(i,0)/(time(ip1,0)-time(im1,0))-sig*rhs(im1,0))/p; } // ====== Set boundary condition last datapoint ====== #ifdef __NATURALSPLINE__ pp(N-1,0) = 0.0; // natural spline oundary condition #else // ______ ypN is first derivative at point N-1 ______ const real8 ypN = (data(N-1,0)-data(N-2,0)) / (time(N-1,0)-time(N-2,0)); const real8 qn = 0.5; const real8 un = (3.0 / (time(N-1,0) - time(N-2,0))) * (ypN - (data(N-1,0) - data(N-2,0)) / (time(N-1,0) - time(N-2,0))); pp(N-1,0) = (un - qn*rhs(N-2,0)) / (qn*pp(N-2,0) + 1.0); #endif // ====== Backsub loop ====== for (i=N-2; i>=0; --i) pp(i,0) = pp(i,0)*pp(i+1,0) + rhs(i,0); // pp(i,0) *= pp(i+1,0) + rhs(i,0); // ?? return pp; // contains second derivatives at datapoints } // END splineinterpol /**************************************************************** * polyfit * * * * Compute coefficients of x=a0+a1*t+a2*t^2+a3*t^3 polynomial * * for orbit interpolation. Do this to facilitate a method * * in case only a few datapoints are given. * * Data t is normalized approximately [-x,x], then polynomial * * coefficients are computed. For poly_val this is repeated * * see getxyz, etc. * * * * input: * * - matrix by getdata with time and position info * * output: * * - matrix with coeff. * * (input for interp. routines) * * * * Bert Kampes, 16-Jun-2003 * ****************************************************************/ matrix polyfit( const matrix &time, const matrix &y, const int32 DEGREE) { TRACE_FUNCTION("polyfit (BK 16-Jun-2003)") if (time.pixels() != 1 || y.pixels() != 1) { PRINT_ERROR("code 902: polyfit: wrong input."); throw(input_error); } if (time.lines() != y.lines()) // number of points { PRINT_ERROR("code 902: polyfit: require same size vectors."); throw(input_error); } // ______ Normalize t for numerical reasons ______ const int32 Npoints = time.lines(); // number of points DEBUG.print("Normalizing t axis for least squares fit"); matrix t=(time-time(Npoints/2,0))/real8(10.0); // ______ Check redundancy ______ const int32 Nunk = DEGREE+1; DEBUG << "Degree of orbit interpolating polynomial: " << DEGREE; DEBUG.print(); DEBUG << "Number of unknowns: " << Nunk; DEBUG.print(); DEBUG << "Number of data points (orbit): " << Npoints; DEBUG.print(); if (Npoints < Nunk) { PRINT_ERROR("polyfit: Number of points is smaller than parameters solved for.") throw(input_error); } // ______ Set up system of equations to solve coeff. ______ DEBUG.print("Setting up lin. system of equations"); matrix A(Npoints,Nunk);// designmatrix for (int32 j=0; j<=DEGREE; j++) { matrix t_tmp = t; t_tmp.mypow(real8(j)); A.setcolumn(j,t_tmp); } DEBUG.print("Solving lin. system of equations with cholesky."); matrix N = matTxmat(A,A); matrix rhs = matTxmat(A,y); matrix Qx_hat = N; choles(Qx_hat); // Cholesky factorisation normalmatrix solvechol(Qx_hat,rhs); // Estimate of unknowns in rhs invertchol(Qx_hat); // Covariance matrix // ______Test inverse______ for (uint i=0; i y_hat = A * rhs; matrix e_hat = y - y_hat; if (max(abs(e_hat)) > 0.02)// 0.05 is already 1 wavelength! (?) { WARNING << "Max. approximation error at datapoints (x,y,or z?): " << max(abs(e_hat)) << "m"; WARNING.print(); } else { INFO << "Max. approximation error at datapoints (x,y,or z?): " << max(abs(e_hat)) << "m"; INFO.print(); } // ___ report computations in detail ___ DEBUG.width(16); DEBUG.precision(15); DEBUG.print("REPORTING POLYFIT LEAST SQUARES ERRORS"); DEBUG.print(" time y yhat ehat"); for (int32 i=0; ilog it. ___ for (int32 i=0; i orbit::modify(const matrix &coeff, orbit &referenceorbit, const real8 tshift, const real8 tmin, const real8 tmax) { TRACE_FUNCTION("orbit::modify (HB 17-Jul-2000)") // ====== update data points ====== const uint degree = coeff.lines()/2-1; for (uint i=0; i datapoints; if (orbvector_type==ORB_PRM_POS) datapoints = matrix(numberofpoints,4); else if (orbvector_type==ORB_PRM_VEL) { datapoints = matrix(numberofpoints,7); datapoints.setdata(0,4,data_xv); datapoints.setdata(0,5,data_yv); datapoints.setdata(0,6,data_zv); } datapoints.setdata(0,0,time); datapoints.setdata(0,1,data_x); datapoints.setdata(0,2,data_y); datapoints.setdata(0,3,data_z); return datapoints; } // END orbit::modify Doris-5.0.3Beta/doris_core/orbitbk.hh000077500000000000000000000223651312547014700175170ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/orbitbk.hh,v $ * * $Revision: 3.13 $ * * $Date: 2005/10/06 11:09:20 $ * * $Author: kampes $ * * * * implementation of orbit class. * * - orbit interpolation. * * - baseline estimation. * * - utility dumping etc. * * * * Compilation with: g++ -D__TESTMAIN__ orbit.cc -o testorbit * * creates a standalone executable for testing of the functions * * of the orbit class. Please see below: "main program". * ****************************************************************/ #ifndef ORBITBK_H // guard #define ORBITBK_H using namespace std; // BK 29-Mar-2003, new compiler? // Jia defined this for compilation under windows // Bert Kampes, 24-Aug-2005 #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "matrixbk.hh" // my matrix class, only 2b included once... #include "slcimage.hh" // my slc image class #include "constants.hh" // global constants #include "readinput.hh" // input structs // ====== Some inline functions ====== // make these private..., but doesn't seem to work ok that way, so do it like this // ______ The setofequation for t2xyz ______ inline real8 eq1_doppler(const cn &velocity, const cn &dsat_P) {return velocity.in(dsat_P);} inline real8 eq2_range(const cn &dsat_P, const real8 &rangetime) {return dsat_P.in(dsat_P)-sqr(SOL*rangetime);} inline real8 eq3_ellipsoid(const cn &P, const real8 &semimajora, const real8 &semiminorb) {return ((sqr(P.x)+sqr(P.y))/sqr(semimajora))+sqr(P.z/semiminorb)-1.0;} // ______ The partial to Pxyz of the 3 eq. for t2xyz ______ // they are best evaluated within calling function: // dE1/dx dE1/dy dE1/dz vel.x ~y ~z // dE2/dx dE2/dy dE2/dz = 2*(pos.x-sat.x) ~y ~z // dE3/dx dE3/dy dE3/dz (2*pos.x)/sqr(ell.a) ~y (2*pos.z)/sqr(ell.b); // ______ The partial to time of dopplereq. for xyz2t ______ inline real8 eq1_doppler_dt(const cn &dsat_P, const cn &velocity, const cn &accerelation) {return accerelation.in(dsat_P)-sqr(velocity.x)-sqr(velocity.y)-sqr(velocity.z);} // ====== The orbit class itself ====== class orbit { // ====== Private data, functions ====== private: // ______ Data ______ //char system[80]; // WGS84, GRS80, Bessel, etc. int16 interp_method; // 0: cubic spline, x: polyfit(x) int32 numberofpoints; // ... int16 orbvector_type; // 30: positional vectors only 31: position + velocity vectors [MA] int32 klo; // index in timevector correct int32 khi; // +part piecewise polynomial matrix time; // vector (numberofpoints,1) matrix data_x; // vector (numberofpoints,1) matrix data_y; // vector (numberofpoints,1) matrix data_z; // vector (numberofpoints,1) matrix coef_x; // vector (numberofpoints,1) matrix coef_y; // vector (numberofpoints,1) matrix coef_z; // vector (numberofpoints,1) matrix data_xv; // vector (numberofpoints,1) matrix data_yv; // vector (numberofpoints,1) matrix data_zv; // vector (numberofpoints,1) matrix coef_xv; // vector (numberofpoints,1) matrix coef_yv; // vector (numberofpoints,1) matrix coef_zv; // vector (numberofpoints,1) // ______ Functions ______ void computecoefficients(); // pp coeffs. //void computecoefficientsV(); // pp coeffs. void getklokhi(real8 t); // piecewize polynomial indices // ====== Public data, functions ====== public: //default method is polynomial degree=npoints, but max degree=5. //orbit() {interp_method=ORB_DEFAULT;numberofpoints=0;}// constructor orbit() {interp_method=ORB_DEFAULT;numberofpoints=0;orbvector_type=ORB_PRM_POS;}// constructor int32 npoints() {return numberofpoints;} void set_interp_method(int16 m){interp_method=m;} void set_orbvector_type(int16 t){orbvector_type=t;} // ______ Read from file&store t,x,y,z; compute coefficients ______ // ______ function initialize should be called first! ______ void initialize (const char *file); // do all... bool is_initialized() {return (numberofpoints!=0) ? true : false;}// constructor void showdata (); // debugging... // ______ Modification from baseline error polynomial [HB] ______ matrix modify(const matrix &coeff, orbit &referenceorbit, const real8 tshift, const real8 tmin, const real8 tmax); // ====== Interpolation ====== //cn getxyz (real8 time) const; // not const, klo/hi updated cn getxyz (real8 time); cn getxyzdot (real8 time); cn getxyzddot (real8 time); // ====== Conversion between coordinate systems ====== // ______ radar coordinate line/pixel to xyz on ellipsoid ______ friend int32 lp2xyz( real8 line, real8 pixel, const input_ell &ell, const slcimage &image, orbit &orb, cn &returnpos, int32 MAXITER=10, // [.] defaults real8 CRITERPOS=1e-6); // [m] // ______ xyz cartesian on ellipsoid to orbital coord. ______ friend int32 xyz2orb( cn &returnpossat, const slcimage &image, orbit &orb, const cn &pointonellips, int32 MAXITER=10, // [.] defaults real8 CRITERTIM=1e-10); // [s] // ______ xyz cartesian on ellipsoid to azimuth/range time ______ friend int32 xyz2t( real8 &returntazi, // azimuth real8 &returntran, // and range time const slcimage &image, orbit &orb, const cn &pos, int32 MAXITER=10, // [.] defaults real8 CRITERTIM=1e-10); // [s] // ______ convert xyz-ellipsoid to line/pixel ______ friend int32 xyz2lp( real8 &returnline, real8 &returnpixel, const slcimage &image, orbit &orb, const cn &pos, int32 MAXITER=10, // defaults real8 CRITERTIM=1e-10); // seconds // ______ Convert ellipsoid to radar coordinates ______ friend int32 ell2lp( real8 &returnline, real8 &returnpixel, const input_ell &ell, const slcimage &image, orbit &orb, real8 phi, real8 lambda, real8 height, int32 MAXITER=10, real8 CRITERTIM=1e-10); // seconds // ______ Convert radar coordinates to ellipsoidal coordinates ______ friend int32 lp2ell( real8 line, real8 pixel, const input_ell &ell, const slcimage &image, orbit &orb, real8 &returnphi, real8 &returnlambda, real8 &returnheight, int32 MAXITER=10, real8 CRITERPOS=1e-6); // meter // ====== Information/debugging ====== // ______ dump computed coeffs, interpolated orbit, etc. ______ void dumporbit( const input_pr_orbits &inputorb, const int16 ID); // ______ compute baseline on a grid ______ friend void compbaseline( const input_gen &generalinput, const slcimage &master, const slcimage &slave, orbit &masterorbit, orbit &slaveorbit); }; // END class orbit #endif // ORBITBK_H guard Doris-5.0.3Beta/doris_core/processor.cc000077500000000000000000005441611312547014700200730ustar00rootroot00000000000000/* @file processor.cc Doris InSAR processor. @brief main routine calling all modules. */ /* * Copyright (c) 1999-2012 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ /**************************************************************** * $Source: /users/.../doris/src/RCS/processor.cc,v $ * * $Revision: 4.06 $ * * $Date: 2011/10/22 22:49:19 $ * * $Author: TUDelft $ * * * * - main() * * - initmessages() * * - handleinput() * * - usage() * * - copyright() * * - quote() * * - preview(...) * ****************************************************************/ using namespace std; // ====== Include files used here ========================================= #include "matrixbk.hh" // my matrix class #include "orbitbk.hh" // my orbit class (includes matrix class) #include "slcimage.hh" // my slc image class #include "productinfo.hh" // my 'products' class #include "constants.hh" // global,general structs/typedefs/constants #include "utilities.hh" // interpolation etc. #include "ioroutines.hh" // errormessages, readinput, ... #include "readdata.hh" // routines to crop data, read info, oversample #include "coregistration.hh" // routines for coarse coreg #include "referencephase.hh" // flatearth, radarcode dem #include "products.hh" // routines for interferogram/coherence #include "geocode.hh" // routines for s2h, DEM generation etc. #include "unwrap.hh" // routines for unwrapping #include "filtering.hh" // routines for filtering #include "exceptions.hh" // error message class (throw these) #include "estorbit.hh" // orbit estimation [HB] #include "bk_baseline.hh" // my baseline class for modeling bperp etc. #include // cout, ... #include // files, ... #include // time #include // system, atoi #include // isspace #include // min max #include // strcat according to g++ (?) #include // function signal() // ====== Global variables, declared extern in constants.h ====== // === Declared extern in constants.h, set in main to be able to use them === // === in readinput.cc they are set via the input file ====================== bk_messages TRACE; bk_messages DEBUG; bk_messages INFO; bk_messages PROGRESS; bk_messages WARNING; bk_messages ERROR; bk_messages matDEBUG; bk_messages matERROR; // ______ used in matrix_bk.cc to keep track of total allocated ______ #ifdef __DEBUGMAT2 // use index checking, alloc uint totalallocated=0; // [B] matrixdebuging #endif // ====== Prototypes functions in this file ====== void initmessages(); void usage(char *programname); void handleinput(int argc, char* argv[], input_gen &for_inputfilename); void quote(); void copyright(); //void preview(int32 previewflag, int32 width, int32 informat, const char *infile, const char *outfile, const char *opts); void preview(int32 previewflag, int32 width, int32 informat, const char *infile, const string &outfile, const string &opts); // otherwise g++ 4.3 complains. [MA] /**************************************************************** @brief main main program @param argc argument count @param argv value of arguments * main * * A big switch to select the modules the user requests. * * Handles some general information such as size of * * current file as well. * * Bert Kampes, 11-Dec-1998 * ****************************************************************/ int main( int argc, char* argv[]) { // ______ Catch math errors, zero division, etc. ______ // ______ v3.15: seems g++ 4 generates SIGSEGV errors due to over-optimization? ___ CatchSignals(handle_signal);// floating point errors, segmentation faults, etc. // try should work with current compilers try{ // ====== Set defaults for message class so we can use it here ====== initmessages(); // set DEBUG etc. #ifndef NO_FASTTRIG // [MA] NO_FASTTRIG, no need to initialized init_fasttrig(); // lookup table for fast_sin() ... etc. #endif // ====== ident string for `what doris` ====== char ident[] = "@(#)Doris InSAR software, $Revision: 4.0.8 $, $Author: TUDelft $"; cerr << endl; INFO.print(ident);//use ident so it is not optimized away // ====== Structs for storing input ====== input_gen input_general; // general inputparameters // misuse logfile for input file name input_ell input_ellips; // ellipsoid pm. input_pr_orbits input_porbits; // inputparam. readfiles slave input_morbits input_m_morbits; // inputparam. modify master orbits [HB] input_readfiles input_m_readfiles; // inputparam. readfiles master input_crop input_m_crop; // inputparam. crop master input_oversample input_m_oversample; // by Raffaele Nutricato input_simamp input_m_simamp; // inputparam. simulated amplitude [FvL, MA] input_mtiming input_m_mtiming; // inputparam. simu. amplitude correl. + master timing error e.i absolute timing [MA] input_readfiles input_s_readfiles; // inputparam. readfiles slave input_morbits input_s_morbits; // inputparam. modify slave orbits [HB] input_crop input_s_crop; // inputparam. crop slave input_oversample input_s_oversample; // by Raffaele Nutricato input_filtazi input_ms_filtazi; // inputparam. azimuth filtering input_resample input_s_resample; // inputparam. resample input_coarsecorr input_i_coarsecorr; // inputparam. coarse correlation input_fine input_i_fine; // inputparam. fine correlation input_reltiming input_i_timing; // inputparam. relative timing error [FvL] input_demassist input_i_demassist; // inputparam. dem assisted coregistraton [FvL] input_coregpm input_i_coregpm; // inputparam. coreg pm comp. input_filtrange input_ms_filtrange; // inputparam. range filtering input_interfero input_i_interfero; // inputparam. interfero. input_coherence input_i_coherence; // inputparam. coherence input_comprefpha input_i_comprefpha; // inputparam. flat earth corr. input_subtrrefpha input_i_subtrrefpha; // inputparam. subtr earth corr. input_comprefdem input_i_comprefdem; // inputparam. ref. dem input_subtrrefdem input_i_subtrrefdem; // inputparam. subtr ref. dem input_filtphase input_i_filtphase; // inputparam. phase filter input_dinsar input_i_dinsar; // inputparam. 3pass diff. insar input_unwrap input_i_unwrap; // inputparam. unwrapping input_estorbits input_i_estorbits; // inputparam. estorbits [HB] input_slant2h input_i_slant2h; // inputparam. slant2height input_geocode input_i_geocode; // inputparam. geocode // ______ Info on images/products ______ slcimage master; // info on master image productinfo simamp; // info on simulated master amplitude slcimage slave; // info on slave image productinfo interferogram; // interferogram productinfo unwrappedinterf; // interferogram unwrapped //productinfo differentialinterf; // diff. interferogram productinfo radarcodedrefdem; // reference DEM productinfo coherence; // coherence image productinfo heightinradarsystem; // s2h, in radarcoord. // ______ Orbital data (interpolation) ______ orbit masterorbit; // class orbit orbit slaveorbit; // class orbit // ______ Matrices for storing polynomial coefficients ______ matrix coeff_cpmL; // coregistration parameters matrix coeff_cpmP; // coregistration parameters matrix coeff_flat; // flatearth correction matrix coeff_h2ph; // h2ph factors, added by FvL // ====== Initialize options ("inputoptionsfile"), files etc ====== handleinput(argc,argv,input_general); // handle input printcpu(1); // initialize timers readinput(input_general, // fill input structs input_ellips, input_porbits, input_m_readfiles, input_m_morbits, // [HB] input_m_crop, input_m_oversample, // added by ____RaffaeleNutricato input_m_simamp, // sim_amp [FvL, MA] input_m_mtiming, // simamp_corr + master timing [MA] input_s_readfiles, input_s_morbits, // [HB] input_s_crop, input_s_oversample, // added by ____RaffaeleNutricato input_ms_filtazi, input_i_coarsecorr, input_i_fine, input_i_timing, // [FvL] input_i_demassist, // [FvL] input_i_coregpm, input_s_resample, input_ms_filtrange, input_i_interfero, input_i_coherence, input_i_comprefpha, input_i_subtrrefpha, input_i_comprefdem, input_i_subtrrefdem, input_i_filtphase, input_i_dinsar, input_i_unwrap, input_i_estorbits, // [HB] input_i_slant2h, input_i_geocode); // ___ Perform some initial tests of platform after SCREEN is set ___ inittest(); // initial tests // ___ transfer general input to orbit ___ masterorbit.set_interp_method(input_general.orb_interp);// transfer input slaveorbit.set_interp_method(input_general.orb_interp);// transfer input // ___ trace function after readinput (screen level known) ___ TRACE_FUNCTION("main"); // ====== Write initial info if appropriate ====== initwrite(input_general.logfile, LOGID); // general info logfile(=1) bool processmaster = doinitwrite(input_general, MASTERID); bool processlave = doinitwrite(input_general, SLAVEID); bool processinterf = doinitwrite(input_general, INTERFID); if (processmaster) initwrite(input_general.m_resfile, MASTERID); // general info master result=2 if (processlave) initwrite(input_general.s_resfile, SLAVEID); // general info slave result=3 if (processinterf) initwrite(input_general.i_resfile, INTERFID); // general info interf_out=4 updatefile("scratchreadinput",input_general.logfile); // copy input2log (readinput) // ====== Check requested processing and fill alreadyprocessed ====== int16 alreadyprocessed[NUMPROCESSES]; checkprocessing(input_general,alreadyprocessed); // initialize alreadyprocessed int16 status = 0; // [MA] check exit status of system calls for proper error handling DEBUG.print("Time spent for initialization:"); printcpu(); PROGRESS.print("Finished initialization"); // ********************************************************* // **** start master **** // ********************************************************* // ====== PROCESS INFOFILES CDROM: MASTER ====== if (input_general.process[pr_m_readfiles]) { PROGRESS.print("Start M_READFILES."); alreadyprocessed[pr_m_readfiles]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing readfiles for master."; getanswer(); } // ______ Select method for READFILES______ switch (input_m_readfiles.sensor_id) { case SLC_ALOS: INFO.print("ALOS: Under development: is ALOS really CEOS/Atlantis like ERS?"); // ______ JERS also ceos? (falls through to ers) ______ case SLC_JERS: INFO.print("JERS: Under development: is JERS really CEOS like ERS?"); // ______ RSAT also CEOS? (falls through to ERS, account in reader) ______ case SLC_RSAT: WARNING.print("RSAT: for orbit highest polyfit recommended."); WARNING.print("RSAT: Under development: CEOS reader seems to work."); // ______ ERS-1/2 ______ case SLC_ERS: // ______ Get checks slave volumefile ______ char c16checkvol1[17]; char c16checkvol2[17]; char c16checkvol3[17]; // check id of volume file if (alreadyprocessed[pr_s_readfiles]) { readres(c16checkvol1,sizeof(c16checkvol1), input_general.s_resfile,"Volume_ID:"); readres(c16checkvol2,sizeof(c16checkvol2), input_general.s_resfile,"Volume_identifier:"); readres(c16checkvol3,sizeof(c16checkvol3), input_general.s_resfile,"Volume_set_identifier:"); } // ______ Extract info ______ readvolume(input_m_readfiles, c16checkvol1, c16checkvol2, c16checkvol3); // ___ written in readvolume ___ updatefile("scratchresvol",input_general.m_resfile); // ___ written in readvolume ___ updatefile("scratchlogvol",input_general.logfile); // ______Get check with master volumefile______ char c8checkleadat[9]; // check vol met lea en dat readres(c8checkleadat,sizeof(c8checkleadat), input_general.m_resfile,"(Check)Number",5); // ______ Extract info ______ // read info readleader(input_m_readfiles, atoi(c8checkleadat)-1); // made in readleader updatefile("scratchreslea",input_general.m_resfile); // made in readleader updatefile("scratchloglea",input_general.logfile); // ______ DONT PROCESS NULLFILE ______ // e readnull(input_m_readfiles); // updatefile("scratchresnull",input_general.m_resfile); // updatefile("scratchlognull",input_general.logfile); // // read data file info readdat(input_m_readfiles, atoi(c8checkleadat)-1); // update resfile updatefile("scratchresdat",input_general.m_resfile); // update logfile updatefile("scratchlogdat",input_general.logfile); break; // ______ ENVISAT ASAR ______ case SLC_ERS_N1: // [MA] (falls through to SLC_ASAR ) WARNING.print("ERS in Envisat format: (under development)"); case SLC_ASAR: case SLC_ASAR_AP_HH: case SLC_ASAR_AP_VV: INFO.reset();// make sure nothing in buffer INFO << "envisat_dump_header2doris.csh " << input_m_readfiles.datfile << " > scratchres_envisat" << endl << ends; char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("With following command the envisat header was read."); INFO.print(cmd); PROGRESS.print("Making system call to envisat_dump_header2doris.csh"); PROGRESS.print("(also requires envisat_dump_header program)"); system(cmd);// this does the work INFO.reset(); PROGRESS.print("Finished system call to envisat_dump_header2doris.csh"); // ___ update resfile ___ updatefile("scratchres_envisat",input_general.m_resfile); // ___ update logfile ___ updatefile("envisat_dump_header.log",input_general.logfile); break; //MA case SLC_ASAR_AP_HH: //MA INFO.reset();// make sure nothing in buffer //MA INFO << "envisat_dump_header2doris.csh " //MA << input_m_readfiles.datfile //MA << " > scratchres_envisat" << endl << ends; //MA // char cmd[512];// command string //MA strcpy(cmd, INFO.get_str()); //MA INFO.print("With following command the envisat header was read."); //MA INFO.print(cmd); //MA PROGRESS.print("Making system call to envisat_dump_header2doris.csh"); //MA PROGRESS.print("(also requires envisat_dump_header program)"); //MA system(cmd);// this does the work //MA INFO.reset(); //MA PROGRESS.print("Finished system call to envisat_dump_header2doris.csh"); //MA // ___ update resfile ___ //MA updatefile("scratchres_envisat",input_general.m_resfile); //MA // ___ update logfile ___ //MA updatefile("envisat_dump_header.log",input_general.logfile); //MA break; //MA //MA case SLC_ASAR_AP_VV: //MA INFO.reset();// make sure nothing in buffer //MA INFO << "envisat_dump_header2doris.csh " //MA << input_m_readfiles.datfile //MA << " > scratchres_envisat" << endl << ends; //MA //char cmd[512];// command string //MA strcpy(cmd, INFO.get_str()); //MA INFO.print("With following command the envisat header was read."); //MA INFO.print(cmd); //MA PROGRESS.print("Making system call to envisat_dump_header2doris.csh"); //MA PROGRESS.print("(also requires envisat_dump_header program)"); //MA system(cmd);// this does the work //MA INFO.reset(); //MA PROGRESS.print("Finished system call to envisat_dump_header2doris.csh"); //MA // ___ update resfile ___ //MA updatefile("scratchres_envisat",input_general.m_resfile); //MA // ___ update logfile ___ //MA updatefile("envisat_dump_header.log",input_general.logfile); //MA break; // ______ TSX COSAR ______ case SLC_TSX: INFO.reset();// make sure nothing in buffer INFO << "tsx_dump_header2doris.py " << input_m_readfiles.leaderfile // this should be XML file for TSX << " > scratchres_tsx" << endl << ends; //char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("With following command the TSX header was read."); INFO.print(cmd); PROGRESS.print("Making system call to tsx_dump_header2doris.py"); PROGRESS.print("(also requires python, gdal and XML libraries)"); status=system(cmd);// this does the work if (status != 0) // [MA] TODO make it a function { ERROR << "tsx_dump_header2doris.py: failed with exit code: " << status; PRINT_ERROR(ERROR.get_str()); throw(some_error); } INFO.reset(); PROGRESS.print("Finished system call to tsx_dump_header2doris.py"); // ___ update resfile ___ updatefile("scratchres_tsx",input_general.m_resfile); // ___ update logfile ___ // updatefile("tsx_dump_header.log",input_general.logfile); break; // ______ Radarsat-2 ______ case SLC_RS2: INFO.reset();// make sure nothing in buffer INFO << "rs2_dump_header2doris.py " << input_m_readfiles.leaderfile // this should be XML file for RS2 << " > scratchres_rs2" << endl << ends; //char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("With following command the Radarsat-2 header was read."); INFO.print(cmd); PROGRESS.print("Making system call to rs2_dump_header2doris.py"); PROGRESS.print("(also requires python, gdal and XML libraries)"); status=system(cmd);// this does the work if (status != 0) // [MA] TODO make it a function { ERROR << "rs2_dump_header2doris.py: failed with exit code: " << status; PRINT_ERROR(ERROR.get_str()) throw(some_error); } INFO.reset(); PROGRESS.print("Finished system call to rs2_dump_header2doris.py"); // ___ update resfile ___ updatefile("scratchres_rs2",input_general.m_resfile); // ___ update logfile ___ // updatefile("rs2_dump_header.log",input_general.logfile); break; // ______ Cosmo-Skymed ______ case SLC_CSK: INFO.reset();// make sure nothing in buffer INFO << "csk_dump_header2doris.py " << input_m_readfiles.datfile // this should be HD5 file for Cosmo-skymed << " > scratchres_csk" << endl << ends; //char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("With following command the Cosmo-skymed header was read."); INFO.print(cmd); PROGRESS.print("Making system call to csk_dump_header2doris.py"); PROGRESS.print("(also requires python, numpy and hd5 libraries)"); status=system(cmd);// this does the work if (status != 0) // [MA] TODO make it a function { ERROR << "csk_dump_header2doris.py: failed with exit code: " << status; PRINT_ERROR(ERROR.get_str()) throw(some_error); } INFO.reset(); PROGRESS.print("Finished system call to csk_dump_header2doris.py"); // ___ update resfile ___ updatefile("scratchres_csk",input_general.m_resfile); // ___ update logfile ___ // updatefile("csk_dump_header.log",input_general.logfile); break; // ______ GAMMA Processed SLC ______ // BO.20100916. case SLC_GAMMA: INFO.reset();// make sure nothing in buffer INFO << "gammaReadfiles.csh " << input_m_readfiles.leaderfile << " " // GAMMA process parameter file. << input_m_readfiles.volfile << " " // GAMMA system parameter file. << input_m_readfiles.datfile // GAMMA Focused SLC. << " > scratchres_gamma" << endl << ends; //char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("With following command the Gamma header was read."); INFO.print(cmd); PROGRESS.print("Making system call to gammaReadfiles.csh"); PROGRESS.print("(also requires python and awk)"); status=system(cmd);// this does the work if (status != 0) // [MA] TODO make it a function { ERROR << "gammaReadfiles.csh: failed with exit code: " << status; PRINT_ERROR(ERROR.get_str()) throw(some_error); } INFO.reset(); PROGRESS.print("Finished system call to gammaReadfiles.csh"); // ___ update resfile ___ updatefile("scratchres_gamma",input_general.m_resfile); // ___ update logfile ___ // updatefile("csk_dump_header.log",input_general.logfile); break; // END BO.20100916 default: PRINT_ERROR("M_READFILES step is impossible, check input and data for the sensor parameters.") throw(input_error);// exit } PROGRESS.print("Finished M_READFILES."); DEBUG.print("Time spent for reading files master:"); printcpu(); } // INFO<<"\n master res : " << input_general.m_resfile << "\n"; // INFO.print(); // MCC // ______Fill slcimage struct______ if (existed(input_general.m_resfile)) { // INFO<<"\n master res : " << input_general.m_resfile << " EXISTS!\n"; // INFO.print(); master.fillslcimage(input_general.m_resfile); interferogram.win = master.currentwindow; } // ______ Account for timing errors ______ if ( input_m_readfiles.az_timing_error !=0.0 || input_m_readfiles.rg_timing_error != 0.0) { PROGRESS.print("The correction values for master image timing errors are specified."); PROGRESS << "m_az_timing_error: " << input_m_readfiles.az_timing_error; PROGRESS.print(); PROGRESS << "m_rg_timing_error: " << input_m_readfiles.rg_timing_error; PROGRESS.print(); master.add_rg_t_error(input_m_readfiles.rg_timing_error); master.add_az_t_error(input_m_readfiles.az_timing_error); master.timingerror_flag = true; // (true) then time is updated manually [MA] } // ====== GET PRECISE ORBITS (GETORB): MASTER ====== // BK 15-Dec-2003 (moved before crop since required if dbow_geo if (input_general.process[pr_m_porbits]) { PROGRESS.print("Start M_PORBITS."); alreadyprocessed[pr_m_porbits]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing get precise orbits for master."; getanswer(); } // ______ Getorb does the real work ______ getorb(master,input_porbits,MASTERID); convertgetorbout(MASTERID); // ______ result of conv.getorb master ______ updatefile("scratchdatapoints",input_general.m_resfile); // ______ remove data section by leader ______ removedatleader(input_general.m_resfile); PROGRESS.print("Finished M_PORBITS."); DEBUG.print("Time spent for obtaining precise orbits master:"); printcpu(); } // ______ Get coefficients for orbit interpolation if data in file ______ //(alreadyprocessed[pr_m_readfiles] && isspace(input_porbits.m_orbdir[0]))) if (alreadyprocessed[pr_m_porbits] || alreadyprocessed[pr_m_readfiles]) masterorbit.initialize(input_general.m_resfile); // ______ Dump interpolated orbit if requested ______ // ______ also possible to dump orbit of readfiles with card M_ORB_DUMP ___ // ___ this returns if no orbit available ___ masterorbit.dumporbit(input_porbits,MASTERID); // ____ start added by HB ____ // ====== M_MORBITS ====== if (input_general.process[pr_m_morbits]) { PROGRESS.print("Start M_MORBITS."); alreadyprocessed[pr_m_morbits]=1; if (input_general.interactive) { cerr << "\nModifying orbits in master result file.\n"; getanswer(); } // ______ apply modification ______ modifyOrbits(input_m_morbits, input_general, MASTERID, input_ellips, master, master, masterorbit, masterorbit); disableOldOrbits(input_general.m_resfile); updatefile("scratchdatapoints",input_general.m_resfile); PROGRESS.print("Finished M_MORBITS."); } // ____ end added by HB ____ // ====== PROCESS DATAFILE CDROM: MASTER ====== if (input_general.process[pr_m_crop]) { PROGRESS.print("Start M_CROP."); alreadyprocessed[pr_m_crop]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing crop for master."; getanswer(); } // ______ Assume orbits loaded, use GEO card if present ______ if (input_m_crop.dbow_geo.pixhi != 0) { PROGRESS.print("Computing m_crop based on center lat/lon/height/width."); real8 centerline, centerpix; real8 centerphi = deg2rad(input_m_crop.dbow_geo.linelo/1e6-360.0); real8 centerlambda = deg2rad(input_m_crop.dbow_geo.linehi/1e6-360.0); real8 centerheight = input_general.terrain_height; DEBUG.print("Using height of HEIGHT card"); cn centerpos;// compute phi/lambda/h-->x,y,z centerpos = input_ellips.ell2xyz(centerphi,centerlambda,centerheight); DEBUG << "Converted M_DBOW_GEO phi,lambda,hei --> x,y,z: " << centerphi << ", " << centerlambda << ", " << centerheight << " --> " << centerpos.x << " " << centerpos.y << " " << centerpos.z; DEBUG.print(); DEBUG << "Center master SLC: x,y,z: " << master.approxcentreoriginal.x << " " << master.approxcentreoriginal.y << " " << master.approxcentreoriginal.z; DEBUG.print(); if (abs(master.approxcentreoriginal.x-centerpos.x)>60000.0)// 50km WARNING.print("M_DBOW_GEO: coordinates seem to be outside SLC area? (X)"); if (abs(master.approxcentreoriginal.y-centerpos.y)>60000.0)// 50km WARNING.print("M_DBOW_GEO: coordinates seem to be outside SLC area? (Y)"); if (abs(master.approxcentreoriginal.z-centerpos.z)>60000.0)// 50km WARNING.print("M_DBOW_GEO: coordinates seem to be outside SLC area? (Z)"); xyz2lp(centerline, centerpix, master, masterorbit, centerpos, 10, 1e-3);// MAXITERATIONS, CONVERGENCE_TIME DEBUG << "CROP: center line/pix: " << centerline << " " << centerpix; DEBUG.print(); int32 l0 = int32(centerline+0.5) - input_m_crop.dbow_geo.pixlo/2; int32 lN = l0 + input_m_crop.dbow_geo.pixlo - 1; int32 p0 = int32(centerpix+0.5) - input_m_crop.dbow_geo.pixhi/2; int32 pN = p0 + input_m_crop.dbow_geo.pixhi - 1; if (l0 < int32(master.currentwindow.linelo)) l0 = master.currentwindow.linelo; if (lN > int32(master.currentwindow.linehi)) lN = master.currentwindow.linehi; if (p0 < int32(master.currentwindow.pixlo)) p0 = master.currentwindow.pixlo; if (pN > int32(master.currentwindow.pixhi)) pN = master.currentwindow.pixhi; INFO << "DBOW from GEO: " << l0 << " " << lN << " " << p0 << " " << pN; INFO.print(); // ___ Simply fill dbow with it and it will be done correctly! ___ input_m_crop.dbow.linelo = uint(l0); input_m_crop.dbow.linehi = uint(lN); input_m_crop.dbow.pixlo = uint(p0); input_m_crop.dbow.pixhi = uint(pN); } // Batu - adding KML generation. // first we need to get the corner coordinates. // if dbow and dbow_geo is not set use currentwindow. if (input_m_crop.dbow.pixhi == 0 || input_m_crop.dbow.pixlo == 0 || input_m_crop.dbow.linehi ==0 || input_m_crop.dbow.linelo == 0) {// if fullscene dbow = currentwindow input_m_crop.dbow = master.currentwindow; } write_kml(input_ellips, input_m_crop.dbow, master, masterorbit, "m_crop.kml"); // Batu - End KML generation. // ______ Check if Gamma Focused Data. BO.20100916 if (master.sar_processor != SARPR_GAM) { // ______ For each sensor, of course the formats differ... ______ // ______ make sure radarsat_dump_data is called for ATLANTIS ______ switch (master.sensor) { case SLC_ALOS: char c8checkleadata[9]; // check vol met lea en dat readres(c8checkleadata,sizeof(c8checkleadata), input_general.m_resfile,"(Check)Number",5); palsar_fine_dump_data(input_general,input_m_crop, atoi(c8checkleadata)-1); updatefile("scratchres2raw",input_general.m_resfile); // update resfile break; // ______ JERS also CEOS? (falls through to ers) ______ case SLC_JERS: WARNING.print("JERS: Under development: is JERS really CEOS like ERS?"); // ______ ERS-1/2 ______ case SLC_ERS: switch (master.sar_processor) { case SARPR_VMP: // --- default, ESA SLCs --- // ______Get check with volumefile______ char c8checkleadat[9]; // check vol met lea en dat readres(c8checkleadat,sizeof(c8checkleadat), input_general.m_resfile,"(Check)Number",5); writeslc(input_general,input_m_crop, atoi(c8checkleadat)-1); updatefile("scratchres2raw",input_general.m_resfile); // update resfile break; case SARPR_ATL: // --- self processed from RAW --- radarsat_dump_data(input_general,input_m_crop);// updatefile("scratchres2raw",input_general.m_resfile); // update resfile WARNING.print("ATLANTIS data cropping not fully checked yet."); break; case SARPR_TUD: //break; default: PRINT_ERROR("unrecognized sar_processor.") throw(input_error);// exit } break; case SLC_ERS_N1: // [MA] (falls through to SLC_ASAR ) WARNING.print("ERS in Envisat format: (under development)"); // ______ ENVISAT ASAR ______ case SLC_ASAR: PROGRESS.print("System call to get ASAR SLC data (requires envisat_dump_data program)"); // ______ Data window must be set correctly ______ if (input_m_crop.dbow.linelo == 0 || input_m_crop.dbow.linehi == 0 || input_m_crop.dbow.pixlo == 0 || input_m_crop.dbow.pixhi == 0) { input_m_crop.dbow = master.currentwindow;// needs to be set correctly after readfiles } envisat_dump_data(input_m_crop); PROGRESS.print("Finished system call to envisat_dump_data"); updatefile("scratchres2raw",input_general.m_resfile); // update resfile break; case SLC_ASAR_AP_HH: PROGRESS.print("System call to get ASAR AP HH SLC data (requires envisat_dump_HH program)"); // ______ Data window must be set correctly ______ if (input_m_crop.dbow.linelo == 0 || input_m_crop.dbow.linehi == 0 || input_m_crop.dbow.pixlo == 0 || input_m_crop.dbow.pixhi == 0) { input_m_crop.dbow = master.currentwindow;// needs to be set correctly after readfiles } envisat_dump_HH(input_m_crop); PROGRESS.print("Finished system call to envisat_dump_HH"); updatefile("scratchres2raw",input_general.m_resfile); // update resfile break; case SLC_ASAR_AP_VV: PROGRESS.print("System call to get ASAR AP VV SLC data (requires envisat_dump_HH program)"); // ______ Data window must be set correctly ______ if (input_m_crop.dbow.linelo == 0 || input_m_crop.dbow.linehi == 0 || input_m_crop.dbow.pixlo == 0 || input_m_crop.dbow.pixhi == 0) { input_m_crop.dbow = master.currentwindow;// needs to be set correctly after readfiles } envisat_dump_VV(input_m_crop); PROGRESS.print("Finished system call to envisat_dump_VV"); updatefile("scratchres2raw",input_general.m_resfile); // update resfile break; // ______ TSX COSAR ______ case SLC_TSX: PROGRESS.print("System call to get TSX SLC/COSAR data (requires tsx_dump_data program)"); // ______ Data window must be set correctly ______ if (input_m_crop.dbow.linelo == 0 || input_m_crop.dbow.linehi == 0 || input_m_crop.dbow.pixlo == 0 || input_m_crop.dbow.pixhi == 0) { input_m_crop.dbow = master.currentwindow;// needs to be set correctly after readfiles } tsx_dump_data(input_m_crop); PROGRESS.print("Finished system call to tsx_dump_data"); updatefile("scratchres2raw",input_general.m_resfile); // update resfile break; // ______ RADARSAT-2 ______ case SLC_RS2: PROGRESS.print("System call to get Radarsat-2 data (requires rs2_dump_data program)"); // ______ Data window must be set correctly ______ if (input_m_crop.dbow.linelo == 0 || input_m_crop.dbow.linehi == 0 || input_m_crop.dbow.pixlo == 0 || input_m_crop.dbow.pixhi == 0) { input_m_crop.dbow = master.currentwindow;// needs to be set correctly after readfiles } rs2_dump_data(input_m_crop); PROGRESS.print("Finished system call to rs2_dump_data"); updatefile("scratchres2raw",input_general.m_resfile); // update resfile break; // ______ RADARSAT (detected by Product specifier) ______ case SLC_RSAT: radarsat_dump_data(input_general,input_m_crop);// updatefile("scratchres2raw",input_general.m_resfile); // update resfile WARNING.print("RSAT (Atlantis) not fully checked yet."); break; // ______ CSK ______ case SLC_CSK: PROGRESS.print("System call to get Cosmo-skymed data (requires csk_dump_data program)"); // ______ Data window must be set correctly ______ if (input_m_crop.dbow.linelo == 0 || input_m_crop.dbow.linehi == 0 || input_m_crop.dbow.pixlo == 0 || input_m_crop.dbow.pixhi == 0) { input_m_crop.dbow = master.currentwindow;// needs to be set correctly after readfiles } csk_dump_data(input_m_crop); PROGRESS.print("Finished system call to csk_dump_data"); updatefile("scratchres2raw",input_general.m_resfile); // update resfile break; default: PRINT_ERROR("M_CROP step is impossible, check input and data for the sensor parameters.") //PRINT_ERROR("impossible error (sensor not ERS JERS RSAT nor ASAR).") throw(input_error);// exit }// switch-case sensor } //if !SARPR_GAM else { INFO.print("SLC focused by Gamma."); gammaprocessor_crop(input_general,master, input_m_crop); PROGRESS.print("Finished data dump. (SARPR_USR)"); updatefile("scratchres2raw", input_general.m_resfile); //update resfile }//else SARPR_GAM PROGRESS.print("Finished M_CROP."); DEBUG.print("Time spent for writing raw format master:"); printcpu(); } //if m_crop // ______ Update info on image ______ if (alreadyprocessed[pr_m_crop]) { INFO.print(""); INFO.print("master: latest known processing stage: crop"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_m_crop]); master.updateslcimage(input_general.m_resfile,SECTIONID); } // ______ Generate magnitude preview of master SLC if requested ______ if (input_general.process[pr_m_crop]) { PROGRESS.print("calling preview for cropped master"); if (master.sensor!=SLC_RSAT && master.sensor!=SLC_ALOS && master.sensor!=SLC_TSX && master.sensor!=SLC_CSK ) // master, slave , resampled slave TODO: convert to preview function preview(input_general.preview, master.currentwindow.pixels(), master.formatflag, master.file, "master_mag.ras", "-e 0.5 -s 1.0 -q mag -o sunraster -b -c gray -M 2/10"); // general //TODO hi CSK // else if (master.sensor == SLC_ALOS) // preview(input_general.preview, // master.currentwindow.pixels(), master.formatflag, // master.file, "master_mag.ras", // "-e 0.5 -s 1.0 -q mag -o sunraster -b -c gray -M 2/2"); // ALOS VV/HH az/ra 5/5 m // else if (master.sensor == SLC_ALOS || master.sensor == SLC_TSX) // else if (master.sensor == SLC_ALOS || master.sensor == SLC_TSX || master.sensor == SLC_RS2 || master.sensor == SLC_CSK ) else if (master.sensor == SLC_ALOS || master.sensor == SLC_TSX || master.sensor == SLC_CSK ) preview(input_general.preview, master.currentwindow.pixels(), master.formatflag, master.file, "master_mag.ras", "-e 0.5 -s 1.0 -q mag -o sunraster -b -c gray -M 10/10"); // [MA] higher mlook to reduce filesize else//multilooking depends on beam preview(input_general.preview, master.currentwindow.pixels(), master.formatflag, master.file, "master_mag.ras", "-e 0.5 -s 1.0 -q mag -o sunraster -b -c gray -M 5/6"); } //____ RaffaeleNutricato START MODIFICATION SECTION 5 ______ // ====== OVERSAMPLE SLC: MASTER ====== if (input_general.process[pr_m_oversample]) { PROGRESS.print("Start M_OVS."); alreadyprocessed[pr_m_oversample]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing oversample for master."; getanswer(); } // ______Master and Slave oversampling ratios should be identical______ if (alreadyprocessed[pr_s_oversample]) { char checkmultilook [20]; int32 checkOsrRange; readres(checkmultilook,sizeof(checkmultilook), input_general.s_resfile,"Multilookfactor_range_direction:"); checkOsrRange = int32(1.0/atof(checkmultilook)+0.5); INFO << "m_ovs: " << input_m_oversample.OsrRange << "checkOsrRange: " << checkOsrRange ; INFO.print() ; if (input_m_oversample.OsrRange != checkOsrRange) WARNING.print("Master and Slave range oversampling factors should be identical!!!"); } if (alreadyprocessed[pr_s_oversample]) { char checkmultilook[20]; int32 checkOsrAzimuth; readres(checkmultilook,sizeof(checkmultilook), input_general.s_resfile,"Multilookfactor_azimuth_direction:"); checkOsrAzimuth = int32(1.0/atof(checkmultilook)+0.5); if (input_m_oversample.OsrAzimuth != checkOsrAzimuth) WARNING.print("Master and Slave azimuth oversampling factors should be identical!!!"); } // ______ Oversample master image ______ OversampleSLC(input_general,master,input_m_oversample,MASTERID); updatefile("scratchoversample",input_general.m_resfile); // update resfile PROGRESS.print("Finished M_OVS."); DEBUG.print("Time spent for oversampling master:"); printcpu(); } // ______ Update info on image ______ if (alreadyprocessed[pr_m_oversample]) { INFO.print(""); INFO.print("master: latest known processing stage: oversample"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_m_oversample]); master.updateslcimage(input_general.m_resfile,SECTIONID);// Bert Kampes, 29-Jul-2005 interferogram.win = master.currentwindow;// larger size } // ______ Generate magnitude preview of master SLC if requested ______ // -M 2/10 may make no sense after oversampling (depends). if (input_general.process[pr_m_oversample]) { PROGRESS.print("calling preview for oversampled master"); preview(input_general.preview, master.currentwindow.pixels(), master.formatflag, master.file, "master_ovs_mag.ras", "-e 0.5 -s 1.0 -q mag -o sunraster -b -c gray -M 4/4"); } // ____ start added by MA ____ /**************************************************************** * SIMAMP + MASTER TIMING ERROR * * * * Estimate timing error (azimuth, range) of master image * * based on simulated amplitude image (DEM based) * * * * 1. Simulate Amplitude * * 2. Correlate MASTER with DEM (SIM. Ampli.) for timing * * * ****************************************************************/ // ====== SIMULATE AMPLITUDE (MASTER) ====== if (input_general.process[pr_m_simamp]) { PROGRESS.print("Start SIMULATE AMPLITUDE."); alreadyprocessed[pr_m_simamp]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nSimulating master amplitude using DEM.\n"; getanswer(); } if (master.timingerror_flag == true ) // [MA] time is already updated, this will shift dem { WARNING << "SAM: M_AZ_T_ERROR = " << input_m_readfiles.az_timing_error << " sec." ; WARNING.print(); WARNING << "SAM: M_RG_T_ERROR = " << input_m_readfiles.rg_timing_error << " sec."; WARNING.print(); WARNING << "SAM: timing error cards are already set, please check. This will effect the simulation." ; WARNING.print(); } // if ( master.timingerror_flag == false || master.timingerror_flag == true ) // this has no effect, just want to keep it for the future [MA] // { sim_amplitude(input_general, input_ellips, input_m_simamp, master, masterorbit); // } // ______ Update log files ______ updatefile("scratchlogsimamp",input_general.logfile); updatefile("scratchressimamp",input_general.m_resfile); // PROGRESS.print("Finished SIMULATE AMPLITUDE."); DEBUG.print("Time spent for simulating master amplitude:"); printcpu(); } // ______ Fill input struct for ______ if (alreadyprocessed[pr_m_simamp]) // update simamp image { INFO.print(""); INFO.print("master: latest known processing stage: simamplitude"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_m_simamp]); simamp.fillproductinfo(input_general.m_resfile,SECTIONID); } // ______ Generate magnitude preview of simulated amlitude if requested ______ if (input_general.process[pr_m_simamp]) { PROGRESS.print("calling preview for simulated amplitude"); if (master.sensor!=SLC_RSAT) preview(input_general.preview, int32((simamp.win.pixels()/simamp.multilookP)), simamp.formatflag, simamp.file, "master_simamp.ras", "-e 1.0 -s 1.0 -q normal -o sunraster -b -c gray -M 2/10"); else//multilooking depends on beam preview(input_general.preview, int32((simamp.win.pixels()/simamp.multilookP)), simamp.formatflag, simamp.file, "master_simamp.ras", "-e 1.0 -s 1.0 -q normal -o sunraster -b -c gray -M 5/6"); } // ====== AMPLITUDE CORRELATION MASTER v.s. DEM (SIMULATED AMPLITUDE) // ====== in order to estimate master timing error if (input_general.process[pr_m_mtiming]) { PROGRESS.print("Start MASTER TIMING."); alreadyprocessed[pr_m_mtiming]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing for master timing error using correlation."; getanswer(); } // if ( master.timingerror_flag == true ) // [MA] manual timing error cards no direct effect on correlation but influences sim. amp. // { // WARNING << "MTE: M_AZ_T_ERROR and M_RG_T_ERROR cards are already set, please check. This does effect amplitude simulation step." ; // WARNING.print(); // } // TODO check that this is not necassary addition // ______Select method______ switch (input_m_mtiming.method) { case cc_magfft: mtiming_correlfft(input_m_mtiming, master, simamp); // infoimage break; case cc_magspace: mtiming_correl(input_m_mtiming, master, simamp); // infoimage break; default: PRINT_ERROR("impossible error for checked input.") throw(input_error);// exit } // ______ Update log files ______ updatefile("scratchlogmtiming",input_general.logfile); // if (existed("scratchlogmtiminghtr")) // if Nwin==1 we don't generate mode value in getmodeoffset { updatefile("scratchlogmtiminghtr",input_general.logfile); // MA mode table of offsets to .log: see coregistration.cc } updatefile("scratchresmtiming",input_general.m_resfile); // PROGRESS.print("Finished MASTER TIMING."); DEBUG.print("Time spent for master timing error estimation with correlation:"); printcpu(); } // ______ Read estimates to interferogram info struct ______ if (alreadyprocessed[pr_m_mtiming]) // [MA] { INFO.print(""); INFO.print("master: latest known processing stage: master timing"); if ( master.timingerror_flag == true ) // [MA] manual timing error cards no direct effect on correlation but influences sim. amp. { // if sb put timing cards and forgot to delete mtiming results, give warning since time is updated twice. WARNING << "MTE: M_AZ_T_ERROR and M_RG_T_ERROR cards are already set, please check. Make sure you don't update master time twice by accident." ; WARNING.print(); } char c6aztimingerrorlines[7]; // estimate azimuth timing error (lines) char c6rtimingerrorpixels[7]; // estimate range timing error (pixels) char c16aztimingerrorsec[17]; // estimate azimuth timing error (sec) char c16rtimingerrorsec[17]; // estimate range timing error (sec) readres(c6aztimingerrorlines,sizeof(c6aztimingerrorlines), input_general.m_resfile,"Coarse_correlation_translation_lines", 1); readres(c6rtimingerrorpixels,sizeof(c6rtimingerrorpixels), input_general.m_resfile,"Coarse_correlation_translation_pixels", 1); readres(c16aztimingerrorsec,sizeof(c16aztimingerrorsec), input_general.m_resfile,"Master_azimuth_timing_error", 1); readres(c16rtimingerrorsec,sizeof(c16rtimingerrorsec), input_general.m_resfile,"Master_range_timing_error", 1); DEBUG << "original master azimuth time : " << setprecision(16) << master.t_azi1 << "\t range time\t\t : " << master.t_range1; DEBUG.print(); DEBUG << "master azimuth time error lines: " << c6aztimingerrorlines << "\t\t range time error pixels: " << c6rtimingerrorpixels; DEBUG.print(); DEBUG << "master azimuth time error [sec]: " << atof(c16aztimingerrorsec) << "\t range time error [sec] : " << atof(c16rtimingerrorsec); DEBUG.print(); // _____ Update Master Azimuth and Range time _____ // master.add_offsetL2az_t_error(-atoi(c6aztimingerrorlines)); // read offsetL (master-dem) and update time (more precise?) // master.add_offsetP2rg_t_error(-atoi(c6rtimingerrorpixels)); // read offsetP (master-dem) and update time master.add_az_t_error(atof(c16aztimingerrorsec)); // read offsetL in seconds from the res filei and update master timing. master.add_rg_t_error(atof(c16rtimingerrorsec)); INFO << "updated master azimuth time : " << master.t_azi1 << " range time\t\t : " << master.t_range1; INFO.print(); // master.az_timing_error = -atoi(c6aztimingerrorlines); // (never used) [MA] // master.r_timing_error = -atoi(c6rtimingerrorpixels); // NOTE: time update is not necessary before reading orbital data // using getorb since we have extra-time. However if there // is shift in more than PRF (lines) than it is better to set M_AZ_T_ERROR cards to read orbits with updated timing. } // alreadyprocessed mtiming // ____ end added by MA ____ // ********************************************************* // **** start slave **** // ********************************************************* // ====== PROCESS INFOFILE CDROM: SLAVE ====== if (input_general.process[pr_s_readfiles]) { PROGRESS.print("Start S_READFILES."); // ___ update alreadyprocessed for this step ___ alreadyprocessed[pr_s_readfiles]=1; if (input_general.interactive) { cerr << "\nProcessing readfiles for slave."; getanswer(); } // ______ Select method for SLAVE READFILES______ switch (input_s_readfiles.sensor_id) { case SLC_ALOS: INFO.print("ALOS: Under development: is ALOS really CEOS/Atlantis like ERS?"); // ______ JERS also ceos? (falls through to ers) ______ case SLC_JERS: INFO.print("JERS: Under development: is JERS really CEOS like ERS?"); // ______ RSAT also CEOS? (falls through to ERS, account in reader) ______ case SLC_RSAT: WARNING.print("RSAT: CEOS reader seems to work."); // ______ ERS-1/2 ______ case SLC_ERS: // ______ Get checks with master volumefile ______ char c16checkvol1[17]; char c16checkvol2[17]; char c16checkvol3[17]; // check id of volume file if (alreadyprocessed[pr_m_readfiles]) { readres(c16checkvol1,sizeof(c16checkvol1), input_general.m_resfile,"Volume_ID:"); readres(c16checkvol2,sizeof(c16checkvol2), input_general.m_resfile,"Volume_identifier:"); readres(c16checkvol3,sizeof(c16checkvol3), input_general.m_resfile,"Volume_set_identifier:"); } // ______ Extract info ______ readvolume(input_s_readfiles, c16checkvol1, c16checkvol2, c16checkvol3); // created in readvolume updatefile("scratchresvol",input_general.s_resfile); // created in readvolume updatefile("scratchlogvol",input_general.logfile); // ______ Get check with slave volumefile ______ char c8checkleadat[9]; // check vol met lea en dat readres(c8checkleadat,sizeof(c8checkleadat), input_general.s_resfile,"(Check)Number",5); // ______ Extract info ______ readleader(input_s_readfiles, atoi(c8checkleadat)-1); updatefile("scratchreslea",input_general.s_resfile); // made in readleader updatefile("scratchloglea",input_general.logfile); // made in readleader // // DONT PROCESS NULLFILE //readnull(input_s_readfiles); //updatefile("scratchresnull",input_general.s_resfile); //updatefile("scratchlognull",input_general.logfile); // ___ read data file info ___ readdat(input_s_readfiles, atoi(c8checkleadat)-1); updatefile("scratchresdat",input_general.s_resfile); // update resfile updatefile("scratchlogdat",input_general.logfile); // update logfile break; // (this break was missing in v3.4, thanks Raffaele Nutricato) // ______ ENVISAT ASAR ______ case SLC_ERS_N1: // [MA] (falls through to SLC_ASAR ) WARNING.print("ERS in Envisat format: (under development)"); case SLC_ASAR: case SLC_ASAR_AP_HH: case SLC_ASAR_AP_VV: INFO.reset();// make sure nothing in buffer INFO << "envisat_dump_header2doris.csh " << input_s_readfiles.datfile << " > scratchres_envisat" << endl << ends; char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("With following command the envisat header was read."); INFO.print(cmd); PROGRESS.print("Making system call to envisat_dump_header2doris.csh"); PROGRESS.print("(also requires envisat_dump_header program)"); system(cmd);// This does the actual work INFO.reset(); PROGRESS.print("Finished system call to envisat_dump_header2doris.csh"); updatefile("scratchres_envisat",input_general.s_resfile); // update resfile updatefile("envisat_dump_header.log",input_general.logfile); // update logfile break; //MA case SLC_ASAR_AP_HH: //MA INFO.reset();// make sure nothing in buffer //MA INFO << "envisat_dump_header2doris.csh " //MA << input_s_readfiles.datfile //MA << " > scratchres_envisat" << endl << ends; //MA // char cmd[512];// command string //MA strcpy(cmd, INFO.get_str()); //MA INFO.print("With following command the envisat header was read."); //MA INFO.print(cmd); //MA PROGRESS.print("Making system call to envisat_dump_header2doris.csh"); //MA PROGRESS.print("(also requires envisat_dump_header program)"); //MA system(cmd);// This does the actual work //MA INFO.reset(); //MA PROGRESS.print("Finished system call to envisat_dump_header2doris.csh"); //MA updatefile("scratchres_envisat",input_general.s_resfile); // update resfile //MA updatefile("envisat_dump_header.log",input_general.logfile); // update logfile //MA break; //MA case SLC_ASAR_AP_VV: //MA INFO.reset();// make sure nothing in buffer //MA INFO << "envisat_dump_header2doris.csh " //MA << input_s_readfiles.datfile //MA << " > scratchres_envisat" << endl << ends; //MA //char cmd[512];// command string //MA strcpy(cmd, INFO.get_str()); //MA INFO.print("With following command the envisat header was read."); //MA INFO.print(cmd); //MA PROGRESS.print("Making system call to envisat_dump_header2doris.csh"); //MA PROGRESS.print("(also requires envisat_dump_header program)"); //MA system(cmd);// This does the actual work //MA INFO.reset(); //MA PROGRESS.print("Finished system call to envisat_dump_header2doris.csh"); //MA updatefile("scratchres_envisat",input_general.s_resfile); // update resfile //MA updatefile("envisat_dump_header.log",input_general.logfile); // update logfile //MA break; // ______ TSX COSAR ______ case SLC_TSX: INFO.reset();// make sure nothing in buffer INFO << "tsx_dump_header2doris.py " << input_s_readfiles.leaderfile // this should be XML file for TSX << " > scratchres_tsx" << endl << ends; // char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("With following command the TSX header was read."); INFO.print(cmd); PROGRESS.print("Making system call to tsx_dump_header2doris.py"); PROGRESS.print("(also requires python, gdal and XML libraries)"); status=system(cmd);// this does the work if (status != 0) // [MA] TODO make it a function { ERROR << "tsx_dump_header2doris.py: failed with exit code: " << status; PRINT_ERROR(ERROR.get_str()) throw(some_error); } INFO.reset(); PROGRESS.print("Finished system call to tsx_dump_header2doris.py"); // ___ update resfile ___ updatefile("scratchres_tsx",input_general.s_resfile); // ___ update logfile ___ // updatefile("tsx_dump_header.log",input_general.logfile); break; // ______ RADARSAT-2 ______ case SLC_RS2: INFO.reset();// make sure nothing in buffer INFO << "rs2_dump_header2doris.py " << input_s_readfiles.leaderfile // this should be XML file for RS2 << " > scratchres_rs2" << endl << ends; // char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("With following command the Radarsat-2 header was read."); INFO.print(cmd); PROGRESS.print("Making system call to rs2_dump_header2doris.py"); PROGRESS.print("(also requires python, gdal and XML libraries)"); status=system(cmd);// this does the work if (status != 0) // [MA] TODO make it a function { ERROR << "rs2_dump_header2doris.py: failed with exit code: " << status; PRINT_ERROR(ERROR.get_str()) throw(some_error); } INFO.reset(); PROGRESS.print("Finished system call to rs2_dump_header2doris.py"); // ___ update resfile ___ updatefile("scratchres_rs2",input_general.s_resfile); // ___ update logfile ___ // updatefile("rs2_dump_header.log",input_general.logfile); break; // ______ Cosmo-Skymed ______ case SLC_CSK: INFO.reset();// make sure nothing in buffer INFO << "csk_dump_header2doris.py " << input_s_readfiles.datfile // this should be HD5 file for Cosmo-skymed << " > scratchres_csk" << endl << ends; //char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("With following command the Cosmo-skymed header was read."); INFO.print(cmd); PROGRESS.print("Making system call to csk_dump_header2doris.py"); PROGRESS.print("(also requires python, numpy and hd5 libraries)"); status=system(cmd);// this does the work if (status != 0) // [MA] TODO make it a function { ERROR << "csk_dump_header2doris.py: failed with exit code: " << status; PRINT_ERROR(ERROR.get_str()) throw(some_error); } INFO.reset(); PROGRESS.print("Finished system call to csk_dump_header2doris.py"); // ___ update resfile ___ updatefile("scratchres_csk",input_general.s_resfile); // ___ update logfile ___ // updatefile("csk_dump_header.log",input_general.logfile); break; // ______ GAMMA Processed SLC ______ // BO.20100916. case SLC_GAMMA: INFO.reset();// make sure nothing in buffer INFO << "gammaReadfiles.csh " << input_s_readfiles.leaderfile << " " // GAMMA process parameter file. << input_s_readfiles.volfile << " " // GAMMA system parameter file. << input_s_readfiles.datfile // GAMMA Focused SLC. << " > scratchres_gamma" << endl << ends; //char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("With following command the Gamma header was read."); INFO.print(cmd); PROGRESS.print("Making system call to gammaReadfiles.csh"); PROGRESS.print("(also requires python and awk)"); status=system(cmd);// this does the work if (status != 0) // [MA] TODO make it a function { ERROR << "gammaReadfiles.csh: failed with exit code: " << status; PRINT_ERROR(ERROR.get_str()) throw(some_error); } INFO.reset(); PROGRESS.print("Finished system call to gammaReadfiles.csh"); // ___ update resfile ___ updatefile("scratchres_gamma",input_general.s_resfile); // ___ update logfile ___ // updatefile("csk_dump_header.log",input_general.logfile); break; // END BO.20100916 default: PRINT_ERROR("S_READFILES step is impossible, check input and data for the sensor parameters.") throw(input_error);// exit } PROGRESS.print("Finished S_READFILES."); DEBUG.print("Time spent for reading files slave:"); printcpu(); } // ______ Fill slcimage struct ______ if (existed(input_general.s_resfile)) slave.fillslcimage(input_general.s_resfile); // ______ Check sensor correspondence ______ if (alreadyprocessed[pr_m_readfiles] && alreadyprocessed[pr_s_readfiles]) if (master.sensor != slave.sensor) WARNING.print("master.sensor not same as slave.sensor (ERS-ERS, ASAR-ASAR only)"); // ______ Account for slave timing errors ______ if ( input_s_readfiles.az_timing_error !=0.0 || input_s_readfiles.rg_timing_error != 0.0) { PROGRESS.print("The correction values for slave image timing errors are specified."); PROGRESS << "s_az_timing_error: " << input_s_readfiles.az_timing_error; PROGRESS.print(); PROGRESS << "s_rg_timing_error: " << input_s_readfiles.rg_timing_error; PROGRESS.print(); slave.add_rg_t_error(input_s_readfiles.rg_timing_error); slave.add_az_t_error(input_s_readfiles.az_timing_error); slave.timingerror_flag = true; // (true) then time is updated manually [MA] } // BK 15-Dec-2003 (moved before crop since required if dbow_geo // ====== GET PRECISE ORBITS (GETORB): SLAVE ====== if (input_general.process[pr_s_porbits]) { PROGRESS.print("Start S_PORBITS."); alreadyprocessed[pr_s_porbits]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing get precise orbits for slave."; getanswer(); } // ______getorb does the real work______ getorb(slave,input_porbits,SLAVEID); convertgetorbout(SLAVEID); updatefile("scratchdatapoints",input_general.s_resfile); // result of conv.getorb slave removedatleader(input_general.s_resfile); // remove data section by leader PROGRESS.print("Finished S_PORBITS."); DEBUG.print("Time spent for obtaining precise orbits slave:"); printcpu(); } // ______ Get coefficients for orbit interpolation if data in file ______ // (alreadyprocessed[pr_s_readfiles] && isspace(input_porbits.s_orbdir[0]))) if (alreadyprocessed[pr_s_porbits] || alreadyprocessed[pr_s_readfiles]) slaveorbit.initialize(input_general.s_resfile); // ______ Dump interpolated orbit if requested ______ //if (alreadyprocessed[pr_s_porbits]) // ___ compbaseline return if no orbit available ___ // ______ also possible to dump orbit of readfiles with card M_ORB_DUMP ___ slaveorbit.dumporbit(input_porbits,SLAVEID); // ____ start added by HB ____ // ====== S_MORBITS [HB] ====== if (input_general.process[pr_s_morbits]) { PROGRESS.print("Start S_MORBITS."); alreadyprocessed[pr_s_morbits]=1; if (input_general.interactive) { cerr << "\nModifying orbits in slave result file.\n"; getanswer(); } // ______ apply modification ______ modifyOrbits(input_s_morbits, input_general, SLAVEID, input_ellips, slave, master, slaveorbit, masterorbit); disableOldOrbits(input_general.s_resfile); updatefile("scratchdatapoints",input_general.s_resfile); PROGRESS.print("Finished S_MORBITS."); } // ____ end added by HB ____ // --- initialize BASELINE class if orbits available --- // Bert Kampes, 04-Apr-2005 BASELINE baseline; baseline.model_parameters(master,slave,masterorbit,slaveorbit,input_ellips); // ______ Stdout baseline parametrizations as INFO ______ //if (alreadyprocessed[pr_m_porbits] && alreadyprocessed[pr_s_porbits]) // ___ compbaseline return if no orbit available ___ //compbaseline(input_general, master, slave, masterorbit, slaveorbit); for (register int32 i=0; ix,y,z //ell2xyz(input_ellips,centerpos,centerphi,centerlambda,centerheight); centerpos = input_ellips.ell2xyz(centerphi,centerlambda,centerheight); DEBUG << "Converted S_DBOW_GEO phi,lambda,hei --> x,y,z: " << centerphi << ", " << centerlambda << ", " << centerheight << " --> " << centerpos.x << " " << centerpos.y << " " << centerpos.z; DEBUG.print(); DEBUG << "Center slave SLC: x,y,z: " << slave.approxcentreoriginal.x << " " << slave.approxcentreoriginal.y << " " << slave.approxcentreoriginal.z; DEBUG.print(); if (abs(slave.approxcentreoriginal.x-centerpos.x)>60000.0)// 60km WARNING.print("S_DBOW_GEO: coordinates seem to be outside SLC area? (X)"); if (abs(slave.approxcentreoriginal.y-centerpos.y)>60000.0)// 60km WARNING.print("S_DBOW_GEO: coordinates seem to be outside SLC area? (Y)"); if (abs(slave.approxcentreoriginal.z-centerpos.z)>60000.0)// 60km WARNING.print("S_DBOW_GEO: coordinates seem to be outside SLC area? (Z)"); xyz2lp(centerline, centerpix, slave, slaveorbit, centerpos, 10, 1e-3);// MAXITERATIONS, CONVERGENCE_TIME DEBUG << "CROP: center line/pix: " << centerline << " " << centerpix; DEBUG.print(); int32 l0 = int32(centerline+0.5) - input_s_crop.dbow_geo.pixlo/2; int32 lN = l0 + input_s_crop.dbow_geo.pixlo - 1; int32 p0 = int32(centerpix+0.5) - input_s_crop.dbow_geo.pixhi/2; int32 pN = p0 + input_s_crop.dbow_geo.pixhi - 1; if (l0 < int32(slave.currentwindow.linelo)) l0 = slave.currentwindow.linelo; if (lN > int32(slave.currentwindow.linehi)) lN = slave.currentwindow.linehi; if (p0 < int32(slave.currentwindow.pixlo)) p0 = slave.currentwindow.pixlo; if (pN > int32(slave.currentwindow.pixhi)) pN = slave.currentwindow.pixhi; INFO << "DBOW from GEO: " << l0 << " " << lN << " " << p0 << " " << pN; INFO.print(); // ___ Simply fill dbow with it and it will be done correctly! ___ input_s_crop.dbow.linelo = uint(l0); input_s_crop.dbow.linehi = uint(lN); input_s_crop.dbow.pixlo = uint(p0); input_s_crop.dbow.pixhi = uint(pN); } // Batu - adding KML generation. if (input_s_crop.dbow.pixhi == 0 || input_s_crop.dbow.pixlo == 0 || input_s_crop.dbow.linehi == 0 || input_s_crop.dbow.linelo == 0 ) { // if dbow.pix_hi!=0 // first we need to get the corner coordinates. // if dbow and dbow_geo empty dbow = currentwindow input_s_crop.dbow = slave.currentwindow; } write_kml(input_ellips, input_s_crop.dbow, slave, slaveorbit, "s_crop.kml"); // Batu - End KML generation. // ______ Check if SARPR_GAM if (slave.sar_processor != SARPR_GAM) { // ______ For each sensor, of course the formats differ... ______ switch (slave.sensor) { // _____ start added by don case SLC_ALOS: char c8checkleadata[9]; // check vol met lea en dat readres(c8checkleadata,sizeof(c8checkleadata), input_general.s_resfile,"(Check)Number",5); palsar_fine_dump_data(input_general,input_s_crop, atoi(c8checkleadata)-1); updatefile("scratchres2raw",input_general.s_resfile); // update resfile break; // _____ end added by don // ______ JERS also CEOS? (falls through to ers) ______ case SLC_JERS: WARNING.print("JERS: Under development: is JERS really CEOS like ERS?"); // ______ ERS-1/2 ______ case SLC_ERS: switch (slave.sar_processor) { case SARPR_VMP: // --- default, ESA SLCs --- // ______ Get check with volumefile ______ char c8checkleadat[9]; // check vol met lea en dat readres(c8checkleadat,sizeof(c8checkleadat), input_general.s_resfile,"(Check)Number",5); writeslc(input_general,input_s_crop, atoi(c8checkleadat)-1); updatefile("scratchres2raw",input_general.s_resfile); // update resfile break; case SARPR_ATL: // --- self processed from RAW using Atlantis --- radarsat_dump_data(input_general,input_s_crop);// updatefile("scratchres2raw",input_general.s_resfile); // update resfile WARNING.print("ATLANTIS data cropping not fully checked yet."); break; case SARPR_TUD: //break; default: PRINT_ERROR("unrecognized sar_processor.") throw(input_error);// exit } break; // ______ ENVISAT ASAR ______ case SLC_ERS_N1: // [MA] (falls through to SLC_ASAR ) WARNING.print("ERS in Envisat format: (under development)"); case SLC_ASAR: PROGRESS.print("System call to get ASAR SLC data (requires envisat_dump_data program)"); // ______ Data window must be set correctly ______ if (input_s_crop.dbow.linelo == 0 || input_s_crop.dbow.linehi == 0 || input_s_crop.dbow.pixlo == 0 || input_s_crop.dbow.pixhi == 0) input_s_crop.dbow = slave.currentwindow; envisat_dump_data(input_s_crop); PROGRESS.print("Finished system call to envisat_dump_data"); updatefile("scratchres2raw",input_general.s_resfile); // update resfile break; case SLC_ASAR_AP_HH: PROGRESS.print("System call to get ASAR SLC data (requires envisat_dump_HH program)"); // ______ Data window must be set correctly ______ if (input_s_crop.dbow.linelo == 0 || input_s_crop.dbow.linehi == 0 || input_s_crop.dbow.pixlo == 0 || input_s_crop.dbow.pixhi == 0) input_s_crop.dbow = slave.currentwindow; envisat_dump_HH(input_s_crop); PROGRESS.print("Finished system call to envisat_dump_HH"); updatefile("scratchres2raw",input_general.s_resfile); // update resfile break; case SLC_ASAR_AP_VV: PROGRESS.print("System call to get ASAR SLC data (requires envisat_dump_VV program)"); // ______ Data window must be set correctly ______ if (input_s_crop.dbow.linelo == 0 || input_s_crop.dbow.linehi == 0 || input_s_crop.dbow.pixlo == 0 || input_s_crop.dbow.pixhi == 0) input_s_crop.dbow = slave.currentwindow; envisat_dump_VV(input_s_crop); PROGRESS.print("Finished system call to envisat_dump_VV"); updatefile("scratchres2raw",input_general.s_resfile); // update resfile break; // ______ TSX COSAR ______ case SLC_TSX: PROGRESS.print("System call to get TSX SLC/COSAR data (requires tsx_dump_data program)"); // ______ Data window must be set correctly ______ if (input_s_crop.dbow.linelo == 0 || input_s_crop.dbow.linehi == 0 || input_s_crop.dbow.pixlo == 0 || input_s_crop.dbow.pixhi == 0) { input_s_crop.dbow = slave.currentwindow;// needs to be set correctly after readfiles } tsx_dump_data(input_s_crop); PROGRESS.print("Finished system call to tsx_dump_data"); updatefile("scratchres2raw",input_general.s_resfile); // update resfile break; // ______ RADARSAT-2 ______ case SLC_RS2: PROGRESS.print("System call to get RADARSAT-2 data (requires rs2_dump_data program)"); // ______ Data window must be set correctly ______ if (input_s_crop.dbow.linelo == 0 || input_s_crop.dbow.linehi == 0 || input_s_crop.dbow.pixlo == 0 || input_s_crop.dbow.pixhi == 0) { input_s_crop.dbow = slave.currentwindow;// needs to be set correctly after readfiles } rs2_dump_data(input_s_crop); PROGRESS.print("Finished system call to rs2_dump_data"); updatefile("scratchres2raw",input_general.s_resfile); // update resfile break; // ______ RADARSAT ______ case SLC_RSAT: radarsat_dump_data(input_general,input_s_crop);// updatefile("scratchres2raw",input_general.s_resfile); // update resfile WARNING.print("RSAT (Atlantis) not fully checked yet."); break; // ______ COSMO-SKYMED ______ case SLC_CSK: PROGRESS.print("System call to get Cosmo-Skymed data (requires csk_dump_data program)"); // ______ Data window must be set correctly ______ if (input_s_crop.dbow.linelo == 0 || input_s_crop.dbow.linehi == 0 || input_s_crop.dbow.pixlo == 0 || input_s_crop.dbow.pixhi == 0) { input_s_crop.dbow = slave.currentwindow;// needs to be set correctly after readfiles } csk_dump_data(input_s_crop); PROGRESS.print("Finished system call to csk_dump_data"); updatefile("scratchres2raw",input_general.s_resfile); // update resfile break; default: PRINT_ERROR("S_CROP step is impossible, check input and data for the sensor parameters.") //PRINT_ERROR("impossible error (sensor not (J)ERS or ASAR).") throw(input_error);// exit }// if !SARPR_GAM } else { INFO.print("SLC focused by Gamma."); gammaprocessor_crop(input_general,slave, input_s_crop); PROGRESS.print("Finished data dump. (SARPR_GAM)"); updatefile("scratchres2raw", input_general.s_resfile); //update resfile }// else SARPR_GAM PROGRESS.print("Finished S_CROP."); DEBUG.print("Time spent for writing raw format slave:"); printcpu(); }// if s_crop // ______ Update info on image ______ if (alreadyprocessed[pr_s_crop]) { INFO.print(""); INFO.print("slave: latest known processing stage: crop"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_s_crop]); slave.updateslcimage(input_general.s_resfile,SECTIONID); } // ______ Check wavelength ______ if (alreadyprocessed[pr_m_crop] && alreadyprocessed[pr_s_crop]) { if (abs(master.wavelength-slave.wavelength) > EPS) WARNING.print("wavelength master not equal to wavelength slave."); } // ______ Generate magnitude preview if requested ______ if (input_general.process[pr_s_crop]) { PROGRESS.print("calling preview for cropped slave"); if (slave.sensor!=SLC_RSAT && slave.sensor!=SLC_ALOS && slave.sensor!=SLC_TSX && slave.sensor!=SLC_CSK) // RS2 preview(input_general.preview, slave.currentwindow.pixels(), slave.formatflag, slave.file, "slave_mag.ras", "-e 0.5 -s 1.0 -q mag -o sunraster -b -c gray -M 2/10"); else if (slave.sensor == SLC_ALOS || slave.sensor == SLC_TSX || slave.sensor == SLC_CSK) preview(input_general.preview, slave.currentwindow.pixels(), slave.formatflag, slave.file, "slave_mag.ras", "-e 0.5 -s 1.0 -q mag -o sunraster -b -c gray -M 10/10"); // [MA] higher mlook to reduce filesize else// multilooking depends on beam preview(input_general.preview, slave.currentwindow.pixels(), slave.formatflag, slave.file, "slave_mag.ras", "-e 0.5 -s 1.0 -q mag -o sunraster -b -c gray -M 5/6"); } //____RaffaeleNutricato START MODIFICATION SECTION 6 // ====== OVERSAMPLE SLC: SLAVE ====== // For the moment only along the range direction if (input_general.process[pr_s_oversample]) { PROGRESS.print("Start S_OVS."); alreadyprocessed[pr_s_oversample]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing oversample for slave."; getanswer(); } // ______Master and Slave oversampling ratioes should be identical______ if (alreadyprocessed[pr_m_oversample]) { char checkmultilook[20]; int32 checkOsrRange; if (alreadyprocessed[pr_m_simamp]) // simamp also has Multilookfactor information. Not to mix up ml factor with oversample ML { readres(checkmultilook,sizeof(checkmultilook), input_general.m_resfile,"Multilookfactor_range_direction:",0,1); // MA skip once : TODO unique step entry } else { readres(checkmultilook,sizeof(checkmultilook), input_general.m_resfile,"Multilookfactor_range_direction:"); // MA no simamp no skip line } checkOsrRange = int32(1.0/atof(checkmultilook)+0.5); if (input_s_oversample.OsrRange != checkOsrRange) WARNING.print("Master and Slave range oversampling factors should be identical!!!"); } if (alreadyprocessed[pr_m_oversample]) { char checkmultilook[20]; int32 checkOsrAzimuth; if (alreadyprocessed[pr_m_simamp]) { readres(checkmultilook,sizeof(checkmultilook), input_general.m_resfile,"Multilookfactor_azimuth_direction:",0,1); // MA skip once } else { readres(checkmultilook,sizeof(checkmultilook), input_general.m_resfile,"Multilookfactor_azimuth_direction:"); // MA } checkOsrAzimuth = int32(1.0/atof(checkmultilook)+0.5); if (input_s_oversample.OsrAzimuth != checkOsrAzimuth) WARNING.print("Master and Slave azimuth oversampling factors should be identical!!!"); } // ______ Oversample slave image ______ OversampleSLC(input_general,slave,input_s_oversample,SLAVEID); updatefile("scratchoversample",input_general.s_resfile); // update resfile PROGRESS.print("Finished S_OVS."); DEBUG.print("Time spent for oversampling slave:"); printcpu(); } // ______ Update info on image ______ if (alreadyprocessed[pr_s_oversample]) { INFO.print(""); INFO.print("slave: latest known processing stage: oversample"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_s_oversample]); slave.updateslcimage(input_general.s_resfile,SECTIONID);// Bert Kampes, 29-Jul-2005 } // ______ Generate magnitude preview of slave SLC if requested ______ // -M 2/10 make no sense after oversampling!! (depends on factors..) if (input_general.process[pr_s_oversample]) { PROGRESS.print("calling preview for oversampled slave"); preview(input_general.preview, slave.currentwindow.pixels(), slave.formatflag, slave.file, "slave_ovs_mag.ras", "-e 0.5 -s 1.0 -q mag -o sunraster -b -c gray -M 4/4"); } //____RaffaeleNutricato END MODIFICATION SECTION 6 // ********************************************************* // **** start interferogram **** // ********************************************************* // ====== COARSE CO-REGISTRATION BASED ON ORBITS ====== if (input_general.process[pr_i_coarse]) { PROGRESS.print("Start COARSE_ORB."); alreadyprocessed[pr_i_coarse]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing coarse co-registration based on orbits."; getanswer(); } coarseporbit(input_ellips, master, slave, masterorbit, slaveorbit, baseline); // ______ Update log files ______ updatefile("scratchlogcoarse",input_general.logfile); // updatefile("scratchrescoarse",input_general.i_resfile); // PROGRESS.print("Finished COARSE_ORB."); DEBUG.print("Time spent for coarse coregistration with orbits:"); printcpu(); } // ______ Read estimates to interferogram info struct ______ if (alreadyprocessed[pr_i_coarse]) { INFO.print(""); INFO.print("ifg: latest known processing stage: coarse (orbits)"); char c6initoffL[7]; // initial offset lines char c6initoffP[7]; // initial offset pixels readres(c6initoffL,sizeof(c6initoffL),input_general.i_resfile, "Coarse_orbits_translation_lines:", 0); readres(c6initoffP,sizeof(c6initoffP),input_general.i_resfile, "Coarse_orbits_translation_pixels:", 0); slave.coarseoffsetL = atoi(c6initoffL); // used as initial value slave.coarseoffsetP = atoi(c6initoffP); // used as initial value slave.coarseorbitoffsetL = atoi(c6initoffL); // to estimate timing error[FvL] slave.coarseorbitoffsetP = atoi(c6initoffP); // to estimate timing error[FvL] //courseoffset is updated by coarse correlation, therefore extra //parameter courseorbitoffset [FvL] master.coarseoffsetL = -slave.coarseoffsetL; // (never used) master.coarseoffsetP = -slave.coarseoffsetP; // azifilt // ______ Corners of current slave in master coordinate system ______ const int32 sL0 = slave.currentwindow.linelo - slave.coarseoffsetL; const int32 sLN = slave.currentwindow.linehi - slave.coarseoffsetL; const int32 sP0 = slave.currentwindow.pixlo - slave.coarseoffsetP; const int32 sPN = slave.currentwindow.pixhi - slave.coarseoffsetP; interferogram.win.linelo = max(sL0,int32(master.currentwindow.linelo)); interferogram.win.linehi = min(sLN,int32(master.currentwindow.linehi)); interferogram.win.pixlo = max(sP0,int32(master.currentwindow.pixlo)); interferogram.win.pixhi = min(sPN,int32(master.currentwindow.pixhi)); } // ====== COARSE CO-REGISTRATION BASED ON CORRELATION ====== if (input_general.process[pr_i_coarse2]) { PROGRESS.print("Start COARSE_CORR."); alreadyprocessed[pr_i_coarse2]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing coarse co-registration with correlation."; getanswer(); } // ______ If requested: use estimated offsets from orbits as initial ______ if (input_i_coarsecorr.initoffsetL == NaN && input_i_coarsecorr.initoffsetL == NaN) // flag for using answer of coarse1 { input_i_coarsecorr.initoffsetL = slave.coarseoffsetL; input_i_coarsecorr.initoffsetP = slave.coarseoffsetP; } // ______Select method______ switch (input_i_coarsecorr.method) { case cc_magfft: coarsecorrelfft(input_i_coarsecorr, master, slave); // infoimage break; case cc_magspace: coarsecorrel(input_i_coarsecorr, master, slave); // infoimage break; default: PRINT_ERROR("impossible error for checked input.") throw(input_error);// exit } // ______ Update log files ______ updatefile("scratchlogcoarse2",input_general.logfile); // updatefile("scratchrescoarse2",input_general.i_resfile); // PROGRESS.print("Finished COARSE_CORR."); DEBUG.print("Time spent for coarse coregistration with correlation:"); printcpu(); } // ______ Read estimates to interferogram info struct ______ if (alreadyprocessed[pr_i_coarse2]) { INFO.print(""); INFO.print("ifg: latest known processing stage: coarse (corr)"); char c6initoffL[7]; // initial offset lines char c6initoffP[7]; // initial offset pixels readres(c6initoffL,sizeof(c6initoffL),input_general.i_resfile, "Coarse_correlation_translation_lines:", 0); readres(c6initoffP,sizeof(c6initoffP),input_general.i_resfile, "Coarse_correlation_translation_pixels:", 0); slave.coarseoffsetL = atoi(c6initoffL); // used as initial value slave.coarseoffsetP = atoi(c6initoffP); // used as initial value master.coarseoffsetL = -slave.coarseoffsetL; // (never used) master.coarseoffsetP = -slave.coarseoffsetP; // azifilt //MCC char c6slopeP[25]; readres(c6slopeP,sizeof(c6slopeP),input_general.i_resfile, "Slope_CoarseCorr_pixels:", 0); slave.slopeP = atof(c6slopeP); // initial slope pixels char c6slopeL[25]; readres(c6slopeL,sizeof(c6slopeL),input_general.i_resfile, "Slope_CoarseCorr_lines:", 0); slave.slopeL = atof(c6slopeL); // initial slope lines char c6realoffsetL[25]; readres(c6realoffsetL,sizeof(c6realoffsetL),input_general.i_resfile, "Initial_Offset_CoarseCorr_lines:", 0); slave.realoffsetL = atof(c6realoffsetL); // initial offset pixels char c6realoffsetP[25]; readres(c6realoffsetP,sizeof(c6realoffsetP),input_general.i_resfile, "Initial_Offset_CoarseCorr_pixels:", 0); slave.realoffsetP = atof(c6realoffsetP); // initial offset lines //MCC // ______ corners of current slave in master coordinate system ______ const int32 sL0 = slave.currentwindow.linelo - slave.coarseoffsetL; const int32 sLN = slave.currentwindow.linehi - slave.coarseoffsetL; const int32 sP0 = slave.currentwindow.pixlo - slave.coarseoffsetP; const int32 sPN = slave.currentwindow.pixhi - slave.coarseoffsetP; // fill these as well to be sure ? (BK) interferogram.win.linelo = max(sL0,int32(master.currentwindow.linelo)); interferogram.win.linehi = min(sLN,int32(master.currentwindow.linehi)); interferogram.win.pixlo = max(sP0,int32(master.currentwindow.pixlo)); interferogram.win.pixhi = min(sPN,int32(master.currentwindow.pixhi)); } // ====== FILTER AZIMUTH: MASTER (and SLAVE directly after) ====== // ______ Do this step here, use coarse corr for fDC polynomial ______ if (input_general.process[pr_m_filtazi]) { PROGRESS.print("Start FILTAZI (master)."); alreadyprocessed[pr_m_filtazi]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing filtering azimuth direction for master."; getanswer(); } // ______ only master; output file name of master ______ strcpy(input_ms_filtazi.foname,input_ms_filtazi.fomaster); azimuthfilter(input_general,input_ms_filtazi,master,slave); updatefile("scratchresfiltazi",input_general.m_resfile); // update resfile updatefile("scratchlogfiltazi",input_general.logfile); // update logfile PROGRESS.print("Finished FILTAZI for master."); DEBUG.print("Time spent for azimuth filtering master:"); printcpu(); } // ______ Update info of master, current filename, format, etc. ______ if (alreadyprocessed[pr_m_filtazi]) { INFO.print(""); INFO.print("master: latest known processing stage: azimuth filtered"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_m_filtazi]); master.updateslcimage(input_general.m_resfile,SECTIONID); } // ====== FILTER AZIMUTH: SLAVE ====== if (input_general.process[pr_s_filtazi]) { PROGRESS.print("Start FILTAZI (slave)."); alreadyprocessed[pr_s_filtazi]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing filtering azimuth direction for slave."; getanswer(); } // ______ only slave ... ______ strcpy(input_ms_filtazi.foname,input_ms_filtazi.foslave); azimuthfilter(input_general,input_ms_filtazi,slave,master); updatefile("scratchresfiltazi",input_general.s_resfile); // update resfile updatefile("scratchlogfiltazi",input_general.logfile); // update logfile PROGRESS.print("Finished FILTAZI slave."); DEBUG.print("Time spent for azimuth filtering slave:"); printcpu(); } // ______ Update info of slave, filename current image, format, etc. ______ if (alreadyprocessed[pr_s_filtazi]) { INFO.print(""); INFO.print("slave: latest known processing stage: azimuth filtered"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_s_filtazi]); slave.updateslcimage(input_general.s_resfile,SECTIONID); } // ====== FILTER RANGE: MASTER&SLAVE porbits ====== // ______ Only one step for master and slave, after coarse coreg. ______ // ______ Method based on orbits only. (For adaptive method see after resampling) ______ // ______ Update of struct should only occur for method porbits, ______ // ______ so first find that out (BK 26-mar-01) ______ if (input_general.process[pr_m_filtrange] && input_ms_filtrange.method==rf_porbits) { PROGRESS.print("Start FILTRANGE (porbits)."); alreadyprocessed[pr_m_filtrange]=1; // update alreadypr. alreadyprocessed[pr_s_filtrange]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nRange filtering based on orbits master and slave."; getanswer(); } // ______ Filter routine ______ rangefiltporbits(input_general,input_ms_filtrange,input_ellips, master,slave,masterorbit,slaveorbit); // ______ Update log files ______ updatefile("scratchlogfiltrange",input_general.logfile); updatefile("scratchresMfiltrange",input_general.m_resfile); updatefile("scratchresSfiltrange",input_general.s_resfile); PROGRESS.print("Finished FILTRANGE."); DEBUG.print("Time spent for range filtering:"); printcpu(); } // ______ Update info of master, size interferogram ______ // ______ Only update if method is porbits ______ if (alreadyprocessed[pr_m_filtrange]) { char c10rfmethod[11]; // method readres(c10rfmethod,sizeof(c10rfmethod),input_general.m_resfile, "Method_rangefilt:", 0); if (!strcmp(c10rfmethod,"porbits")) { INFO.print(""); INFO.print("master: latest known processing stage: filtrange (orbits)"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_m_filtrange]); master.updateslcimage(input_general.m_resfile,SECTIONID); // ______ cut out overlay master slave exact ______ interferogram.win = master.currentwindow; } } // ______ Update info of slave, size interferogram ______ if (alreadyprocessed[pr_s_filtrange]) // same time as _m_ { char c10rfmethod[11]; // method readres(c10rfmethod,sizeof(c10rfmethod),input_general.s_resfile, "Method_rangefilt:", 0); if (!strcmp(c10rfmethod,"porbits")) { INFO.print(""); INFO.print("slave: latest known processing stage: filtrange (orbits)"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_s_filtrange]); slave.updateslcimage(input_general.s_resfile,SECTIONID); } } // ====== FINE CO-REGISTRATION ====== if (input_general.process[pr_i_fine]) { PROGRESS.print("Start FINE."); alreadyprocessed[pr_i_fine]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing fine co-registration."; getanswer(); } // ______ If requested: Read result coarse from file ______ if (input_i_fine.initoffsetL == NaN && // flag for using input_i_fine.initoffsetL == NaN) // asnwer of coarse2 { input_i_fine.initoffsetL = slave.coarseoffsetL; input_i_fine.initoffsetP = slave.coarseoffsetP; } //MCC //Computes a radar-coded DEM using the code of demassist // setunspecified(input_i_fine.firefdem); //testing // setunspecified(input_i_fine.forefdem); //testing if (input_i_fine.method == fc_coherence && specified( input_i_fine.firefdem)) { input_comprefdem input_fine_dem; setunspecified(input_fine_dem.firefdem); // check later, mandatory setunspecified(input_fine_dem.fodemi); // check later, then set default //_____ added by FvL setunspecified(input_fine_dem.foh2ph); // check later, then set default // ____ end added by FvL setunspecified(input_fine_dem.forefdemhei); // check later, then set default strcpy(input_fine_dem.fodem,"demcrop.raw"); strcpy(input_fine_dem.forefdem, "refPhaseDEM.raw" ); strcpy(input_fine_dem.firefdem, input_i_fine.firefdem); INFO << "file In : " << input_fine_dem.firefdem << endl; INFO.print(); input_fine_dem.iformatflag = input_i_fine.iformatflag; input_fine_dem.demrows = input_i_fine.demrows; input_fine_dem.demcols = input_i_fine.demcols; input_fine_dem.demdeltalat = input_i_fine.demdeltalat; input_fine_dem.demdeltalon = input_i_fine.demdeltalon; input_fine_dem.demlatleftupper = input_i_fine.demlatleftupper; input_fine_dem.demlonleftupper = input_i_fine.demlonleftupper; input_fine_dem.demnodata = input_i_fine.demnodata; input_fine_dem.includerefpha = false; input_fine_dem.isCCC = true; productinfo dummyinterferogram = interferogram; dummyinterferogram.multilookL = 1; dummyinterferogram.multilookP = 1; dummyinterferogram.win = master.currentwindow; try { radarcodedem(input_general, input_ellips, input_fine_dem, master, slave,dummyinterferogram, masterorbit, slaveorbit); strcpy(input_i_fine.forefdem, input_fine_dem.forefdem); } catch (int e) { WARNING << "I could NOT radar-code your DEM. Exception: " << e << endl; WARNING <<"Continuing CCC without DEM \n"; WARNING.print(); setunspecified(input_i_fine.forefdem); } } // INFO <<"master.Ks" << master.Ks; // INFO.print(); finecoreg(input_i_fine, master, slave,input_ellips, masterorbit, slaveorbit, baseline); // ______ Update log files ______ updatefile("scratchlogfine",input_general.logfile); updatefile("scratchresfine",input_general.i_resfile); PROGRESS.print("Finished FINE."); DEBUG.print("Time spent for fine coregistration:"); printcpu(); // ______ Plot if requested, use gmt script: plotoffsets ______ INFO.reset();// make sure nothing in buffer INFO << "plotoffsets " << input_general.i_resfile << " " << master.currentwindow.linelo << " " << master.currentwindow.linehi << " " << master.currentwindow.pixlo << " " << master.currentwindow.pixhi << " " << input_i_fine.plotthreshold << " "; // ______ optional 7th argument for background ______ if (input_i_fine.plotmagbg) INFO << master.file; INFO << "&" << endl << ends; char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("Following command plots the estimated offset vectors:"); INFO.print(cmd); // ______ Actual make the call if requested ______ if (input_i_fine.plotoffsets) system(cmd); } // _______ Fill oversampling factor for coregpm routine ______ //uint osfactor = 32;// oversamplingsfactor if (alreadyprocessed[pr_i_fine]) { INFO.print(""); INFO.print("ifg: latest known processing stage: fine"); //char c4osfactor[4]; //readres(c4osfactor,sizeof(c4osfactor),input_general.i_resfile, // "Oversampling", 1); //osfactor = uint(atoi(c4osfactor)); } // ____ start added by FvL ____ // ====== RELATIVE TIMING ERROR ====== if (input_general.process[pr_i_timing]) { PROGRESS.print("Start TIMING."); alreadyprocessed[pr_i_timing]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nComputation relative timing error.\n"; getanswer(); } // _____ Compute master-slave timing errors _____ ms_timing_error(master, input_general.i_resfile, input_i_timing, slave.coarseorbitoffsetL,slave.coarseorbitoffsetP); // ______ Update log files ______ updatefile("scratchlogtiming",input_general.logfile); updatefile("scratchrestiming",input_general.i_resfile); PROGRESS.print("Finished TIMING."); DEBUG.print("Time spent for computation relative timing error:"); printcpu(); } // ______ Read estimates to slave info struct ______ if (alreadyprocessed[pr_i_timing]) { char c6aztimingerrorlines[7]; // estimate azimuth timing error (lines) char c6rtimingerrorpixels[7]; // estimate range timing error (pixels) char c16aztimingerrorsec[17]; // estimate azimuth timing error (sec) char c16rtimingerrorsec[17]; // estimate range timing error (sec) readres(c6aztimingerrorlines,sizeof(c6aztimingerrorlines), input_general.i_resfile,"Estimated_azimuth_timing_error_lines", 1); readres(c6rtimingerrorpixels,sizeof(c6rtimingerrorpixels), input_general.i_resfile,"Estimated_range_timing_error_pixels", 1); readres(c16aztimingerrorsec,sizeof(c16aztimingerrorsec), input_general.i_resfile,"Estimated_azimuth_timing_error_sec", 1); readres(c16rtimingerrorsec,sizeof(c16rtimingerrorsec), input_general.i_resfile,"Estimated_range_timing_error_sec", 1); slave.add_az_t_error(atof(c16aztimingerrorsec)); slave.add_rg_t_error(atof(c16rtimingerrorsec)); slave.az_timing_error = atoi(c6aztimingerrorlines); slave.r_timing_error = atoi(c6rtimingerrorpixels); INFO << atof(c16aztimingerrorsec); INFO.print(); INFO << atof(c16rtimingerrorsec); INFO.print(); INFO << atoi(c6aztimingerrorlines); INFO.print(); INFO << atoi(c6rtimingerrorpixels); INFO.print(); } // ====== DEM ASSISTED COREGISTRATION ====== if (input_general.process[pr_i_demassist]) { PROGRESS.print("Start DEMASSIST."); alreadyprocessed[pr_i_demassist]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nCoregistration using DEM.\n"; getanswer(); } demassist(input_general, input_ellips, input_i_demassist, master, slave, masterorbit, slaveorbit); // ______ Update log files ______ updatefile("scratchlogdemassist",input_general.logfile); updatefile("scratchresdemassist",input_general.i_resfile); PROGRESS.print("Finished DEMASSIST."); DEBUG.print("Time spent for DEM assisted coregistration:"); printcpu(); } // ______ Read estimates to slave info struct ______ if (alreadyprocessed[pr_i_demassist]) { char c16slavel00[17]; // delta line slave00 char c16slavep00[17]; // delta pixel slave00 char c16slavel0N[17]; // delta line slave0N char c16slavep0N[17]; // delta pixel slave0N char c16slavelN0[17]; // delta line slaveN0 char c16slavepN0[17]; // delta pixel slaveN0 char c16slavelNN[17]; // delta line slaveNN char c16slavepNN[17]; // delta pixel slaveNN readres(c16slavel00,sizeof(c16slavel00), input_general.i_resfile,"Deltaline_slave00_dem:", 0); readres(c16slavep00,sizeof(c16slavep00), input_general.i_resfile,"Deltapixel_slave00_dem:", 0); readres(c16slavel0N,sizeof(c16slavel0N), input_general.i_resfile,"Deltaline_slave0N_dem:", 0); readres(c16slavep0N,sizeof(c16slavep0N), input_general.i_resfile,"Deltapixel_slave0N_dem:", 0); readres(c16slavelN0,sizeof(c16slavelN0), input_general.i_resfile,"Deltaline_slaveN0_dem:", 0); readres(c16slavepN0,sizeof(c16slavepN0), input_general.i_resfile,"Deltapixel_slaveN0_dem:", 0); readres(c16slavelNN,sizeof(c16slavelNN), input_general.i_resfile,"Deltaline_slaveNN_dem:", 0); readres(c16slavepNN,sizeof(c16slavepNN), input_general.i_resfile,"Deltapixel_slaveNN_dem:", 0); slave.add_offsetl00(atof(c16slavel00)); slave.add_offsetp00(atof(c16slavep00)); slave.add_offsetl0N(atof(c16slavel0N)); slave.add_offsetp0N(atof(c16slavep0N)); slave.add_offsetlN0(atof(c16slavelN0)); slave.add_offsetpN0(atof(c16slavepN0)); slave.add_offsetlNN(atof(c16slavelNN)); slave.add_offsetpNN(atof(c16slavepNN)); INFO << atof(c16slavel00); INFO.print(); INFO << atof(c16slavep00); INFO.print(); INFO << atof(c16slavel0N); INFO.print(); INFO << atof(c16slavep0N); INFO.print(); INFO << atof(c16slavelN0); INFO.print(); INFO << atof(c16slavepN0); INFO.print(); INFO << atof(c16slavelNN); INFO.print(); INFO << atof(c16slavepNN); INFO.print(); } // ____ end added by FvL ____ // ====== COMPUTATION CO-REGISTRATION PARAMETERS ====== if (input_general.process[pr_i_coregpm]) { PROGRESS.print("Start COREGPM."); alreadyprocessed[pr_i_coregpm]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing computation of co-registration parameters."; getanswer(); } //coregpm(master, input_general.i_resfile, input_i_coregpm, osfactor); coregpm(master, slave, input_general.i_resfile, input_i_coregpm, alreadyprocessed[pr_i_demassist]); // ______ Update log files ______ updatefile("scratchlogcpm",input_general.logfile); updatefile("scratchrescpm",input_general.i_resfile); PROGRESS.print("Finished COREGPM."); DEBUG.print("Time spent for computation of coregistration parameters:"); printcpu(); // ______ Plot if requested, use gmt script: plotcpm ______ INFO.reset();// make sure nothing in buffer INFO << "plotcpm CPM_Data " << master.currentwindow.linelo << " " << master.currentwindow.linehi << " " << master.currentwindow.pixlo << " " << master.currentwindow.pixhi << " "; // ______ optional 6th argument for background ______ if (input_i_coregpm.plotmagbg) INFO << master.file; // not ok? BK 27-Jun-00: omem << "&" << ends; INFO << "&" << endl << ends; char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("Next command will plot solution:"); INFO.print(cmd); // ______ Actual make the call if requested ______ if (input_i_coregpm.plot) system(cmd); } // ______ Fill matrix coefficients, interferogram info struct ______ // ______ Approximate overlap in master system in interf. window ______ if (alreadyprocessed[pr_i_coregpm]) { INFO.print(""); INFO.print("ifg: latest known processing stage: coregpm"); char c10offL[11]; readres(c10offL,sizeof(c10offL),input_general.i_resfile,"Degree_cpm:"); int32 degreecpm = atoi(c10offL); coeff_cpmL = readcoeff(input_general.i_resfile, "Estimated_coefficientsL:",Ncoeffs(degreecpm)); coeff_cpmP = readcoeff(input_general.i_resfile, "Estimated_coefficientsP:",Ncoeffs(degreecpm)); // bk 1 sep 2000, req. for resample... //interferogram.win = getoverlap(master,slave,coeff_cpmL,coeff_cpmP); // ______ start added by FvL _____ if (input_general.process[pr_s_resample]) // [MA] quick soln. if no resampling no need to read these parameters? To increase compatiblity with older result files { char c16slavel00[17]; // delta line slave00 char c16slavep00[17]; // delta pixel slave00 char c16slavel0N[17]; // delta line slave0N char c16slavep0N[17]; // delta pixel slave0N char c16slavelN0[17]; // delta line slaveN0 char c16slavepN0[17]; // delta pixel slaveN0 char c16slavelNN[17]; // delta line slaveNN char c16slavepNN[17]; // delta pixel slaveNN readres(c16slavel00,sizeof(c16slavel00), input_general.i_resfile,"Deltaline_slave00_poly:", 0); readres(c16slavep00,sizeof(c16slavep00), input_general.i_resfile,"Deltapixel_slave00_poly:", 0); readres(c16slavel0N,sizeof(c16slavel0N), input_general.i_resfile,"Deltaline_slave0N_poly:", 0); readres(c16slavep0N,sizeof(c16slavep0N), input_general.i_resfile,"Deltapixel_slave0N_poly:", 0); readres(c16slavelN0,sizeof(c16slavelN0), input_general.i_resfile,"Deltaline_slaveN0_poly:", 0); readres(c16slavepN0,sizeof(c16slavepN0), input_general.i_resfile,"Deltapixel_slaveN0_poly:", 0); readres(c16slavelNN,sizeof(c16slavelNN), input_general.i_resfile,"Deltaline_slaveNN_poly:", 0); readres(c16slavepNN,sizeof(c16slavepNN), input_general.i_resfile,"Deltapixel_slaveNN_poly:", 0); slave.add_offsetl00(atof(c16slavel00)); slave.add_offsetp00(atof(c16slavep00)); slave.add_offsetl0N(atof(c16slavel0N)); slave.add_offsetp0N(atof(c16slavep0N)); slave.add_offsetlN0(atof(c16slavelN0)); slave.add_offsetpN0(atof(c16slavepN0)); slave.add_offsetlNN(atof(c16slavelNN)); slave.add_offsetpNN(atof(c16slavepNN)); INFO << atof(c16slavel00); INFO.print(); INFO << atof(c16slavep00); INFO.print(); INFO << atof(c16slavel0N); INFO.print(); INFO << atof(c16slavep0N); INFO.print(); INFO << atof(c16slavelN0); INFO.print(); INFO << atof(c16slavepN0); INFO.print(); INFO << atof(c16slavelNN); INFO.print(); INFO << atof(c16slavepNN); } // [MA] end of quick soln. // ______ end added by FvL ______ } // ====== RESAMPLING OF SLAVE IMAGE ====== if (input_general.process[pr_s_resample]) { PROGRESS.print("Start RESAMPLE."); alreadyprocessed[pr_s_resample]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing resampling of slave image. (might take some time.)"; getanswer(); } matrix minMaxL(2,1); minMaxL = readnormcoeff(input_general.i_resfile, "Normalization_Lines:"); matrix minMaxP(2,1); minMaxP = readnormcoeff(input_general.i_resfile, "Normalization_Pixels:"); INFO << "\n Normalized lines to [-2,2] from:" <x,y,z cn centerpos = input_ellips.ell2xyz(centerphi,centerlambda,centerheight); DEBUG << "Converted RS_DBOW_GEO phi,lambda,hei --> x,y,z:" << centerphi << ", " << centerlambda << ", " << centerheight << " --> " << centerpos.x << " " << centerpos.y << " " << centerpos.z; DEBUG.print(); /* DEBUG << "Center master SLC: x,y,z: " << master.approxcentreoriginal.x << " " << master.approxcentreoriginal.y << " " << master.approxcentreoriginal.z; DEBUG.print(); */ if (abs(master.approxcentreoriginal.x - centerpos.x) > 60000.0)// 50km WARNING.print("RS_DBOW_GEO: coordinates seem to be outside SLC area? (X)"); if (abs(master.approxcentreoriginal.y - centerpos.y) > 60000.0)// 50km WARNING.print("RS_DBOW_GEO: coordinates seem to be outside SLC area? (Y)"); if (abs(master.approxcentreoriginal.z - centerpos.z) > 60000.0)// 50km WARNING.print("RS_DBOW_GEO: coordinates seem to be outside SLC area? (Z)"); xyz2lp(centerline, centerpix, master, masterorbit, centerpos, 10, 1e-3);// MAXITERATIONS, CONVERGENCE_TIME DEBUG << "RS_DBOW_GEO: center line/pix: " << centerline << " " << centerpix; DEBUG.print(); int32 l0 = int32(centerline+0.5) - input_s_resample.dbow_geo.pixlo/2; int32 lN = l0 + input_s_resample.dbow_geo.pixlo - 1; int32 p0 = int32(centerpix+0.5) - input_s_resample.dbow_geo.pixhi/2; int32 pN = p0 + input_s_resample.dbow_geo.pixhi - 1; if (l0 < int32(master.currentwindow.linelo)) l0 = master.currentwindow.linelo; if (lN > int32(master.currentwindow.linehi)) lN = master.currentwindow.linehi; if (p0 < int32(master.currentwindow.pixlo)) p0 = master.currentwindow.pixlo; if (pN > int32(master.currentwindow.pixhi)) pN = master.currentwindow.pixhi; INFO << "RS_DBOW from GEO: " << l0 << " " << lN << " " << p0 << " " << pN; INFO.print(); // ___ Simply fill dbow with it and it will be done correctly! ___ input_s_resample.dbow.linelo = uint(l0); input_s_resample.dbow.linehi = uint(lN); input_s_resample.dbow.pixlo = uint(p0); input_s_resample.dbow.pixhi = uint(pN); } // Batu - adding KML generation. if (input_s_resample.dbow.pixhi == 0 || input_s_resample.dbow.pixlo == 0 || input_s_resample.dbow.linehi == 0 || input_s_resample.dbow.linelo == 0) { INFO << "RS_DBOW not set. Using master window(crop area) for KML"; INFO.print(); input_s_resample.dbow = master.currentwindow; } write_kml(input_ellips, input_s_resample.dbow, master, masterorbit, "resample.kml"); // Batu - End KML generation. // ______ (interf.win contains approx. offset) ______ // resample(input_general, input_s_resample, // master, slave, coeff_cpmL, coeff_cpmP, // alreadyprocessed[pr_i_demassist]); resample(input_general, input_s_resample, master, slave, coeff_cpmL, coeff_cpmP, alreadyprocessed[pr_i_demassist],minMaxL,minMaxP); // ______ Update log files ______ updatefile("scratchlogresample",input_general.logfile); updatefile("scratchresresample",input_general.s_resfile); PROGRESS.print("Finished RESAMPLE."); DEBUG.print("Time spent for resampling of slave image:"); printcpu(); } // ______ Update info of slave, size interferogram ______ if (alreadyprocessed[pr_s_resample]) { INFO.print(""); INFO.print("slave: latest known processing stage: resample"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_s_resample]); slave.updateslcimage(input_general.s_resfile,SECTIONID); // (this is in master coord. system, as it should be) (BK 26-1-00) // in some routines this might be used, should be changed // wins are in same system interferogram.win = getoverlap(master.currentwindow,slave.currentwindow); } // ___ generate a preview of amplitude if requested ______ if (input_general.process[pr_s_resample]) { PROGRESS.print("calling preview for resampled slave"); if (master.sensor!=SLC_RSAT && master.sensor!=SLC_ALOS && master.sensor!=SLC_TSX ) preview(input_general.preview, slave.currentwindow.pixels(), slave.formatflag, slave.file, "slave_rs_mag.ras", "-e 0.5 -s 1.0 -q mag -o sunraster -b -c gray -M 2/10"); else if (master.sensor == SLC_ALOS || master.sensor == SLC_TSX ) preview(input_general.preview, slave.currentwindow.pixels(), slave.formatflag, slave.file, "slave_rs_mag.ras", "-e 0.5 -s 1.0 -q mag -o sunraster -b -c gray -M 10/10"); // [MA] higher mlook to reduce filesize else//multilooking depends on beam preview(input_general.preview, slave.currentwindow.pixels(), slave.formatflag, slave.file, "slave_rs_mag.ras", "-e 0.5 -s 1.0 -q mag -o sunraster -b -c gray -M 5/6"); } // ====== FILTER RANGE: MASTER&SLAVE adaptive ====== // ______ Only one step for master and slave, after resampling. ______ // ______ Method adaptive only, for method based on orbits see after coarse. ______ if (input_general.process[pr_m_filtrange] && input_ms_filtrange.method==rf_adaptive) { PROGRESS.print("Start FILTRANGE (adaptive)."); alreadyprocessed[pr_m_filtrange]=1; // update alreadypr. alreadyprocessed[pr_s_filtrange]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nAdaptive range filtering master and slave."; getanswer(); } // ______ Filter routine ______ rangefilter(input_general,master,slave,interferogram,input_ms_filtrange); // ______ Update log files ______ updatefile("scratchlogfiltrange",input_general.logfile); updatefile("scratchresMfiltrange",input_general.m_resfile); updatefile("scratchresSfiltrange",input_general.s_resfile); PROGRESS.print("Finished FILTRANGE."); DEBUG.print("Time spent for range filtering:"); printcpu(); } // ______ Update info of slave, size interferogram ______ if (alreadyprocessed[pr_m_filtrange]) { char c10rfmethod[11]; // method readres(c10rfmethod,sizeof(c10rfmethod),input_general.m_resfile, "Method_rangefilt:", 0); if (!strcmp(c10rfmethod,"adaptive")) { INFO.print(""); INFO.print("master: latest known processing stage: adaptive range filtered"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_m_filtrange]); master.updateslcimage(input_general.m_resfile,SECTIONID); // ______ cut out overlay master slave exact ______ interferogram.win = master.currentwindow; } } // ______ Update info of slave, size interferogram ______ if (alreadyprocessed[pr_s_filtrange]) // same time as _m_ { char c10rfmethod[11]; // method readres(c10rfmethod,sizeof(c10rfmethod),input_general.s_resfile, "Method_rangefilt:", 0); if (!strcmp(c10rfmethod,"adaptive")) { INFO.print(""); INFO.print("slave: latest known processing stage: adaptive range filtered"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_s_filtrange]); slave.updateslcimage(input_general.s_resfile,SECTIONID); // ______ cut out overlay master slave exact, coord in master system ______ if (slave.currentwindow.linelo != master.currentwindow.linelo || slave.currentwindow.linehi != master.currentwindow.linehi || slave.currentwindow.pixlo != master.currentwindow.pixlo || slave.currentwindow.pixhi != master.currentwindow.pixhi ) { WARNING.print("master/slave should overlap exactly after adaptive range filtering?"); master.showdata(); slave.showdata(); } } } // ______ Fill matrix coefficients flatearth ______ // ______ because might be requested to b subtracted ______ if (alreadyprocessed[pr_i_comprefpha]) { INFO.print(""); INFO.print("ifg: latest known processing stage: comprefpha"); char c10offL[11]; readres(c10offL,sizeof(c10offL),input_general.i_resfile,"Degree_flat:"); int32 degreeflat = atoi(c10offL); coeff_flat = readcoeff(input_general.i_resfile, "Estimated_coefficients_flatearth:",Ncoeffs(degreeflat)); } // ====== COMPUTATION OF (COMPLEX) INTERFEROGRAM ====== if (input_general.process[pr_i_interfero]) { PROGRESS.print("Start INTERFERO."); alreadyprocessed[pr_i_interfero]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing computation of interferogram."; getanswer(); } // ______ Select method ______ // ______ slave.currentwin is in master system (after resample) and is ______ // ______ smaller than master.currentwin ______ if (input_i_interfero.method==int_oldmethod) compinterfero(master, slave, input_general, input_i_interfero); else if (input_i_interfero.method==int_oversample) { PRINT_ERROR("NOT IMPLEMENTED IN THIS VERSION.") throw(input_error);// exit } else { PRINT_ERROR("unknown method interfero.") throw(input_error);// exit } // ______ Update log files ______ updatefile("scratchloginterfero",input_general.logfile); updatefile("scratchresinterfero",input_general.i_resfile); PROGRESS.print("Finished INTERFERO."); DEBUG.print("Time spent for computation of interferogram:"); printcpu(); } // ______ Fill input struct for filenames ______ if (alreadyprocessed[pr_i_interfero]) // update productinfo { INFO.print(""); INFO.print("ifg: latest known processing stage: interfero"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_i_interfero]); interferogram.fillproductinfo(input_general.i_resfile,SECTIONID); } // ______ Generate preview if requested ______ if (input_general.process[pr_i_interfero]) { // ___ floor is not required, we do int division (BK, april 2003) ___ // int32(floor(interferogram.win.pixels()/interferogram.multilookP)), PROGRESS.print("calling preview for complex interferogram"); preview(input_general.preview, int32((interferogram.win.pixels()/interferogram.multilookP)), interferogram.formatflag, interferogram.file, "interferogram_mag.ras", "-e 0.3 -s 1.0 -q mag -o sunraster -b -c gray -M 2/2"); preview(input_general.preview, int32((interferogram.win.pixels()/interferogram.multilookP)), interferogram.formatflag, interferogram.file, "interferogram_pha.ras", "-q phase -o sunraster -b -c jet -M 2/2"); preview(input_general.preview, int32((interferogram.win.pixels()/interferogram.multilookP)), interferogram.formatflag, interferogram.file, "interferogram_mix.ras", "-e 0.3 -s 1.2 -q mixed -o sunraster -b -c hsv -M 2/2"); } // ====== COMPUTATION OF REFERENCE PHASE (FLATEARTH) ====== if (input_general.process[pr_i_comprefpha]) { PROGRESS.print("Start COMPREFPHA."); alreadyprocessed[pr_i_comprefpha]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing computation of reference interferogram."; getanswer(); } if (input_i_comprefpha.method == fe_porbits) flatearth(input_i_comprefpha, input_ellips, master, slave, interferogram, masterorbit, slaveorbit); else if (input_i_comprefpha.method == fe_method2) { PRINT_ERROR("NOT IMPLEMENTED IN THIS VERSION.") throw(input_error);// exit } // ______ Update log files ______ updatefile("scratchlogflat",input_general.logfile); updatefile("scratchresflat",input_general.i_resfile); PROGRESS.print("Finished COMPREFPHA."); DEBUG.print("Time spent for computation of reference interferogram 'flat earth':"); printcpu(); } // ______Fill matrix coefficients flatearth______ if (alreadyprocessed[pr_i_comprefpha]) { INFO.print(""); INFO.print("ifg: latest known processing stage: comprefpha"); char c10offL[11]; readres(c10offL,sizeof(c10offL),input_general.i_resfile,"Degree_flat:"); int32 degreeflat = atoi(c10offL); coeff_flat = readcoeff(input_general.i_resfile, "Estimated_coefficients_flatearth:",Ncoeffs(degreeflat)); //____ added by FvL ____________ readres(c10offL,sizeof(c10offL),input_general.i_resfile,"Degree_h2ph:"); int32 degreeh2ph = atoi(c10offL); coeff_h2ph = readcoeff(input_general.i_resfile, "Estimated_coefficients_h2ph:",Ncoeffs(degreeh2ph)); //_____ end added by FvL ________ } // ====== SUBTRACT REFERENCE PHASE (FLATEARTH) ====== if (input_general.process[pr_i_subtrrefpha]) { PROGRESS.print("Start SUBTRREFPHA."); alreadyprocessed[pr_i_subtrrefpha]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing subtraction of reference phase from interferogram.\n"; getanswer(); } // ______ Select appropriate module ______ switch (input_i_subtrrefpha.method) { case srp_polynomial: subtrrefpha(master,interferogram, input_general,input_i_subtrrefpha, coeff_flat,coeff_h2ph); // coeff_h2ph added by FvL break; case srp_exact: subtrrefpha(input_ellips, master, slave, interferogram, input_general, input_i_subtrrefpha, masterorbit, slaveorbit); break; default: PRINT_ERROR("PANIC: not possible, bert.") throw(unhandled_case_error);// exit } // ______ Update log files ______ updatefile("scratchlogsubtrrefpha",input_general.logfile); updatefile("scratchressubtrrefpha",input_general.i_resfile); PROGRESS.print("Finished SUBTRREFPHA."); DEBUG.print("Time spent for subtraction of reference phase:"); printcpu(); } // ______ Fill input struct for filenames ______ if (alreadyprocessed[pr_i_subtrrefpha]) // update productinfo { INFO.print(""); INFO.print("ifg: latest known processing stage: subtrrefpha"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_i_subtrrefpha]); interferogram.fillproductinfo(input_general.i_resfile,SECTIONID); } // ______ Generate preview if requested ______ if (input_general.process[pr_i_subtrrefpha]) { PROGRESS.print("calling preview for refpha corrected image"); // ____ if refphase dumped, tmp change filename ___ //if (!strcmp(interferogram.file,"NO_OUTPUT_ONLY_DUMPING_REF_PHA") if (input_i_subtrrefpha.dumponlyrefpha==true) strcpy(interferogram.file,input_i_subtrrefpha.forefpha); preview(input_general.preview, int32((interferogram.win.pixels()/interferogram.multilookP)), interferogram.formatflag, interferogram.file, "interferogram_srp_mag.ras", "-e 0.3 -s 1.0 -q mag -o sunraster -b -c gray -M 2/2"); preview(input_general.preview, int32((interferogram.win.pixels()/interferogram.multilookP)), interferogram.formatflag, interferogram.file, "interferogram_srp_pha.ras", "-q phase -o sunraster -b -c jet -M 2/2"); preview(input_general.preview, int32((interferogram.win.pixels()/interferogram.multilookP)), interferogram.formatflag, interferogram.file, "interferogram_srp_mix.ras", "-e 0.3 -s 1.2 -q mixed -o sunraster -b -c jet -M 2/2"); // MA //"interferogram_srp_mix.ras", "-e 0.3 -s 1.2 -q mixed -o sunraster -b -c cool -M 2/2"); if (input_i_subtrrefpha.dumponlyrefpha==true) {INFO.print("exiting, only dumped refpha"); exit(1);} } // ====== COMPUTE REFERENCE PHASE (DEM) ====== if (input_general.process[pr_i_comprefdem]) { PROGRESS.print("Start COMPREFDEM."); alreadyprocessed[pr_i_comprefdem]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing computation of reference phase from DEM.\n"; getanswer(); } // if (input_i_comprefdem.method == gtopo30) radarcodedem(input_general, input_ellips, input_i_comprefdem, master, slave, interferogram, masterorbit, slaveorbit); // ______ Update log files ______ updatefile("scratchlogcomprefdem",input_general.logfile); updatefile("scratchrescomprefdem",input_general.i_resfile); //WARNING("Not tested properly yet."); PROGRESS.print("Finished COMPREFDEM."); DEBUG.print("Time spent for computation of reference DEM:"); printcpu(); } // ______ Fill input struct for ______ if (alreadyprocessed[pr_i_comprefdem]) // update slcimage { INFO.print(""); INFO.print("ifg: latest known processing stage: comprefdem"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_i_comprefdem]); radarcodedrefdem.fillproductinfo(input_general.i_resfile,SECTIONID); } // ___ generate preview if requested and just processed ___ if (input_general.process[pr_i_comprefdem]) { // ______ See if we can trick cpxfiddle in believing this is cpx ______ // ______ Should also work for real4 ______ // BK 16-Jun-2003 ______ PROGRESS.print("calling preview for comprefdem (phase)"); preview(input_general.preview, int32((radarcodedrefdem.win.pixels()/radarcodedrefdem.multilookP)), radarcodedrefdem.formatflag, radarcodedrefdem.file, "comprefdem_phase.ras", "-q normal -o sunraster -b -c jet -M 2/2"); if (specified(input_i_comprefdem.forefdemhei)) { PROGRESS.print("calling preview for comprefdem (height)"); preview(input_general.preview, int32((radarcodedrefdem.win.pixels()/radarcodedrefdem.multilookP)), FORMATR4, input_i_comprefdem.forefdemhei, "comprefdem_height.ras", "-q normal -o sunraster -b -c jet -M 2/2"); } } // ====== SUBTRACT REFERENCE PHASE (DEM) ====== if (input_general.process[pr_i_subtrrefdem]) { PROGRESS.print("Start SUBTRREFDEM."); alreadyprocessed[pr_i_subtrrefdem]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing subtraction of reference DEM from interferogram.\n"; getanswer(); } subtrrefdem(interferogram,radarcodedrefdem,input_general,input_i_subtrrefdem); // ______ Update log files ______ updatefile("scratchlogsubtrrefdem",input_general.logfile); updatefile("scratchressubtrrefdem",input_general.i_resfile); PROGRESS.print("Finished SUBTRREFDEM."); DEBUG.print("Time spent for subtraction of reference DEM:"); printcpu(); } // ______ Fill input struct for filenames ______ if (alreadyprocessed[pr_i_subtrrefdem]) // update slcimage { INFO.print(""); INFO.print("ifg: latest known processing stage: subtrrefdem"); //WARNING("check this ..., nothing changed except filenaem?"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_i_subtrrefdem]); interferogram.fillproductinfo(input_general.i_resfile,SECTIONID); } // ______ Generate preview if requested ______ if (input_general.process[pr_i_subtrrefdem]) { PROGRESS.print("calling preview for refdem corrected interferogram"); preview(input_general.preview, int32((interferogram.win.pixels()/interferogram.multilookP)), interferogram.formatflag, interferogram.file, "interferogram_srd_mag.ras", "-e 0.3 -s 1.0 -q mag -o sunraster -b -c gray -M 2/2"); preview(input_general.preview, int32((interferogram.win.pixels()/interferogram.multilookP)), interferogram.formatflag, interferogram.file, "interferogram_srd_pha.ras", "-q phase -o sunraster -b -c jet -M 2/2"); preview(input_general.preview, int32((interferogram.win.pixels()/interferogram.multilookP)), interferogram.formatflag, interferogram.file, "interferogram_srd_mix.ras", "-e 0.3 -s 1.2 -q mixed -o sunraster -b -c jet -M 2/2"); //MA //"interferogram_srd_mix.ras", "-e 0.3 -s 1.2 -q mixed -o sunraster -b -c hot -M 2/2"); } // [don] the computation of the coherence image has been moved // after the computation of the reference phase (DEM) in // order to include the radarcodedrefdem_phase_correction // ====== COMPUTATION OF COHERENCE IMAGE ====== // (use also other external computed phase in future!) if (input_general.process[pr_i_coherence]) { PROGRESS.print("Start COHERENCE."); alreadyprocessed[pr_i_coherence]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing computation of coherence."; getanswer(); } // ______ Select method ______ switch (input_i_coherence.method) { case coh_oldmethod: // use flatearth, compute interferogram again // compcoherence(master,slave,interferogram, compcoherence(master, slave, input_general, input_i_coherence, coeff_flat); break; case coh_newmethod: // start_added_by_don if (alreadyprocessed[pr_i_comprefdem]) // use flatearth and radarcodedrefdem, compute interferogram again compcoherence(master, slave, radarcodedrefdem, input_general, input_i_coherence, coeff_flat); else { ERROR << "Requested step: " << pr_i_coherence << " (" << processcontrol[pr_i_coherence] << ") seems impossible, because step " << pr_i_comprefdem << " (" << processcontrol[pr_i_comprefdem] << ") is not in resultfile."; PRINT_ERROR(ERROR.get_str()) throw(input_error);// exit } // end_added_by_don break; default: PRINT_ERROR("unknown method coherence.") throw(unhandled_case_error);// exit } // ______ Update log files ______ updatefile("scratchlogcoherence",input_general.logfile); updatefile("scratchrescoherence",input_general.i_resfile); PROGRESS.print("Finished COHERENCE."); DEBUG.print("Time spent for computation of coherence:"); printcpu(); } // ______ Fill input struct for filenames ______ if (alreadyprocessed[pr_i_coherence]) // update slcimage { INFO.print(""); INFO.print("ifg: latest known processing stage: coherence"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_i_coherence]); coherence.fillproductinfo(input_general.i_resfile,SECTIONID); } // ___ generate preview if requested and just processed ___ if (input_general.process[pr_i_coherence]) { // ______ See if we can trick cpxfiddle in believing this is cpx ______ // ______ Should also work for real4 ______ // BK 16-Jun-2003 ______ PROGRESS.print("calling preview for coherence"); preview(input_general.preview, int32((coherence.win.pixels()/coherence.multilookP)), coherence.formatflag, coherence.file, "coherence.ras", "-q normal -o sunraster -b -c gray -M 2/2 -r 0.0/1.0 "); // coherence range 0 to 1. } // ====== PHASE FILTERING ====== if (input_general.process[pr_i_filtphase]) { PROGRESS.print("Start FILTPHASE."); alreadyprocessed[pr_i_filtphase]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing phase filtering."; getanswer(); } switch (input_i_filtphase.method) { case fp_modgoldstein: DEBUG << "Coherence file for modgoldstein:"; DEBUG << coherence.file; DEBUG.print(); if (existed(coherence.file)) phasefilter(input_general,interferogram,input_i_filtphase,coherence); else { ERROR << "Coherence file does not exist: " << coherence.file; PRINT_ERROR(ERROR.get_str()) throw(some_error); } break; case fp_goldstein: phasefilter(input_general,interferogram,input_i_filtphase,coherence); break; case fp_spatialconv: spatialphasefilt(input_general,interferogram,input_i_filtphase); break; case fp_spectral: phasefilterspectral(input_general,interferogram,input_i_filtphase); break; default: PRINT_ERROR("PANIC: not possible.") throw(unhandled_case_error);// exit } // ______ Update log files ______ updatefile("scratchlogfiltphase",input_general.logfile); updatefile("scratchresfiltphase",input_general.i_resfile); PROGRESS.print("Finished FILTPHASE."); DEBUG.print("Time spent for phase filtering:"); printcpu(); } // ______ Fill info struct for filenames ______ if (alreadyprocessed[pr_i_filtphase]) // update productinfo { INFO.print(""); INFO.print("ifg: latest known processing stage: filtphase"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_i_filtphase]); interferogram.fillproductinfo(input_general.i_resfile,SECTIONID); } // ______ Generate preview if requested ______ if (input_general.process[pr_i_filtphase]) { PROGRESS.print("calling preview for phase filtered corrected interferogram"); preview(input_general.preview, int32((interferogram.win.pixels()/interferogram.multilookP)), interferogram.formatflag, interferogram.file, "interferogram_filt_mag.ras", "-e 0.3 -s 1.0 -q mag -o sunraster -b -c gray -M 2/2"); preview(input_general.preview, int32((interferogram.win.pixels()/interferogram.multilookP)), interferogram.formatflag, interferogram.file, "interferogram_filt_pha.ras", "-q phase -o sunraster -b -c jet -M 2/2"); preview(input_general.preview, int32((interferogram.win.pixels()/interferogram.multilookP)), interferogram.formatflag, interferogram.file, "interferogram_filt_mix.ras", "-e 0.3 -s 1.2 -q mixed -o sunraster -b -c hsv -M 2/2"); } // ====== DIFFERENTIAL 3 PASS, DEFO PROCESSING ====== if (input_general.process[pr_i_dinsar]) { PROGRESS.print("Start DINSAR."); alreadyprocessed[pr_i_dinsar]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing differential interferometry."; getanswer(); } dinsar(input_general,input_i_dinsar,input_ellips, master,masterorbit, slave,slaveorbit,interferogram); // (defopair) // ______ Update log files ______ updatefile("scratchlogdinsar",input_general.logfile); updatefile("scratchresdinsar",input_general.i_resfile); PROGRESS.print("Finished DINSAR."); DEBUG.print("Time spent for 3 pass differential interferometry:"); printcpu(); } // ______ Fill info struct for filenames ______ // ______ use interferogram because you want to unwrap it? ______ if (alreadyprocessed[pr_i_dinsar]) // update productinfo { INFO.print(""); INFO.print("ifg: latest known processing stage: dinsar"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_i_dinsar]); interferogram.fillproductinfo(input_general.i_resfile,SECTIONID); } // ______ Generate preview if requested ______ if (input_general.process[pr_i_dinsar]) { PROGRESS.print("calling preview for differential interferogram"); preview(input_general.preview, int32((interferogram.win.pixels()/interferogram.multilookP)), interferogram.formatflag, interferogram.file, "interferogram_dinsar_mag.ras", "-e 0.3 -s 1.0 -q mag -o sunraster -b -c gray -M 2/2"); preview(input_general.preview, int32((interferogram.win.pixels()/interferogram.multilookP)), interferogram.formatflag, interferogram.file, "interferogram_dinsar_pha.ras", "-q phase -o sunraster -b -c jet -M 2/2"); preview(input_general.preview, int32((interferogram.win.pixels()/interferogram.multilookP)), interferogram.formatflag, interferogram.file, "interferogram_dinsar_mix.ras", "-e 0.3 -s 1.2 -q mixed -o sunraster -b -c jet -M 2/2"); } // ====== UNWRAPPING INTERFEROGRAM ====== unwrappedinterf = interferogram; if (input_general.process[pr_i_unwrap]) { PROGRESS.print("Start UNWRAP."); alreadyprocessed[pr_i_unwrap]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing unwrapping of interferogram."; getanswer(); } switch (input_i_unwrap.method) { // ___ Branch cut ___ case uw_method1: unwraptreeframon( input_general, input_i_unwrap, interferogram); break; // ___ Statistic minimal cost flow ___ case uw_method2: snaphu_unwrap( input_general, input_i_unwrap, interferogram, master, slave, masterorbit, slaveorbit, input_ellips); if (specified(input_i_unwrap.snaphu_log)) { if (input_i_unwrap.snaphu_dumponlyconf == false) updatefile(input_i_unwrap.snaphu_log,input_general.logfile); } break; // ___ Minimal cost flow algorithm ___ case uw_method3: PRINT_ERROR("NOT IMPLEMENTED IN THIS VERSION.") throw(unhandled_case_error);// exit break; default: PRINT_ERROR("PANIC: NOT POSSIBLE.") throw(unhandled_case_error);// exit } // // ______ Apply bias to unwrapped interferogram, based on tiepoint ______ // // ______ This simply loads the created unwrapped ifg; ______ // // ______ computes the tiepoint, and saves it to the same file. ______ // if (abs(input_i_unwrap.tiepoint.x) < 0.001 && // abs(input_i_unwrap.tiepoint.y) < 0.001 && // abs(input_i_unwrap.tiepoint.z) < 0.001) // { // PROGRESS.print("Computating integration constant based on tiepoint"); // add_bias_unwrap( // input_general, // input_i_unwrap, // interferogram, // master, slave, // masterorbit, slaveorbit, // input_ellips); //++++ also add in unwrap.h // } // ______ Update log files ______ updatefile("scratchlogunwrap",input_general.logfile); updatefile("scratchresunwrap",input_general.i_resfile); PROGRESS.print("Finished UNWRAP."); DEBUG.print("Time spent for unwrapping:"); printcpu(); } // ______ Fill info struct for filenames ______ // ______ 2b sure, initialize unwrappedinterf with interferogram ______ unwrappedinterf = interferogram; if (alreadyprocessed[pr_i_unwrap]) // update productinfo { INFO.print(""); INFO.print("ifg: latest known processing stage: unwrap"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_i_unwrap]); unwrappedinterf.fillproductinfo(input_general.i_resfile,SECTIONID); } // ___ generate preview if requested and just now computed____ if (input_general.process[pr_i_unwrap]) { // ______ Generate preview if requested and oformat was hgt?______ // ______ See if we can trick cpxfiddle in believing this is cpx ______ // ______ Should also work for real4 ______ // BK 13-Apr-2003 PROGRESS.print("calling preview for unwrapped interferogram"); preview(input_general.preview, int32((unwrappedinterf.win.pixels()/unwrappedinterf.multilookP)), unwrappedinterf.formatflag, unwrappedinterf.file, "unwrapped_interferogram.ras", "-q normal -o sunraster -b -c jet -M 2/2");// -V } // ____ start added by HB ____ // ====== ESTORBITS ====== if (input_general.process[pr_i_estorbits]) { // ______ check feasibility of step depending on method ______ (not possible in ioroutines.cc) if (input_i_estorbits.method==eo_lsq && !alreadyprocessed[pr_i_unwrap]) { PRINT_ERROR("Orbit estimation using method LSQ seems impossible, because step UNWRAP is not in resultfile."); throw(input_error); } PROGRESS.print("Start ESTORBITS."); alreadyprocessed[pr_i_estorbits]=1; if (input_general.interactive) { cerr << "\nEstimating updates to orbit parameters.\n"; getanswer(); } // ______ process orbit error estimation ______ if (input_i_estorbits.method==eo_gridsearch) estorbits(input_i_estorbits, input_general, input_ellips, master, slave, masterorbit, slaveorbit, interferogram, coherence, baseline); else // method = eo_lsq estorbits(input_i_estorbits, input_general, input_ellips, master, slave, masterorbit, slaveorbit, unwrappedinterf, coherence, baseline); updatefile("scratchlogestorbit",input_general.logfile); updatefile("scratchresestorbit",input_general.i_resfile); PROGRESS.print("Finished ESTORBITS."); DEBUG.print("Time spent for orbit estimation:"); printcpu(); } // ____ end added by HB ____ // ====== SLANT TO HEIGHT CONVERSION ====== if (input_general.process[pr_i_slant2h]) { PROGRESS.print("Start SLANT2H."); alreadyprocessed[pr_i_slant2h]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing slant to height conversion."; getanswer(); } if (!strcmp(input_i_slant2h.fohei,unwrappedinterf.file)) { PRINT_ERROR("slant2h: same filename input/output") throw(input_error);// exit } switch (input_i_slant2h.method) { case s2h_schwabisch: slant2hschwabisch( input_general, input_i_slant2h, input_ellips, master, slave, unwrappedinterf, masterorbit, slaveorbit); break; case s2h_rodriguez: slant2hrodriguez( input_general, input_i_slant2h, input_ellips, master, slave, unwrappedinterf, coeff_flat, masterorbit, slaveorbit, baseline); break; case s2h_ambiguity: slant2hambiguity( input_general, input_i_slant2h, input_ellips, master, slave, unwrappedinterf, masterorbit, slaveorbit, baseline); // ______ This method includes geocoding, but probably contains trend ______ alreadyprocessed[pr_i_geocoding]=1; // update alreadypr. break; default: PRINT_ERROR("slant2h: unknown method.") throw(unhandled_case_error);// exit } // ______ Update log files ______ updatefile("scratchlogslant2h",input_general.logfile); updatefile("scratchresslant2h",input_general.i_resfile); PROGRESS.print("Finished SLANT2H."); DEBUG.print("Time spent for slant-to-height:"); printcpu(); } // ______ Fill info struct for filenames ______ if (alreadyprocessed[pr_i_slant2h]) // update productinfo { INFO.print(""); INFO.print("ifg: latest known processing stage: slant2h"); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_i_slant2h]); heightinradarsystem.fillproductinfo(input_general.i_resfile,SECTIONID); } // ___ generate preview if requested and just processed ___ if (input_general.process[pr_i_slant2h]) { // ______ Generate preview if requested and oformat was hgt?______ // ______ See if we can trick cpxfiddle in believing this is cpx ______ // ______ Should also work for real4 ______ // ______ note that there is not point in preview of these heights? _____ // BK 13-Apr-2003 PROGRESS.print("calling preview for slant to height"); preview(input_general.preview, int32((heightinradarsystem.win.pixels()/heightinradarsystem.multilookP)), heightinradarsystem.formatflag, heightinradarsystem.file, "height_in_radarcoordinates.ras", "-q normal -o sunraster -b -c jet -M 2/2");// -V } // ====== GEOCODING ====== if (input_general.process[pr_i_geocoding]) { PROGRESS.print("Start GEOCODE."); alreadyprocessed[pr_i_geocoding]=1; // update alreadypr. if (input_general.interactive) { cerr << "\nProcessing geocoding."; getanswer(); } geocode( input_general, input_i_geocode, input_ellips, master, heightinradarsystem, masterorbit); // ______ Update log files ______ updatefile("scratchloggeocode",input_general.logfile); updatefile("scratchresgeocode",input_general.i_resfile); PROGRESS.print("Finished GEOCODE."); DEBUG.print("Time spent for geocoding:"); printcpu(); } // ______ No need fillproductinfo after last one ______ // // ______ but do it for consistentness/preview card one day _____ // // ______ Fill info struct for filenames ______ if (alreadyprocessed[pr_i_geocoding]) // update productinfo { INFO.print(""); INFO.print("ifg: latest known processing stage: geocoding"); } // ====== TIDY UP ====== // ______ Update process control flags in resultfiles ______ if (processmaster) updateprocesscontrol(input_general.m_resfile,MASTERID); if (processlave) updateprocesscontrol(input_general.s_resfile,SLAVEID); if (processinterf) updateprocesscontrol(input_general.i_resfile,INTERFID); DEBUG.print("Time spent for tidying up:"); printcpu(); cout << "\n\nProcessing results are in parameter file"; if ((processmaster && processlave) || (processmaster && processinterf) || (processlave && processinterf)) cout << "s:\n"; else cout << ":\n"; if (processmaster) cout << " " << input_general.m_resfile << endl; if (processlave) cout << " " << input_general.s_resfile << endl; if (processinterf) cout << " " << input_general.i_resfile << endl; quote(); WARNING.summary(); }// --- end of try block; now catch thrown exceptions ------------- catch(USAGE_ERROR& usage_error)// catch errors of EXCEPTION class { exit(-1);// normal exit; } catch(EXCEPTION& error)// catch errors of EXCEPTION class { cerr << "Caught error of EXCEPTION class!" << endl; cerr << "It is: " << (const char*)error << endl; printcpu(); WARNING.summary(); exit(1); } catch(const char* error_string)// catch handled errors { cerr << "Caught error!" << endl; cerr << "It is: " << error_string << endl; printcpu(); WARNING.summary(); exit(2); } catch(...) // catches other errors { cerr << "Caught an unhandled error!" << endl; printcpu(); WARNING.summary(); exit(3); } cout << "\n\nNormal termination.\nThank you for using Doris.\n\n"; return int32(0); } // END main /**************************************************************** @brief initmessages initializes logging messages @param none no arguments * initmessages * * set defaults for global messages objects * * #%// BK 12-Apr-2003 * ****************************************************************/ void initmessages() { TRACE.setidentifyer("TRACE"); TRACE.dostderr(0); TRACE.doprint(0); TRACE.bellrings(0); DEBUG.setidentifyer("DEBUG"); DEBUG.dostderr(0); DEBUG.doprint(0); DEBUG.bellrings(0); INFO.setidentifyer("INFO"); INFO.dostderr(0); INFO.doprint(1); INFO.bellrings(0); PROGRESS.setidentifyer("PROGRESS"); PROGRESS.dostderr(1); PROGRESS.doprint(1); PROGRESS.bellrings(1); WARNING.setidentifyer("WARNING"); WARNING.dostderr(1); WARNING.doprint(1); WARNING.bellrings(2); ERROR.setidentifyer("ERROR"); ERROR.dostderr(1); ERROR.doprint(1); ERROR.bellrings(3); ERROR.doexit(0); matDEBUG.setidentifyer("mtxDEBUG"); matDEBUG.dostderr(0); matDEBUG.doprint(1);// default print, define prevents too much matERROR.setidentifyer("mtxERROR"); matERROR.dostderr(1); matERROR.doprint(1); matERROR.bellrings(10);// should not occur anyway matERROR.doexit(1); } // END initmessages /**************************************************************** @brief handleinput parses input @param argc original command line input to program @param argv original command line input to program @param input_gen general input struct * handleinput * * returns inputfilename as input_gen.logfile * * BK 01-Dec-1999 * ****************************************************************/ void handleinput(int argc, char* argv[], input_gen &input_general) { TRACE_FUNCTION("handleinput"); // ====== Handle command line arguments ====== switch (argc) { case 3: // help search term ; // do nothing, assume argv[1] is -h ... //--- fall through --- // case 2: // optionsfilename, -h, or -ver if (!strcmp(argv[1],"-ver") || !strcmp(argv[1],"-v") || !strcmp(argv[1],"-VER") || !strcmp(argv[1],"-V")) // version number asked { cerr << "Software name: " << SWNAME << "\nSoftware version: " << SWVERSION << endl; exit(0); } // ______ Help wanted ______ else if (!strcmp(argv[1],"-h") || !strcmp(argv[1],"-H") || !strcmp(argv[1],"-help") || !strcmp(argv[1],"-HELP")) { // g++ makes: helpdoris (null) if empty argv[2] if (argc==2) { INFO.print("Making system call:"); INFO.print("helpdoris"); system("helpdoris"); } else { INFO << "helpdoris " << argv[2] << ends; // search pattern char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("Making system call:"); INFO.print(cmd); system(cmd); } exit(0); } // ______ Copyright notice ______ else if (!strcmp(argv[1],"-c") || !strcmp(argv[1],"-C")) { copyright(); } // ______ Random quote ______ else if (!strcmp(argv[1],"-q") || !strcmp(argv[1],"-Q")) { quote(); exit(0); } // ______ Assume input file ______ else strcpy(input_general.logfile,argv[1]); // store in logfile. break; // --- stop falling, no more options --- // // default no name for inputfile //case 1: // no arguments // strcpy(input_general.logfile,"inputoptionsfile"); // default name // break; default: usage(argv[0]); } // switch handle arguments // ______ Check command line arguments ______ if (existed(input_general.logfile)==true) { INFO << "input file: \"" << input_general.logfile << "\""; INFO.print(); } else { ERROR << argv[0] << " input file: \"" << input_general.logfile << "\" not found."; ERROR.print(); throw(input_error);// check if exception is caught in try block //usage(argv[0]); } } // END handleinput /**************************************************************** @brief return extra libraries used with Doris * @param none * * usage * * MA 19-May-2009 * * TODO merge with ioroutines usedinfo? * ****************************************************************/ string checklibs() { TRACE_FUNCTION("checklib"); string libs = "none!"; #ifdef __USE_FFTW_LIBRARY__ extern const char fftwf_version[]; //libs="fftw"; libs=fftwf_version; #endif #ifdef __USE_VECLIB_LIBRARY__ if (libs.length() == 5) // len("none!") == 5 { libs="veclib"; } else { libs += ", veclib"; } #endif #ifdef __USE_LAPACK_LIBRARY__ #if !defined(WIN32) && !defined (__CYGWIN__) && (!__MINGW32__) // [MA] on cygwin lapack misses ilaver_ to return version info. //#warning "win32 platform" int32 major, minor, patch; ilaver(&major, &minor, &patch); // get lapack version, imported from matrix.cc char libver [15]; //char* libver = "lapack-xx.xx.xx"; // didn't worked why? sprintf(libver,"lapack-%d.%d.%d", major, minor, patch); // lapack-3.1.1 #else const char* libver = "lapack"; #endif if (libs.length() == 5) { libs=string(libver); } else { libs += ", " + string(libver); } #endif return libs; } /**************************************************************** @brief usage echos synopsis @param programname name of this program * usage * * BK 01-Dec-1999 * ****************************************************************/ void usage(char *programname) { TRACE_FUNCTION("usage"); string libs = checklibs(); cerr << "\n\t *** ** ** * **" << "\n\t * * * * * * * *" << "\n\t * * * * * * * *" << "\n\t * * * * * * * *" << "\n\t *** ** * * * **\n\n\n"; cerr << "\n Program: \"" << programname << "\" " << SWVERSION << "\n\tInterferometric processor for SAR SLC data.\n" << "\n\t(c) 1999-2012 Delft University of Technology, the Netherlands." // << "\n\t Created by: Bert Kampes.\n\n" << "\n\n" << " SYNOPSIS:\n\t" << programname << " infile | -h [searchterm] | -v | -c | -q\n\n" << "\t infile: input file for " << programname << endl //<< "\n\t\t\t(default: \"inputoptionsfile\")\n" << "\t -h [term]: call \"helpdoris\" (script with searchable help)\n" << "\t -c: return copyright notice.\n" << "\t -q: return random quote (not so random).\n" << "\t -v: return version number.\n\n\n" << " LIBRARIES (used): " << libs << "\n\n" << " Compiled on DATE: " __DATE__ << " at: " << __TIME__ << endl << endl; throw(usage_error);// normal exit } // END usage /**************************************************************** @brief quote like fortune program * quote * * I copied some quotes from the internet etc. * * sorry not to have a source for them. * * BK 15-Nov-2000 * ****************************************************************/ void quote() { TRACE_FUNCTION("quote"); // ______ Initialize quotes (send me new ones) ______ const int32 largestquote = ONE27*2; const char QUOTES[][largestquote] = { "tip: Check out \"http://doris.tudelft.nl/\"", "tip: Check out \"http://doris.tudelft.nl/dig/\"", "tip: See the online manual at \"http://doris.tudelft.nl/usermanual/\"", "tip: Type: \"helpdoris\" for a synopsis of all input cards.", "tip: The \"run\" script can be used to generate template input files.", "tip: Get ASAR/ERS[12] precise orbits via \"http://www.deos.tudelft.nl/ers/precorbs/\"", "tip: For RADARSAT, use polyfit orbit interpolation, not approximation.", "tip: cpxfiddle is a nifty little utility.", "tip: dateconv is a nifty little utility.", "GMT is a great package.", "The only thing we have to fear is fear itself.", "2b || !2b = 1", "Sent me better quotes. Quick.", // 10 "The whole is more than the sum of its parts.", "To Thales the primary question was not what do we know,\n\tbut how do we know it.", "For the things of this world cannot be made known without\n\ta knowledge of mathematics.", "Life is a school of probability.", "\"Obvious\" is the most dangerous word in mathematics.", "An expert is a man who has made all the mistakes, which can be made,\n\tin a very narrow field.", "Structures are the weapons of the mathematician.", "A witty statesman said, you might prove anything by figures.", "Men pass away, but their deeds abide.", "It is a good thing for an uneducated man to read books of quotations.", // 20 "Mathematics is written for mathematicians.", "Revolutions never occur in mathematics.", "It is easier to square the circle than to get round a mathematician.", "Cognito ergo sum. \"I think, therefore I am.\"", "It is not enough to have a good mind. The main thing is to use it well.", "From a drop of water a logician could predict an Atlantic or a Niagara.", "I don't believe in mathematics.", "Imagination is more important than knowledge.", "A Mathematician is a machine for turning coffee into theorems.", "Whenever you can, count.", // 30 "Mathematics is a language.", "One should always generalize.", "Statistics: the mathematical theory of ignorance.", "When we ask advice, we are usually looking for an accomplice.", "What we know is not much. What we do not know is immense.", "Medicine makes people ill, mathematics make them sad and theology makes them sinful.", "A great truth is a truth whose opposite is also a great truth.", "I feign no hypotheses.", "It is not certain that everything is uncertain.", "Though this be madness, yet there is method in it.", // 40 "I have no faith in political arithmetic.", "Fourier is a mathematical poem.", "We think in generalities, but we live in details.", "I think that God in creating man somewhat overestimated his ability.", "Add little to little and there will be a big pile.", "Computers in the future may weigh no more than 1.5 tons. (1949)", "There is no reason anyone would want a computer in their home. (1977)", "Heavier-than-air flying machines are impossible. (1895)", "Everything that can be invented has been invented. (1899)", "640K ought to be enough for anybody. (1981)", // 50 "Pentiums melt in your PC, not in your hand.", "Always remember you're unique, just like everyone else.", "Ever notice how fast Windows runs? Neither did I.", "Double your drive space - delete Windows!", "Circular definition: see Definition, circular.", "43.3% of statistics are meaningless.", "Very funny, Scotty. Now beam down my clothes.", "I've got a problem. I say everything twice", "Don't insult the alligator till after you cross the river.", "Black holes are where God divided by zero.", // 60 "% make fire\n\tMake: Don't know how to make fire. Stop.", "% why not?\n\tNo match.", "% gotta light?\n\tNo match.", "% !1984\n\t 1984: Event not found. # (on some systems)", "% How's my lovemaking?\n\t Unmatched '.", "% \"How would you rate his incompetence?\n\tUnmatched \".", "% [Where is Jimmy Hoffa?\n\tMissing ].", "% [Where is my brain?\n\tMissing ].", "% ^How did the sex change^ operation go?\n\tModifier failed.", "% ar x \"my love life\"\n\tar: my love life does not exist", // 70 "This time it will surely run.", "Bug? That's not a bug, that's a feature.", "It's redundant! It's redundant!", "cpxfiddle is a great program.", "The shortest path between two truths in the real domain\n\tpasses through the complex domain.", "You have a tendency to feel you are superior to most computers.", "The first 90% of a project takes 90% of the time.", "The last 10% of a project takes 90% of the time.", "Any given program, when running, is obsolete.", "Any given program costs more and takes longer.", "If a program is useful, it will have to be changed.", // 80 "If a program is useless, it will have to be documented.", "Any given program will expand to fill all available memory.", "The value of a program is porportional to the weight of its output.", "Program complexity grows until it exceeds the capability\n\tof the programmer who must maintain it.", "Make it possible for programmers to write programs in English\n\tand you will find that programmers cannot write in English.", "On a helmet mounted mirror used by US cyclists:\n\t\"REMEMBER, OBJECTS IN THE MIRROR ARE ACTUALLY BEHIND YOU.\"", "On a New Zealand insect spray\n\t\"THIS PRODUCT NOT TESTED ON ANIMALS.\"", "In some countries, on the bottom of Coke bottles:\n\t\"OPEN OTHER END.\"", "On a Sears hairdryer:\n\t\"DO NOT USE WHILE SLEEPING.\"", "On a bar of Dial soap:\n\t\"DIRECTIONS - USE LIKE REGULAR SOAP.\"", // 90 "On a Korean kitchen knife:\n\t\"warning keep out of children.\"", // changed to lowercase to avoid confusion when grepping for warnings in the output [HB] "On an American Airlines packet of nuts:\n\t\"INSTRUCTIONS - OPEN PACKET, EAT NUTS.\"", "On a child's superman costume:\n\t\"WEARING OF THIS GARMENT DOES NOT ENABLE YOU TO FLY.\"", "Looking at wrapped interferograms is like running in circles.", "Conversation equals conservation (proposition with thesis Ramon Hanssen).", "Unlikely children's book title:\n\t\"Curios George and the High-Voltage Fence\".", "Unlikely children's book title:\n\t\"Controlling the Playground: Respect through Fear\".", "Unlikely children's book title:\n\t\"Mr Fork and Ms Electrical Outlet Become Friends\".", "Unlikely children's book title:\n\t\"Strangers Have the Best Candy\".", "Unlikely children's book title:\n\t\"Daddy Drinks Because You Cry\".", // 100 "Stanley looked quite bored and somewhat detached, but then penguins often do.", "Trouble with Windows? Reboot. Trouble with Unix? Be root.", "The good thing about standards is that there are so many to choose from.", "You can always count on people to do the right thing,\n\tafter they have exhausted all the alternatives.", "Where there is matter, there is geometry.", "The simplest schoolboy is now familiar with facts for which Archimedes\n\twould have sacrificed his life.", "Get the fastest fourier transform in the west at http://www.fftw.org/", "See http://www.gnu.org/ for compiler updates, etc.", "You can only find truth with logic if you have already found truth without it.", "Everything should be made as simple as possible, but not simpler.", // 110 "Seek simplicity, and distrust it.", "Descartes commanded the future from his study more\n\tthan Napoleon from the throne.", "Say what you know, do what you must, come what may.", "To the devil with those who published before us.", "The words figure and fictitious both derive from\n\tthe same Latin root, fingere. Beware!", "The best material model of a cat is another, or preferably the same, cat.", "He who loves practice without theory is like the sailor who boards ship\n\twithout a rudder and compass.", "Nature uses as little as possible of anything.", "Mathematics is not yet ready for such problems.", "You can only find truth with logic if you have already found truth without it.", // 120 "Natural selection is a mechanism for generating an exceedingly high\n\tdegree of improbability.", "Similar figures exist only in pure geometry.", "Writing briefly takes far more time than writing at length.", "Like the crest of a peacock so is mathematics at the head of all knowledge.", "The real danger is not that computers will begin to think like men,\n\tbut that men will begin to think like computers.", "Why did the blond stare at the orange juice?\n\tit said concentrate.", "Hofstadter's Law: It always takes longer than you expect,\neven when you take into account Hofstadter's Law.", "It can be of no practical use to know that Pi is irrational, but if we\n\tcan know, it surely would be intolerable not to know.", "Life is a complex, it has real and imaginary parts.", "Beauty can be perceived but not explained.", // 130 "Programming is like sex: one mistake and you have to\n\tsupport it for the rest of your life. [Michael Sinz]", "I wish you were here and I was there [me].", "In mathematics you dont understand things, you just get used to them [Neumann].", "A man is incomplete until he is married. After that, he is finished [Zsa Zsa Gabor].", "Unlikely children's book title:\n\t\"The Kids' Guide to Hitchhiking\".", // 138 "Unlikely children's book title:\n\t\"Whining, Kicking and Crying to Get Your Way\".", "Unlikely children's book title:\n\t\"Dads New Wife Robert\".", "Unlikely children's book title:\n\t\"The Little Sissy Who Snitched\".", "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe [Einstein].", "The definition of insanity is doing the same thing over and over again and expecting different results [Einstein].", "Reality is merely an illusion, albeit a very persistent one [Einstein].", "The definition of insanity is doing the same thing over and over again and expecting different results [Einstein]", // 145 "Warning: Objects in your calendar are closer than they appear! Jim Duncan", "Wise men talk because they have something to say; fools, because they have to say something. [Plato]", "If the only tool you have is a hammer, you tend to see every problem as a nail. -- Abraham Maslow", "A meeting is an event at which the minutes are kept and the hours are lost. -- Murphy's Laws", "In theory, there is no difference between theory and practice. In practice, there is. -- Yogi Berra", // 150 "Free time? There's no such thing. It just comes in varying prices... -- Anonymous", "Pain is inevitable. Suffering is optional. M. Kathleen Casey", "You may delay, but time will not. [Benjamin Franklin]", "A clever person solves a problem. A wise person avoids it. [Einstein]", "The nice part about being a pessimist is that you are constantly being either proven right or pleasantly surprised. -- George F. Will", //155 "Statistics are like a bikini. What they reveal is suggestive, but what they conceal is vital. -Aaron Levenstein", "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty. Churchill", "Any sufficiently advanced technology is indistinguishable from magic – Arthur C. Clarke", "Pilot: \"...Tower, please call me a fuel truck.\"\n Tower: \"Roger. You are a fuel truck.\"", ""}; // ______ Get random seed and print quote +endl ______ const int32 NUMQUOTES = 159; const int32 seed = time(NULL); const int32 quotenumber = seed%NUMQUOTES; cerr << "\n ..." << QUOTES[quotenumber] << "\n\n"; } // END quote /**************************************************************** @brief copyright echos copyriht info * copyright * * BK 15-Nov-2000 * ****************************************************************/ void copyright() { TRACE_FUNCTION("copyright"); cerr << "\n\t *** ** ** * **" << "\n\t * * * * * * *" << "\n\t * * * * * * *" << "\n\t * * * * * * *" << "\n\t *** ** * * **\n" << "\n" << "\n" << "COPYRIGHT NOTICE:\n" << "-----------------\n" << " Doris program is free software; you can redistribute it and/or modify\n" << "it under the terms of the GNU General Public License as published by\n" << "the Free Software Foundation; either version 2 of the License, or\n" << "(at your option) any later version.\n" << "\n" << "Doris is distributed in the hope that it will be useful,\n" << "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" << "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" << "GNU General Public License for more details.\n" << "\n" << "You should have received a copy of the GNU General Public License\n" << "along with this program; if not, write to the Free Software\n" << "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n" << "--- (END COPYRIGHT NOTICE) ---\n" << "\n" << "Publications that contain results produced by the Doris software should \n" << "contain an acknowledgment. (For example: The interferometric processing \n" << "was performed using the freely available Doris software package developed \n" << "by the Delft Institute of Earth Observation and Space Systems (DEOS), Delft \n" << "University of Technology, or include a reference to: Bert Kampes and \n" << "Stefania Usai. \"Doris: The Delft Object-oriented Radar Interferometric \n" << "software.\" In: proceedings 2nd ITC ORS symposium, August 1999. (cdrom)).\n" << "\n[Written by Bert Kampes, (c)1998-2003].\n\n"; /* << "COPYRIGHT NOTICE:\n" << "Doris is a scientific-purpose software and cannot be commercialized, nor \n" << "can parts or products of it be commercialized. Parties interested in using \n" << "Doris or its products for any commercial purposes are requested to contact \n" << "Prof. Dr. Roland Klees of DEOS (r.klees@citg.tudelft.nl)\n" << "\n" << "Our version of the software is the only official one. Please do not \n" << "distribute the Doris software to third parties, instead refer to the Doris \n" << "home page. This in order to guarantee uniformity in the distribution of \n" << "updates and information.\n" << "\n" << "Delft University of Technology is not responsible for any damage caused by \n" << "errors in the software or the documentation.\n" << "\n" << "Users are very welcome to extend the capabilities of the Doris software by \n" << "implementing new algorithms or improving the existing ones. It is intended \n" << "that if new software is developed based on Doris, that this also is made \n" << "available for free to the other users (through us).\n" << "\n" << "We would appreciate if any addition or modification of the software would \n" << "be announced first to us, so that it can be included in the official \n" << "(next) version of the software.\n" << "\n" << "Publications that contain results produced by the Doris software should \n" << "contain an acknowledgment. (For example: The interferometric processing \n" << "was performed using the freely available Doris software package developed \n" << "by the Delft Institute of Earth Observation and Space Systems (DEOS), Delft \n" << "University of Technology, or include a reference to: Bert Kampes and \n" << "Stefania Usai. \"Doris: The Delft Object-oriented Radar Interferometric \n" << "software.\" In: proceedings ITC 2nd ORS symposium, August 1999. (cdrom)).\n" << "\n[Written by Bert Kampes, (c)1998-2003].\n\n"; */ exit(0); } // END copyright /**************************************************************** @brief preview generates cpxfiddle scripts for quicklooks @param previewflag etc. * preview * * create scritps to generate sunraster files. * * previewflag set by PREVIEW card: * * i.e.: 0: OFF; 1:ON (generate sh script); 2:xv (call shscript)* * BK 07-Feb-2002 * * MA 24 Dec 2008 updates due to g++ 4.3 * ****************************************************************/ void preview( int32 previewflag, int32 width, int32 formatflag, const char *infile, const string &outfile, const string &opts) { TRACE_FUNCTION("preview (BK 07-Feb-2002)"); DEBUG << "previewflag: " << previewflag; DEBUG.print(); if (previewflag==0) { DEBUG.print("NO preview requested."); return; } char scriptname[127]; #if defined WIN32 || defined (WINDOWS) strcpy(scriptname,outfile.c_str()); strcat(scriptname,".bat"); #else strcpy(scriptname,"./");// prevent error if "." is not in path (unix/linux/cygwin slash) //strcat(scriptname,outfile); strcat(scriptname,outfile.c_str()); strcat(scriptname,".sh"); #endif INFO.reset();// be sure to get rid of old chars before system call if (previewflag<3) { PROGRESS.print("Start PREVIEW generation."); // ______ find out format of inputfile ______ switch (formatflag) { case FORMATCR4: { INFO << "cpxfiddle -w " << width << " " << opts; INFO << " -f cr4 -l1 -p1 -P" << width;// -L? break; } case FORMATCI2: { INFO << "cpxfiddle -w " << width << " " << opts; INFO << " -f ci2 -l1 -p1 -P" << width;// -L? break; } // ___ trick cpxfiddle, make it think this complex ___ // ___ width is in complex pixels, but hgt is band interleaved ___ // ___ read second band (phase) as part of complex file___ // ___ -q normal must be set to trick cpxfiddle ___ case FORMATHGT: { PROGRESS.print( "Trying to trick cpxfiddle for HGT format (should work)"); int32 start_band_2 = int32(floor(width/2.0)+2.0);// (start at 1) DEBUG << "start of second band for cpxfiddle: " << start_band_2; DEBUG.print(); INFO << "cpxfiddle -w " << width << " " << opts; INFO << " -f cr4 -l1 -p" << start_band_2 << " -P" << width; break; } // ___ trick cpxfiddle, make it think this complex ___ // ___ this may not always work (in case of odd width)___ // ___ -q normal must be set to trick cpxfiddle ___ case FORMATR4: { // [added real4 option to cpxfiddle BK 13-Apr-2003] PROGRESS.print( "Trying to trick cpxfiddle for REAL4 format (should work)"); INFO << "cpxfiddle -w " << width << " " << opts; INFO << " -f r4 -l1 -p1 -P" << width; break; } default: PRINT_ERROR("PREVIEW generation: Unknown formatflag.") throw(unhandled_case_error);// exit } INFO << " " << infile << " > " << outfile << ends; INFO.print("With following command the SUNraster image can be generated again."); INFO.print(INFO.get_str());// buffer should not be touched by previous print // ______ Create the script ______ // ofstream scriptfile; scriptfile.open(scriptname, ios::out); bk_assert(scriptfile,scriptname,__FILE__,__LINE__); #ifdef WIN32 scriptfile << "REM !/bin/sh\n" << "REM Script generated by Doris software to preview binary file.\n" << "REM The program cpxfiddle is called to create a SUNraster file.\n" << "REM For unwrapped interferograms (hgt format) cpxfiddle is tricked.\n" << "REM Send comments to: doris-users \n" << "REM to run this script type at prompt:\n" << "REM " << scriptname << endl << INFO.get_str() << endl; if (previewflag==2) { scriptfile << "cximage " << outfile << endl;// Jia uses this windows viewer } scriptfile << "REM EOF\n"; scriptfile.close(); #else scriptfile << "#!/bin/sh\n" << "# Script generated by Doris software to preview binary file.\n" << "# The program cpxfiddle is called to create a SUNraster file.\n" << "# For unwrapped interferograms (hgt format) cpxfiddle is tricked.\n" << "# Send comments to: doris-users \n" << "# to run, type at prompt:\n" << "# " << scriptname << endl << INFO.get_str() << endl; if (previewflag==2) { scriptfile << "xv " << outfile << endl; } scriptfile << "# EOF\n"; scriptfile.close(); // // ______ Make file executable via system call to chmod ______ // DEBUG << "chmod +x " << scriptname << endl << ends; DEBUG.print();// rewinds buffer (for next call) system(DEBUG.get_str()); #endif // ______ Actual make the call ______ // INFO.reset();// make sure buffer is empty before system call INFO << scriptname << "&" << endl << ends; system(INFO.get_str()); INFO.print();// resets buffer (for next call) PROGRESS << "SUNraster file created of: " << infile << " (see also file: " << scriptname << ")"; PROGRESS.print(); } else { PRINT_ERROR("PREVIEW generation: Unknown option.") throw(unhandled_case_error);// exit } } // END preview Doris-5.0.3Beta/doris_core/productinfo.cc000077500000000000000000000537411312547014700204070ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/productinfo.cc,v $ * * $Revision: 3.13 $ * * $Date: 2005/08/01 15:51:19 $ * * $Author: kampes $ * * * * implementation of product info class. * * - data filling/updating. * * - reading in matrices. * * - etc. * #%// BK 01-Sep-2000 ****************************************************************/ #include "constants.hh" // DEBUG #include "productinfo.hh" // declarations, constants.h #include "ioroutines.hh" // printcpu #include "exceptions.hh" // my exceptions class /**************************************************************** * productinfo::fillproductinfo * * Fills data of productinfo object, read from resultfile after * * steps that produced a product, identified by 'iden'. * * 13 lines are checked for info, first occurence counts. * * exit if 8 are found, or 15 lines are checked. * * and read information upto string ":_NORMAL" (i.e., only read * * appropriate section * * * * "Data_output_file:" * * "Data_output_format:" * * "Multilookfactor_azimuth_direction:" * * "Multilookfactor_range_direction:" * * "First_line" (w.r.t. original): * * "Last_line" (w.r.t. original): * * "First_pixel" (w.r.t. original): * * "Last_pixel" (w.r.t. original): * * * * input: * * - resultfilename * * - identifier * * output: * * - (updated) productinfo * * * * Bert Kampes, 22-Dec-1998 * * Dont know why found1 is used more then ones? * * BK 13-april-2000 * #%// BK 01-Sep-2000 class implementation * * added check for filesize * #%// BK 08-Mar-2001 * * added stop after ":_NORMAL" found * #%// Bert Kampes, 01-Aug-2005 * #%// Mahmut Arikan, 02/2010 ONE27 --> 2*ONE27 * ****************************************************************/ void productinfo::fillproductinfo( const char* resultfile, const char* iden) { TRACE_FUNCTION("fillproductinfo (BK 01-Sep-2000)") char word[4*ONE27]=" "; // MA 4*ONE27 char dummyline[4*ONE27]; // ______Open file______ ifstream resfile(resultfile, ios::in); bk_assert(resfile,resultfile,__FILE__,__LINE__); bool foundiden = false; while(resfile) { if (strcmp(word,iden)) // Lookfor identifier { resfile.getline(dummyline,4*ONE27,'\n'); // next line resfile >> word; // read word } else { foundiden = true; break; } } // ______Check if section has been found______ if (!foundiden) { ERROR << "(fillproductinfo). identifier: \"" << iden << "\" not found in file: " << resultfile; PRINT_ERROR(ERROR.get_str()) throw(file_error); } // ======Extract info (file name/format and window size)====== int32 numlineschecked = 0; // number of lines checked after iden bool foundfilename = false; bool foundfileformat = false; bool foundfirstline = false; bool foundlastline = false; bool foundfirstpixel = false; bool foundlastpixel = false; bool foundmlL = false; bool foundmlP = false; while(resfile) // i.e. rest of file { resfile.getline(dummyline,4*ONE27,'\n'); // next line TRACE << "dummyline: " << dummyline; TRACE.print(); // ___ Check if we are at end of section already ____ char *pch; pch = strstr(dummyline,":_NORMAL");// section terminator if (pch != NULL) { DEBUG.print("Section terminator found (string \":_NORMAL\")."); break;// section ends } // ___ Check if all parameters are found ______ if (foundfilename && foundfileformat && foundfirstline && foundlastline && foundfirstpixel && foundlastpixel && foundmlL && foundmlP) break; //if (numlineschecked == 13) break; // report that 13 was too little for some output sections // so increased it to 15, BK 07-05-2002 if (numlineschecked == 15) break; numlineschecked++; // ___ Check for strings with parameters ___ resfile >> word; // read word if (!strcmp(word,"Data_output_file:")) { if (!foundfilename) { foundfilename = true; resfile >> file; DEBUG << "String: \"Data_output_file:\", \t\t\tvalue: " << file; DEBUG.print(); } else WARNING.print("String: \"Data_output_file:\" found again (ignored)."); } else if (!strcmp(word,"Data_output_format:")) { if (!foundfileformat) { foundfileformat = true; resfile >> word; if (!strcmp(word,"complex_short")) formatflag = FORMATCI2; else if (!strcmp(word,"complex_real4")) formatflag = FORMATCR4; else if (!strcmp(word,"real4")) formatflag = FORMATR4; else if (!strcmp(word,"hgt")) formatflag = FORMATHGT; else { PRINT_ERROR("wrong format specifier (impossible?)") throw(unhandled_case_error); } DEBUG << "String: \"Data_output_format:\", \t\tvalue: " << formatflag; DEBUG.print(); } else WARNING.print("String: \"Data_output_format:\" found again (ignored)."); } else if (!strcmp(word,"Multilookfactor_azimuth_direction:")) { if (!foundmlL) { foundmlL = true; resfile >> multilookL; DEBUG << "String: \"Multilookfactor_azimuth_direction:\", value: " << multilookL; DEBUG.print(); } else WARNING.print("String: \"Multilookfactor_azimuth_direction:\" found again (ignored)."); } else if (!strcmp(word,"Multilookfactor_range_direction:")) { if (!foundmlP) { foundmlP = true; resfile >> multilookP; DEBUG << "String: \"Multilookfactor_range_direction:\", \tvalue: " << multilookP; DEBUG.print(); } else WARNING.print("String: \"Multilookfactor_range_direction:\" found again (ignored)."); } else if (!strcmp(word,"First_line")) // (w.r.t. original): { if (!foundfirstline) { foundfirstline = true; resfile >> word >> word >> win.linelo ; DEBUG << "String: \"First_line:\", \t\t\tvalue: " << win.linelo; DEBUG.print(); } else WARNING.print("String: \"First_line:\" found again (ignored)."); } else if (!strcmp(word,"Last_line")) // (w.r.t. original): { if (!foundlastline) { foundlastline = true; resfile >> word >> word >> win.linehi ; DEBUG << "String: \"Last_line:\", \t\t\tvalue: " << win.linehi; DEBUG.print(); } else WARNING.print("String: \"Last_line:\" found again (ignored)."); } else if (!strcmp(word,"First_pixel")) // (w.r.t. original): { if (!foundfirstpixel) { foundfirstpixel = true; resfile >> word >> word >> win.pixlo ; DEBUG << "String: \"First_pixel:\", \t\t\tvalue: " << win.pixlo; DEBUG.print(); } else WARNING.print("String: \"First_pixel:\" found again (ignored)."); } else if (!strcmp(word,"Last_pixel")) // (w.r.t. original): { if (!foundlastpixel) { foundlastpixel = true; resfile >> word >> word >> win.pixhi ; DEBUG << "String: \"Last_pixel:\", \t\t\tvalue: " << win.pixhi; DEBUG.print(); } else WARNING.print("String: \"Last_pixel:\" found again (ignored)."); } } // while resultfile // ______ Check filesize with format/dimensions (BK 08-Mar-2001) ______ // BK 08-Mar-2001 //ifstream tmpfile(file, ios::in | ios::nocreate); ifstream tmpfile(file, ios::in); if (tmpfile) { tmpfile.seekg(0,ios::end); // internal filesize, normal one exists if not exists // uint filesizetrue = tmpfile.tellg(); const streamoff &filesizetrue = tmpfile.tellg(); // [MA] file > 4GB support, this fix eliminates wrong warning int16 bytesperelem = 4; if (formatflag==FORMATCI2) bytesperelem=4; if (formatflag==FORMATCR4) bytesperelem=8; if (formatflag==FORMATR4) bytesperelem=4; if (formatflag==FORMATI2) bytesperelem=2; if (formatflag==FORMATI2_BIGENDIAN) bytesperelem=2; if (formatflag==FORMATR8) bytesperelem=8; if (formatflag==FORMATHGT) bytesperelem=8; // int32 filesizecomp = int32(win.lines()/multilookL) * uint64 filesizecomp = (uint64)(win.lines()/multilookL) * (win.pixels()/multilookP) * bytesperelem; DEBUG << "Checking format/dimensions file=" << file; DEBUG.print(); if (filesizecomp != filesizetrue) { WARNING << "File: \'" << file << "\' has wrong fileformat or dimensions" // [MA] reorganized + add file << ": bytesperpix=" << bytesperelem << ", #l=" << win.lines()/multilookL // [MA] << ", #p=" << win.pixels()/multilookP << "; size_computed=" << filesizecomp << "B" << " v." << " size_ondisk=" << filesizetrue << "B"; WARNING.print(); } else { DEBUG.print("Fileformat and dimensions are checked and ok."); } tmpfile.close(); } // stream ok else { WARNING << "File: " << file << " does not seem to exist (may not be a problem)."; WARNING.print(); } // ______Tidy up______ DEBUG.print(""); resfile.close(); #ifdef __DEBUG DEBUG.print("finished fillproductinfo"); DEBUG.print("content of struct:"); showdata(); #endif } // END fillproductinfo /**************************************************************** * productinfo::readphase * * read data from file in a real4 matrix * * phase is extracted from hgt, not unwrapped set to NaN * * real4 is read 'as is'. * * complex real4: angle is taken. * * hgt: phase is read, set to NaN if amplitude==0 * * cutout window in own system starting at line 1, * * (no offset win) * * This function is useful for reading products: complex interf.* * unwrapped interf. and to get phase for s2h etc. * #%// BK 22-Sep-2000 * ****************************************************************/ matrix productinfo::readphase( window cutout) const // window to be read { TRACE_FUNCTION("productinfo::readphase (BK 22-Sep-2000)") // ______ Check if cutout < #lines/pixels ______ const int32 linesondisk = int32(win.lines()/multilookL); const int32 pixelsondisk = int32(win.pixels()/multilookP); #ifdef __DEBUGMAT2 if (cutout.linelo < 1) { PRINT_ERROR("readphase: cutout window larger than what's on disk!") throw(input_error); } if (cutout.linehi>linesondisk) { PRINT_ERROR("readphase: cutout window larger than what's on disk!") throw(input_error); } if (cutout.pixlo < 1) { PRINT_ERROR("readphase: cutout window larger than what's on disk!") throw(input_error); } if (cutout.pixhi>pixelsondisk) { PRINT_ERROR("readphase: cutout window larger than what's on disk!") throw(input_error); } #endif // ______ Open file ______ //#ifdef __NO_IOS_BINARY__ // ifstream ifile(file, ios::in); //#else // ifstream ifile(file, ios::in | ios::binary); //#endif ifstream ifile; openfstream(ifile,file); bk_assert(ifile,file,__FILE__,__LINE__); matrix Result(cutout.lines(),cutout.pixels()); // ====== Actual read data ====== switch (formatflag) { case FORMATR4: { // why not use readfile function? DEBUG.print("reading real4 from file"); matrix LINE(1,cutout.pixels()); // phase for (int32 line=cutout.linelo; line<=cutout.linehi; ++line) { uint64 start = (uint64)(cutout.pixlo-1 + pixelsondisk*(line-1)) * sizeof(real4); ifile.seekg(start,ios::beg); ifile >> LINE; Result.setrow(line-cutout.linelo,LINE); // not the fastest way... // but cannot write directly // to private data ... (bk) } break; } case FORMATCR4: { DEBUG.print("reading complex real4 from file (get phase)"); const window dummyoffset(1,99999,1,99999); // only 1's used -> no offset matrix TMP(cutout.lines(),cutout.pixels()); readfile(TMP,file,linesondisk,cutout,dummyoffset); Result = angle(TMP); break; } // ______ hgt: first amplitude band, then phase, then next line ______ case FORMATHGT: { DEBUG.print("reading hgt (band interleaved) from file (get phase)"); // ______ Read in one line, set to NaN, fill result ______ matrix LINE(1,win.pixels()*2); // disk phase/ampl band interleaved for (int32 line=cutout.linelo; line<=cutout.linehi; ++line) { const int32 start = (line-1) * pixelsondisk * 2 * sizeof(real4); ifile.seekg(start,ios::beg); // file pointer to 1st pix of line ifile >> LINE; for (int32 pix=cutout.pixlo; pix<=cutout.pixhi; ++pix) { // ______ Check amplitude defined as 0 if not unwrapped ok. ______ if (LINE(0,pix-1) == 0.) // ampl. band Result(line-cutout.linelo,pix-cutout.pixlo) = NaN; else // phase band Result(line-cutout.linelo,pix-cutout.pixlo) = LINE(0,pix-1+pixelsondisk); } } break; } default: PRINT_ERROR("readphase::not correct format on file.") throw(unhandled_case_error); } ifile.close(); return Result; } // END readphase /**************************************************************** * productinfo::readdata * * read data from file in a complex real4 matrix * * complex real4 * * cutout window in own system starting at line 1, * * (no offset win) * * This function is useful for reading products: complex interf.* * unwrapped interf. and to get phase for s2h etc. * #%// BK 22-Sep-2000 (readphase) * #%// Batu 30-JUL-2007 * ****************************************************************/ matrix productinfo::readdata( window cutout) const // window to be read { TRACE_FUNCTION("productinfo::readdata (Batu 30-JUL-2007)") // ______ Check if cutout < #lines/pixels ______ const int32 linesondisk = int32(win.lines()/multilookL); const int32 pixelsondisk = int32(win.pixels()/multilookP); #ifdef __DEBUGMAT2 if (cutout.linelo < 1) { PRINT_ERROR("readdata: cutout window larger than what's on disk!") throw(input_error); } if (cutout.linehi>linesondisk) { PRINT_ERROR("readdata: cutout window larger than what's on disk!") throw(input_error); } if (cutout.pixlo < 1) { PRINT_ERROR("readdata: cutout window larger than what's on disk!") throw(input_error); } if (cutout.pixhi>pixelsondisk) { PRINT_ERROR("readdata: cutout window larger than what's on disk!") throw(input_error); } #endif // ______ Open file ______ //#ifdef __NO_IOS_BINARY__ // ifstream ifile(file, ios::in); //#else // ifstream ifile(file, ios::in | ios::binary); //#endif ifstream ifile; openfstream(ifile,file); bk_assert(ifile,file,__FILE__,__LINE__); matrix Result(cutout.lines(),cutout.pixels()); // ====== Actual read data ====== DEBUG.print("reading complex real4 from file (readdata)"); const window dummyoffset(1,99999,1,99999); // only 1's used -> no offset readfile(Result,file,linesondisk,cutout,dummyoffset); ifile.close(); return Result; } // END readdata /**************************************************************** * productinfo::readdatar4 * * read data from file in a complex real4 matrix * * complex real4 * * cutout window in own system starting at line 1, * * (no offset win) * * This function is useful for reading products: complex interf.* * unwrapped interf. and to get phase for s2h etc. * #%// BK 22-Sep-2000 (readphase) * #%// Batu 30-JUL-2007 * #%// MA 19-NOV-2008 [TODO] template * ****************************************************************/ matrix productinfo::readdatar4( window cutout) const // window to be read { TRACE_FUNCTION("productinfo::readdatar4 (MA & BO 19-NOV-2008)") // --- Log debug info --- DEBUG << "Reading file: " << file; DEBUG.print(); DEBUG << "Formatflag: " << formatflag; DEBUG.print(); DEBUG << "Currentwindow: "; win.disp(); // appends to DEBUG and prints // [MA] tricked since productinfo lacks currentwindow() DEBUG << "Window from file: "; cutout.disp(); // appends to DEBUG and prints // // ______ Check if cutout < #lines/pixels ______ const int32 linesondisk = int32(win.lines()/multilookL); const int32 pixelsondisk = int32(win.pixels()/multilookP); #ifdef __DEBUGMAT2 if (cutout.linelo < 1) { PRINT_ERROR("readdata: cutout window larger than what's on disk!") throw(input_error); } if (cutout.linehi>linesondisk) { PRINT_ERROR("readdata: cutout window larger than what's on disk!") throw(input_error); } if (cutout.pixlo < 1) { PRINT_ERROR("readdata: cutout window larger than what's on disk!") throw(input_error); } if (cutout.pixhi>pixelsondisk) { PRINT_ERROR("readdata: cutout window larger than what's on disk!") throw(input_error); } #endif ifstream ifile; openfstream(ifile,file); bk_assert(ifile,file,__FILE__,__LINE__); ifile.close(); //matrix Result(cutout.lines(),cutout.pixels()); // ====== Actual read data ====== switch (formatflag) { case FORMATR4: // [MA] bigendian support { matrix Result(cutout.lines(),cutout.pixels()); DEBUG.print("reading real4 from file (readdata)"); //const window dummyoffset(1,99999,1,99999); // only 1's used -> no offset //readfile(Result,file,linesondisk,cutout,dummyoffset); readfile(Result,file,linesondisk,cutout,win); return Result; break; } // case FORMATR8: // { // matrix Result(cutout.lines(),cutout.pixels()); // DEBUG.print("reading real8 from file (readdata)"); // readfile(Result,file,linesondisk,cutout,win); // return Result; // break; // } // case FORMATCR4: // { // matrix Result(cutout.lines(),cutout.pixels()); // DEBUG.print("reading complex real4 from file (readdata)"); // readfile(Result,file,linesondisk,cutout,win); // return Result; // break; // } default: PRINT_ERROR("readdata::not correct format on file.") throw(file_error); } //return Result; } // END readdatar4 Doris-5.0.3Beta/doris_core/productinfo.hh000077500000000000000000000104061312547014700204100ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/productinfo.hh,v $ * * $Revision: 3.10 $ * * $Date: 2005/08/24 10:03:18 $ * * $Author: kampes $ * * * * The productinfo class contains the definition of the data * * and functions for 'products' (i.e. not slc images, but the * * interferogram, coherence image, DEM etc.) * * Data mainly public because this used to be a struct and I * * did not want to change the other code. * * It also consists of functions reading files etc. * #%// BK 25-Aug-2000 ****************************************************************/ #ifndef PRODUCTINFO_H #define PRODUCTINFO_H using namespace std; // BK 29-Mar-2003, new compiler? // Jia defined this for compilation under windows // Bert Kampes, 24-Aug-2005 #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "constants.hh" // typedefs #include // strcpy, req. on some systems // ====== Define template functions (no member no friend) ====== // ______ (matrix class is declared way below) ______ template class matrix; // ====== Struct slcimage: information on master/slave ====== class productinfo // info on 'products' { public: char file[EIGHTY]; // current filename // ______ window / multilook factors ______ window win; // current window, line(1:N) etc uint multilookL; // multilookfactor in line (azi) dir. uint multilookP; // multilookfactor in pixel (ra) dir. // ______ file format ______ int16 formatflag; // current read formatflag // ______ Public function in struct ______ // ______ constructor ______ productinfo() { formatflag = -1;// undefined multilookL = 1; multilookP = 1; } // rest ==0 // ______ fill it from info in resultfiles ______ void fillproductinfo(const char *file, const char *iden); // ______ assignment operator ______ productinfo& operator = (productinfo X) { if (this != &X) { strcpy(file,X.file); win = X.win; multilookL = X.multilookL; multilookP = X.multilookP; formatflag = X.formatflag; } return *this; }; // ______ show content ______ inline void showdata() const // show content {DEBUG << "\ncurrent file: \t" << file << "\nformatflag: \t" << formatflag << "\nmultilook: \t" << multilookL << " " << multilookP << "\nwindow: \t" << win.linelo << " " << win.linehi << " " << win.pixlo << " " << win.pixhi; DEBUG.print(); } // ______ read data from file ______ matrix readphase(window win) const; // ______ read data from file ______ matrix readdata(window win) const; matrix readdatar4(window win) const; // [MA] }; // END class productinfo #endif // PRODUCTINFO_H Doris-5.0.3Beta/doris_core/products.cc000077500000000000000000004355061312547014700177210ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/products.cc,v $ * * $Revision: 3.21 $ * * $Date: 2006/05/18 11:09:20 $ * * $Author: kampes $ * * * * implementation of computation of products. * * -complex interferogram * * -interferogram (minus reference fase) * * -magnitude image -> coherence image * * -differential insar. * ****************************************************************/ #include "constants.hh" // global constants #include "matrixbk.hh" // my matrix class #include "orbitbk.hh" // my orbit class #include "slcimage.hh" // my slc image class #include "productinfo.hh" // my 'products' class #include "products.hh" // header file #include "utilities.hh" // utils #include "ioroutines.hh" // #include "exceptions.hh" // my exceptions class #include "bk_baseline.hh" // my baseline class #include "referencephase.hh" // getcorners, griddatalinear for simamp ; // getcorners --> should go to utilities.hh I guess [MA] TODO #include // generic max #ifdef WIN32 // Jia defined this here, i did this in constants.hh // Bert Kampes, 24-Aug-2005 //#define max _MAX //#define min _MIN #endif #ifdef WIN32 // [MA] following added due to ntohl requirments in master_timing simulation // Jia defined this. // Bert Kampes, 24-Aug-2005 #include "winsock2.h" #else #include // ntohl byteorder x86-HP unix #endif /**************************************************************** * compinterfero * * * * Compute products: * * - (compex) interferogram * * note: master-slave * * Assumed that slave.currentwin is in master coord. system * * and is smaller than or equal to maste.currentwin. * * * * Input: * * - input arguments, filenames * * Output: * * - files on disk * * Bert Kampes, 07-Apr-1999 * * * * bugfix computations, subtract reference phase * * for all points before multilooking. * * Bert Kampes, 06-Oct-1999 * * * * Change log: - FvL, 23-Jul-2014, removed unwanted automatic * * removal of pre-calculated reference phase * ****************************************************************/ void compinterfero( const slcimage &master, const slcimage &slave, const input_gen &input_general, const input_interfero &input_i_interfero) { TRACE_FUNCTION("compinterfero (BK 06-Oct-1999)"); INFO << "INTERFERO: master input file: " << master.file; INFO.print(); INFO << "INTERFERO: slave input file: " << slave.file; INFO.print(); #ifdef __DEBUG // ______This should be checked before, impossible______ if (slave.currentwindow.linelo < master.currentwindow.linelo || slave.currentwindow.linehi > master.currentwindow.linehi || slave.currentwindow.pixlo < master.currentwindow.pixlo || slave.currentwindow.pixhi > master.currentwindow.pixhi ) { slave.currentwindow.disp(); master.currentwindow.disp(); slave.currentwindow.disp(); PRINT_ERROR("Panic, interferogram.win smaller than master win.") throw(file_error); } #endif INFO << "INTERFERO: interferogram (master coord.): " << slave.currentwindow.linelo << ":" << slave.currentwindow.linehi << "; " << slave.currentwindow.pixlo << ":" << slave.currentwindow.pixhi; INFO.print(); // ___ Check what to do ___ //const uint BUFFERMEMSIZE = input_general.memory; const real8 BUFFERMEMSIZE = input_general.memory; const int32 multiL = input_i_interfero.multilookL; const int32 multiP = input_i_interfero.multilookP; bool nocint = true; // output complex phase image bool noint = true; // no output real phase image if (specified(input_i_interfero.focint)) nocint = false; if (specified(input_i_interfero.foint)) noint = false; // ______ Normalize data for polynomial ______ const real8 minL = master.originalwindow.linelo; const real8 maxL = master.originalwindow.linehi; const real8 minP = master.originalwindow.pixlo; const real8 maxP = master.originalwindow.pixhi; // ====== Open output files ====== ofstream ofilecint; if (!nocint) { openfstream(ofilecint,input_i_interfero.focint,input_general.overwrit); bk_assert(ofilecint,input_i_interfero.focint,__FILE__,__LINE__); } ofstream ofileint; if (!noint) { openfstream(ofileint,input_i_interfero.foint,input_general.overwrit); bk_assert(ofileint,input_i_interfero.foint,__FILE__,__LINE__); } // ====== allocate matrices ====== const int32 numpixels = (slave.currentwindow.pixels()); const int32 bytesperline = numpixels * sizeof(complr4); const real4 numbigmatrices = 3.2; // M, S //int32 numlines = int32((BUFFERMEMSIZE/numbigmatrices)/bytesperline);// lines in buffer int32 numlines = int32(ceil( (BUFFERMEMSIZE/numbigmatrices) / bytesperline )); // lines in buffer [MA] see reference.cc BUFFERMEMSIZE while (numlines%multiL) // correct numlines to multiple of multiL numlines -= 1; if (numlines%multiL) { PRINT_ERROR("panic : totally impossible on HP aCC compiler.") throw(input_error); } int32 nummllines = numlines/multiL; // exact int32 nummlpixels = numpixels/multiP; // floor... if (nummllines < 1) { PRINT_ERROR("Please increase memory (MEMORY card) or decrease multiL (INT_MULTILOOK card).") throw(input_error); } DEBUG << "Number of lines per buffer: " << numlines; DEBUG.print(); // ______ Number of lines on file ______ // Ifile contains lines of resampled slave ? //const uint Mfilelines = master.currentwindow.lines(); const uint Ifilelines = slave.currentwindow.lines(); // ______ Window in master system to load from file ______ window winfile(slave.currentwindow.linelo, slave.currentwindow.linelo + numlines - 1, slave.currentwindow.pixlo, slave.currentwindow.pixhi); // ====== Loop over all totally filled buffers ====== // ______ Mis-use Master to store complex interferogram (also multilooked) //register int32 i,blocks; const int32 numfullbuffers = Ifilelines/numlines; // fully filled buffers const int32 numrestlines = Ifilelines%numlines; // restlines total const int32 nummlrestlines = numrestlines/multiL; // floor... const int32 EXTRABUFFER = nummlrestlines ? 1 : 0; for (int32 blocks=1; blocks<=numfullbuffers+EXTRABUFFER; blocks++) { // ______ Progress info ______ PROGRESS << "INTERFERO: " << int32(100*real4(blocks-1)/(real4(Ifilelines)/real4(numlines))+0.5) << "%"; PROGRESS.print(); // ______ Check last block ______ if (blocks == (numfullbuffers+1)) // there is an extra (smaller) block { numlines = multiL * nummlrestlines; winfile.linehi = numlines + winfile.linelo - 1; } // ______ Fill buffers master/slave from disk ______ matrix MASTER = master.readdata(winfile); matrix SLAVE = slave.readdata(winfile); // ______ Compute M = M* conj(S) ______ MASTER *= conj(SLAVE); // ?better SLAVE.conj(); for speed and memory // ====== Multilook if appropriate ====== matrix ML = multilook(MASTER,multiL,multiP); // ====== Write (partial) products to file ====== if (!nocint) // complex interferogram ofilecint << ML; if (!noint) // phase image ofileint << fast_angle(ML); // ______ Update window from file ______ winfile.linelo = winfile.linehi + 1; winfile.linehi += numlines; } // loop blocks // ====== Write results to file ====== ofstream scratchlogfile("scratchloginterfero", ios::out | ios::trunc); bk_assert(scratchlogfile,"compinterfero: scratchloginterfero",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* COMPUTATION OF INTERFEROGRAM" << "\n*******************************************************************" << "\nInput file master (format): \t\t\t" << master.file << " " << master.formatflag << "\nInput file slave (format): \t\t\t" << slave.file << " " << slave.formatflag << "\ncomplex interferogram: \t\t" << input_i_interfero.focint << "\ninterferogram: \t\t" << input_i_interfero.foint << "\nNumber of lines (multilooked): \t" << Ifilelines / multiL << "\nNumber of pixels (multilooked): \t" << nummlpixels << "\nMultilookfactor in line direction: \t" << multiL << "\nMultilookfactor in pixel direction: \t" << multiP << "\nTip: dismph " << input_i_interfero.focint << " " << nummlpixels << " 1 500" << "\n*******************************************************************\n"; scratchlogfile.close(); ofstream scratchresfile("scratchresinterfero", ios::out | ios::trunc); bk_assert(scratchresfile,"compinterfero: scratchresinterfero",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************" << "\n*_Start_" << processcontrol[pr_i_interfero] << "\n*******************************************************************"; if (!nocint) { scratchresfile << "\nData_output_file: \t\t\t" << input_i_interfero.focint << "\nData_output_format: \t\t\t" << "complex_real4"; } if (!noint) { scratchresfile << "\nData_output_file_real_interferogram: \t" << input_i_interfero.foint << "\nData_output_format_real_interferogram: \t\t" << "real4"; } scratchresfile << "\nFirst_line (w.r.t. original_master): \t" << slave.currentwindow.linelo << "\nLast_line (w.r.t. original_master): \t" << slave.currentwindow.linehi << "\nFirst_pixel (w.r.t. original_master): \t" << slave.currentwindow.pixlo << "\nLast_pixel (w.r.t. original_master): \t" << slave.currentwindow.pixhi << "\nMultilookfactor_azimuth_direction: \t" << multiL << "\nMultilookfactor_range_direction: \t" << multiP << "\nNumber of lines (multilooked): \t\t" << Ifilelines / multiL << "\nNumber of pixels (multilooked): \t" << nummlpixels << "\n*******************************************************************" << "\n* End_" << processcontrol[pr_i_interfero] << "_NORMAL" << "\n*******************************************************************\n"; scratchresfile.close(); // ______Tidy up______ PROGRESS.print("finished compinterfero."); if (!nocint) ofilecint.close(); if (!noint) ofileint.close(); } // END compinterfero /**************************************************************** * compcoherence * * * * Compute products: * * - (compex) coherence. * * note: master-slave-ref * * Assumed that slave.currentwin is in master coord. system * * and is smaller than or equal to maste.currentwin. * * * * Input: * * - input arguments, filenames * * Output: * * - files on disk * * * * Bert Kampes, 16-Apr-1999 * ****************************************************************/ void compcoherence( const slcimage &master, const slcimage &slave, const input_gen &input_general, const input_coherence &input_i_coherence, const matrix &coeff_flatearth) { TRACE_FUNCTION("compcoherence (BK 16-Apr-1999)") #ifdef __DEBUG // ______This should be checked before, impossible______ if (slave.currentwindow.linelo < master.currentwindow.linelo || slave.currentwindow.linehi > master.currentwindow.linehi || slave.currentwindow.pixlo < master.currentwindow.pixlo || slave.currentwindow.pixhi > master.currentwindow.pixhi ) { PRINT_ERROR("Panic, impossible 3333.") throw(input_error); } #endif bool nocoh = true; // no output real coherence bool noccoh = true; // no output complex coherence bool noflatearthcorrection = false; // do correction string METHOD = "REFPHASE_ONLY"; // updated when necessary if (specified(input_i_coherence.focoh)) nocoh = false; if (specified(input_i_coherence.foccoh)) noccoh = false; if (coeff_flatearth.size() == 0) // step flatearth not done { // (not in result file) WARNING.print("Computation of coherence without subtracting of reference image."); noflatearthcorrection = true; METHOD = "NO_REFPHASE_REMOVED"; } // ______ Normalize data for polynomial ______ const real8 minL = master.originalwindow.linelo; const real8 maxL = master.originalwindow.linehi; const real8 minP = master.originalwindow.pixlo; const real8 maxP = master.originalwindow.pixhi; INFO << "compcoherence: polynomial normalized by factors: " << minL << " " << maxL << " " << minP << " " << maxP << " to [-2,2]"; INFO.print(); // ______ Some other variables ______ //const uint BUFFERMEMSIZE = input_general.memory; const real8 BUFFERMEMSIZE = input_general.memory; const int32 multiL = input_i_coherence.multilookL; const int32 multiP = input_i_coherence.multilookP; //const int32 multiLP = multiL*multiP; const int32 winsizeL = input_i_coherence.cohsizeL; const int32 winsizeP = input_i_coherence.cohsizeP; // ====== Open output files ====== ofstream ofileccoh; if (!noccoh) { openfstream(ofileccoh,input_i_coherence.foccoh,input_general.overwrit); bk_assert(ofileccoh,input_i_coherence.foccoh,__FILE__,__LINE__); } ofstream ofilecoh; if (!nocoh) { openfstream(ofilecoh,input_i_coherence.focoh,input_general.overwrit); bk_assert(ofilecoh,input_i_coherence.focoh,__FILE__,__LINE__); } // ====== allocate matrices ====== const int32 numpixels = (slave.currentwindow.pixhi-slave.currentwindow.pixlo+1); const int32 bytesperline = numpixels * sizeof(complr4); int32 numlines; // lines in buffer // ______ estimate numlines for correct memory usage ______ if (noflatearthcorrection) //numlines = int32((BUFFERMEMSIZE / 3.0) / bytesperline); numlines = int32(ceil( (BUFFERMEMSIZE / 3.0) / bytesperline )); // [MA] BUFFERMEMSIZE as real8 else numlines = int32(ceil( (BUFFERMEMSIZE / 3.5) / bytesperline )); while (numlines%multiL) // correct numlines to multiple of multiL numlines -= 1; if (numlines%multiL) { PRINT_ERROR("PANIC: multilookwindow not exactly in numlines.") throw(input_error); } int32 nummllines = numlines/multiL; // exact zero fraction int32 nummlpixels = numpixels/multiP; // i.e., floor() if (nummllines < 1) { PRINT_ERROR("increase memory (MEMORY card) or reduce multiL (COH_MULTILOOK card).") throw(input_error); } // ______ adapt numlines to extra for window ______ int32 numlines2 = numlines; // number of lines output of coherence numlines += (winsizeL - 1); // number of lines from file // ______ Number of lines on file ______ //const uint Mfilelines = master.currentwindow.lines(); const uint Ifilelines = slave.currentwindow.lines(); // ______ Window in master system to load from file ______ // uint firstline = slave.currentwindow.linelo; // uint lastline = firstline + numlines - 1; // do little different cause of firstblock //register int32 i,j; uint zerolinesstart = (winsizeL-1)/2;// overlap previous block? uint trailinglines = (winsizeL)/2;// overlap next block? int32 extrazerolines = 0;// larger last block /* // ____ ? why is this here? it seems not required ___ // ____ ? e.g., coh win=64, ml win=10 fails if this is done // ____ ? but I guess there was a situation, e.g., when // ____ ? the slave is resampled larger than the master? // ____ ? or when the ML window is much larger than the coh win. // ____ ? BK, sep.2004: commented out. uint writeallzero = zerolinesstart/multiL;// ?? int32 zerorestlines = zerolinesstart%multiL;// ?? INFO << "coherence: starting with zero lines: " << writeallzero; INFO.print(); if (writeallzero != 0) { if (!noccoh) { matrix zeroline(1,nummlpixels); for (i=0; i zeroline(1,nummlpixels); for (i=0; i SLAVE(winfile.linehi-winfile.linelo+1,numpixels); matrix MASTER; // ______ Axis for reference phase ______ matrix p_axis; if (!noflatearthcorrection) { p_axis.resize(numpixels,1); for (int32 i=0; i slave.currentwindow.linehi) // more then there is on file { lastblock = true; // ______ find out if execution of this buffer is required ______ int32 restlines = Ifilelines%multiL; // extra lines on file if (winfile.linelo+zerolinesstart >= slave.currentwindow.linehi-restlines+1) break; // ______ Resize matrices for last loop (1) ______ // ______ (not that well programmed...) ______ int32 lastlinerequired = slave.currentwindow.linehi - restlines + trailinglines; if (lastlinerequired > int32(slave.currentwindow.linehi)) { winfile.linehi = slave.currentwindow.linehi; extrazerolines = lastlinerequired - slave.currentwindow.linehi; } else { winfile.linehi = lastlinerequired; } INFO << "coherence: extra zero lines last buffer: " << extrazerolines; INFO.print(); MASTER.resize(winfile.linehi-winfile.linelo+1,numpixels); SLAVE.resize (winfile.linehi-winfile.linelo+1,numpixels); } else // not lastblock: give approx PROGRESS { // ______ Progress info: not totally accurate ______ PROGRESS << "COHERENCE: " << int32(100.0*real4(blocks)/(real4(Ifilelines)/real4(numlines2))+0.5) << "%"; PROGRESS.print(); } // ______ Fill buffers master/slave from disk ______ INFO << "coherence winfile: [" << winfile.linelo << ":" << winfile.linehi << ", " << winfile.pixlo << ":" << winfile.pixhi << "]"; INFO.print(); MASTER = master.readdata(winfile); SLAVE = slave.readdata(winfile); // ______ Add zero lines if firstblock ______ if (firstblock == true) { matrix TMP = SLAVE; SLAVE.resize(BUF*multiL+winsizeL-1,TMP.pixels()); const window wintmp(SLAVE.lines()-TMP.lines(), SLAVE.lines()-1, 0, SLAVE.pixels()-1); const window windef(0, 0, 0, 0); SLAVE.setdata(wintmp,TMP,windef); TMP = MASTER; MASTER.resize(BUF*multiL+winsizeL-1,TMP.pixels()); MASTER.setdata(wintmp,TMP,windef); INFO << "coherence: increase lines for first block: " << SLAVE.lines()-TMP.lines(); INFO.print(); } // ______ Resize matrices for last loop (2) ______ // ______ (not that well programmed...) ______ if (extrazerolines != 0) { const window wintmp(0, MASTER.lines()-1, 0, MASTER.pixels()-1); const window windef(0, 0, 0, 0); matrix TMP = SLAVE; SLAVE.resize(TMP.lines()+extrazerolines,TMP.pixels()); SLAVE.setdata(wintmp,TMP,windef); TMP = MASTER; MASTER.resize(TMP.lines()+extrazerolines,TMP.pixels()); MASTER.setdata(wintmp,TMP,windef); INFO << "coherence: increase lines for last block: " << SLAVE.lines()-TMP.lines(); INFO.print(); } // ______ Compute reference phase ______ uint sizeL = SLAVE.lines(); uint sizeP = SLAVE.pixels(); if (!noflatearthcorrection) { matrix l_axis(sizeL,1); for (uint i=0; i REFPHASE = polyval(l_axis, p_axis, coeff_flatearth); // ______ Complex interferogram in master, norms in slave ______ for (uint i=0; i CCOHERENCE = multilook( coherence(MASTER,SLAVE,winsizeL,winsizeP),multiL,multiP); ofileccoh << CCOHERENCE; ofilecoh << magnitude(CCOHERENCE); } else // thus only complex coherence { ofileccoh << multilook( coherence(MASTER,SLAVE,winsizeL,winsizeP),multiL,multiP); } } else if (!nocoh) // thus only (real) coherence requested { //ofilecoh << multilook( //coherence2(MASTER,SLAVE,winsizeL,winsizeP),multiL,multiP); // test: see size of blocks by using tmp matrix... matrix COHERENCE = coherence2(MASTER,SLAVE,winsizeL,winsizeP); INFO << "block: " << blocks << "; size COHERENCE matrix: " << COHERENCE.lines();// multiple of multiL ?? INFO.print(); ofilecoh << multilook(COHERENCE, multiL,multiP); } // ______ impossible request, is checked before. ______ else { PRINT_ERROR("2212 panic impossible.") throw(unhandled_case_error); } // ______ update windows/matrix size ______ winfile.linelo = winfile.linehi - trailinglines + 1 - zerolinesstart; winfile.linehi = winfile.linelo + numlines - 1; if (firstblock) { firstblock = false;// next time MASTER.resize(winfile.linehi-winfile.linelo+1,numpixels); SLAVE.resize(winfile.linehi-winfile.linelo+1,numpixels); } } // loop over all blocks // ====== Write results to file ====== ofstream scratchlogfile("scratchlogcoherence", ios::out | ios::trunc); bk_assert(scratchlogfile,"compcoherence: scratchlogcoherence",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* COMPUTATION OF COHERENCE" << "\n*******************************************************************" << "\nMethod: \t\t\t\t" << "REFPHASE_ONLY" << "\nInput file master (format): \t" << master.file << " " << master.formatflag << "\nInput file slave (format): \t" << slave.file << " " << slave.formatflag << "\ncomplex coherence: \t" << input_i_coherence.foccoh << "\ncoherence: \t" << input_i_coherence.focoh << "\nNumber of lines (multilooked): \t" << Ifilelines / multiL << "\nNumber of pixels (multilooked): \t" << nummlpixels << "\nMultilookfactor in line direction: \t" << multiL << "\nMultilookfactor in pixel direction: \t" << multiP << "\nNumber of lines window for coherence estimation: " << winsizeL << "\nNumber of pixels window for coherence estimation: " << winsizeP << "\nNumber of ml lines per buffer during computation: " << BUF << "\nTip: disfloat " << input_i_coherence.focoh << " " << nummlpixels << " 1 500" << "\n*******************************************************************\n"; scratchlogfile.close(); ofstream scratchresfile("scratchrescoherence", ios::out | ios::trunc); bk_assert(scratchresfile,"compcoherence: scratchrescoherence",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************" //<< "\n*_Start_coherence" << "\n*_Start_" << processcontrol[pr_i_coherence] << "\n*******************************************************************" << "\nMethod: \t\t\t\t" << METHOD; if (!nocoh) { scratchresfile << "\nData_output_file: \t\t\t" << input_i_coherence.focoh << "\nData_output_format: \t\t\t" << "real4"; } if (!noccoh) { scratchresfile << "\nData_output_file_complex_coherence: " << input_i_coherence.foccoh << "\nData_output_format_complex_coherence: \t\t" << "complex_real4"; } scratchresfile << "\nFirst_line (w.r.t. original_master): \t" // updateproductinfo greps these << slave.currentwindow.linelo << "\nLast_line (w.r.t. original_master): \t" << slave.currentwindow.linehi << "\nFirst_pixel (w.r.t. original_master): \t" << slave.currentwindow.pixlo << "\nLast_pixel (w.r.t. original_master): \t" << slave.currentwindow.pixhi << "\nMultilookfactor_azimuth_direction: \t" << multiL << "\nMultilookfactor_range_direction: \t" << multiP << "\nNumber of lines (multilooked): \t\t" << Ifilelines / multiL << "\nNumber of pixels (multilooked): \t" << nummlpixels << "\n*******************************************************************" << "\n* End_" << processcontrol[pr_i_coherence] << "_NORMAL" << "\n*******************************************************************\n"; scratchresfile.close(); // ______Tidy up______ PROGRESS.print("finished compcoherence."); if (!noccoh) ofileccoh.close(); if (!nocoh) ofilecoh.close(); } // END compcoherence /**************************************************************** * compcoherence * * * * Compute products: * * - (complex) coherence. * * Note: master-slave-ref.phase-demphase * * Assumptions: * * - slave.currentwin is in master coord. system and * * is smaller than or equal to maste.currentwin. * * - DEM ref.phase is not multilooked. * * * * Input: * * - input arguments, filenames * * Output: * * - files on disk * * * * Bert Kampes, 16-Apr-1999 * * Davide Oscar Nitti, 14-Nov-2008 (removal of topo slope) * * Mahmut Arikan, 09-Jan-2009 (nonML refdem update ) * ****************************************************************/ void compcoherence( const slcimage &master, const slcimage &slave, const productinfo &radarcodedrefdem, const input_gen &input_general, const input_coherence &input_i_coherence, const matrix &coeff_flatearth) { TRACE_FUNCTION("compcoherence (don 14-Nov-2008)") #ifdef __DEBUG // ______This should be checked before, impossible______ if (slave.currentwindow.linelo < master.currentwindow.linelo || slave.currentwindow.linehi > master.currentwindow.linehi || slave.currentwindow.pixlo < master.currentwindow.pixlo || slave.currentwindow.pixhi > master.currentwindow.pixhi ) { PRINT_ERROR("Panic, impossible 3333.") throw(input_error); } #endif // _____ start added by MA _____ string refdemfilenoML = string(radarcodedrefdem.file) + ".noML" ; // filename for no-mlooked refdem phase const uint &refdemmlL = radarcodedrefdem.multilookL; const uint &refdemmlP = radarcodedrefdem.multilookP; if ( !existed(refdemfilenoML.c_str()) && refdemmlL != 1) // [MA] multilooking of the refdem must match with the master and slave. { ERROR << "Coherence: missing non-multilook " << refdemfilenoML << " file."; PRINT_ERROR(ERROR.get_str()) ERROR.print("and MultilookfactorL ref. dem not equal to 1."); throw(input_error); } else if (!existed(refdemfilenoML.c_str()) && refdemmlP != 1) { ERROR << "Coherence: missing non-multilook " << refdemfilenoML << " file."; PRINT_ERROR(ERROR.get_str()) ERROR.print("and MultilookfactorP ref. dem not equal to 1."); throw(input_error); } // _____ end added by MA _____ bool nocoh = true; // no output real coherence bool noccoh = true; // no output complex coherence bool noflatearthcorrection = false; // do correction char checkrefdemIncludeFE[20]; readres(checkrefdemIncludeFE,sizeof(checkrefdemIncludeFE), input_general.i_resfile,"Include_flatearth:"); if (specified(input_i_coherence.focoh)) nocoh = false; if (specified(input_i_coherence.foccoh)) noccoh = false; if (!strcmp(checkrefdemIncludeFE,"Yes")) { noflatearthcorrection = true; // flatearth phase included in refdem_phase } else { if (coeff_flatearth.size() == 0) // step flatearth not done { // (not in result file) noflatearthcorrection = true; PRINT_ERROR("step flatearth not done") throw(input_error); } } // ______ Normalize data for polynomial ______ const real8 minL = master.originalwindow.linelo; const real8 maxL = master.originalwindow.linehi; const real8 minP = master.originalwindow.pixlo; const real8 maxP = master.originalwindow.pixhi; INFO << "compcoherence: polynomial normalized by factors: " << minL << " " << maxL << " " << minP << " " << maxP << " to [-2,2]"; INFO.print(); // ______ Some other variables ______ //const uint BUFFERMEMSIZE = input_general.memory; const real8 BUFFERMEMSIZE = input_general.memory; const int32 multiL = input_i_coherence.multilookL; const int32 multiP = input_i_coherence.multilookP; //const int32 multiLP = multiL*multiP; const int32 winsizeL = input_i_coherence.cohsizeL; const int32 winsizeP = input_i_coherence.cohsizeP; // ====== Open output files ====== ofstream ofileccoh; if (!noccoh) { openfstream(ofileccoh,input_i_coherence.foccoh,input_general.overwrit); bk_assert(ofileccoh,input_i_coherence.foccoh,__FILE__,__LINE__); } ofstream ofilecoh; if (!nocoh) { openfstream(ofilecoh,input_i_coherence.focoh,input_general.overwrit); bk_assert(ofilecoh,input_i_coherence.focoh,__FILE__,__LINE__); } // ====== allocate matrices ====== const int32 numpixels = (slave.currentwindow.pixhi-slave.currentwindow.pixlo+1); const int32 bytesperline = numpixels * sizeof(complr4); int32 numlines; // lines in buffer // ______ estimate numlines for correct memory usage ______ if (noflatearthcorrection) //numlines = int32((BUFFERMEMSIZE / 3.0) / bytesperline); numlines = int32(ceil( (BUFFERMEMSIZE / 3.0) / bytesperline )); else numlines = int32(ceil( (BUFFERMEMSIZE / 3.5) / bytesperline )); while (numlines%multiL) // correct numlines to multiple of multiL numlines -= 1; if (numlines%multiL) { PRINT_ERROR("PANIC: multilookwindow not exactly in numlines.") throw(input_error); } int32 nummllines = numlines/multiL; // exact zero fraction int32 nummlpixels = numpixels/multiP; // i.e., floor() if (nummllines < 1) { PRINT_ERROR("increase memory (MEMORY card) or reduce multiL (COH_MULTILOOK card).") throw(input_error); } // ______ adapt numlines to extra for window ______ int32 numlines2 = numlines; // number of lines output of coherence numlines += (winsizeL - 1); // number of lines from file // ______ Number of lines on file ______ //const uint Mfilelines = master.currentwindow.lines(); const uint Ifilelines = slave.currentwindow.lines(); // ______ Window in master system to load from file ______ // uint firstline = slave.currentwindow.linelo; // uint lastline = firstline + numlines - 1; // do little different cause of firstblock //register int32 i,j; uint zerolinesstart = (winsizeL-1)/2;// overlap previous block? uint trailinglines = (winsizeL)/2;// overlap next block? int32 extrazerolines = 0;// larger last block /* // ____ ? why is this here? it seems not required ___ // ____ ? e.g., coh win=64, ml win=10 fails if this is done // ____ ? but I guess there was a situation, e.g., when // ____ ? the slave is resampled larger than the master? // ____ ? or when the ML window is much larger than the coh win. // ____ ? BK, sep.2004: commented out. uint writeallzero = zerolinesstart/multiL;// ?? int32 zerorestlines = zerolinesstart%multiL;// ?? INFO << "coherence: starting with zero lines: " << writeallzero; INFO.print(); if (writeallzero != 0) { if (!noccoh) { matrix zeroline(1,nummlpixels); for (i=0; i zeroline(1,nummlpixels); for (i=0; i SLAVE(winfile.linehi-winfile.linelo+1,numpixels); matrix REFDEMPHA(winfile.linehi-winfile.linelo+1,numpixels); matrix MASTER; // ______ Axis for reference phase ______ matrix p_axis; if (!noflatearthcorrection) { p_axis.resize(numpixels,1); for (int32 i=0; i slave.currentwindow.linehi) // more then there is on file { lastblock = true; // ______ find out if execution of this buffer is required ______ int32 restlines = Ifilelines%multiL; // extra lines on file if (winfile.linelo+zerolinesstart >= slave.currentwindow.linehi-restlines+1) break; // ______ Resize matrices for last loop (1) ______ // ______ (not that well programmed...) ______ int32 lastlinerequired = slave.currentwindow.linehi - restlines + trailinglines; if (lastlinerequired > int32(slave.currentwindow.linehi)) { winfile.linehi = slave.currentwindow.linehi; extrazerolines = lastlinerequired - slave.currentwindow.linehi; } else { winfile.linehi = lastlinerequired; } INFO << "coherence: extra zero lines last buffer: " << extrazerolines; INFO.print(); MASTER.resize(winfile.linehi-winfile.linelo+1,numpixels); SLAVE.resize (winfile.linehi-winfile.linelo+1,numpixels); REFDEMPHA.resize (winfile.linehi-winfile.linelo+1,numpixels); } else // not lastblock: give approx PROGRESS { // ______ Progress info: not totally accurate ______ PROGRESS << "COHERENCE: " << int32(100.0*real4(blocks)/(real4(Ifilelines)/real4(numlines2))+0.5) << "%"; PROGRESS.print(); } // ______ Fill buffers master/slave from disk ______ INFO << "coherence winfile: [" << winfile.linelo << ":" << winfile.linehi << ", " << winfile.pixlo << ":" << winfile.pixhi << "]"; INFO.print(); MASTER = master.readdata(winfile); SLAVE = slave.readdata(winfile); // _____ start added by MA _____ if ( refdemmlL == 1 && refdemmlP == 1 ) // [MA] give precedence to regular refdem phase if both files exists // use the regular file since it's not multilooked. { INFO << "topo refphase file: [" << radarcodedrefdem.file << "is used." ; INFO.print(); readfile(REFDEMPHA,radarcodedrefdem.file, slave.currentwindow.lines(),winfile,slave.currentwindow); } else if ( existed(refdemfilenoML.c_str()) ) // use mas_sla.demphase.noML file { INFO << "topo refphase file: [" << refdemfilenoML << "is used." ; INFO.print(); readfile(REFDEMPHA,refdemfilenoML.c_str(), slave.currentwindow.lines(),winfile,slave.currentwindow); } // _____ end added by MA _____ // ______ Add zero lines if firstblock ______ if (firstblock == true) { matrix TMP = SLAVE; SLAVE.resize(BUF*multiL+winsizeL-1,TMP.pixels()); const window wintmp(SLAVE.lines()-TMP.lines(), SLAVE.lines()-1, 0, SLAVE.pixels()-1); const window windef(0, 0, 0, 0); SLAVE.setdata(wintmp,TMP,windef); TMP = MASTER; MASTER.resize(BUF*multiL+winsizeL-1,TMP.pixels()); MASTER.setdata(wintmp,TMP,windef); INFO << "coherence: increase lines for first block: " << SLAVE.lines()-TMP.lines(); INFO.print(); matrix TMPr4 = REFDEMPHA; REFDEMPHA.resize(BUF*multiL+winsizeL-1,TMPr4.pixels()); REFDEMPHA.setdata(wintmp,TMPr4,windef); } // ______ Resize matrices for last loop (2) ______ // ______ (not that well programmed...) ______ if (extrazerolines != 0) { const window wintmp(0, MASTER.lines()-1, 0, MASTER.pixels()-1); const window windef(0, 0, 0, 0); matrix TMP = SLAVE; SLAVE.resize(TMP.lines()+extrazerolines,TMP.pixels()); SLAVE.setdata(wintmp,TMP,windef); TMP = MASTER; MASTER.resize(TMP.lines()+extrazerolines,TMP.pixels()); MASTER.setdata(wintmp,TMP,windef); INFO << "coherence: increase lines for last block: " << SLAVE.lines()-TMP.lines(); INFO.print(); matrix TMPr4 = REFDEMPHA; REFDEMPHA.resize(TMPr4.lines()+extrazerolines,TMPr4.pixels()); REFDEMPHA.setdata(wintmp,TMPr4,windef); } // ______ Compute reference phase ______ uint sizeL = SLAVE.lines(); uint sizeP = SLAVE.pixels(); if (!noflatearthcorrection) { matrix l_axis(sizeL,1); for (uint i=0; i REFPHASE = polyval(l_axis, p_axis, coeff_flatearth); // ______ Complex interferogram in master, norms in slave ______ for (uint i=0; i CCOHERENCE = multilook( coherence(MASTER,SLAVE,winsizeL,winsizeP),multiL,multiP); ofileccoh << CCOHERENCE; ofilecoh << magnitude(CCOHERENCE); } else // thus only complex coherence { ofileccoh << multilook( coherence(MASTER,SLAVE,winsizeL,winsizeP),multiL,multiP); } } else if (!nocoh) // thus only (real) coherence requested { //ofilecoh << multilook( //coherence2(MASTER,SLAVE,winsizeL,winsizeP),multiL,multiP); // test: see size of blocks by using tmp matrix... matrix COHERENCE = coherence2(MASTER,SLAVE,winsizeL,winsizeP); INFO << "block: " << blocks << "; size COHERENCE matrix: " << COHERENCE.lines();// multiple of multiL ?? INFO.print(); ofilecoh << multilook(COHERENCE, multiL,multiP); } // ______ impossible request, is checked before. ______ else { PRINT_ERROR("2212 panic impossible.") throw(unhandled_case_error); } // ______ update windows/matrix size ______ winfile.linelo = winfile.linehi - trailinglines + 1 - zerolinesstart; winfile.linehi = winfile.linelo + numlines - 1; if (firstblock) { firstblock = false;// next time MASTER.resize(winfile.linehi-winfile.linelo+1,numpixels); SLAVE.resize(winfile.linehi-winfile.linelo+1,numpixels); REFDEMPHA.resize(winfile.linehi-winfile.linelo+1,numpixels); } } // loop over all blocks // ====== Write results to file ====== ofstream scratchlogfile("scratchlogcoherence", ios::out | ios::trunc); bk_assert(scratchlogfile,"compcoherence: scratchlogcoherence",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* COMPUTATION OF COHERENCE" << "\n*******************************************************************" << "\nMethod: \t\t\t\t" << "INCLUDE_REFDEM" << "\nInput file master (format): \t" << master.file << " " << master.formatflag << "\nInput file slave (format): \t" << slave.file << " " << slave.formatflag << "\ncomplex coherence: \t" << input_i_coherence.foccoh << "\ncoherence: \t" << input_i_coherence.focoh << "\nNumber of lines (multilooked): \t" << Ifilelines / multiL << "\nNumber of pixels (multilooked): \t" << nummlpixels << "\nMultilookfactor in line direction: \t" << multiL << "\nMultilookfactor in pixel direction: \t" << multiP << "\nNumber of lines window for coherence estimation: " << winsizeL << "\nNumber of pixels window for coherence estimation: " << winsizeP << "\nNumber of ml lines per buffer during computation: " << BUF << "\nTip: disfloat " << input_i_coherence.focoh << " " << nummlpixels << " 1 500" << "\n*******************************************************************\n"; scratchlogfile.close(); ofstream scratchresfile("scratchrescoherence", ios::out | ios::trunc); bk_assert(scratchresfile,"compcoherence: scratchrescoherence",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************" << "\n*_Start_" << processcontrol[pr_i_coherence] << "\n*******************************************************************" << "\nMethod: \t\t\t\t" << "INCLUDE_REFDEM"; if (!nocoh) { scratchresfile << "\nData_output_file: \t\t\t" << input_i_coherence.focoh << "\nData_output_format: \t\t\t" << "real4"; } if (!noccoh) { scratchresfile << "\nData_output_file_complex_coherence: " << input_i_coherence.foccoh << "\nData_output_format_complex_coherence: \t\t" << "complex_real4"; } scratchresfile << "\nFirst_line (w.r.t. original_master): \t" // updateproductinfo greps these << slave.currentwindow.linelo << "\nLast_line (w.r.t. original_master): \t" << slave.currentwindow.linehi << "\nFirst_pixel (w.r.t. original_master): \t" << slave.currentwindow.pixlo << "\nLast_pixel (w.r.t. original_master): \t" << slave.currentwindow.pixhi << "\nMultilookfactor_azimuth_direction: \t" << multiL << "\nMultilookfactor_range_direction: \t" << multiP << "\nNumber of lines (multilooked): \t\t" << Ifilelines / multiL << "\nNumber of pixels (multilooked): \t" << nummlpixels << "\n*******************************************************************" << "\n* End_" << processcontrol[pr_i_coherence] << "_NORMAL" << "\n*******************************************************************\n"; scratchresfile.close(); // ______Tidy up______ PROGRESS.print("finished compcoherence."); if (!noccoh) ofileccoh.close(); if (!nocoh) ofilecoh.close(); } // END compcoherence /**************************************************************** * subtrrefpha (polynomial) * * * * Compute complex_interferogram .* conj(REF.PHA) * * note: master-slave-ref.phase * * ref.phase is 2d-polynomial model of ellipsoid phase * * * * Input: * * - input arguments, multilook, filenames * * Output: * * - new files on disk * * Bert Kampes, 09-Feb-2000 * ****************************************************************/ void subtrrefpha( const slcimage &master, // normalization factor polynomial const productinfo &interferogram, const input_gen &input_general, const input_subtrrefpha &input_i_subtrrefpha, const matrix &coeff_flatearth, const matrix &coeff_h2ph) // added by FvL { TRACE_FUNCTION("subtrrefpha (polynomial) (BK 09-Feb-2000)") // ====== Input options ====== const int32 multiL = input_i_subtrrefpha.multilookL; const int32 multiP = input_i_subtrrefpha.multilookP; // ====== Get number of buffers etc. ====== const int32 mldiskL = interferogram.multilookL; // cint on disk const int32 mldiskP = interferogram.multilookP; // cint on disk const int32 numlinesdisk = interferogram.win.lines()/mldiskL; const int32 numpixelsdisk = interferogram.win.pixels()/mldiskP; // ______ In original master radar coordinate system ______ const real4 veryfirstline = real4(interferogram.win.linelo) + (real4(mldiskL) - 1.) / 2.; const real4 firstpixel = real4(interferogram.win.pixlo) + (real4(mldiskP) - 1.) / 2.; const int32 totalmlL = mldiskL*multiL; const int32 totalmlP = mldiskP*multiP; const int32 numlinesoutput = numlinesdisk/multiL; // floor const int32 numpixelsoutput = numpixelsdisk/multiP; // floor // const int32 lastlineoutput = interferogram.win.linelo // [MA] These were used be dumped to the res file. // + totalmlL*numlinesoutput - 1; // Now, They are replaced by interferogram.win.linehi // const int32 lastpixeloutput = interferogram.win.pixlo // and interferogram.win.pixhi. // + totalmlP*numpixelsoutput - 1; // see: comprefdem const bool outputh2ph = specified(input_i_subtrrefpha.foh2ph); // if spec. then output, added by FvL // ______ Normalize data for polynomial ______ const real8 minL = master.originalwindow.linelo; const real8 maxL = master.originalwindow.linehi; const real8 minP = master.originalwindow.pixlo; const real8 maxP = master.originalwindow.pixhi; INFO << "subtrrefpha: polynomial ref.phase normalized by factors: " << minL << " " << maxL << " " << minP << " " << maxP << " to [-2,2]"; INFO.print(); // ====== Open files ====== // ______ If requested, dump ref.pha and do nothing else ______ ifstream ifcint; // input file complex interf. ofstream ofilecint; // output file complex interf. ofstream ofrefpha; // output file ref. phase if (input_i_subtrrefpha.dumponlyrefpha) { openfstream(ofrefpha,input_i_subtrrefpha.forefpha,input_general.overwrit); bk_assert(ofrefpha,input_i_subtrrefpha.forefpha,__FILE__,__LINE__); } else // compute cint and dump this... { openfstream(ofilecint,input_i_subtrrefpha.focint,input_general.overwrit); bk_assert(ofilecint,input_i_subtrrefpha.focint,__FILE__,__LINE__); if (interferogram.formatflag != FORMATCR4) { PRINT_ERROR("code: .. Complex interferogram on disk must be complex real4.") throw(unhandled_case_error); } openfstream(ifcint,interferogram.file); bk_assert(ifcint,interferogram.file,__FILE__,__LINE__); } //______________________________________________________________________ //__________ added by FvL ______________________________________________ //______________________________________________________________________ ofstream ofh2ph; if (outputh2ph==true) { openfstream(ofh2ph,input_i_subtrrefpha.foh2ph,input_general.overwrit); bk_assert(ofh2ph,input_i_subtrrefpha.foh2ph,__FILE__,__LINE__); } //______________________________________________________________________ //__________ end added by FvL ______________________________________________ //______________________________________________________________________ // ====== Loop parameters ====== //const uint BUFFERMEMSIZE = input_general.memory; const real8 BUFFERMEMSIZE = input_general.memory; const int32 bytesperline = 2*sizeof(real4)*numpixelsdisk; const real4 nummatrices = 3; // CINT and REFPHA //int32 bufferlines = int32((BUFFERMEMSIZE / nummatrices) / bytesperline); // lines in buffer int32 bufferlines = int32(ceil((BUFFERMEMSIZE / nummatrices) / bytesperline )); // lines in buffer while (bufferlines%multiL) // correct bufferlines to multiple of multiL { bufferlines -= 1; } DEBUG << "bufferlines per buffer: " << bufferlines; DEBUG.print(); if (bufferlines%multiL != 0) { PRINT_ERROR("panic: refphase bufferlines totally impossible on HP.") throw(some_error); } const int32 numfullbuffers = numlinesdisk/bufferlines; // floor int32 restlines = numlinesdisk%bufferlines; while (restlines%multiL) // correct bufferlines to multiple of multiL { restlines -= 1; } DEBUG << "restlines last buffer: " << restlines << "; and: " << numfullbuffers << " buffers of #lines: " << bufferlines; DEBUG.print(); if (restlines%multiL != 0) { PRINT_ERROR("panic: i thought restlines is always exactly fitted this way??.") throw(some_error); } const int32 EXTRABUFFER = (restlines) ? 1 : 0; // ______ Axis for polyval ______ register int32 i; matrix p_axis(numpixelsdisk,1); // must be standing for (i=0; i l_axis(bufferlines,1); for (i=0; i REFPHASE = polyval(l_axis, p_axis, coeff_flatearth); // computation done in real8 // ______ Dump this and continue if requested ______ if (outputh2ph==true) // dump h2ph, added by FvL { matrix H2PH = polyval(l_axis, p_axis, coeff_h2ph); // added by FvL matrix output_layer(H2PH.lines(),H2PH.pixels()); convert_type(H2PH, output_layer); // ex: real8 --> real4 ofh2ph << multilook(output_layer, multiL, multiP); // H2PH H2PH(1,1); //deallocate } if (input_i_subtrrefpha.dumponlyrefpha) // dump complex ref.phase for checking { //matrix REFPHASECR4 = fast_angle2cmplx(REFPHASE); //ofrefpha << REFPHASECR4; matrix REFPHASECR8 = fast_angle2cmplx(REFPHASE); //matrix output_layer(REFPHASE.lines(),REFPHASE.pixels()); matrix output_layer(REFPHASECR8.lines(),REFPHASECR8.pixels()); convert_type(REFPHASECR8, output_layer); // [MA] real8 --> real4 ofrefpha << multilook(output_layer, multiL, multiP); // unwrapped REFPHASE continue; // next buffer } // ====== Read in buffer of complex interferogram ====== matrix CINT(bufferlines,numpixelsdisk); ifcint >> CINT; // readin: assumed format complr4 // ====== Subtract phase by complex multiplication (Euler) ====== // CINT *= conj(angle2cmplx(REFPHASE)); // pointwise multiplication with conj. // ______ changes CINT ______ fast_dotmultconjphase(CINT,REFPHASE); // pointwise multiplication with conj. // ====== Write multilooked output to new file ====== ofilecint << multilook(CINT, multiL, multiP); } // buffer loop ifcint.close(); ofilecint.close(); if (input_i_subtrrefpha.dumponlyrefpha) ofrefpha.close(); if (outputh2ph==true) // added by FvL ofh2ph.close(); // ====== Log info/results ====== ofstream scratchlogfile("scratchlogsubtrrefpha", ios::out | ios::trunc); bk_assert(scratchlogfile,"subtrrefpha: scratchlogsubtrrefpha",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* SUBTRREFPHA" << "\n*******************************************************************" << "\nMethod: \t\t\t\t\tpolynomial"; if (input_i_subtrrefpha.dumponlyrefpha) { scratchlogfile << "\nOnly dump of reference phase, no subtraction." << "\nData_output_file_ref.phase: \t\t\t" << input_i_subtrrefpha.forefpha; } else { scratchlogfile << "\nInput_file_complex_interferogram: \t\t" << interferogram.file << "\nData_output_file_complex_interferogram: \t" << input_i_subtrrefpha.focint << "\nData_output_format_complex_interferogram: \t" << "complex_real4"; } scratchlogfile << "\nFirst_line (w.r.t. original_master): \t\t" // updateproductinfo greps these << interferogram.win.linelo << "\nLast_line (w.r.t. original_master): \t\t" << interferogram.win.linehi //lastlineoutput << "\nFirst_pixel (w.r.t. original_master): \t\t" << interferogram.win.pixlo << "\nLast_pixel (w.r.t. original_master): \t\t" << interferogram.win.pixhi //lastpixeloutput << "\nMultilookfactor_azimuth_direction: \t\t" << totalmlL << "\nMultilookfactor_range_direction: \t\t" << totalmlP << "\nNumber of lines (multilooked): \t\t\t" << numlinesoutput << "\nNumber of pixels (multilooked): \t\t" << numpixelsoutput << "\n\nMultilookfactors input complex interferogram: \t" << mldiskL << " " << mldiskP << "\nMultilookfactors requested in this step: \t" << multiL << " " << multiP << "\nNumber of buffers used (size): \t\t\t" << numfullbuffers << " (" << bufferlines << "," << numpixelsdisk << ")" << "\n*******************************************************************\n\n"; scratchlogfile.close(); ofstream scratchresfile("scratchressubtrrefpha", ios::out | ios::trunc); bk_assert(scratchresfile,"subtrrefpha: scratchressubtrrefpha",__FILE__,__LINE__); scratchresfile // ______ Updateproductinfo greps these ______ << "\n\n*******************************************************************" << "\n*_Start_" << processcontrol[pr_i_subtrrefpha] << "\n*******************************************************************" << "\nMethod: \t\t\t\tpolynomial" << "\nData_output_file: \t\t\t"; if (input_i_subtrrefpha.dumponlyrefpha) { scratchresfile << "NO_OUTPUT_ONLY_DUMPING_REF_PHA" << "\nFile_name of ref.phase: \t\t" << input_i_subtrrefpha.forefpha << "\nData_output_format: \t\t\t" << "complex_real4"; } else { scratchresfile << input_i_subtrrefpha.focint << "\nData_output_format: \t\t\t" << "complex_real4"; } scratchresfile << "\nFirst_line (w.r.t. original_master): \t" << interferogram.win.linelo << "\nLast_line (w.r.t. original_master): \t" << interferogram.win.linehi //lastlineoutput << "\nFirst_pixel (w.r.t. original_master): \t" << interferogram.win.pixlo << "\nLast_pixel (w.r.t. original_master): \t" << interferogram.win.pixhi //lastpixeloutput << "\nMultilookfactor_azimuth_direction: \t" << totalmlL << "\nMultilookfactor_range_direction: \t" << totalmlP << "\nNumber of lines (multilooked): \t\t" << numlinesoutput << "\nNumber of pixels (multilooked): \t" << numpixelsoutput << "\n*******************************************************************" << "\n* End_" << processcontrol[pr_i_subtrrefpha] << "_NORMAL" << "\n*******************************************************************\n"; scratchresfile.close(); // ====== Tidy up ====== // ?? } // END subtrrefpha polynomial /**************************************************************** * subtrrefpha (exact) * * * * Compute complex_interferogram .* conj(REF.PHA) * * note: master-slave-ref.phase * * ref.phase is computed here by evaluating system of 3 eq. * * * * Input: * * - input arguments, multilook, filenames * * Output: * * - new files on disk * * Bert Kampes, 03-Jul-2000 * ****************************************************************/ void subtrrefpha( const input_ell &ellips, const slcimage &master, const slcimage &slave, const productinfo &interferogram, const input_gen &input_general, const input_subtrrefpha &input_i_subtrrefpha, orbit &masterorbit, orbit &slaveorbit) { TRACE_FUNCTION("subtrrefpha (BK 03-Jul-2000)") const int32 MAXITER = 10; // number iterations const real8 CRITERPOS = 1e-6; // meters const real8 CRITERTIM = 1e-10; // seconds INFO << "SUBTRREFPHA: MAXITER: " << MAXITER << "; " << "CRITERPOS: " << CRITERPOS << " m; " << "CRITERTIM: " << CRITERTIM << " s"; INFO.print(); // ====== Input options ====== const int32 multiL = input_i_subtrrefpha.multilookL; const int32 multiP = input_i_subtrrefpha.multilookP; // ====== Get some variables ====== const int32 mldiskL = interferogram.multilookL; // cint on disk const int32 mldiskP = interferogram.multilookP; // cint on disk const int32 numlinesdisk = interferogram.win.lines()/mldiskL; const int32 numpixelsdisk = interferogram.win.pixels()/mldiskP; // ______ In original master radar coordinate system ______ const real4 veryfirstline = real4(interferogram.win.linelo) + (real4(mldiskL) - 1.) / 2.; const real4 firstpixel = real4(interferogram.win.pixlo) + (real4(mldiskP) - 1.) / 2.; const int32 totalmlL = mldiskL*multiL; const int32 totalmlP = mldiskP*multiP; const int32 numlinesoutput = numlinesdisk/multiL; // floor const int32 numpixelsoutput = numpixelsdisk/multiP; // floor // const int32 lastlineoutput = interferogram.win.linelo // [MA] These were used be dumped to the res file. // + totalmlL*numlinesoutput - 1; // Now, They are replaced by interferogram.win.linehi // const int32 lastpixeloutput = interferogram.win.pixlo // and interferogram.win.pixhi. // + totalmlP*numpixelsoutput - 1; // see: comprefdem const bool outputh2ph = specified(input_i_subtrrefpha.foh2ph); // if spec. then output, added by FvL // ====== Open files ====== // ______ If requested, dump ref.pha and do nothing else ______ ifstream ifcint; // input file complex interf. ofstream ofilecint; // output file complex interf. ofstream ofrefpha; // output file ref. phase if (input_i_subtrrefpha.dumponlyrefpha) { openfstream(ofrefpha,input_i_subtrrefpha.forefpha,input_general.overwrit); bk_assert(ofrefpha,input_i_subtrrefpha.forefpha,__FILE__,__LINE__); } else // compute cint and dump this... { openfstream(ofilecint,input_i_subtrrefpha.focint,input_general.overwrit); bk_assert(ofilecint,input_i_subtrrefpha.focint,__FILE__,__LINE__); if (interferogram.formatflag != FORMATCR4) { PRINT_ERROR("code: .. Complex interferogram on disk must be complex real4.") throw(unhandled_case_error); } openfstream(ifcint,interferogram.file); bk_assert(ifcint,interferogram.file,__FILE__,__LINE__); } //______________________________________________________________________ //__________ added by FvL ______________________________________________ //______________________________________________________________________ ofstream ofh2ph; if (outputh2ph==true) { openfstream(ofh2ph,input_i_subtrrefpha.foh2ph,input_general.overwrit); bk_assert(ofh2ph,input_i_subtrrefpha.foh2ph,__FILE__,__LINE__); } //______________________________________________________________________ //__________ end added by FvL ______________________________________________ //______________________________________________________________________ // ====== Loop parameters ====== matrix REFPHASE(multiL,numpixelsdisk); // computed, read multiple of multiL matrix H2PH(multiL,numpixelsdisk); // computed, added by FvL int32 tenpercent = int32(floor(numlinesoutput/10.)); // better round this if (tenpercent==0) tenpercent = 1000; int32 percentage = 0; real8 line = veryfirstline; // master coord. system, buffer0 const real8 m_minpi4cdivlam = (-4*PI*SOL)/master.wavelength; const real8 s_minpi4cdivlam = (-4*PI*SOL)/slave.wavelength; // ====== Compute delta range for all points ====== // ______ Read in numlinesoutput buffers of size multiL ______ for (register int32 buffer=0; bufferSP) then S is to the right of slant line, then B perp is positive. cn r1 = Psat_master.min(P); cn r2 = Psat_slave.min(P); // real8 theta = Psat_master.angle(r1); // return look angle real8 theta = P.angle(r1); // incidence angle real8 theta_slave = P.angle(r2); // incidence angle slave real8 Bperp = (theta > theta_slave) ? // sign ok sqrt(sqr(B)-sqr(Bpar)) : -sqrt(sqr(B)-sqr(Bpar)); H2PH(i,j) = Bperp/(m_trange*SOL*sin(theta)); } // ____________________________________________________________________________________ // _____________ End added part by FvL ________________________________________________ //_____________________________________________________________________________________ } // pixels line += mldiskL; // update here } // multilines loop // ______ Either dump refphase or subtract it ______ if (input_i_subtrrefpha.dumponlyrefpha) { //matrix REFPHASECR4 = fast_angle2cmplx(REFPHASE); //ofrefpha << multilook(REFPHASECR4,multiL,multiP); matrix REFPHASECR8 = fast_angle2cmplx(REFPHASE); matrix output_layer(REFPHASECR8.lines(),REFPHASECR8.pixels()); convert_type(REFPHASECR8, output_layer); ofrefpha << multilook(output_layer, multiL, multiP); } else { // subtrrefphase matrix CINT(multiL,numpixelsdisk); // read from disk as real4 ifcint >> CINT; // read next buffer, filepointer++ // ______ Changes CINT ______ fast_dotmultconjphase(CINT,REFPHASE); // pointwise multiplication with conj. ofilecint << multilook(CINT,multiL,multiP); // write next line REFPHASE(1,1); //deallocate } if (outputh2ph==true) // dump h2ph, added by FvL { matrix output_layer(H2PH.lines(),H2PH.pixels()); convert_type(H2PH, output_layer); // [MA] ex: real8 --> real4 ofh2ph << multilook(output_layer, multiL, multiP); // H2PH --> outfile H2PH(1,1); //deallocate } } // azimuth buffers // ______ Close files ______ if (input_i_subtrrefpha.dumponlyrefpha) ofrefpha.close(); else { ofilecint.close(); ifcint.close(); } if (outputh2ph==true) // added by FvL ofh2ph.close(); // ====== Log info/results ====== // TODO put date and time to log as well ofstream scratchlogfile("scratchlogsubtrrefpha", ios::out | ios::trunc); bk_assert(scratchlogfile,"subtrrefpha: scratchlogsubtrrefpha",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* SUBTRREFPHA" << "\n*******************************************************************" << "\nMethod: \t\t\t\t\texact"; if (input_i_subtrrefpha.dumponlyrefpha) { scratchlogfile << "\nOnly dump of reference phase, no subtraction." << "\nData_output_file_ref.phase: \t\t\t" << input_i_subtrrefpha.forefpha; } else { scratchlogfile << "\nInput file complex interferogram: \t\t" << interferogram.file << "\nData_output_file_complex_interferogram: \t" << input_i_subtrrefpha.focint << "\nData_output_format_complex_interferogram: \t" << "complex_real4"; } scratchlogfile << "\nFirst_line (w.r.t. original_master): \t\t" // updateproductinfo greps these << interferogram.win.linelo << "\nLast_line (w.r.t. original_master): \t\t" << interferogram.win.linehi //lastlineoutput << "\nFirst_pixel (w.r.t. original_master): \t\t" << interferogram.win.pixlo << "\nLast_pixel (w.r.t. original_master): \t\t" << interferogram.win.pixhi //lastpixeloutput << "\nMultilookfactor_azimuth_direction: \t\t" << totalmlL << "\nMultilookfactor_range_direction: \t\t" << totalmlP << "\nNumber of lines (multilooked): \t\t\t" << numlinesoutput << "\nNumber of pixels (multilooked): \t\t" << numpixelsoutput << "\n\nMultilookfactors input complex interferogram: \t" << mldiskL << " " << mldiskP << "\nMultilookfactors requested in this step: \t" << multiL << " " << multiP << "\nNumber of buffers used (size): \t\t\t" //<< numfullbuffers << "(" << bufferlines << "," << numpixelsdisk << ")" << numlinesoutput/multiL << "(" << multiL << "," << numpixelsoutput << ")" << "\n*******************************************************************\n\n"; scratchlogfile.close(); ofstream scratchresfile("scratchressubtrrefpha", ios::out | ios::trunc); bk_assert(scratchresfile,"subtrrefpha: scratchressubtrrefpha",__FILE__,__LINE__); scratchresfile // ______ Updateproductinfo greps these ______ << "\n\n*******************************************************************" << "\n*_Start_" << processcontrol[pr_i_subtrrefpha] << "\n*******************************************************************" << "\nMethod: \t\t\t\texact" << "\nData_output_file: \t\t\t"; if (input_i_subtrrefpha.dumponlyrefpha) { scratchresfile << "NO_OUTPUT_ONLY_DUMPING_REF_PHA" << "\nFile_name of ref.phase: \t\t" << input_i_subtrrefpha.forefpha << "\nData_output_format: \t\t\t" << "complex_real4"; } else { scratchresfile << input_i_subtrrefpha.focint << "\nData_output_format: \t\t\t" << "complex_real4"; } scratchresfile << "\nFirst_line (w.r.t. original_master): \t" << interferogram.win.linelo << "\nLast_line (w.r.t. original_master): \t" << interferogram.win.linehi //lastlineoutput << "\nFirst_pixel (w.r.t. original_master): \t" << interferogram.win.pixlo << "\nLast_pixel (w.r.t. original_master): \t" << interferogram.win.pixhi //lastpixeloutput << "\nMultilookfactor_azimuth_direction: \t" << totalmlL << "\nMultilookfactor_range_direction: \t" << totalmlP << "\nNumber of lines (multilooked): \t\t" << numlinesoutput << "\nNumber of pixels (multilooked): \t" << numpixelsoutput << "\n*******************************************************************" << "\n* End_" << processcontrol[pr_i_subtrrefpha] << "_NORMAL" << "\n*******************************************************************\n"; scratchresfile.close(); // ====== Tidy up ====== // ?? } // END subtrrefpha exact /**************************************************************** * subtrrefdem * * * * Compute complex_interferogram .* conj(REF.DEM) * * note: master-slave-ref.phase-demphase * * DEM ref.phase is a file containing float phase values * * Optionally multilook again (not expected) * * Subtract in small buffers, assume size is same as cint. * * * * Input: * * - input arguments, filenames * * Output: * * - new complex interferogram on disk * * Bert Kampes, 10-Feb-2000 * * added offset if specified by user, not automatically computed* * Card SRD_OFFSET l p * #%// BK 24-Apr-2002 * ****************************************************************/ void subtrrefdem( const productinfo &interferogram, const productinfo &radarcodedrefdem, const input_gen &input_general, const input_subtrrefdem &input_i_subtrrefdem) { TRACE_FUNCTION("subtrrefdem (BK 10-Feb-2000)") const int32 additional_offsetL = input_i_subtrrefdem.offsetL; const int32 additional_offsetP = input_i_subtrrefdem.offsetP; // ====== Handle input ====== // do not multilook in this step..., neither cutout // const int32 mlL = input_i_subtrrefdem.mlL; // const int32 mlP = input_i_subtrrefdem.mlP; // ______ Add offset from correlation to these windows ______ //window cint = interferogram.wininterfero; window refdem = radarcodedrefdem.win; // IF INPUT METHOD = CORRELATE // FIRST COMPUTE BEST SHIFT DEM AT PIXEL LEVEL // THEN ADD THIS SHIFT TO WIN.REFDEM ... // Do this by correlation of the phase image at lot of patches? // or for total image within +-4 pixels. //WARNING.print("BERT TESTING ADDITIONAL OFFSET SPECIFIED BY USER IN INPUT"); refdem.linelo += (additional_offsetL * radarcodedrefdem.multilookL); refdem.linehi += (additional_offsetL * radarcodedrefdem.multilookL); refdem.pixlo += (additional_offsetP * radarcodedrefdem.multilookP); refdem.pixhi += (additional_offsetP * radarcodedrefdem.multilookP); // then DEM is shifted to the right wrt. cint // ====== Compute overlap interferogram, ref.dem ====== // ______ Output cint always same size input cint ______ if (interferogram.multilookL != radarcodedrefdem.multilookL) { PRINT_ERROR("MultilookfactorL complex interferogram, ref. dem not equal.") throw(file_error); } if (interferogram.multilookP != radarcodedrefdem.multilookP) { PRINT_ERROR("MultilookfactorP complex interferogram, ref. dem not equal.") throw(file_error); } if ((interferogram.win.linelo-refdem.linelo)%radarcodedrefdem.multilookL != 0) WARNING.print("Seems reference phase DEM does not lie at same grid as complex interferogram."); if ((interferogram.win.pixlo-refdem.pixlo)%radarcodedrefdem.multilookP != 0) WARNING.print("Seems reference phase DEM does not lie at same grid as complex interferogram."); const int32 cintfilelines = interferogram.win.lines() /interferogram.multilookL; const int32 cintfilepixels = interferogram.win.pixels()/interferogram.multilookP; const int32 demfilelines = radarcodedrefdem.win.lines() /radarcodedrefdem.multilookL; const int32 demfilepixels = radarcodedrefdem.win.pixels()/radarcodedrefdem.multilookP; // YOU FORGOT TO TAKE PRIOR MULTILOOKING IN ACCOUNT !!!!!!! // CHECK THIS (BK 11-feb-2000) const int32 offsetL = (int32(refdem.linelo)-int32(interferogram.win.linelo))/ int32(interferogram.multilookL); const int32 skiplinesstart = max(0,offsetL); // number of ml.lines no overlap const int32 skiplinesend = max(0,cintfilelines-demfilelines-offsetL); const int32 numpixoverlap = int32(min(int32(interferogram.win.pixhi),int32(refdem.pixhi)) - max(int32(interferogram.win.pixlo),int32(refdem.pixlo)) + 1 ) / int32(radarcodedrefdem.multilookP); const int32 startcintP = // startindex in CINT array max(0,(int32(refdem.pixlo-interferogram.win.pixlo))/ int32(radarcodedrefdem.multilookP)); const int32 startrefdemP = // startindex in REFDEM array max(0,(int32(interferogram.win.pixlo-refdem.pixlo))/ int32(radarcodedrefdem.multilookP)); DEBUG << " skiplinesstart: " << skiplinesstart << " skiplinesend: " << skiplinesend << " offsetL: " << offsetL << " numpixoverlap: " << numpixoverlap << " startcintP: " << startcintP << " startrefdemP: " << startrefdemP; DEBUG.print(); // ====== Open files ====== if (interferogram.formatflag != FORMATCR4) { PRINT_ERROR("code ..: Complex interferogram on disk assumed to be complex real4.") throw(file_error); } if (radarcodedrefdem.formatflag != FORMATR4) { PRINT_ERROR("code ..: Reference phase DEM on disk assumed to be real4.") throw(file_error); } ifstream ifcint; openfstream(ifcint,interferogram.file); bk_assert(ifcint,interferogram.file,__FILE__,__LINE__); ifstream ifrefdem; openfstream(ifrefdem,radarcodedrefdem.file); bk_assert(ifrefdem,radarcodedrefdem.file,__FILE__,__LINE__); ofstream ofilecint; openfstream(ofilecint,input_i_subtrrefdem.focint,input_general.overwrit); bk_assert(ofilecint,input_i_subtrrefdem.focint,__FILE__,__LINE__); // ====== Loop over complex interferogram per line ====== matrix CINT (1,cintfilepixels); // read one line at a time matrix REFDEM (1,demfilepixels); // read one line at a time register int32 i,line; #define COMP_COHER #ifdef COMP_COHER real8 coher = 0;// BK 24-Apr-2002 #endif for (line=0; line> CINT; ofilecint << CINT; } for (line=0; line<-offsetL; ++line) // set file pointer refdem ifrefdem >> REFDEM; // do nothing ... for (line=0; line> CINT; ifrefdem >> REFDEM; // ______ Multiply by complex conjugated of phase (subtraction) ______ // might be faster in matrix notation (DEM2=getpartdem; cint*=dem2) for (i=0; i> CINT; ofilecint << CINT; } // loop line ifcint.close(); ofilecint.close(); // ====== Log info/results ====== ofstream scratchlogfile("scratchlogsubtrrefdem", ios::out | ios::trunc); bk_assert(scratchlogfile,"subtrrefdem: scratchlogsubtrrefdem",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* SUBTRREFDEM PHASE" << "\n*******************************************************************" << "\nInput file complex interferogram: \t\t\t" << interferogram.file << "\nInput file reference dem: \t\t\t" << radarcodedrefdem.file << "\nAdditional_azimuth_shift: \t" << additional_offsetL << "\nAdditional_range_shift: \t" << additional_offsetP << "\nCoherence IFG DEMPHASE: \t" << coher << "\n*******************************************************************\n\n"; scratchlogfile.close(); ofstream scratchresfile("scratchressubtrrefdem", ios::out | ios::trunc); bk_assert(scratchresfile,"subtrrefdem: scratchressubtrrefdem",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************" << "\n*_Start_" << processcontrol[pr_i_subtrrefdem] << "\n*******************************************************************" << "\nMethod: \t" << "NOT_USED" << "\nAdditional_azimuth_shift: \t" << additional_offsetL << "\nAdditional_range_shift: \t" << additional_offsetP << "\nData_output_file: \t" << input_i_subtrrefdem.focint << "\nData_output_format: \t" << "complex_real4" << "\nFirst_line (w.r.t. original_master): \t" << interferogram.win.linelo << "\nLast_line (w.r.t. original_master): \t" << interferogram.win.linehi << "\nFirst_pixel (w.r.t. original_master): \t" << interferogram.win.pixlo << "\nLast_pixel (w.r.t. original_master): \t" << interferogram.win.pixhi << "\nMultilookfactor_azimuth_direction: \t" << interferogram.multilookL << "\nMultilookfactor_range_direction: \t" << interferogram.multilookP << "\nNumber of lines (multilooked): \t" << cintfilelines << "\nNumber of pixels (multilooked): \t" << cintfilepixels << "\n*******************************************************************" << "\n* End_" << processcontrol[pr_i_subtrrefdem] << "_NORMAL" << "\n*******************************************************************\n"; scratchresfile.close(); } // END subtrrefdem /**************************************************************** * dinsar * * Differential insar with an unwrapped topo interferogram * * (hgt or real4 format) and a wrapped(!) defo interf. * * if r4 then NaN==-999 is problem with unwrapping, else hgt * * if ampl. =0 then problem flagged with unwrapping. * * The topography is removed from the deformation interferogram * * by the formula (prime ' denotes defo pair): * * dr = lambda\4pi * [phi' - phi(Bperp'/Bperp)] * * phi_diff = phi(Bperp'/Bperp) - phi' * * where Bperp is the perpendicular baseline for points on the * * ellipsoid (and not the true one)! * * I implemented this by computing the baseline for a number * * of points for topo and defo, and then modeling the ratio * * as a 2D polynomial of degree 1 for the image. * * Then evaluating this to compute the new phase (defo only). * * I assume the interferogram files are coregistered on each * * other and have the same dimensions. * * * * If TOPOMASTER file is empty (" "), then use current master * * res file for master orbit (== 3pass), else get orbit * * (==4pass). * * * * Input: * * -input parameters * * -orbits * * -info on input files * * - * * Output: * * -complex float file with differential phase. * * (set to (0,0) for not ok unwrapped parts) * * * * See also Zebker, 1994. * #%// BK 22-Sep-2000 * ****************************************************************/ void dinsar( const input_gen &input_general, const input_dinsar &dinsarinput, const input_ell &ellips, const slcimage &master, orbit &masterorbit, const slcimage &defoslave, orbit &defoorbit, const productinfo &defointerferogram ) { TRACE_FUNCTION("dinsar (BK 22-Sep-2000)") // ====== Get input, check file dimensions ====== char difffile[2*ONE27]; // output file name strcpy(difffile,dinsarinput.fodinsar); // ______ Fill these from resultfiles topo-pair processing ______ // ______ Processing topo pair has to be until unwrap ______ slcimage topomaster; // only fill if 4 pass slcimage toposlave; // info on slave image productinfo topounwrappedinterf; // interferogram orbit topomasterorbit; // only fill if 4 pass orbit toposlaveorbit; // always fill // ______ Check 4 pass if topomaster is specified (diff than m_res) ______ bool FOURPASS = true; // assume 4pass if (!specified(dinsarinput.topomasterresfile)) FOURPASS = false; if (!strcmp(dinsarinput.topomasterresfile,input_general.m_resfile)) FOURPASS = false; if (FOURPASS==true) { INFO.print("Using 4 pass differential interferometry (card IN_TOPOMASTER)."); INFO.print("Reading primary (topography pair) master parameters."); topomaster.fillslcimage(dinsarinput.topomasterresfile); // fill wavelength etc. INFO.print("Modelling primary (topography pair) master orbit."); topomasterorbit.initialize(dinsarinput.topomasterresfile); // fill interp. coeff. } INFO.print("Reading primary (topography pair) slave parameters."); toposlave.fillslcimage(dinsarinput.toposlaveresfile); // fill wavelength etc. INFO.print("Reading (topography pair) unwrapped section."); char SECTIONID[ONE27]; strcpy(SECTIONID,"*_Start_"); strcat(SECTIONID,processcontrol[pr_i_unwrap]); topounwrappedinterf.fillproductinfo(dinsarinput.topointresfile,SECTIONID); // fill info INFO.print("Modelling primary (topography pair) slave orbit."); toposlaveorbit.initialize(dinsarinput.toposlaveresfile); // fill interp. coeff. // ______ Check dimensions ______ if (defointerferogram.multilookL != topounwrappedinterf.multilookL) { WARNING << "multilookfactor defo != factor topo: " << defointerferogram.multilookL << " != " << topounwrappedinterf.multilookL; WARNING.print(); } if (defointerferogram.multilookP != topounwrappedinterf.multilookP) { WARNING << "multilookfactor defo != factor topo: " << defointerferogram.multilookP << " != " << topounwrappedinterf.multilookP; WARNING.print(); } if (defointerferogram.win != topounwrappedinterf.win) WARNING.print("window defo pair != window topo pair"); if (defointerferogram.formatflag != FORMATCR4) { PRINT_ERROR("format defo interferogram not complr4.") throw(file_error); } // not overlap, multilooked, center of pixel, trouble //const window overlap = getoverlap(topounwrappedinterf.win, // defointerferogram.win); // ______ Normalization factors for polynomial ______ const real8 minL = master.originalwindow.linelo; const real8 maxL = master.originalwindow.linehi; const real8 minP = master.originalwindow.pixlo; const real8 maxP = master.originalwindow.pixhi; INFO << "dinsar: polynomial for ratio normalized by: " << minL << " " << maxL << " " << minP << " " << maxP << " to [-2,2]"; INFO.print(); /* // TODO BASELINE topo_baseline, defo_baseline; if (FOURPASS==true) { topomasterorbit topo_baseline.model_parameters(topomaster,toposlave,topomasterorbit,toposlaveorbit,ellips); defo_baseline.model_parameters(defomaster,defoslave,defomasterorbit,defoslaveorbit,ellips); } else { } const real8 Bperp = topo_baseline.get_bperp(line,pixel); const real8 Bperp = defo_baseline.get_bperp(line,pixel); ... */ // ====== Model perpendicular baseline for master and slave ====== // ______ compute B on grid every 500 lines, 100 pixels // ______ in window for topo/defo ______ const int32 numpointsL = 20; // grid for modelling const int32 numpointsP = 10; // grid for modelling real8 dlines = (topounwrappedinterf.win.linehi-topounwrappedinterf.win.linelo) / (numpointsL-1); real8 dpixels = (topounwrappedinterf.win.pixhi -topounwrappedinterf.win.pixlo) / (numpointsP-1); INFO << "Computing baseline on grid (" << topounwrappedinterf.win.linelo << ":" << dlines << ":" << topounwrappedinterf.win.linehi << "," << topounwrappedinterf.win.pixlo << ":" << dpixels << ":" << topounwrappedinterf.win.pixhi << ") = (" << numpointsL << "x" << numpointsP << ")"; INFO.print(); matrix LINENUMBER(numpointsL*numpointsP,1); matrix PIXELNUMBER(numpointsL*numpointsP,1); int32 i,j; int32 k=0; for (i=0; i Bperptopo(LINENUMBER.lines(),1); matrix Bperpdefo(LINENUMBER.lines(),1); for (int32 i=0; i Ratio = Bperpdefo/Bperptopo; #ifdef __DEBUG DEBUG.print("data dump to files: LINENUMBER, PIXELNUMBER, Bperptopo, Bperpdefo, Ratio"); dumpasc("LINENUMBER",LINENUMBER); dumpasc("PIXELNUMBER",PIXELNUMBER); dumpasc("Bperptopo",Bperptopo); dumpasc("Bperpdefo",Bperpdefo); dumpasc("Ratio",Ratio); #endif // old, better but changes info i want later. //normalize(LINENUMBER,minL,maxL); //normalize(PIXELNUMBER,minP,maxP); //A.setcolumn(0,1.); //A.setcolumn(1,LINENUMBER); //A.setcolumn(2,PIXELNUMBER); // ______ Set designmatrix, compute normalmatrix, righthandside ______ matrix A(Ratio.lines(),3); for (uint i=0; i N = matTxmat(A,A); matrix rhs = matTxmat(A,Ratio); // ______ Compute solution ______ matrix Qx_hat = N; choles(Qx_hat); // Cholesky factorisation normalmatrix solvechol(Qx_hat,rhs); // Estimate unknowns (a00,a10,a01) in rhs invertchol(Qx_hat); // Covariance matrix of unknowns // ______ Test inverse (thus stability cholesky) ______ for (uint i=0; i crop?"; PRINT_ERROR(ERROR.get_str()) throw(some_error); } else if (maxdev > 0.001) { WARNING.print("Deviation quite large. careful!"); } // ______ Some other stuff for logfile ______ // matrix Qy_hat = A * (matxmatT(Qx_hat,A)); matrix y_hat = A * rhs; matrix e_hat = Ratio - y_hat; uint pos,dummy; const real8 maxerrorratio = max(abs(e_hat),pos,dummy); const real8 maxrelerror = 100.0 * maxerrorratio / Ratio(pos,0); INFO << "maximum error for l,p: " << LINENUMBER(pos,0) << "," << PIXELNUMBER(pos,0) << "; Ratio=" << Ratio(pos,0) << " estimate=" << y_hat(pos,0) << "; rel. err=" << maxrelerror << "%. "; INFO.print(); if (maxrelerror < 5.0 ) { INFO.print("max err OK"); } else { WARNING.print("max err quite large"); WARNING.print("Error in deformation vector larger than 5% due to mismodeling baseline!"); } // ====== Per 100 lines, read in topo and defo interf. ====== ofstream ofcint,ofscaledtopo; openfstream(ofcint,dinsarinput.fodinsar,input_general.overwrit); bk_assert(ofcint,dinsarinput.fodinsar,__FILE__,__LINE__); bool writescaledtopo=false; if (specified(dinsarinput.foscaleduint)) { INFO.print("writing scaled version of unwrapped topo interferogram in real4 format."); writescaledtopo=true; openfstream(ofscaledtopo,dinsarinput.foscaleduint,input_general.overwrit); bk_assert(ofscaledtopo,dinsarinput.foscaleduint,__FILE__,__LINE__); } const int32 numlines = defointerferogram.win.lines() / defointerferogram.multilookL; const int32 numpixels = defointerferogram.win.pixels() / defointerferogram.multilookP; const real4 firstline = defointerferogram.win.linelo + (real8(defointerferogram.multilookL-1.)/2.); const real4 firstpixel= defointerferogram.win.pixlo + (real8(defointerferogram.multilookP-1.)/2.); matrix ratioline(1,numpixels); for (int32 i=0; i DEFO(1,numpixels); // buffer // test if reading phase was ok... //cerr << "test: writing hgt phase and cint.\n"; //ofstream oftest1("TOPO.raw", ios::out | ios::binary | ios::trunc); //ofstream oftest2("CINT.raw", ios::out | ios::binary | ios::trunc); int32 tenpercent = int32(floor(numlines/10.)); if (tenpercent==0) tenpercent = 1000; int32 percent = 0; for (int32 i=0; i ratio = ratioline + real4(rhs(1,0))*normalize(line,real4(minL),real4(maxL)); // ______ read from file, correct, write to file ______ ifdefocint >> DEFO; // read next full line const window filewin(i+1,i+1,1,numpixels); matrix TOPO = topounwrappedinterf.readphase(filewin); // seems faster, but how to check for unwrapping? //TOPO *= ratio; // scaled topo to defo baseline //DEFO *= complr4(cos(TOPO),-sin(TOPO)); // better matrix index = TOPO.find(NaN); later reset?? // and topo=topo*ratio; and defo(index)=(0,0); // but how to implement this best in matrixclass? // BK 24-Oct-2000 for (int32 j=0; j (via phase slope) * * Freek van Leijen (topo slope) * * Mahmut Arikan * * * * See paper by Eineder 2003 * * * ****************************************************************/ void sim_amplitude( const input_gen &generalinput, const input_ell &ellips, const input_simamp &simamp, const slcimage &master, orbit &masterorbit) { TRACE_FUNCTION("sim_amplitude (MA, FvL, BO 31-OCT-2008)") const string STEP="SAM: "; const string STEPlog="SAM"; const int32 MAXITER = 10; const real8 CRITERPOS = 1e-6; const real8 CRITERTIM = 1e-10; const real8 lat0file = simamp.demlatleftupper;// first pix on disk w02090 const real8 lon0file = simamp.demlonleftupper;// first pix on disk const real8 DEMdeltalat = simamp.demdeltalat; // in radians const real8 DEMdeltalon = simamp.demdeltalon; // in radians const int32 numberoflonpixels = simamp.demcols; // NCOLS on file const int32 numberoflatpixels = simamp.demrows; // NROWS on file const real8 NODATA = simamp.demnodata; // (BK 4 may 2001) //const bool outputdemi = specified(simamp.fodemi);// if spec. then output const bool outputrefdemhei = specified(simamp.fodemlp); // MA SPT const bool outputthetalp = specified(simamp.fothetalp); // MA SPT //const int32 mlL = 1/master.ovs_az; // multilookfactor azimuth //const int32 mlP = 1/master.ovs_rg; // multilookfactor range this is ifgmetric convention of Doris const int32 mlL = 1; // multilookfactor azimuth const int32 mlP = 1; // multilookfactor range SLCs should be 1 even if oversampled. //INFO << "master multilook_az = " << mlL; //INFO.print(); //INFO << "master multilook_rg = " << mlP; //INFO.print(); //DEBUG << "master wavelength = " << master.wavelength; //DEBUG.print(); //DEBUG << "slave wavelength = " << slave.wavelength; //DEBUG.print(); const real8 latNfile = lat0file-DEMdeltalat*(numberoflatpixels-1); // upper=max. lat value const real8 lonNfile = lon0file+DEMdeltalon*(numberoflonpixels-1); // left=min. lon value // ______ Extra info ______ INFO << "DEM input: w/e/s/n: \t" << rad2deg(lon0file) << "/" << rad2deg(lonNfile) << "/" << rad2deg(latNfile) << "/" << rad2deg(lat0file); INFO.print(); // ______ Get corners of master (approx) to select DEM ______ // ______ in radians (if height were zero)______ real8 extralat = (1.5*DEMdeltalat + deg2rad(4.0/25.0)); real8 extralong = (1.5*DEMdeltalon + deg2rad(4.0/25.0)); real8 phimin; real8 phimax; real8 lambdamin; real8 lambdamax; int32 indexphi0DEM; int32 indexphiNDEM; int32 indexlambda0DEM; int32 indexlambdaNDEM; getcorners(master.currentwindow.linelo,master.currentwindow.linehi, master.currentwindow.pixlo,master.currentwindow.pixhi, extralat,extralong,lat0file,lon0file, DEMdeltalat,DEMdeltalon,numberoflatpixels,numberoflonpixels, ellips,master,masterorbit,phimin,phimax,lambdamin,lambdamax, indexphi0DEM,indexphiNDEM,indexlambda0DEM,indexlambdaNDEM); // ______ Extra info ______ INFO << "DEM input required: w/e/s/n: \t" << rad2deg(lambdamin) << "/" << rad2deg(lambdamax) << "/" << rad2deg(phimin) << "/" << rad2deg(phimax); INFO.print(); INFO << "DEM input window (l0,lN,p0,pN): \t" << indexphi0DEM << " " << indexphiNDEM << " " << indexlambda0DEM << " " << indexlambdaNDEM ; INFO.print(); INFO << "For master window (l0,lN,p0,pN): \t" << master.currentwindow.linelo << " " << master.currentwindow.linehi << " " << master.currentwindow.pixlo << " " << master.currentwindow.pixhi; INFO.print(); // ______ Check corners of DEM ______ // check if DEM is appropriate for master // DEM should at least partially cover master // note: phi is [90:-90] if (phimax <= latNfile)// DEM is more north than master { ERROR << "master outside DEM: most South latitude: " << rad2deg(latNfile) << " [deg]; master requires: " << rad2deg(phimax) << " [deg]"; PRINT_ERROR(ERROR.get_str()) throw(some_error); } // DEM is more south than master if (phimin >= lat0file)// largest latitude at first line of file { ERROR << "master outside DEM: most North latitude: " << rad2deg(lat0file) << " [deg]; master requires: " << rad2deg(phimax) << " [deg]"; PRINT_ERROR(ERROR.get_str()) throw(some_error); } if (lambdamax <= lon0file) { ERROR << "master outside DEM: most West longitude: " << rad2deg(lon0file) << " [deg]; master window requires: " << rad2deg(lambdamax) << " [deg]"; PRINT_ERROR(ERROR.get_str()) throw(some_error); } if (lambdamin >= lonNfile) { ERROR << "master outside DEM: most East longitude: " << rad2deg(lonNfile) << " [deg]; master window requires: " << rad2deg(lambdamin) << " [deg]"; PRINT_ERROR(ERROR.get_str()) throw(some_error); } //=================================================================== //============ First loop: radarcode DEM ============================ //============ (DEM geometry) ============================ //=================================================================== int32 numvalid = 0;// number of good values, not NODATA in buffer int32 numNODATA = 0;// number of NODATA values in buffer real8 meancroppedDEM = 0.0;// to detect byte order problems, formats real8 min_input_dem = 100000.0;// stats real8 max_input_dem = -100000.0;// stats // ______ Compute buffer size radarcoding DEM______ const real8 BUFFERMEMSIZE = generalinput.memory;// Bytes const int32 NcolsDEM = indexlambdaNDEM-indexlambda0DEM+1; const int32 NrowsDEM = indexphiNDEM-indexphi0DEM+1; const real8 Nrows_possible_DEM = BUFFERMEMSIZE / (5*8*NcolsDEM); int32 bufferlines = int32(ceil(Nrows_possible_DEM)); if (bufferlines>NrowsDEM) bufferlines=NrowsDEM; int32 numfullbuffers = NrowsDEM / bufferlines; int32 restlines = NrowsDEM % bufferlines; int32 extrabuffer = (restlines == 0) ? 0 : 1; // ______ Extra info ______ INFO << "DEM output total pixels: " << NcolsDEM; INFO.print(); INFO << "DEM output total lines : " << NrowsDEM; INFO.print(); INFO << "Radar coding of DEM in: " << numfullbuffers << " buffers of " << bufferlines << " lines and " << extrabuffer << " extra buffer of " << restlines << " lines."; INFO.print(); const string fsuccess = "sam_m_theta.success"; // [MA] a file to check successfull run of first loop //if(!existed("sam_m_theta.temp")) // The condition to skip first loop if(!existed(fsuccess.c_str())) // The condition to skip first loop { // ______ Open (temporary) output files ______ // DEM heights ofstream demofile; openfstream(demofile,simamp.fodem,generalinput.overwrit); bk_assert(demofile,simamp.fodem,__FILE__,__LINE__); // theta (incidence angle) (in DEM coords) ofstream thetaoutfile("sam_m_theta.temp", ios::out | ios::trunc); bk_assert(thetaoutfile,"sam_m_theta.temp",__FILE__,__LINE__); // master line coordinates of DEM ofstream masterdemlineoutfile("sam_m_demline.temp", ios::out | ios::trunc); bk_assert(masterdemlineoutfile,"sam_m_demline.temp",__FILE__,__LINE__); // master pixel coordinates of DEM ofstream masterdempixeloutfile("sam_m_dempixel.temp", ios::out | ios::trunc); bk_assert(masterdempixeloutfile,"sam_m_dempixel.temp",__FILE__,__LINE__); // ______ DEM loop per buffer ______ register int32 j,i;// DEM index grid counter, register j first to ensure allocation for (register int32 buffer=0; buffer DEM(blines,NcolsDEM); // ______ Extra info ______ PROGRESS << STEP << "Buffer# [l0:lN, p0:pN]: " << buffer+1 << " [" << indexphi0BUFFER << ": " << indexphiNBUFFER << ", " << indexlambda0DEM << ": " << indexlambdaNDEM << "]"; PROGRESS.print(); // ______ lat/lon for first pixel in matrix read from file ______ // ______ upper is max. latitude, left is min. longitude ______ const real8 upperleftphi = lat0file-indexphi0BUFFER*DEMdeltalat; const real8 upperleftlambda = lon0file+indexlambda0DEM*DEMdeltalon; window zerooffset (0,0,0,0); window winfromfile (indexphi0BUFFER,indexphiNBUFFER, indexlambda0DEM,indexlambdaNDEM); // ______ Read in grdfile of DEM in matrix R4 (raw data, no header) _______ // ______ added formats (BK 4-May-2001) ______ PROGRESS << STEP << "Reading crop of DEM for buffer: " << buffer+1; PROGRESS.print(); DEBUG.print("Reading input DEM into real4 matrix (buffer)."); switch (simamp.iformatflag) // TODO [MA] potential external function { // ______ Read as short BE, then convert to host order ______ case FORMATI2_BIGENDIAN: { matrix DEMi2(blines,NcolsDEM); readfile(DEMi2,simamp.firefdem,numberoflatpixels,winfromfile,zerooffset); for (int32 iii=0; iii DEMi2(blines,NcolsDEM); readfile(DEMi2,simamp.firefdem,numberoflatpixels,winfromfile,zerooffset); for (int32 iii=0; iii DEMr8(blines,NcolsDEM); readfile(DEMr8,simamp.firefdem,numberoflatpixels,winfromfile,zerooffset); for (int32 iii=0; iiimax_dem_buffer) max_dem_buffer=DEM(i,j);// stats } else { numNODATA++; } }//loop dem for stats }//loop dem for stats min_input_dem = min(min_input_dem,min_dem_buffer);//global stats max_input_dem = max(max_input_dem,max_dem_buffer);//global stats // ====== Radarcoding DEM ============================== // ______ DEM contains values from leftupper with ______ // ______ spacing (DEMdeltalat,DEMdeltalon) ______ // ______ Transform DEM to l,p,refphase ______ PROGRESS.print("Converting DEM to radar system for this buffer."); const int32 NpointsDEM = DEM.size(); const int32 NpixelsDEM = DEM.pixels(); // ______ Extra info ______ INFO << "Number of points in DEM: " << NpointsDEM; INFO.print(); matrix masterDEMline(DEM.lines(),DEM.pixels()); matrix masterDEMpixel(DEM.lines(),DEM.pixels()); matrix theta_array(DEM.lines(),DEM.pixels()); // --- Loop DEM --- cn P; real8 phi,lambda,height,l,p,theta; //,sim_amp; already a matrix see below [MA] phi = upperleftphi; for (i=0; i Nlinesml) bufferlines=Nlinesml; numfullbuffers = Nlinesml / bufferlines; restlines = Nlinesml % bufferlines; extrabuffer = (restlines == 0) ? 0 : 1; // ______ Extra info ______ INFO << "Interpolation in: " << numfullbuffers << " buffers of " << bufferlines << " lines and " << extrabuffer << " extra buffer of " << restlines << " lines."; INFO.print(); // ______ Open output files ______ ofstream simampofile; openfstream(simampofile,simamp.fosimamp,generalinput.overwrit); bk_assert(simampofile,simamp.fosimamp,__FILE__,__LINE__); // if request for height in radar coordinates l,p ofstream samheiofile; // MA if (outputrefdemhei==true) { openfstream(samheiofile,simamp.fodemlp,generalinput.overwrit); bk_assert(samheiofile,simamp.fodemlp,__FILE__,__LINE__); } // if request for theta in radar coordinates l,p ofstream samthetaofile; // MA if (outputrefdemhei==true) { openfstream(samthetaofile,simamp.fothetalp,generalinput.overwrit); bk_assert(samthetaofile,simamp.fothetalp,__FILE__,__LINE__); } // ______ interpolation loop per buffer ______ for (register int32 buffer = 0; buffer < numfullbuffers + extrabuffer; ++buffer) { // Determine indices for buffer const int32 blines = (buffer == numfullbuffers) ? restlines : bufferlines; const real8 firstline_buffer = veryfirstline+buffer*bufferlines*mlL; const real8 lastline_buffer = firstline_buffer+(blines-1)*mlL; // ______ Extra info ______ PROGRESS << STEP << "Interpolation buffer: " << buffer+1 << "of" << numfullbuffers + extrabuffer << " [l0:lN, p0:pN]: " << " [" << firstline_buffer << ": " << lastline_buffer << ", " << firstpixel << ": " << lastpixel << "]"; PROGRESS.print(); // Get corners of buffer real8 phimin_az; real8 phimax_az; real8 lambdamin_az; real8 lambdamax_az; getcorners(firstline_buffer+offset,lastline_buffer+offset, firstpixel+offset,lastpixel+offset, extralat,extralong,phimax,lambdamin, DEMdeltalat,DEMdeltalon,NrowsDEM,NcolsDEM, ellips,master,masterorbit,phimin_az,phimax_az,lambdamin_az,lambdamax, indexphi0DEM,indexphiNDEM,indexlambda0DEM,indexlambdaNDEM); window zerooffset (0,0,0,0); window winfromfile (indexphi0DEM,indexphiNDEM, indexlambda0DEM,indexlambdaNDEM); const int32 NrowsDEM_buffer = indexphiNDEM-indexphi0DEM+1; const int32 NcolsDEM_buffer = indexlambdaNDEM-indexlambda0DEM+1; PROGRESS << STEP << "Reading input for interpolation buffer: " << buffer+1 << "of" << numfullbuffers + extrabuffer; PROGRESS.print(); // read x,y matrix DEMline_buffer(NrowsDEM_buffer,NcolsDEM_buffer); matrix DEMpixel_buffer(NrowsDEM_buffer,NcolsDEM_buffer); readfile(DEMline_buffer,"sam_m_demline.temp",NrowsDEM,winfromfile,zerooffset); readfile(DEMpixel_buffer,"sam_m_dempixel.temp",NrowsDEM,winfromfile,zerooffset); // read z (multiple, number can easily be increased, e.g. simulated intensity) int32 Nz = 2; //number of z, matrix depth matrix input_buffer(NrowsDEM_buffer *Nz ,NcolsDEM_buffer); matrix temp_input_buffer(NrowsDEM_buffer,NcolsDEM_buffer); // Read in real4 dem heights and convert to real8 for computation [MA] TODO potential external function matrix dem_input(NrowsDEM_buffer,NcolsDEM_buffer); readfile(dem_input,simamp.fodem,NrowsDEM,winfromfile,zerooffset); // TODO modify this so it can handle conversion as well for (register int32 i =0 ; i < NrowsDEM_buffer ; i++) for(register int32 j = 0; j < NcolsDEM_buffer; j++) temp_input_buffer(i,j) = real8(dem_input(i,j)); dem_input.resize(1,1); // deallocation // readfile(temp_input_buffer,simamp.fodem,NrowsDEM,winfromfile,zerooffset); input_buffer.setdata(0, 0, temp_input_buffer); readfile(temp_input_buffer,"sam_m_theta.temp",NrowsDEM,winfromfile,zerooffset); input_buffer.setdata(NrowsDEM_buffer * (Nz-1) , 0, temp_input_buffer); DEBUG << "NrowsDEM: " << NrowsDEM << " window " << indexphi0DEM << " " << indexphiNDEM << " " << indexlambda0DEM << " " << indexlambdaNDEM ; DEBUG.print(); // initialize output array Nz = 2; matrix output_buffer(blines * Nz, Npixelsml); // interpolation DEBUG << "fl_buf: " << firstline_buffer << " ll_buf: " << lastline_buffer << " p: " << firstpixel << " P: " << lastpixel << " mlL: " << mlL << " mlP: " << mlP << " r_a_ratio: " << r_az_ratio << " offset: " << offset << " nodata: " << NODATA ; DEBUG.print(); DEBUG << "theta: " << input_buffer(NrowsDEM_buffer * (Nz-1),0) << " =? " << temp_input_buffer(0,0) << " " << NrowsDEM << " " << simamp.fodem ; DEBUG.print(); griddatalinear(DEMline_buffer,DEMpixel_buffer,input_buffer, firstline_buffer,lastline_buffer,firstpixel,lastpixel, mlL,mlP,r_az_ratio,offset,NODATA,output_buffer); DEBUG << "temp_input_buffer size: " << temp_input_buffer.size() << " l: " << temp_input_buffer.lines() << " p: " << temp_input_buffer.pixels() << "\n\t:" << " input_buffer size : " << input_buffer.size() << " l: " << input_buffer.lines() << " p: " << input_buffer.pixels() << "\n\t:" << " output_buffer size : " << output_buffer.size() << " l: " << output_buffer.lines() << " p: " << output_buffer.pixels() ; DEBUG.print(); DEBUG << "NrowsDEM_buffer,NcolsDEM_buffer: " << NrowsDEM_buffer << "," << NcolsDEM_buffer ; DEBUG.print(); DEBUG << "blines, Npixelsml: " << blines << "," << Npixelsml ; DEBUG.print(); if (outputrefdemhei==true) { Nz = 1; // radarcoded topo matrix topo(blines,Npixelsml); //topo matrix in master coords. in local scope for (register int32 i = 0 ; i < blines ; i++) for(register int32 j = 0; j < Npixelsml; j++) topo(i,j)= real4(output_buffer((Nz-1)*blines+i,j)); // real8 --> real4 // could use window() but here needed real4 conversion // samheiofile << output_buffer(window((Nz-1) * blines,Nz * blines - 1, 0, Npixelsml -1 )); samheiofile << topo; } if (outputthetalp==true) // theta matrix dump { Nz = 2; // radarcoded theta matrix theta(blines,Npixelsml); //theta matrix in master coords. in local scope for (register int32 i = 0 ; i < blines ; i++) for(register int32 j = 0; j < Npixelsml; j++) theta(i,j)= real4(output_buffer((Nz-1)*blines+i,j)); // real8 --> real4 samthetaofile << theta; } // real8 theta = output_buffer(blines+int(blines/2),int(Npixelsml/2)); // is it constant if so const const real8 slant_range = SOL/(2*master.rsr2x); real8 grad, alpha, local_inc_angle, theta, ground_range; matrix sim_amp(blines,Npixelsml); //sim_amp matrix in master coords. Nz=2; for (register int16 i = 0 ; i < blines ; i ++) for(register int16 j = 0; j < Npixelsml; j++) if (j < Npixelsml-1) { theta = output_buffer((Nz-1)*blines+i,j); // incidence angle ground_range = slant_range/sin(theta); grad = output_buffer(i,j+1) - output_buffer(i,j); // hei gradient alpha = atan(grad/ground_range); // slope local_inc_angle = theta-alpha; //sim_amp(i,j) = (real4) alpha; //sim_amp(i,j) = (real4) local_inc_angle; //sim_amp(i,j) = (real4) cos(local_inc_angle)/sin(local_inc_angle); // see eineder2003 // sim_amp(i,j) = (real4) sin(-local_inc_angle); // used //sim_amp(i,j) = (real4) sin(-local_inc_angle)+1; // used, +1 shift to positive range of values. //sim_amp(i,j) = (real4) pow(sim_amp(i,j),2); // intensity to be tested if ( output_buffer(i,j) == 0 ) // search for sea where hei ~ 0; [TODO] introduce external mask { sim_amp(i,j) = 0; } else { sim_amp(i,j) = (real4) sin(-local_inc_angle)+1; // used, +1 shift to positive range of values. //sim_amp(i,j) = (real4) pow((sin(-local_inc_angle)+1),2); // intensity } } else { sim_amp(i,j) = sim_amp(i,j-1); // cp previous coln as last coln } // Write results to output files PROGRESS << STEP << "Writing radar coded SIM_AMPLITUDE to file, buffer#: " << buffer+1 << " of " << numfullbuffers + extrabuffer ; PROGRESS.print(); simampofile << sim_amp; DEMline_buffer.resize(1,1); //deallocate DEMpixel_buffer.resize(1,1); input_buffer.resize(1,1); temp_input_buffer.resize(1,1); output_buffer.resize(1,1); sim_amp.resize(1,1); } //end loop INFO << "Closing output files"; INFO.print(); simampofile.close(); if (outputrefdemhei==true) samheiofile.close(); if (outputthetalp==true) samthetaofile.close(); //if(!remove(fsuccess.c_str())) // when success report removed. // { // DEBUG << STEP << "Removed existing " << fsuccess << "file."; // DEBUG.print(); // } ; const string assertmsg = STEP + fsuccess; ofstream scratchfile(fsuccess.c_str(), ios::out | ios::trunc); // [MA] //bk_assert(scratchfile, strcat("SAM: ", fsuccess.c_str()) ,__FILE__,__LINE__); // this does not work bk_assert(scratchfile, assertmsg.c_str() ,__FILE__,__LINE__); //bk_assert(scratchfile, fsuccess.c_str() ,__FILE__,__LINE__); scratchfile << "sam_m_theta.temp succeeded!" << endl; scratchfile.close(); // ====== Write output information ====== //*char croppeddemi[ONE27]; //*strcpy(croppeddemi,"NO output requested"); //*if (outputdemi) strcpy(croppeddemi,simamp.fodemi); INFO << "Min. value of input DEM covering sim. amplitude (master): " << min_input_dem; INFO.print(); INFO << "Max. value of input DEM covering sim. amplitude (master): " << max_input_dem; INFO.print(); ofstream scratchlogfile("scratchlogsimamp", ios::out | ios::trunc); bk_assert(scratchlogfile,"simamp: scratchlogsimamp",__FILE__,__LINE__); scratchlogfile << "\n*******************************************************************" << "\n* " << processcontrol[pr_m_simamp] << "\n*******************************************************************" << "\n1) DEM source file: \t" << simamp.firefdem << "\nFormat: \t"; switch (simamp.iformatflag) { case FORMATI2: { scratchlogfile << "SHORT SIGNED INTEGER (HOST ENDIANNESS)"; break; } case FORMATI2_BIGENDIAN: { scratchlogfile << "SHORT SIGNED INTEGER, BIG ENDIAN"; break; } case FORMATR4: { scratchlogfile << "REAL4 SIGNED FLOAT"; break; } case FORMATR8: { scratchlogfile << "REAL8 SIGNED DOUBLE"; break; } default: { scratchlogfile << "UNKNOWN? IMPOSSIBLE..."; break; } } scratchlogfile << "\nByte order: \t" << "check it yourself..." << "\nNumber of lines: \t" << numberoflatpixels << "\nNumber of pixels: \t" << numberoflonpixels << "\nResolution latitude: \t" << rad2deg(DEMdeltalat) << " [deg]" << "\nResolution longitude: \t" << rad2deg(DEMdeltalon) << " [deg]" << "\nMost West point in input DEM: \t" << rad2deg(lon0file) << "\nMost East point in input DEM: \t" << rad2deg(lonNfile) << "\nMost South point in input DEM: \t" << rad2deg(latNfile) << "\nMost North point in input DEM: \t" << rad2deg(lat0file) << "\nMin. value of input DEM covering master: " << min_input_dem << "\nMax. value of input DEM covering master: " << max_input_dem << "\n2) Output file cropped DEM: \t" << simamp.fodem << "\nFormat: \t" << "REAL4" << "\nByte order: \t" << "(same as host)" << "\nNumber of lines (multilooked): \t" << NrowsDEM << "\nNumber of pixels (multilooked): \t" << NcolsDEM << "\nDEM extend w/e/s/n : \t" << rad2deg(lambdamin) << "/" << rad2deg(lambdamax) << "/" << rad2deg(phimin) << "/" << rad2deg(phimax) // << "\nMean value: \t" << meancroppedDEM // << "\n3) Output file interpolated crop DEM: \t" << croppeddemi << "\nFormat: \t" << "REAL4" << "\nByte order: \t" << "(same as host)" << "\nNumber of lines (multilooked): \t" << Nlinesml << "\nNumber of pixels (multilooked): \t" << Npixelsml << "\n3) Output file synthetic amplitude: \t" << simamp.fosimamp << "\nFormat: \t" << "REAL4" << "\nByte order: \t" << "(same as host)" << "\nNumber of lines (multilooked): \t" << Nlinesml << "\nNumber of pixels (multilooked): \t" << Npixelsml; if (outputrefdemhei==true) { scratchlogfile << "\n4) Output file radarcoded DEM: \t" << simamp.fodemlp << "\nFormat: \t" << "REAL4" << "\nByte order: \t" << "(same as host)" << "\nNumber of lines (multilooked): \t" << Nlinesml << "\nNumber of pixels (multilooked): \t" << Npixelsml; } if (outputthetalp==true) { scratchlogfile << "\n5) Output file local_inc angle theta: \t" << simamp.fothetalp << "\nFormat: \t" << "REAL4" << "\nByte order: \t" << "(same as host)" << "\nNumber of lines (multilooked): \t" << Nlinesml << "\nNumber of pixels (multilooked): \t" << Npixelsml; } scratchlogfile // << "\nDeltaline_slave00_dem: \t" << deltaline_slave00 // [MA no gridlinear so no corners] // << "\nDeltapixel_slave00_dem: \t" << deltapixel_slave00 // [? put getcorners instead] // << "\nDeltaline_slave0N_dem: \t" << deltaline_slave0N // << "\nDeltapixel_slave0N_dem: \t" << deltapixel_slave0N // << "\nDeltaline_slaveN0_dem: \t" << deltaline_slaveN0 // << "\nDeltapixel_slaveN0_dem: \t" << deltapixel_slaveN0 // << "\nDeltaline_slaveNN_dem: \t" << deltaline_slaveNN // << "\nDeltapixel_slaveNN_dem: \t" << deltapixel_slaveNN << "\n*******************************************************************\n\n"; scratchlogfile.close(); ofstream scratchresfile("scratchressimamp", ios::out | ios::trunc); bk_assert(scratchresfile,"simamp: scratchressimamp",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************" << "\n*_Start_" << processcontrol[pr_m_simamp] << "\n*******************************************************************"; scratchresfile << "\nDEM source file: \t" << simamp.firefdem << "\nMin. of input DEM: \t" << min_input_dem << "\nMax. of input DEM: \t" << max_input_dem << "\nData_output_file: \t" << simamp.fosimamp << "\nData_output_format: \t" << "real4"; if (outputrefdemhei==true) scratchresfile << "\n" << STEPlog << "_outdem_file: \t" << simamp.fodemlp; if (outputthetalp==true) scratchresfile << "\n" << STEPlog << "_theta_file: \t" << simamp.fothetalp; scratchresfile << "\nFirst_line (w.r.t. original_master): \t" << master.currentwindow.linelo << "\nLast_line (w.r.t. original_master): \t" << master.currentwindow.linehi << "\nFirst_pixel (w.r.t. original_master): \t" << master.currentwindow.pixlo << "\nLast_pixel (w.r.t. original_master): \t" << master.currentwindow.pixhi << "\nMultilookfactor_azimuth_direction: \t" << mlL << "\nMultilookfactor_range_direction: \t" << mlP << "\nNumber of lines (multilooked): \t" << Nlinesml << "\nNumber of pixels (multilooked): \t" << Npixelsml << "\n*******************************************************************" << "\n* End_" << processcontrol[pr_m_simamp] << "_NORMAL" << "\n*******************************************************************\n"; scratchresfile.close(); } // END simulate_amp; Doris-5.0.3Beta/doris_core/products.hh000077500000000000000000000112301312547014700177130ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/products.hh,v $ * $Revision: 3.9 $ * $Date: 2006/05/18 10:03:18 $ * $Author: kampes $ * * Declaration of routines for computation of products (interferogram etc.) ****************************************************************/ #ifndef PRODUCTS_H // guard #define PRODUCTS_H using namespace std; // BK 29-Mar-2003, new compiler? // Jia defined this for compilation under windows // Bert Kampes, 24-Aug-2005 #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "constants.hh" // typedefs #include "readinput.hh" // input structs #include "orbitbk.hh" // my orbit class #include "slcimage.hh" // my slc image class #include "productinfo.hh" // my 'products' class // ______ Simulate amplitude ______ [MA] void sim_amplitude( const input_gen &generalinput, const input_ell &ellips, const input_simamp &simamp, const slcimage &master, orbit &masterorbit); // ______ Compute the (complex) interferogram ______ void compinterfero( const slcimage &master, const slcimage &slave, const input_gen &input_general, const input_interfero &input_i_interfero); // ______ Subtract ref.pha from complex interferogram ______ // ______ evaluate polynomial from comprefpha ______ void subtrrefpha( const slcimage &master, const productinfo &interferogram, const input_gen &input_general, const input_subtrrefpha &input_i_subtrrefpha, const matrix &coeff_refpha, const matrix &coeff_h2ph); // added by FvL // ______ evaluate ref. pha foreach pixel ______ void subtrrefpha( const input_ell &ellips, const slcimage &master, const slcimage &slave, const productinfo &interferogram, const input_gen &input_general, const input_subtrrefpha &input_i_subtrrefpha, orbit &masterorbit, orbit &slaveorbit); // ______ Compute the (complex) coherence image ______ void compcoherence( const slcimage &master, const slcimage &slave, const input_gen &input_general, const input_coherence &input_i_coherence, const matrix &coeff_flatearth); // ______ Compute the (complex) coherence image [NEW method] ______ added by DON void compcoherence( const slcimage &master, const slcimage &slave, const productinfo &radarcoderefdem, const input_gen &input_general, const input_coherence &input_i_coherence, const matrix &coeff_flatearth); // ______ Subtract ref.dem from complex interferogram ______ void subtrrefdem( const productinfo &interferogram, // filename, size info const productinfo &radarcoderefdem, // filename, size info const input_gen &input_general, // overwrite, memory const input_subtrrefdem &input_i_subtrrefdem); // ______ Scale defo-interferogram with ratio of Bperp ______ void dinsar( const input_gen &input_general, // overwrite, memory const input_dinsar &dinsarinput, const input_ell &ellips, const slcimage &master, orbit &masterorbit, const slcimage &defoslave, orbit &defoorbit, const productinfo &defointerferogram); #endif // PRODUCTS_H Doris-5.0.3Beta/doris_core/readdata.cc000077500000000000000000006464701312547014700176270ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/readdata.cc,v $ * $Revision: 3.37 $ * $Date: 2005/10/06 11:09:20 $ * $Author: kampes $ * * routines for initial work, reading SLC, * writing to internal format. * see e.g: http://earth.esa.int:81/sarslc ****************************************************************/ #include "matrixbk.hh" #include "constants.hh" #include "slcimage.hh" // my slc image class #include "ioroutines.hh" // ? #include "exceptions.hh" // my exceptions class #include "coregistration.hh" // for kernel raised cosine #include // for streams #include // setw #include // atoi, system #include // strcmp #include // some compilers, remove function #include // some compilers, strptime function #ifdef WIN32 #include "winsock2.h" // Jia changed this #else #include // ntohl byteorder x86-HP unix #endif #include // max,min #include "utilities.hh" // sinc() cr4toci2() char *strptime(const char *s, const char *format, struct tm *tm); /**************************************************************** * julday() * * mm JAN=1, FEB=2, etc; id: day=1,2,3.., iyyy=1996 * * * #%// Bert Kampes, 07-Apr-2005 ****************************************************************/ #define IGREG (15+31L*(10+12L*1582)) int32 julday(int32 id, int32 mm, int32 iyyy) { int32 jul; int32 ja,jy,jm; if (iyyy==0) { //PRINT_ERROR("julday: error") //throw(some_error); WARNING.print("julday: year=0; impossible; continuing (only for Btemp computation)"); return 0; } if (iyyy<0) ++iyyy; if (mm>2) { jy=iyyy; jm=mm+1; } else { jy=iyyy-1; jm=mm+13; } jul = int32(floor(365.25*jy)+floor(30.6001*jm)+id+1720995); if (id+31L*(mm+12L*iyyy) >= IGREG) { ja = int32(0.01*jy); jul += 2-ja+int32(0.25*ja); } return jul; } #undef IGREG /**************************************************************** * readvolume * * * * reads volumefile * * and writes to scratchlogfile and resfile * * checks if master is same as slave by id * * see: annex C ERS SAR.SLC CCTand EXABYTE * * doc:er-is-epo-gs-5902.3 * http://earth.esa.int/rootcollection/sysutil/01008.html * * * input: * * - struct: input options for readfiles * * - 3 checks with other (slave or master) volumefile * * output: * * - void, scratchfiles: ? * * * * Bert Kampes, 11-Dec-1998 * * if radarsat, skip record number 4 of 360 bytes. * * according to specs * #%// Bert Kampes, 02-Aug-2004 * #%// Davide Nitti (Don), 11-Nov-2008 Reader update for ALOS * ****************************************************************/ void readvolume( input_readfiles &readfiles_arg, const char* checkvol1, const char* checkvol2, const char* checkvol3) { TRACE_FUNCTION("readvolume (BK 11-Dec-1998)") const int16 sizeb1 = 1, // some constants for reading sizeb4 = 4, // binary fields. sizei4 = 4, // binary fields. sizei8 = 8, sizea8 = 8, sizea12 = 12, sizea16 = 16, sizea28 = 28, sizea40 = 40, sizea60 = 60; uint lenrec1, // length of record1 lenrec2, // length of record2 lenrec3, // length of record3 lenrec4, // length of record4 numpointrec, // volfile... numrec, // volfile... numvol; // volfile... char c4dummy[5], // correctly 5 for \0 c8date[9], c8time[9], c8agency[9], // correctly 9 for \0 c8nlins[9], // correctly 9 for \0 c12logvol[13], c12country[13], c12facility[13], // correctly 13 for \0 c16physid[17], c16logvolid[17], c16setid[17], c16checkfilename[17], c16dataref[17], // correctly 17 for \0 c28leaderrefclass[29], c28datarefclass[29], c40typespec[41], c40physvolid[41], c40sceneid[41], c40sceneloc[41], c60product[61]; // --- Check for Atlantis processor (RSAT?) #%// Bert Kampes, 02-Aug-2004 --- uint rec_seq;// type B4 unsigned char rec_sub1, rec_type, rec_sub2, rec_sub3;// type B1 // ======Open files====== // ___ check if opened correctly, if not, try to use uppercase // ___ from SCENE1/lea_01.001 #%// BK 27-Nov-2003 ifstream volumefile; openfstream(volumefile,readfiles_arg.volfile); bk_assert(volumefile,readfiles_arg.volfile,__FILE__,__LINE__); // ______First check control arguments, allow check to be wrong ______ DEBUG.print("readvol: check on filename consistency."); for (register int32 i=0; i<999; i++) // try some times { volumefile.seekg(44,ios::beg); volumefile.read((char*)&c16physid,sizea16); // physical logical volume ID c16physid[16]='\0'; volumefile.read((char*)&c16logvolid,sizea16); // logical volume ID c16logvolid[16]='\0'; volumefile.read((char*)&c16setid,sizea16); // volume set ID c16setid[16]='\0'; if (readfiles_arg.sensor_id==SLC_ALOS) // added by don { char c8logvoltime[9]; volumefile.seekg(120,ios::beg); volumefile.read((char*)&c8logvoltime,sizea8); // Logical volume creation time c8logvoltime[8]='\0'; for (register int32 idx=0; idx<8; idx++) c16physid[idx+8]=c8logvoltime[idx]; } if ((!strcmp(checkvol1,c16physid)) && // check failed (!strcmp(checkvol2,c16logvolid)) && (!strcmp(checkvol3,c16setid))) { if (i==0) // first time { WARNING.print("Volume file of master and slave seem to be the same, please change cd."); getanswer(); // wait } else if (i==1) // second time { WARNING << "ID of volume file 1: " << c16physid << ": " << c16logvolid << ": " << c16setid; WARNING.print(); WARNING << "ID of volume file 2: " << checkvol1 << ":" << checkvol2 << ":" << checkvol3; WARNING.print(); WARNING.print("Next time I will assume they are different."); getanswer(); // wait } else // if i == 2, enough tries { break; } } else // check passed { break; } } // ======Read volumefile====== // --- RECORD 1 --- DEBUG.print("record 1 of volume file."); volumefile.seekg(0,ios::beg);// place pointer at beginning of file volumefile.read((char*)&rec_seq,sizeb4);// record number rec_seq = ntohl(rec_seq);// Bert Kampes, 07-Apr-2005 volumefile.read((char*)&rec_sub1,sizeb1);// first record sub type code volumefile.read((char*)&rec_type,sizeb1);// record type code volumefile.read((char*)&rec_sub2,sizeb1);// second record sub type code volumefile.read((char*)&rec_sub3,sizeb1);// third record sub type code DEBUG.print("Expecting record 1 with code {192,192,18,18}"); DEBUG << "rec_seq: " << rec_seq << "; rec_sub1: " << int(rec_sub1) << "; rec_type: " << int(rec_type) << "; rec_sub2: " << int(rec_sub2) << "; rec_sub3: " << int(rec_sub3); DEBUG.print(); // --- Read important fields --- volumefile.seekg(8,ios::beg); volumefile.read((char*)&lenrec1,sizeb4); // length of record1 lenrec1 = ntohl(lenrec1); // bk 6 jul 2000, byteorder x86 machines. if (lenrec1 != 360 ) { WARNING.print("probably something wrong here, byte order x86 (?)."); WARNING << "readvolume: length of record 1 = \"" << lenrec1 << "\"; expected \"360\" for ESA SLC (full scene)."; WARNING.print(); } volumefile.seekg(32,ios::beg); volumefile.read((char*)&c12logvol,sizea12); // logical volume etc. c12logvol[12]='\0'; volumefile.seekg(112,ios::beg); volumefile.read((char*)&c8date,sizea8); // generating date c8date[8]='\0'; volumefile.read((char*)&c8time,sizea8); // generating time c8time[8]='\0'; volumefile.read((char*)&c12country,sizea12); // generating country c12country[12]='\0'; volumefile.read((char*)&c8agency,sizea8); // generating agency c8agency[8]='\0'; volumefile.read((char*)&c12facility,sizea12); // generating facility c12facility[12]='\0'; volumefile.read((char*)&c4dummy,sizei4); // #pointer records in vol. c4dummy[4]='\0'; numpointrec = atoi(c4dummy); // if (readfiles_arg.sensor_id!=SLC_RSAT) // Modified by LG for reading ALOS Fine if ((readfiles_arg.sensor_id!=SLC_RSAT) && (readfiles_arg.sensor_id!=SLC_ALOS) ) { if (numpointrec!=2) { ERROR << "readvolume: number of pointer records = \"" << c4dummy << "\"; expected \"2\" for ESA SLC (full scene)." << ends; WARNING.print(ERROR.get_str());// Jan Kianicka report atlantis processor WARNING.print("but for Atlantis processor this may be correct?"); ERROR.reset(); } } else if (numpointrec!=3) WARNING.print("expected 3 pointer records for Radarsat?"); volumefile.read((char*)&c4dummy,sizei4); // #records in vol. c4dummy[4]='\0'; numrec = atoi(c4dummy); // Modified by LG for reading ALOS Fine if (readfiles_arg.sensor_id == SLC_ALOS) { if (numrec!=1) { ERROR << "readvolume: number of records = \"" << c4dummy << "\"; expected \"1\" for JAXA SLC (full scene)." << ends; WARNING.print(ERROR.get_str()); ERROR.reset(); } } else if (readfiles_arg.sensor_id!=SLC_RSAT) { if (numrec!=4) { ERROR << "readvolume: number of records = \"" << c4dummy << "\"; expected \"4\" for ESA SLC (full scene)." << ends; WARNING.print(ERROR.get_str()); ERROR.reset(); } } else if (numrec!=5) WARNING.print("expected 5 records for Radarsat?"); volumefile.read((char*)&c4dummy,sizei4); // #vol. c4dummy[4]='\0'; numvol = atoi(c4dummy); if (readfiles_arg.sensor_id!=SLC_RSAT) if (numvol!=1) { ERROR << "readvolume: number of volumes = \"" << c4dummy << "\"; expected \"1\" for ESA SLC (full scene)." << ends; WARNING.print(ERROR.get_str()); ERROR.reset(); } // --- RECORD 2 --- const uint startrec2 = lenrec1; volumefile.seekg(startrec2,ios::beg); volumefile.read((char*)&rec_seq,sizeb4);// record number rec_seq = ntohl(rec_seq);// Bert Kampes, 07-Apr-2005 volumefile.read((char*)&rec_sub1,sizeb1);// first record sub type code volumefile.read((char*)&rec_type,sizeb1);// record type code volumefile.read((char*)&rec_sub2,sizeb1);// second record sub type code volumefile.read((char*)&rec_sub3,sizeb1);// third record sub type code DEBUG.print("Expecting record 2 with code {219,192,18,18}"); DEBUG << "rec_seq: " << rec_seq << "; rec_sub1: " << int(rec_sub1) << "; rec_type: " << int(rec_type) << "; rec_sub2: " << int(rec_sub2) << "; rec_sub3: " << int(rec_sub3); DEBUG.print(); // --- Read important fields --- volumefile.seekg(startrec2+8,ios::beg); // leader file pointer rec. DEBUG.print("record 2 of volume file."); volumefile.read((char*)&lenrec2,sizeb4); // length of record2 lenrec2 = ntohl(lenrec2); // bk 6 jul 2000, byteorder x86 machines. if (lenrec2 != 360 ) { WARNING.print("probably something wrong here, byte order x86. (?)"); WARNING << "readvolume: length of record 2 = \"" << lenrec2 << "\"; expected \"360\" for ESA SLC (full scene)."; WARNING.print(); } volumefile.seekg(startrec2+20,ios::beg); volumefile.read((char*)&c16checkfilename,sizea16); // referenced file name c16checkfilename[16]='\0'; volumefile.read((char*)&c28leaderrefclass,sizea28); // referenced file class c28leaderrefclass[28]='\0'; // --- RECORD 3 --- DEBUG.print("record 3 of volume file."); const uint startrec3 = lenrec1 + lenrec2; volumefile.seekg(startrec3,ios::beg); volumefile.read((char*)&rec_seq,sizeb4);// record number rec_seq = ntohl(rec_seq);// Bert Kampes, 07-Apr-2005 volumefile.read((char*)&rec_sub1,sizeb1);// first record sub type code volumefile.read((char*)&rec_type,sizeb1);// record type code volumefile.read((char*)&rec_sub2,sizeb1);// second record sub type code volumefile.read((char*)&rec_sub3,sizeb1);// third record sub type code DEBUG.print("Expecting record 3 with code {219,192,18,18}"); DEBUG << "rec_seq: " << rec_seq << "; rec_sub1: " << int(rec_sub1) << "; rec_type: " << int(rec_type) << "; rec_sub2: " << int(rec_sub2) << "; rec_sub3: " << int(rec_sub3); DEBUG.print(); // --- Read important fields --- volumefile.seekg(startrec3+8,ios::beg); // data file pointer rec. volumefile.read((char*)&lenrec3,sizeb4); // length of record3 lenrec3 = ntohl(lenrec3); // bk 6 jul 2000, byteorder x86 machines. if (lenrec3 != 360 ) { WARNING.print("probably something wrong here, byte order x86. (?)"); WARNING << "readvolume: length of record 3 = \"" << lenrec3 << "\"; expected \"360\" for ESA SLC (full scene)."; WARNING.print(); } volumefile.seekg(startrec3+20,ios::beg); volumefile.read((char*)&c16dataref,sizea16); // referenced file name c16dataref[16]='\0'; volumefile.read((char*)&c28datarefclass,sizea28); // referenced file class c28datarefclass[28]='\0'; volumefile.seekg(startrec3+100,ios::beg); // numlines for checking volumefile.read((char*)&c8nlins,sizei8); c8nlins[8]='\0'; // --- RECORD 4 --- uint startrec4 = lenrec1 + lenrec2 + lenrec3; //if (readfiles_arg.sensor_id==SLC_RSAT) // startrec4=startrec4+360;// skip trailer record for RSAT DEBUG.print("record 4 of volume file."); DEBUG << "readvolume::rec4: start at byte: " << startrec4; DEBUG.print(); // --- Check this record, RSAT has for us useless trailer info as rec.4 --- // --- while next record of 360 is the text record of ERS --- // ---start test for ATLANTIS (RSAT) ------------------------------------------ DEBUG.print("VMP: Expecting record 4 with code {18,63,18,18}"); volumefile.seekg(startrec4,ios::beg); volumefile.read((char*)&rec_seq,sizeb4);// record number rec_seq = ntohl(rec_seq);// Bert Kampes, 07-Apr-2005 volumefile.read((char*)&rec_sub1,sizeb1);// first record sub type code volumefile.read((char*)&rec_type,sizeb1);// record type code volumefile.read((char*)&rec_sub2,sizeb1);// second record sub type code volumefile.read((char*)&rec_sub3,sizeb1);// third record sub type code DEBUG << "rec_seq: " << rec_seq << "; rec_sub1: " << int(rec_sub1) << "; rec_type: " << int(rec_type) << "; rec_sub2: " << int(rec_sub2) << "; rec_sub3: " << int(rec_sub3); DEBUG.print(); if (int(rec_sub1)==18 && int(rec_type)==63 && int(rec_sub2)==18 && int(rec_sub3)==18) { DEBUG.print("This is the expected text record with code {18,63,18,18}"); readfiles_arg.sar_processor = SARPR_VMP;// set determined sar processor/format } else { //WARNING.print("This is not the expected text record, trying next one.") readfiles_arg.sar_processor = SARPR_ATL;// set determined sar processor/format // Modified by LG for reading ALOS Fine if ( (readfiles_arg.sensor_id == SLC_ALOS) && (int(rec_type)==192) ) readfiles_arg.sar_processor = SARPR_JAX; else if (readfiles_arg.sensor_id!=SLC_RSAT) { DEBUG.print("This is NOT the expected text record with code {18,63,18,18}"); DEBUG.print("I assume in following Atlantis processed data (ERS or RSAT)."); DEBUG.print("If this is not the case, please contact doris_users@tudelft.nl"); } volumefile.seekg(startrec4+8,ios::beg); // text record volumefile.read((char*)&lenrec4,sizeb4); // length of record4 lenrec4 = ntohl(lenrec4); // bk 6 jul 2000, byteorder x86 machines. startrec4 = startrec4 + lenrec4;// hopefully there is a next record } // ---end test for ATLANTIS (RSAT) ------------------------------------------- // --- Read important fields --- volumefile.seekg(startrec4+8,ios::beg); // text record volumefile.read((char*)&lenrec4,sizeb4); // length of record4 lenrec4 = ntohl(lenrec4); // bk 6 jul 2000, byteorder x86 machines. if (lenrec4 != 360 ) { WARNING.print("probably something wrong here, byte order x86. (?)"); WARNING << "readvolume: length of record 3 = \"" << lenrec4 << "\"; expected \"360\" for ESA SLC (full scene)."; WARNING.print(); } volumefile.seekg(startrec4+16,ios::beg); volumefile.read((char*)&c40typespec,sizea40); // product type specifier c40typespec[40]='\0'; volumefile.read((char*)&c60product,sizea60); // loc&date product gen. c60product[60]='\0'; volumefile.read((char*)&c40physvolid,sizea40); // physical vol id c40physvolid[40]='\0'; volumefile.read((char*)&c40sceneid,sizea40); // scene id c40sceneid[40]='\0'; volumefile.read((char*)&c40sceneloc,sizea40); // scene loc c40sceneloc[40]='\0'; volumefile.close(); // ====== Write results to scratch files ====== ofstream scratchlogfile("scratchlogvol", ios::out | ios::trunc); bk_assert(scratchlogfile,"scratchlogvol",__FILE__,__LINE__); // ______Write information to scratchfiles______ scratchlogfile << "\n*******************************************************************" << "\n* EXTRACTED DATA FROM VOLUME FILE: " << readfiles_arg.volfile << " *" << "\n*******************************************************************" << "\n\nVolume descriptor record" << "\n------------------------" << "\nLogical volume generating facility software " << "\n +release and revision level: \t\t\t" << c12logvol << "\nID of physical volume containing " << "\n +this volume descriptor: \t\t\t" << c16physid << "\nLogical volume identifier: \t\t\t" << c16logvolid << "\nVolume set identifier: \t\t\t\t" << c16setid << "\nLogical volume creation date (YYYYMMDD): \t" << c8date << "\nLogical volume creation time (HHMMSSDD): \t" // DD=deci-secs << c8time << "\nLogical volume generation country: \t\t" << c12country << "\nLogical volume generating agency: \t\t" << c8agency << "\nLogical volume generation facility: \t\t" << c12facility << "\n\nLeader file pointer record" << "\n--------------------------" << "\nReferenced file name: \t\t\t\t" << c16checkfilename << "\nReferenced file class: \t\t\t\t" << c28leaderrefclass << "\n\nData file pointer record" << "\n------------------------" << "\nReferenced file name: \t\t\t\t" << c16dataref << "\nReferenced file class: \t\t\t\t" << c28datarefclass << "\nNumber of records in referenced file: \t\t" << c8nlins << "\n\nText record" << "\n-----------" << "\nProduct type specifier: \t\t\t" << c40typespec << "\nLocation and date/time of product creation: \t" << c60product << "\nPhysical volume identification: \t\t" << c40physvolid << "\nScene identification: \t\t\t\t" << c40sceneid << "\nScene location: \t\t\t\t" << c40sceneloc << "\nEND VOLUME FILE " << readfiles_arg.volfile << endl << endl; scratchlogfile.close(); ofstream scratchresfile("scratchresvol", ios::out | ios::trunc); bk_assert(scratchresfile,"scratchresvol",__FILE__,__LINE__); scratchresfile << "\n*******************************************************************"; if (readfiles_arg.fileid==MASTERID) scratchresfile << "\n*_Start_" << processcontrol[pr_m_readfiles]; if (readfiles_arg.fileid==SLAVEID) scratchresfile << "\n*_Start_" << processcontrol[pr_m_readfiles]; scratchresfile << "\n*******************************************************************" << "\nVolume file: \t\t\t\t\t" << readfiles_arg.volfile << "\nVolume_ID: \t\t\t\t\t" << c16physid << "\nVolume_identifier: \t\t\t\t" << c16logvolid << "\nVolume_set_identifier: \t\t\t\t" << c16setid << "\n(Check)Number of records in ref. file: \t\t" << atoi(c8nlins); // --- write new string to determine sar processor --- // --- this is used in cropping the data --- if (readfiles_arg.sar_processor==SARPR_VMP) scratchresfile << "\nSAR_PROCESSOR: \t\t\t\tVMP"; if (readfiles_arg.sar_processor==SARPR_ATL) scratchresfile << "\nSAR_PROCESSOR: \t\t\t\tATLANTIS"; if (readfiles_arg.sar_processor==SARPR_TUD) scratchresfile << "\nSAR_PROCESSOR: \t\t\t\tTUD"; // start_added_by_don if (readfiles_arg.sar_processor==SARPR_JAX) scratchresfile << "\nSAR_PROCESSOR: \t\t\t\tJAX"; // end_added_by_don if (readfiles_arg.sensor_id==SLC_RSAT) scratchresfile << "\nProduct type specifier: \t\t\t" << "RSAT";// else it is just "PRODUCT:", but it is used in CROP step // start_added_by_don else if (readfiles_arg.sensor_id==SLC_ALOS) scratchresfile << "\nProduct type specifier: \t\t\t" << "PRODUCT ALOS";// else it is just "PRODUCT:", but it is used in CROP step // end_added_by_don else scratchresfile << "\nProduct type specifier: \t\t\t" << c40typespec; scratchresfile << "\nLogical volume generating facility: \t\t\t" << c12facility << "\nLogical volume creation date: \t\t\t" << c8date << "\nLocation and date/time of product creation: \t" << c60product << "\nScene identification: \t\t\t\t" << c40sceneid << "\nScene location: \t\t\t\t" << c40sceneloc << endl; scratchresfile.close(); // ______Tidy up______ PROGRESS.print("readvolume finished."); } // END READVOLUME /**************************************************************** * readleader * * * * reads leaderfile * * and writes to scratchlogfile, scratchresfile * * checks with volumefile #lines * * * * input: * * - struct with arguments for step0 * * - check with volumefile * * output: * * - scratchlogfile * * - scratchresfile * * - scratchdatapoints * * see: annex C ERS SAR.SLC CCTand EXABYTE * * doc:er-is-epo-gs-5902.3 * * * * Bert Kampes, 11-Dec-1998 * * Included RSAT format based on document of ASF * #%// Bert Kampes, 03-Aug-2004 * #%// Davide Nitti (Don), 11-Nov-2008 fixes for doppler * # coefficient unit for Radarsat1 and ALOS * ****************************************************************/ void readleader( input_readfiles &readfiles_arg, const int32 checklines) { TRACE_FUNCTION("readleader (BK 11-Dec-1998)") const int16 sizea2 = 2, sizeb1 = 1, // some constants for reading sizeb4 = 4, // some constants for reading sizei4 = 4, // binary fields. sizea4 = 4, // binary fields. sizei8 = 8, sizea8 = 8, sizea12 = 12, sizea16 = 16, sizef16 = 16, sizei16 = 16, sized22 = 22, sizea24 = 24, sizea32 = 32, sizea64 = 64; uint lenrec1, // length of record1 lenrec2, // length of record2 lenrec3, // length of record3 lenrec4, // bc length of record4 lenrec5, // bc/gk length of record5 lenrec6, // gk length of record6 lenrec7; // bk rsat record char c2motioncomp[3], c4dummy[5], // correctly 5 for \0 c4year[5], c4month[5], c4day[5], c4dayofyear[5], c4conversion[5], c4compression[5], c4clutterlock[5], c4autofocus[5], c8dummy[9], // dummy c8orbitnr[9], c8platformlat[9], c8platformlon[9], c8platformheading[9], c8clockangle[9], c8incidence[9], c8freq[9], c8systemid[9], c8versionid[9], c8satclockstep[9], c8extindex[9], c8qperch[9], c8timeline[9], c8timepix[9], c8linecontent[9], c12qdesc[13], c16dummy[17], c16lat11[17], c16lon11[17], c16lat1N[17], c16lon1N[17], c16latNN[17], c16lonNN[17], c16latN1[17], c16lonN1[17], c16leafilename[17], c16centerlat[17], c16centerlon[17], c16centerheading[17], c16ellipsoid[17], c16semimajor[17], c16semiminor[17], c16GM[17], c16J2[17], c16J3[17], c16J4[17], c16scenelength[17], c16scenewidth[17], c16platformid[17], c16wavelength[17], c16facilityid[17], c16numpix[17], c16numlin[17], c16interpix[17], c16interlin[17], c16pulse[17], c16ampconst[17], c16amplinear[17], c16ampquadratic[17], c16ampcubic[17], c16ampquartic[17], c16phaseconst[17], c16phaselinear[17], c16phasequadratic[17], c16phasecubic[17], c16phasequartic[17], c16sattimecode[17], c16samplingrate[17], c16rangedelay[17], c16ranpulselen[17], c16dci[17], c16dcq[17], c16boresight[17], c16imbalance[17], c16prf[17], c16looksazi[17], c16looksrange[17], c16bandazi[17], c16bandrange[17], c16bandazitot[17], c16bandrangetot[17], c16inputsource[17], c16resrange[17], c16resazi[17], c16linespace[17], c16pixspace[17], c16atdoppcconst[17], c16atdoppclinear[17], c16atdoppcquadratic[17], c16xtdoppcconst[17], c16xtdoppclinear[17], c16xtdoppcquadratic[17], c16atdopprconst[17], c16atdopprlinear[17], c16atdopprquadratic[17], c16xtdopprconst[17], c16xtdopprlinear[17], c16xtdopprquadratic[17], c16rcompdes[17], c16zd1strange[17], c16zdcenrange[17], c16zdlstrange[17], c16orien[17], c16platincl[17], c16platascn[17], c16geocenter[17], c16platalt[17], c16plathead[17], c16platgs[17], c16refmajor[17], c16refminor[17], c16ltposerr[17], c16ctposerr[17], c16rposerr[17], c22dummy[23], c22seconds[23], c22interval[23], c22gmha[23], c24zd1stazitime[25], c24zdcenazitime[25], c24zdlstazitime[25], c32sceneref[33], c32scenetime[33], c32sensorid[33], c32typespec[33], c32algid[33], c32projection[33], c32sattime[33], c32weightrange[33], c32weightazi[33], c32refellips[33], c64rcs[65]; // --- Check for RSAT #%// Bert Kampes, 02-Aug-2004 --- uint rec_seq;// type B4 unsigned char rec_sub1, rec_type, rec_sub2, rec_sub3;// type B1 // ======Open files====== ifstream leaderfile; openfstream(leaderfile,readfiles_arg.leaderfile); bk_assert(leaderfile,readfiles_arg.leaderfile,__FILE__,__LINE__); // ======Read leaderfile====== // --- RECORD 1 --- leaderfile.seekg(0,ios::beg);// place pointer at beginning of file leaderfile.read((char*)&rec_seq,sizeb4);// record number rec_seq = ntohl(rec_seq);// Bert Kampes, 07-Apr-2005 leaderfile.read((char*)&rec_sub1,sizeb1);// first record sub type code leaderfile.read((char*)&rec_type,sizeb1);// record type code leaderfile.read((char*)&rec_sub2,sizeb1);// second record sub type code leaderfile.read((char*)&rec_sub3,sizeb1);// third record sub type code DEBUG.print("Expecting record 1 with code {63,192,18,18}"); DEBUG << "rec_seq: " << rec_seq << "; rec_sub1: " << int(rec_sub1) << "; rec_type: " << int(rec_type) << "; rec_sub2: " << int(rec_sub2) << "; rec_sub3: " << int(rec_sub3); DEBUG.print(); // --- Read important data --- leaderfile.seekg(8,ios::beg); // file descriptor record leaderfile.read((char*)&lenrec1,sizeb4); // length of record1 lenrec1 = ntohl(lenrec1); // bk 6 jul 2000, byteorder x86 machines. DEBUG << "readleader::record 1 of leader file: length: " << lenrec1; DEBUG.print(); if (lenrec1 != 720 ) { WARNING.print("probably something wrong here, byte order x86."); WARNING << "readleader: length of record 1 = \"" << lenrec1 << "\"; expected \"720\" for ESA SLC (full scene)."; WARNING.print(); } leaderfile.seekg(48,ios::beg); leaderfile.read((char*)&c16leafilename,sizea16); // file name c16leafilename[16]='\0'; // --- RECORD 2 --- DEBUG.print("readleader::reading record 2 of leader file."); uint startrec2 = lenrec1; leaderfile.seekg(startrec2,ios::beg);// place pointer at beginning of record leaderfile.read((char*)&rec_seq,sizeb4);// record number rec_seq = ntohl(rec_seq);// Bert Kampes, 07-Apr-2005 leaderfile.read((char*)&rec_sub1,sizeb1);// first record sub type code leaderfile.read((char*)&rec_type,sizeb1);// record type code leaderfile.read((char*)&rec_sub2,sizeb1);// second record sub type code leaderfile.read((char*)&rec_sub3,sizeb1);// third record sub type code DEBUG.print("ERS: Expecting record 2 with code {10,10,31,20}"); DEBUG.print("RSAT: Expecting record 2 with code {18,10,18,20}"); DEBUG.print("RSAT record length is 4096, ERS 1886, but"); DEBUG.print("ERS contains more info on zero doppler times, etc."); DEBUG.print("RSAT seems to have that info in the data file."); DEBUG << "rec_seq: " << rec_seq << "; rec_sub1: " << int(rec_sub1) << "; rec_type: " << int(rec_type) << "; rec_sub2: " << int(rec_sub2) << "; rec_sub3: " << int(rec_sub3); DEBUG.print(); // ___ Read important parameters ___ leaderfile.seekg(startrec2+8,ios::beg); // slc data set summary record leaderfile.read((char*)&lenrec2,sizeb4); // length of record2 lenrec2 = ntohl(lenrec2); // bk 6 jul 2000, byteorder x86 machines. DEBUG << "readleader::record 2: start at: " << lenrec1 << "; length: " << lenrec2; DEBUG.print(); //if (readfiles_arg.sensor_id==SLC_RSAT) if (readfiles_arg.sar_processor==SARPR_ATL) { if (lenrec2 != 4096) { WARNING.print("SARPR_ATL (RSAT) has 4096 record length, but other value found?"); } } // start_added_by_don else if (readfiles_arg.sar_processor==SARPR_JAX) { if (lenrec2 != 4096) { WARNING.print("SARPR_JAX (ALOS) has 4096 record length, but other value found?"); } } // end_added_by_don else { if (lenrec2 != 1886) { WARNING.print("SARPR_ATL (RSAT) has 4096 record length"); WARNING.print("probably something wrong here, byte order on x86?"); WARNING << "readleader: length of record 2 = \"" << lenrec2 << "\"; expected \"1886\" for ESA SLC (full scene). continuing"; WARNING.print(); } } // ______Scene parameters______ // Modified by LG for reading ALOS Fine if (readfiles_arg.sensor_id == SLC_ALOS) { leaderfile.seekg(startrec2+20,ios::beg); leaderfile.read((char*)&c32sceneref,sizea32); leaderfile.seekg(startrec2+20+sizea32+1,ios::beg); } else { leaderfile.seekg(startrec2+36,ios::beg); leaderfile.read((char*)&c32sceneref,sizea32); // scene ref. number } c32sceneref[32]='\0'; leaderfile.read((char*)&c32scenetime,sizea32); // scene center time c32scenetime[32]='\0'; leaderfile.seekg(startrec2+116,ios::beg); leaderfile.read((char*)&c16centerlat,sizef16); // centre latitude c16centerlat[16]='\0'; leaderfile.read((char*)&c16centerlon,sizef16); // centre longitude c16centerlon[16]='\0'; leaderfile.read((char*)&c16centerheading,sizef16); // center true heading c16centerheading[16]='\0'; leaderfile.read((char*)&c16ellipsoid,sizea16); // ell. designated c16ellipsoid[16]='\0'; leaderfile.read((char*)&c16semimajor,sizef16); // ell. semi major c16semimajor[16]='\0'; leaderfile.read((char*)&c16semiminor,sizef16); // ell. semi minor c16semiminor[16]='\0'; leaderfile.read((char*)&c16GM,sizef16); // GM c16GM[16]='\0'; leaderfile.read((char*)&c16dummy,sizef16); // dummy leaderfile.read((char*)&c16J2,sizef16); // J2 c16J2[16]='\0'; leaderfile.read((char*)&c16J3,sizef16); // J3 c16J3[16]='\0'; leaderfile.read((char*)&c16J4,sizef16); // J4 c16J4[16]='\0'; leaderfile.read((char*)&c16dummy,sizef16); // dummy leaderfile.read((char*)&c16dummy,sizef16); // dummy leaderfile.read((char*)&c8dummy,sizei8); // center line# c8dummy[8]='\0'; uint scenecenterline = atoi(c8dummy); leaderfile.read((char*)&c8dummy,sizei8); // center pixel# c8dummy[8]='\0'; uint scenecenterpixel = atoi(c8dummy); leaderfile.read((char*)&c16scenelength,sizef16); // scene length c16scenelength[16]='\0'; leaderfile.read((char*)&c16scenewidth,sizef16); // scene width c16scenewidth[16]='\0'; // ______General mission / sensor parameters______ leaderfile.seekg(startrec2+396,ios::beg); leaderfile.read((char*)&c16platformid,sizea16); // platform mission id c16platformid[16]='\0'; leaderfile.read((char*)&c32sensorid,sizea32); // sensor id c32sensorid[32]='\0'; leaderfile.read((char*)&c8orbitnr,sizea8); // orbit number c8orbitnr[8]='\0'; leaderfile.read((char*)&c8platformlat,sizea8); // platform latitude c8platformlat[8]='\0'; leaderfile.read((char*)&c8platformlon,sizea8); // platform longitude c8platformlon[8]='\0'; leaderfile.read((char*)&c8platformheading,sizea8); // platform heading c8platformheading[8]='\0'; leaderfile.read((char*)&c8clockangle,sizea8); // sensor clock angle c8clockangle[8]='\0'; leaderfile.read((char*)&c8incidence,sizea8); // incidence angle c8incidence[8]='\0'; leaderfile.read((char*)&c8freq,sizea8); // radar frequency c8freq[8]='\0'; leaderfile.read((char*)&c16wavelength,sizea16); // radar wavelength c16wavelength[16]='\0'; leaderfile.read((char*)&c2motioncomp,sizea2); // indicator for compensation c2motioncomp[2]='\0'; leaderfile.read((char*)&c16pulse,sizea16); // range pulse code specifier c16pulse[16]='\0'; leaderfile.read((char*)&c16ampconst,sizef16); // amplitude constant term c16ampconst[16]='\0'; leaderfile.read((char*)&c16amplinear,sizef16); // amplitude linear term c16amplinear[16]='\0'; leaderfile.read((char*)&c16ampquadratic,sizef16); // amplitude quadrati term c16ampquadratic[16]='\0'; leaderfile.read((char*)&c16ampcubic,sizef16); // amplitude cubic term c16ampcubic[16]='\0'; leaderfile.read((char*)&c16ampquartic,sizef16); // amplitude quartic term c16ampquartic[16]='\0'; leaderfile.read((char*)&c16phaseconst,sizef16); // phase constant term c16phaseconst[16]='\0'; leaderfile.read((char*)&c16phaselinear,sizef16); // phase linear term c16phaselinear[16]='\0'; leaderfile.read((char*)&c16phasequadratic,sizef16); // phase quadratic term c16phasequadratic[16]='\0'; leaderfile.read((char*)&c16phasecubic,sizef16); // phase cubicterm c16phasecubic[16]='\0'; leaderfile.read((char*)&c16phasequartic,sizef16); // phase quartic term c16phasequartic[16]='\0'; leaderfile.read((char*)&c8extindex,sizei8); // chirp extraction c8extindex[8]='\0'; leaderfile.read((char*)&c8dummy,sizei8); // spare leaderfile.read((char*)&c16samplingrate,sizef16); // range sampling rate c16samplingrate[16]='\0'; leaderfile.read((char*)&c16rangedelay,sizef16); // delay c16rangedelay[16]='\0'; leaderfile.read((char*)&c16ranpulselen,sizef16); // range pulselength c16ranpulselen[16]='\0'; leaderfile.read((char*)&c4conversion,sizea4); // flag c4conversion[4]='\0'; leaderfile.read((char*)&c4compression,sizea4); // flag c4compression[4]='\0'; leaderfile.read((char*)&c16dummy,sizef16); // reserved leaderfile.read((char*)&c16dummy,sizef16); // reserved leaderfile.read((char*)&c8qperch,sizei8); // quantization c8qperch[8]='\0'; leaderfile.read((char*)&c12qdesc,sizea12); // quantization description c12qdesc[12]='\0'; leaderfile.read((char*)&c16dci,sizef16); // bias for i comp. c16dci[16]='\0'; leaderfile.read((char*)&c16dcq,sizef16); // bias for q comp. c16dcq[16]='\0'; leaderfile.read((char*)&c16imbalance,sizef16); // gain imbalance i&q c16imbalance[16]='\0'; leaderfile.read((char*)&c16dummy,sizef16); // spare leaderfile.read((char*)&c16dummy,sizef16); // spare leaderfile.read((char*)&c16dummy,sizef16); // reserved leaderfile.read((char*)&c16boresight,sizef16); // antenna c16boresight[16]='\0'; leaderfile.read((char*)&c4dummy,sizea4); // reserved leaderfile.read((char*)&c16prf,sizef16); // pulse repetition frequency c16prf[16]='\0'; // ______Sensor specific parameters______ leaderfile.seekg(startrec2+982,ios::beg); leaderfile.read((char*)&c16sattimecode,sizei16); // sat time code c16sattimecode[16]='\0'; leaderfile.read((char*)&c32sattime,sizea32); // sat time c32sattime[32]='\0'; leaderfile.read((char*)&c8satclockstep,sizei8); // sat clock step length c8satclockstep[8]='\0'; // ______General processing parameters______ leaderfile.seekg(startrec2+1046,ios::beg); leaderfile.read((char*)&c16facilityid,sizea16); // proc. facility id c16facilityid[16]='\0'; leaderfile.read((char*)&c8systemid,sizea8); // proc. system id c8systemid[8]='\0'; leaderfile.read((char*)&c8versionid,sizea8); // proc. version id c8versionid[8]='\0'; leaderfile.read((char*)&c16dummy,sizef16); // dummy leaderfile.read((char*)&c16dummy,sizef16); // dummy leaderfile.read((char*)&c32typespec,sizea32); // produkt type spec. c32typespec[32]='\0'; leaderfile.read((char*)&c32algid,sizea32); // proc. alg. id c32algid[32]='\0'; leaderfile.read((char*)&c16looksazi,sizef16); // number of looks c16looksazi[16]='\0'; leaderfile.read((char*)&c16looksrange,sizef16); // number of looks c16looksrange[16]='\0'; leaderfile.read((char*)&c16bandazi,sizef16); // bandwidth c16bandazi[16]='\0'; leaderfile.read((char*)&c16bandrange,sizef16); // bandwidth c16bandrange[16]='\0'; leaderfile.read((char*)&c16bandazitot,sizef16); // bandwidth c16bandazitot[16]='\0'; leaderfile.read((char*)&c16bandrangetot,sizef16); // bandwidth c16bandrangetot[16]='\0'; leaderfile.read((char*)&c32weightazi,sizea32); // weighting function c32weightazi[32]='\0'; leaderfile.read((char*)&c32weightrange,sizea32); // weighting function c32weightrange[32]='\0'; leaderfile.read((char*)&c16inputsource,sizea16); // data input c16inputsource[16]='\0'; leaderfile.read((char*)&c16resrange,sizef16); // resolution c16resrange[16]='\0'; leaderfile.read((char*)&c16resazi,sizef16); // resolution c16resazi[16]='\0'; leaderfile.read((char*)&c16dummy,sizef16); // reserved leaderfile.read((char*)&c16dummy,sizef16); // reserved leaderfile.read((char*)&c16atdoppcconst,sizef16); // along track centroid c16atdoppcconst[16]='\0'; leaderfile.read((char*)&c16atdoppclinear,sizef16); // along track centroid c16atdoppclinear[16]='\0'; leaderfile.read((char*)&c16atdoppcquadratic,sizef16); // along track centroid c16atdoppcquadratic[16]='\0'; leaderfile.read((char*)&c16dummy,sizef16); // spare leaderfile.read((char*)&c16xtdoppcconst,sizef16); // cross track centroid c16xtdoppcconst[16]='\0'; leaderfile.read((char*)&c16xtdoppclinear,sizef16); // cross track centroid c16xtdoppclinear[16]='\0'; leaderfile.read((char*)&c16xtdoppcquadratic,sizef16); // cross track centroid c16xtdoppcquadratic[16]='\0'; leaderfile.read((char*)&c8timepix,sizea8); // time direction c8timepix[8]='\0'; leaderfile.read((char*)&c8timeline,sizea8); // time direction c8timeline[8]='\0'; leaderfile.read((char*)&c16atdopprconst,sizef16); // along track rate c16atdopprconst[16]='\0'; leaderfile.read((char*)&c16atdopprlinear,sizef16); // along track rate c16atdopprlinear[16]='\0'; leaderfile.read((char*)&c16atdopprquadratic,sizef16); // along track rate c16atdopprquadratic[16]='\0'; leaderfile.read((char*)&c16dummy,sizef16); // spare leaderfile.read((char*)&c16xtdopprconst,sizef16); // cross track rate c16xtdopprconst[16]='\0'; leaderfile.read((char*)&c16xtdopprlinear,sizef16); // cross track rate c16xtdopprlinear[16]='\0'; leaderfile.read((char*)&c16xtdopprquadratic,sizef16); // cross track rate c16xtdopprquadratic[16]='\0'; leaderfile.read((char*)&c16dummy,sizef16); // spare leaderfile.read((char*)&c8linecontent,sizea8); // indicator c8linecontent[8]='\0'; leaderfile.read((char*)&c4clutterlock,sizea4); // flag c4clutterlock[4]='\0'; leaderfile.read((char*)&c4autofocus,sizea4); // flag c4autofocus[4]='\0'; leaderfile.read((char*)&c16linespace,sizef16); // c16linespace[16]='\0'; leaderfile.read((char*)&c16pixspace,sizef16); // c16pixspace[16]='\0'; leaderfile.read((char*)&c16rcompdes,sizea16); // range compression designator c16rcompdes[16]='\0'; // --- RSAT does not fill this spare part of the record (blanks) --- DEBUG.print("Assuming user has specified method RSAT if it is RSAT."); DEBUG.print("although we could also easily detect it before"); bool skipmapprojrecord = false; // some problem s with old IPAF? uint numdatapoints=99999; char c16incangle1strange[17], //bc c16incanglecenrange[17], //bc c16incanglelstrange[17], //bc calK[17], //gk repplspwr[17]; //gk char c4numvalid[5]; //bk char c4numinvalid[5]; //bk strcpy(c16incangle1strange, "skipped"); strcpy(c16incanglecenrange, "skipped"); strcpy(c16incanglelstrange, "skipped"); strcpy(calK, "skipped"); strcpy(repplspwr, "skipped"); strcpy(c4numvalid, "999"); strcpy(c4numinvalid, "999"); matrix STATE;// has to be declared at large scope, used later. matrix STATE_INERTIAL;// has to be declared at large scope, used later. //if (readfiles_arg.sar_processor!=SARPR_ATL) // seems ERS data are same, also with Atlantis, so only check for RSAT here. if (readfiles_arg.sensor_id!=SLC_RSAT) { DEBUG.print("Reading rest of this record, which for RSAT is empty."); // ______Sensor specific local use segment______ leaderfile.seekg(startrec2+1766,ios::beg); leaderfile.read((char*)&c16zd1strange,sizef16); // zero doppler 1st pixel c16zd1strange[16]='\0'; leaderfile.read((char*)&c16zdcenrange,sizef16); // zero doppler centre pixel c16zdcenrange[16]='\0'; leaderfile.read((char*)&c16zdlstrange,sizef16); // zero doppler last pixel 2way c16zdlstrange[16]='\0'; leaderfile.read((char*)&c24zd1stazitime,sizea24); // zero doppler 1st pixel c24zd1stazitime[24]='\0'; leaderfile.read((char*)&c24zdcenazitime,sizea24); // zero doppler 1st pixel c24zdcenazitime[24]='\0'; leaderfile.read((char*)&c24zdlstazitime,sizea24); // zero doppler 1st pixel c24zdlstazitime[24]='\0'; // --- RECORD 3 --- DEBUG.print("record 3 of leader file (ERS)."); uint startrec3 = lenrec1 + lenrec2; leaderfile.seekg(startrec3,ios::beg);// map projection data record leaderfile.read((char*)&rec_seq,sizeb4);// record number rec_seq = ntohl(rec_seq);// Bert Kampes, 07-Apr-2005 leaderfile.read((char*)&rec_sub1,sizeb1);// first record sub type code leaderfile.read((char*)&rec_type,sizeb1);// record type code leaderfile.read((char*)&rec_sub2,sizeb1);// second record sub type code leaderfile.read((char*)&rec_sub3,sizeb1);// third record sub type code DEBUG.print("ERS: Expecting record 3 with code {10,20,31,20}"); DEBUG.print("RSAT: Expecting record 3 with code {18,60,18,20}"); DEBUG.print("RSAT record length is 4096, ERS 1886, but"); DEBUG.print("ERS contains more info on zero doppler times, etc."); DEBUG.print("RSAT seems to have that in data file"); DEBUG << "rec_seq: " << rec_seq << "; rec_sub1: " << int(rec_sub1) << "; rec_type: " << int(rec_type) << "; rec_sub2: " << int(rec_sub2) << "; rec_sub3: " << int(rec_sub3); DEBUG.print(); // ___ Read important information ___ leaderfile.seekg(startrec3+8,ios::beg); // map projection data record leaderfile.read((char*)&lenrec3,sizeb4); // length of record3 lenrec3 = ntohl(lenrec3); // bk 6 jul 2000, byteorder x86 machines. DEBUG << "readleader::record 3: start at: " << startrec3 << "; length: " << lenrec3; DEBUG.print(); //if (lenrec3 != 1620 ) // quarter scene 1046 (?) if (lenrec3 < 1620 ) // quarter scene 1046 (?) { WARNING.print("Probably something wrong here, byte order on x86?"); WARNING.print("you may also be trying to read leader of ESA.RAW not ESA.SLC."); WARNING.print("format (or quarter scene)."); WARNING.print("We try to do something useful still, but be careful."); WARNING.print("Skipping map projection record, not in ESA.RAW leaderfile format."); WARNING << "readleader: length of record 3 = \"" << lenrec3 << "\"; expected \"1620\" for ESA SLC (full scene)."; WARNING.print(); lenrec3 = 0; skipmapprojrecord = true; } // --- Trying to read anyway if it is longer --- if (lenrec3 > 1620 ) // atlantis? rec2 is 4096 not 1886 (?) { //skipmapprojrecord = true;// no: want to read it sometimes... WARNING.print("record length longer than expected. Atlantis?. reading map."); WARNING.print("seems not ok. assuming mapprojection record not present"); WARNING.print("trying to read further with next record"); startrec3 = lenrec1+lenrec2+lenrec3;// try to continue with rec4??? rec3 seems platform data lenrec3 = 0;// so next time this record is read, but with platform data format... } // skip map projection record if not present ... // BK 18-Jul-2000 if (skipmapprojrecord) // not present, do not read. { WARNING.print("Skipping map projection record. Not found."); WARNING.print("Continuing with platform position data."); } else // ESA.SLC format, do read map proj. record. { // ______ Map projection general information ______ leaderfile.seekg(startrec3+28,ios::beg); leaderfile.read((char*)&c32projection,sizea32); // map proj. descr. c32projection[32]='\0'; leaderfile.read((char*)&c16numpix,sizei16); // numpixels c16numpix[16]='\0'; leaderfile.read((char*)&c16numlin,sizei16); // numlines c16numlin[16]='\0'; // ______ Continue ______ leaderfile.read((char*)&c16interpix,sizef16); // dist inter-pixel c16interpix[16]='\0'; leaderfile.read((char*)&c16interlin,sizef16); // dist inter-lines c16interlin[16]='\0'; leaderfile.read((char*)&c16orien,sizef16); // orientation at output c16orien[16]='\0'; leaderfile.read((char*)&c16platincl,sizef16); // actual platform inclination c16platincl[16]='\0'; leaderfile.read((char*)&c16platascn,sizef16); // actual ascending node c16platascn[16]='\0'; leaderfile.read((char*)&c16geocenter,sizef16); // c16geocenter[16]='\0'; leaderfile.read((char*)&c16platalt,sizef16); // altitude c16platalt[16]='\0'; leaderfile.read((char*)&c16platgs,sizef16); // ground speed c16platgs[16]='\0'; leaderfile.read((char*)&c16plathead,sizef16); // heading c16plathead[16]='\0'; leaderfile.read((char*)&c32refellips,sizea32); // ellipsoid c32refellips[32]='\0'; leaderfile.read((char*)&c16refmajor,sizef16); // semi major c16refmajor[16]='\0'; leaderfile.read((char*)&c16refminor,sizef16); // semi minor c16refminor[16]='\0'; // ______ Coordinates of four corner points ______ leaderfile.seekg(startrec3+1072,ios::beg); leaderfile.read((char*)&c16lat11,sizef16); // lat. 1st line 1st pix. c16lat11[16]='\0'; leaderfile.read((char*)&c16lon11,sizef16); // lon. 1st line 1st pix. c16lon11[16]='\0'; leaderfile.read((char*)&c16lat1N,sizef16); // lat. 1st line last pix. c16lat1N[16]='\0'; leaderfile.read((char*)&c16lon1N,sizef16); // lon. 1st line last pix. c16lon1N[16]='\0'; leaderfile.read((char*)&c16latNN,sizef16); // lat. last line last pix. c16latNN[16]='\0'; leaderfile.read((char*)&c16lonNN,sizef16); // lon. last line last pix. c16lonNN[16]='\0'; leaderfile.read((char*)&c16latN1,sizef16); // lat. last line 1st pix. c16latN1[16]='\0'; leaderfile.read((char*)&c16lonN1,sizef16); // lon. last line 1st pix. c16lonN1[16]='\0'; } // end skip map proj. // --- RECORD 4 --- DEBUG.print("record 4 of leader file."); uint startrec4=lenrec1+lenrec2+lenrec3; leaderfile.seekg(startrec4+8,ios::beg); // slc platform position data record leaderfile.read((char*)&lenrec4,sizeb4); // length of record4 lenrec4 = ntohl(lenrec4); // bk 6 jul 2000, byteorder x86 machines. DEBUG << "readleader::record 4: start at: " << startrec4 << "; length (variable): " << lenrec4; DEBUG.print(); // ______ Positional data points ______ leaderfile.seekg(startrec4+140,ios::beg); leaderfile.read((char*)&c4dummy,sizei4); // number of data points c4dummy[4]='\0'; numdatapoints = atoi(c4dummy); leaderfile.read((char*)&c4year,sizei4); // year c4year[4]='\0'; leaderfile.read((char*)&c4month,sizei4); // month c4month[4]='\0'; leaderfile.read((char*)&c4day,sizei4); // day c4day[4]='\0'; leaderfile.read((char*)&c4dayofyear,sizei4); // day of year c4dayofyear[4]='\0'; leaderfile.read((char*)&c22seconds,sized22); // sec c22seconds[22]='\0'; leaderfile.read((char*)&c22interval,sized22); // interval time c22interval[22]='\0'; leaderfile.read((char*)&c64rcs,sizea64); // ref. coord. system c64rcs[64]='\0'; leaderfile.read((char*)&c22gmha,sized22); // greenwich mean hour angle c22gmha[22]='\0'; leaderfile.read((char*)&c16ltposerr,sizef16); // along track pos. error c16ltposerr[16]='\0'; leaderfile.read((char*)&c16ctposerr,sizef16); // across track pos. error c16ctposerr[16]='\0'; leaderfile.read((char*)&c16rposerr,sizef16); // radial pos. error c16rposerr[16]='\0'; // ______ Read statevector of data points ______ if (numdatapoints==0) // test, sometimes on linux problems { WARNING.print("numdatapoints=0: probalbly something wrong with filepointer"); WARNING.print("But continuing, be very careful!"); numdatapoints=1; // arbitrary... STATE.resize(6,numdatapoints); // storage statevector } else { STATE.resize(6,numdatapoints); // storage statevector for (register int32 i=0;i10000000.0 && rsrcomputed<30000000.0) if (rsrcomputed>10000.0) { WARNING.print("Adapting RSR from Hz to MHz."); WARNING << "Old value rsrcomputed: " << rsrcomputed << "; new value rsrcomputed: " << rsrcomputed/1e6; WARNING.print(); rsrcomputed/=1e6; } real8 rangebandwidth = atof(c16bandrangetot); // start_added_by_don if (readfiles_arg.sensor_id==SLC_ALOS) rangebandwidth /= 1e3; // end_added_by_don if (rangebandwidth < 1.0)// e.g. JERS not annotated. { WARNING.print("computed rangebandwidth < 1.0 ignoring this."); rangebandwidth = rsrcomputed;// set this to no oversampling } //if (rangebandwidth>10000000.0 && rangebandwidth<30000000.0) if (rangebandwidth>10000.0) { WARNING.print("Adapting RBW from Hz to MHz."); WARNING << "Old value rangebandwidth: " << rangebandwidth << "; new value rangebandwidth: " << rangebandwidth/1e6; WARNING.print(); rangebandwidth/=1e6; } // ====== Write information to scratchfiles ====== ofstream scratchlogfile("scratchloglea", ios::out | ios::trunc); bk_assert(scratchlogfile,"readleader: scratchloglea",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* EXTRACTED DATA FROM LEADER FILE: " << readfiles_arg.leaderfile << " *" << "\n*******************************************************************" << "\n\nFile descriptor record" << "\n----------------------" << "\nFile name: " << c16leafilename << "\n\nSLC data set summary record: scene parameters" << "\n---------------------------------------------" << "\nScene reference number: \t\t\t\t" // (e.g. orbit-frame number): " << c32sceneref << "\nScene centre time (UTC) : \t\t" << c32scenetime << "\nProcessed scene centre geodetic latitude" << "\n +(positive for North latitude) (degrees): \t\t" << c16centerlat << "\nProcessed scene centre longitude" << "\n +(negative for West longitude) (degrees): \t\t" << c16centerlon << "\nProcessed scene centre true heading (degrees): \t\t" << c16centerheading << "\nEllipsoid designator: \t\t\t\t\t" << c16ellipsoid << "\nEllipsoid semimajor axis (km): \t\t\t\t" << c16semimajor << "\nEllipsoid semiminor axis (km): \t\t\t\t" << c16semiminor << "\nEarth mass times grav. const. (M.G) (kg.m/s^2): \t" << c16GM << "\nEllipsoid J2 parameter: \t\t\t\t" << c16J2 << "\nEllipsoid J3 parameter: \t\t\t\t" << c16J3 << "\nEllipsoid J4 parameter: \t\t\t\t" << c16J4 << "\nScene center line number (the line number at " << "\n +the scene centre including zero fill): \t\t" << scenecenterline << "\nScene center pixel number (the pixel number at" << "\n +the scene centre including zero fill): \t\t" << scenecenterpixel << "\nProcessed scene length incl. zero fill (km): \t\t" << c16scenelength << "\nProcessed scene width incl. zero fill (km): \t\t" << c16scenewidth << "\n\nSLC data set summary record: general mission/sensor parameters" << "\n--------------------------------------------------------------" << "\nSensor platform mission identifier: \t\t\t" << c16platformid << "\nSensor ID, mode of op. for this channel: \t\t" << c32sensorid << "\nOrbit number: \t\t\t\t\t\t\t" << c8orbitnr << "\nSensor platform geodetic latitude at nadir" << "\n +corresponding to scene centre" << "\n +(positive for North latitude) (degrees): \t\t\t" << c8platformlat << "\nSensor platform geodetic longitude at nadir" << "\n +corresponding to scene centre" << "\n +(negative for West longitude) (degrees): \t\t\t" << c8platformlon << "\nSensor platform heading at nadir" << "\n +corresponding to scene centre" << "\n +(clockwise positive from North) (degrees): \t\t\t" << c8platformheading << "\nSensor clock angle as measured relative to" << "\n +sensor platform flight direction (degrees): \t" << c8clockangle << "\nIncidence angle at scene centre as derived" << "\n +from sensor platform orientation (degrees): \t" << c8incidence << "\nRadar frequency (GHz): \t\t\t\t\t\t" << c8freq << "\nRadar wavelength (meters): \t\t\t" << c16wavelength << "\nMotion compensator identifier" << "\n +(00=no, 01=on board, 10=in processor, 11=both): \t" << c2motioncomp << "\nRange pulse specifier: \t\t\t\t\t" << c16pulse << "\nNominal range pulse (chirp) amplitude coefficient," << "\n +constant term: \t\t\t\t\t" << c16ampconst << "\n +linear term (sec-1): \t\t\t\t\t" << c16amplinear << "\n +quadratic term (sec-2): \t\t\t\t" << c16ampquadratic << "\n +cubic term (sec-3): \t\t\t\t\t" << c16ampcubic << "\n +quartic term (sec-4): \t\t\t\t" << c16ampquartic << "\nNominal range pulse (chirp) phase coefficient," << "\n +constant term (cycles): \t\t\t\t" << c16phaseconst << "\n +linear term (Hz): \t\t\t\t\t" << c16phaselinear << "\n +quadratic term (Hz/sec): \t\t\t\t" << c16phasequadratic << "\n +cubic term (Hz/sec2): \t\t\t\t" << c16phasecubic << "\n +quartic term (Hz/sec3): \t\t\t\t" << c16phasequartic << "\nDown linked chirp extraction index (samples): \t\t\t" << c8extindex << "\nRange sampling rate (MHz): \t\t\t\t" << c16samplingrate << "\nRange gate delay at early ege (in time)" << "\n +at the start of the image (microsec): \t" << c16rangedelay << "\nRange pulse length (microsec): \t\t\t\t" << c16ranpulselen << "\nBase band conversion flag: \t\t\t" << c4conversion << "\nRange compressed flag (YES=range compressed data): \t" << c4compression << "\nQuantization per channel I & Q" << "\n +(5I 5Q/6I 6Q for OGRB/OBRC) (bits): \t\t\t\t" << c8qperch << "\nQuantizer descriptor: \t\t\t\t\t" << c12qdesc << "\nDC Bias for I-component (actual value): \t\t" << c16dci << "\nDC Bias for Q-component (actual value): \t\t" << c16dcq << "\nGain imbalance for I & Q (actual value): \t\t" << c16imbalance << "\nAntenna mechanical boresight angle" << "\n +relative to platform vertical axis: \t\t\t" << c16boresight << "\nPulse Repetition Frequency (PRF) (actual value): \t" << c16prf << "\n\nSLC data set summary record: sensor specific parameters" << "\n-------------------------------------------------------" << "\nSatellite encoded binary time code: \t\t\t" << c16sattimecode << "\nSatellite clock time (UTC) (YYYYMMDDhhmmssttt): \t" << c32sattime << "\nSatellite clock step length (nanosec): \t\t\t\t" << c8satclockstep << "\n\nSLC data set summary record: general processing parameters" << "\n----------------------------------------------------------" << "\nProcessing facility identifier: \t\t\t" << c16facilityid << "\nProcessing system identifier: \t\t\t\t" << c8systemid << "\nProcessing version identifier: \t\t\t\t" << c8versionid << "\nProduct type specifier: \t\t\t\t" << c32typespec << "\nProcessing algorithm identifier: \t\t\t" << c32algid << "\nNominal number of looks processed in azimuth (looks): \t" << c16looksazi << "\nNominal number of looks processed in range (looks): \t" << c16looksrange << "\nBandwidth per look in azimuth (null-to-null) (Hz): \t" << c16bandazi << "\nBandwidth per look in range (MHz): \t\t\t" << c16bandrange << "\nTotal processor bandwidth in azimuth (Hz): \t\t" << c16bandazitot << "\nTotal processor bandwidth in range (MHz): \t\t" << c16bandrangetot << "\nWeighting function designator in azimuth: \t\t" << c32weightazi << "\nWeighting function designator in range: \t\t" << c32weightrange << "\nData input source: \t\t\t\t\t" << c16inputsource << "\nNominal resolution in range (3-dB width) (m): \t\t" << c16resrange << "\nNominal resolution in azimuth (3-dB width) (m): \t" << c16resazi << "\nAlong track Doppler frequency centroid" << "\n +at early edge of image" << "\n +constant term (Hz): \t\t\t\t\t" << c16atdoppcconst << "\n +linear term (Hz/sec): \t\t\t\t" << c16atdoppclinear << "\n +quadratic term (Hz/sec/sec): \t\t\t\t" << c16atdoppcquadratic << "\nCross track Doppler frequency centroid" << "\n +at early edge of image" << "\n +constant term (Doppler centroid) (Hz): \t\t" << c16xtdoppcconst << "\n +linear term (Slope of Doppler centroid) (Hz/sec): \t" << c16xtdoppclinear << "\n +quadratic term (Hz/sec/sec): \t\t\t\t" << c16xtdoppcquadratic << "\nTime direction indicator along pixel direction: \t" << c8timepix << "\nTime direction indicator along line direction: \t\t" << c8timeline << "\nAlong track Doppler frequency rate" << "\n +at early edge of image" << "\n +constant term (Hz/sec): \t\t\t\t" << c16atdopprconst << "\n +linear term (Hz/sec/sec): \t\t\t\t" << c16atdopprlinear << "\n +quadratic term (Hz/sec/sec/sec): \t\t\t" << c16atdopprquadratic << "\nCross track Doppler frequency rate" << "\n +at early edge of image" << "\n +constant term (Azimuth FM rate) (Hz/sec): \t\t" << c16xtdopprconst << "\n +linear term (Slope of Azimuth FM rate) (Hz/sec/sec): \t" << c16xtdopprlinear << "\n +quadratic term (Hz/sec/sec/sec): \t\t\t" << c16xtdopprquadratic << "\nLine content indicator: \t\t\t\t" << c8linecontent << "\nClutterlock applied flag: \t\t\t\t" << c4clutterlock << "\nAutofocussing applied flag: \t\t\t\t" << c4autofocus << "\nLine spacing (m): \t\t\t\t\t" << c16linespace << "\nPixel spacing (in range) (m): \t\t\t\t" << c16pixspace << "\nProcessor range compression designator: \t\t" << c16rcompdes << "\n\nSLC data set summary record: sensor specific local use segment" << "\n--------------------------------------------------------------" << "\nZero-doppler range time (two-way)" << "\n +of first range pixel (millisec): \t\t\t" << c16zd1strange << "\n +of centre range pixel (millisec): \t\t\t" << c16zdcenrange << "\n +of last range pixel (millisec): \t\t\t" << c16zdlstrange << "\nZero-doppler azimuth time" << "\n +of first azimuth pixel (UTC): \t\t" << c24zd1stazitime << "\n +of centre azimuth pixel (UTC): \t\t" << c24zdcenazitime << "\n +of last azimuth pixel (UTC): \t\t\t" << c24zdlstazitime << "\n\nMap projection data record: general information" << "\n-----------------------------------------------" << "\nMap projection descriptor: \t\t\t\t" << c32projection << "\nNumber of pixels per line of image: \t\t\t" << c16numpix << "\nNumber of lines: \t\t\t\t\t" << c16numlin << "\nNominal inter-pixel distance in output scene (m): \t" << c16interpix << "\nNominal inter-line distance in output scene (m): \t" << c16interlin << "\nOrientation at output scene centre" << "\n +[for geodetic products this is simply the" << "\n +convergence of the meridians, ie: the angle" << "\n +between geographic north and map grid north" << "\n +(angle of projection axis from true North)] (degrees): " << c16orien << "\nActual platform orbital inclination (degrees): \t\t" << c16platincl << "\nActual ascending node (longitude at equator) (degrees): " << c16platascn << "\nGeocentre to platform distance at input scene centre: \t" << c16geocenter << "\nPlatform geodetic altitude over the ellipsoid: \t\t" << c16platalt << "\nGround speed at nadir at input scene centre time: \t" << c16platgs << "\nPlatform heading at nadir" << "\n +corresponding to scene centre (degrees): \t\t" << c16plathead << "\nName of reference ellipsoid: \t\t\t\t" << c32refellips << "\nSemimajor axis of ref.ellipsoid (km): \t\t\t" << c16refmajor << "\nSemiminor axis of ref.ellipsoid (km): \t\t\t" << c16refminor << "\n\nMap projection data record: coordinates of four corner points" << "\n-------------------------------------------------------------" << "\n1st line 1st pixel geodetic latitude" << "\n +(positive for North latitude) (degrees): \t\t" << c16lat11 << "\n1st line 1st pixel geodetic longitude" << "\n +(negative for West longitude) (degrees): \t\t" << c16lon11 << "\n1st line last pixel geodetic latitude (degrees): \t" << c16lat1N << "\n1st line last pixel geodetic longitude (degrees): \t" << c16lon1N << "\nlast line last pixel geodetic latitude (degrees): \t" << c16latNN << "\nlast line last pixel geodetic longitude (degrees): \t" << c16lonNN << "\nlast line 1st pixel geodetic latitude (degrees): \t" << c16latN1 << "\nlast line 1st pixel geodetic longitude (degrees): \t" << c16lonN1 << "\n\nSLC platform position data record: positional data points" << "\n---------------------------------------------------------" << "\nNumber of data points: \t\t\t\t" << numdatapoints << "\nYear of data point : \t\t\t" << c4year << "\nMonth of data point <$$MM>: \t\t\t" << c4month << "\nDay of data point <$$DD>: \t\t\t" << c4day << "\nDay in the year (jan 1st=day 1): \t\t" << c4dayofyear << "\nSeconds of day of data: \t\t\t" << c22seconds << "\nTime interval between data points: \t\t" << c22interval << "\nReference coordinate system: \t\t\t" << c64rcs << "\nGreenwich mean hour angle (degrees): \t\t" << c22gmha << "\nAlong track position error (meters): \t\t" << c16ltposerr << "\nAcross track position error (meters): \t\t" << c16ctposerr << "\nRadial position error (meters): \t\t" << c16rposerr << "\n\nSLC facility related data record [general type]: calibration information" << "\n------------------------------------------------------------------------" << "\nIncidence angle at first range pixel (at mid-azimuth): \t" << c16incangle1strange //bc << "\nIncidence angle at centre range pixel (at mid-azimuth): " << c16incanglecenrange //bc << "\nIncidence angle at last range pixel (at mid-azimuth): \t" << c16incanglelstrange //bc << "\nAbsolute calibration constant K: \t" << calK //gk << "\nLenrec6: \t" << lenrec6 //gk << "\nReplica Pulse Power: \t" << repplspwr//gk << "\nNumber of valid samples: \t\t\t" << c4numvalid << "\nNumber of invalid samples: \t\t\t" << c4numinvalid << endl; int32 point; // --- STATE VECTORS in INERTIAL SYSTEM --- // only convert these if RSAT and ATLANTIS? //if (readfiles_arg.sensor_id==SLC_RSAT) if (readfiles_arg.sensor_id==SLC_RSAT && readfiles_arg.sar_processor==SARPR_ATL) { scratchlogfile << "\nRSAT: INERTIAL system orbital data as in leaderfile"; for (register int32 k=0;k 11 since we have iiiii.dddddd decimal digits for day of seconds << atof(c22seconds)+real4(l)*atof(c22interval); for (register int32 m=0;m<3;m++) // no velocities { scratchresfile << " \t" << setprecision(13) << STATE(m,l); } scratchresfile << endl; } scratchresfile << "\n*******************************************************************" << "\n* End_leader_datapoints:_NORMAL" // fixed string... << "\n*******************************************************************\n"; scratchresfile.close(); // ______ Check with volumefile (but first write what is read) ______ if (atoi(c16numlin) != checklines) { WARNING << "Number of lines of leader file seems " << "not to be consistent with volume file: " << c16numlin << " != " << checklines; WARNING.print(); WARNING.print("This may be caused by wrong? format SLC of this PAF, check parameterpool."); } if (100*((atof(c16prf)-prfcomputed)/prfcomputed) > 2.) WARNING.print("deviation PRF computed from PRF read in leaderfile > 2%"); if (100*((atof(c16samplingrate)-rsrcomputed)/rsrcomputed) > 2.) WARNING.print("deviation range sampling rate computed from RSR read in leaderfile > 2%"); // ______ Write some info ______ INFO << "Number of lines, pixels: " << c16numlin << " " << c16numpix; INFO.print(); INFO << "Pulse repetition frequency (Hz): " << c16prf << ends; INFO.print(); INFO << "Pulse repetition frequency (computed): " << setprecision(16) << prfcomputed; INFO.print(); INFO << "Range sampling rate (Mhz): " << c16samplingrate << ends; INFO.print(); INFO << "Range sampling rate (computed Mhz): " << setprecision(16) << rsrcomputed; INFO.print(); INFO << "UTC of first azimuth line: " << c24zd1stazitime; INFO.print(); INFO << "UTC of last azimuth line: " << c24zdlstazitime; INFO.print(); INFO << "Range time to first pixel (2way ms): " << c16zd1strange; INFO.print(); INFO << "Range time to last pixel (2way ms): " << c16zdlstrange; INFO.print(); INFO << "First corner of image (lat,lon): " << c16lat11 << " " << c16lon11; INFO.print(); INFO << "Second corner of image (lat,lon): " << c16lat1N << " " << c16lon1N; INFO.print(); INFO << "Third corner of image (lat,lon): " << c16latNN << " " << c16lonNN; INFO.print(); INFO << "Fourth corner of image (lat,lon): " << c16latN1 << " " << c16lonN1; INFO.print(); INFO << "Weighting function designator azimuth: " << c32weightazi; INFO.print(); toupper(c32weightazi); if (strncmp(c32weightazi,"HAMMING",7)) { WARNING << INFO.get_str() << " not HAMMING."; WARNING.print(); } INFO << "Weighting function designator range: " << c32weightrange; INFO.print(); toupper(c32weightrange); if (strncmp(c32weightrange,"HAMMING",7)) { WARNING << INFO.get_str() << " not HAMMING."; WARNING.print(); } PROGRESS.print("readleader finished."); } // END READLEADER /**************************************************************** * readnull * * * * reads nullfile * * and writes to scratchlogfile, scratchresfile * * see: annex C ERS SAR.SLC CCTand EXABYTE * * doc:er-is-epo-gs-5902.3 * * * * Bert Kampes, 11-Dec-1998 * ****************************************************************/ void readnull( const input_readfiles &readfiles_arg) { // ======Open files====== ifstream nullfile; openfstream(nullfile,readfiles_arg.nullfile); bk_assert(nullfile,readfiles_arg.nullfile,__FILE__,__LINE__); ofstream scratchlogfile("scratchlognull", ios::out | ios::trunc); bk_assert(scratchlogfile,"readnull: scratchlognull",__FILE__,__LINE__); ofstream scratchresfile("scratchresnull", ios::out | ios::trunc); bk_assert(scratchresfile,"readnull: scratchresnull",__FILE__,__LINE__); // ======Read nullfile====== DEBUG.print("nullfile should be read?"); // ______Tidy up______ nullfile.close(); scratchlogfile.close(); scratchresfile.close(); PROGRESS.print("readnull finished."); } // END READNUL /**************************************************************** * readdat * * * * Extract info from data file, * * see also appendix C of CD-R distribution (ESA). * * checks with volumefile #lines * * checks some things like numchannels * * * * info is written to scratchresfile? * * * * Bert Kampes, 21-Dec-1998 * ****************************************************************/ void readdat( input_readfiles &readfiles_arg, const int32 checklines) { TRACE_FUNCTION("readdat (BK 21-Dec-1998)") const int16 sizeb4 = 4, // some constants for reading sizeb1 = 1, sizei4 = 4, // binary fields. sizei6 = 6, sizei8 = 8; uint numchannels, // number of channels (=1?) leftborder, // offset (=0?) rightborder, // offset (=0?) bottomborder, // offset (=0?) topborder; // offset (=0?) uint numdatarec, // number of SAR DATA records numlines, // number of lines numpixels, // number of pixels numbytesdata, // bytes per line lendatarec2; // SAR DATA records length char c4[5], // correctly 5 for \0 c6[7], // correctly 7 for \0 c8[9]; // correctly 9 for \0 // --- Check for RSAT #%// Bert Kampes, 02-Aug-2004 --- uint rec_seq;// type B4 unsigned char rec_sub1, rec_type, rec_sub2, rec_sub3;// type B1 // ______Open files______ ifstream datfile; openfstream(datfile,readfiles_arg.datfile); bk_assert(datfile,readfiles_arg.datfile,__FILE__,__LINE__); // --- RECORD 1 --- DEBUG.print("record 1 of data file (ERS and RSAT)."); datfile.seekg(0,ios::beg);// datfile.read((char*)&rec_seq,sizeb4);// record number rec_seq = ntohl(rec_seq);// Bert Kampes, 07-Apr-2005 datfile.read((char*)&rec_sub1,sizeb1);// first record sub type code datfile.read((char*)&rec_type,sizeb1);// record type code datfile.read((char*)&rec_sub2,sizeb1);// second record sub type code datfile.read((char*)&rec_sub3,sizeb1);// third record sub type code DEBUG.print("ERS/RSAT: Expecting record 1 with code {63,192,18,18}"); DEBUG << "rec_seq: " << rec_seq << "; rec_sub1: " << int(rec_sub1) << "; rec_type: " << int(rec_type) << "; rec_sub2: " << int(rec_sub2) << "; rec_sub3: " << int(rec_sub3); DEBUG.print(); if (int(rec_sub1)==63 && int(rec_type)==192 && int(rec_sub2)==18 && int(rec_sub3)==18) DEBUG.print("This is the expected record with code {63,192,18,18}"); else WARNING.print("This is NOT the expected record with code {63,192,18,18}"); uint lenrec1; // length of record1 datfile.seekg(8,ios::beg);// datfile.read((char*)&lenrec1,sizeb4);// length of record lenrec1 = ntohl(lenrec1); // bk 6 jul 2000, byteorder x86 machines. DEBUG.print("ERS: Expecting record 1 with length 10012"); DEBUG.print("RSAT: Expecting record 1 with length 16252"); DEBUG << "readdat::record 1: start at: " << 0 << "; length: " << lenrec1; DEBUG.print(); // ====== Get general info ====== datfile.seekg(180,ios::beg); datfile.read((char*)&c6,sizei6); // number of SAR DATA records (lines) c6[6]='\0'; numdatarec = atoi(c6); datfile.read((char*)&c6,sizei6); // SAR DATA record length c6[6]='\0'; lendatarec2 = atoi(c6); datfile.seekg(232,ios::beg); // SAR Related data datfile.read((char*)&c4,4); c4[4]='\0'; numchannels = atoi(c4); datfile.read((char*)&c8,sizei8); c8[8]='\0'; numlines = atoi(c8); datfile.read((char*)&c4,sizei4); c4[4]='\0'; leftborder = atoi(c4); datfile.read((char*)&c8,sizei8); // number of pixels c8[8]='\0'; numpixels = atoi(c8); datfile.read((char*)&c4,sizei4); c4[4]='\0'; rightborder = atoi(c4); datfile.read((char*)&c4,sizei4); c4[4]='\0'; topborder = atoi(c4); datfile.read((char*)&c4,sizei4); c4[4]='\0'; bottomborder = atoi(c4); datfile.seekg(280,ios::beg); // Record data datfile.read((char*)&c8,sizei8); c8[8]='\0'; numbytesdata = atoi(c8); // ======Write to scratchfiles====== ofstream scratchlogdat("scratchlogdat", ios::out | ios::trunc); bk_assert(scratchlogdat,"readdat: scratchlogdat",__FILE__,__LINE__); scratchlogdat << "\n\n*******************************************************************" << "\n* EXTRACTED DATA FROM DATA FILE: " << readfiles_arg.datfile << " *" << "\n*******************************************************************" << "\nNumber of SAR channels in file: \t" << numchannels << "\nNumber of lines: \t" << numlines << "\nNumber of pixels: \t" << numpixels << "\nNumber of left border pixels per line: \t" << leftborder << "\nNumber of right border pixels per line: \t" << rightborder << "\nNumber of topborder lines: \t" << topborder << "\nNumber of bottom border lines: \t" << bottomborder << "\nNumber of bytes per data group: \t" << numbytesdata << endl; scratchlogdat.close(); // --- write RESULTFILE, add info for RSAT which was not in LEADER --- ofstream scratchresdat("scratchresdat", ios::out | ios::trunc); bk_assert(scratchresdat,"readdat: scratchresdat",__FILE__,__LINE__); scratchresdat << "Datafile: \t\t\t\t\t" << readfiles_arg.datfile << "\nNumber_of_lines_original: \t\t\t" << numlines << "\nNumber_of_pixels_original: \t\t\t" << numpixels; // --- if rsat, read datfile further, write az/rg time ---------------- //if (readfiles_arg.sensor_id==SLC_RSAT) //if (readfiles_arg.sar_processor==SARPR_ATL) if ((readfiles_arg.sar_processor==SARPR_ATL) || (readfiles_arg.sar_processor==SARPR_JAX)) //LG { // --- RECORD 2 --- uint startrec2 = lenrec1; DEBUG.print("record 2 of data file (RSAT)."); datfile.seekg(startrec2,ios::beg);// datfile.read((char*)&rec_seq,sizeb4);// record number rec_seq = ntohl(rec_seq);// Bert Kampes, 07-Apr-2005 datfile.read((char*)&rec_sub1,sizeb1);// first record sub type code datfile.read((char*)&rec_type,sizeb1);// record type code datfile.read((char*)&rec_sub2,sizeb1);// second record sub type code datfile.read((char*)&rec_sub3,sizeb1);// third record sub type code DEBUG.print("RSAT: Expecting record 2 with code {50,11,18,20}"); DEBUG << "rec_seq: " << rec_seq << "; rec_sub1: " << int(rec_sub1) << "; rec_type: " << int(rec_type) << "; rec_sub2: " << int(rec_sub2) << "; rec_sub3: " << int(rec_sub3); DEBUG.print(); if (int(rec_sub1)==50 && int(rec_type)==11 && int(rec_sub2)==18 && int(rec_sub3)==20) DEBUG.print("This is the expected record with code {50,11,18,20}"); else WARNING.print("This is NOT the expected record with code {50,11,18,20}"); uint lenrec2; // length of record2 datfile.seekg(startrec2+8,ios::beg);// datfile.read((char*)&lenrec2,sizeb4);// length of record lenrec2 = ntohl(lenrec2); // bk 6 jul 2000, byteorder x86 machines. DEBUG.print("RSAT: Expecting record 2 with length variable"); DEBUG << "readdat::record 2: start at: " << startrec2 << "; length: " << lenrec2; DEBUG.print(); uint startrec3 = lenrec1+lenrec2; uint startrecN = lenrec1+(numlines-1)*lenrec2;// start of last record // --- azimuth time to first line (depends on decrease/increase): --- uint zdmsecofday1 = 99999;// B4 uint zdmsecofday2 = 99999;// B4 uint zdmsecofdayN = 99999;// B4 datfile.seekg(startrec2+44,ios::beg);// datfile.read((char*)&zdmsecofday1,sizeb4);// range to first pix zdmsecofday1 = ntohl(zdmsecofday1);// Bert Kampes, 07-Apr-2005 datfile.seekg(startrec3+44,ios::beg);// datfile.read((char*)&zdmsecofday2,sizeb4);// range to first pix zdmsecofday2 = ntohl(zdmsecofday2);// Bert Kampes, 07-Apr-2005 datfile.seekg(startrecN+44,ios::beg);// datfile.read((char*)&zdmsecofdayN,sizeb4);// range to first pix zdmsecofdayN = ntohl(zdmsecofdayN);// Bert Kampes, 07-Apr-2005 INFO << "zdmsecofday1: " << zdmsecofday1; INFO.print(); DEBUG << "zdmsecofday2: " << zdmsecofday2; DEBUG.print(); INFO << "zdmsecofdayN: " << zdmsecofdayN; INFO.print(); // --- Check PRF/RSR --- real8 prf_check = real8(numlines-1)/(abs(real8(zdmsecofday1)-real8(zdmsecofdayN))/1000.0); INFO << "PRF check (computed [Hz]): " << prf_check; INFO.print(); // format should be: "22-AUG-1997 18:22:10.246" if (zdmsecofday1 < zdmsecofdayN)// increase, use ZD time of first line { INFO.print("INCREASING azimuth time detected RSAT"); } else // decrease: use first-numlines*prf? or read last record. { INFO.print("DECREASING azimuth time detected (flip image up-down) RSAT"); zdmsecofday1 = zdmsecofdayN;// use last record (line) as first line (flip) startrec2 = startrecN;// use last record (line) as first line (flip) } // --- Format the string UTC --- uint acq_year = 1999; uint acq_day = 19; datfile.seekg(startrec2+36,ios::beg);// datfile.read((char*)&acq_year,sizeb4);// range to first pix acq_year = ntohl(acq_year);// Bert Kampes, 07-Apr-2005 datfile.read((char*)&acq_day,sizeb4);// range to first pix acq_day = ntohl(acq_day);// Bert Kampes, 07-Apr-2005 INFO << "acq_year: " << acq_year; INFO.print(); INFO << "acq_day: " << acq_day; INFO.print(); // --- fill tm struct using daynumber with strptime, re-format it using strftime --- char datestring[13];// e.g., "25-Jan-1999" struct tm tm_tmp; char buf[9]; // e.g., "1999 191"; sprintf(buf,"%4d %03d", acq_year,acq_day); strptime(buf,"%Y %j",&tm_tmp); int q = strftime(datestring,12,"%d-%b-%Y",&tm_tmp);// q: number of bytes written INFO << "numbytes in datestring: (12?) " << q; INFO.print(); // --- Fill important part: (sec of day) --- char c24zd1stazitime[25]; int32 hour = int32(real8(zdmsecofday1)/1000.0/60.0/60.0);// floor int32 min = int32((real8(zdmsecofday1)-hour*1000.0*60.0*60.0)/1000.0/60.0);// floor int32 sec = int32((real8(zdmsecofday1)-hour*1000.0*60.0*60.0-min*1000.0*60.0)/1000.0);// floor int32 msec = int32((real8(zdmsecofday1)-hour*1000.0*60.0*60.0-min*1000.0*60.0-1000.0*sec));// floor //sprintf(c24zd1stazitime,"01-JAN-1990 %02d:%02d:%02d.%03d", hour,min,sec,msec); sprintf(c24zd1stazitime,"%11s %02d:%02d:%02d.%03d", datestring, hour,min,sec,msec); INFO << "c24zd1stazitime: " << c24zd1stazitime; INFO.print(); // --- range time to first pixel is distance ------------------------- uint range1st = 99999;// uint rangelst = 99999; // start_added_by_don real8 zd1strange; if (readfiles_arg.sar_processor==SARPR_JAX) { datfile.seekg(startrec2+116,ios::beg);// datfile.read((char*)&range1st,sizeb4);// range to first pix range1st = ntohl(range1st);// Bert Kampes, 07-Apr-2005 zd1strange = 2000.0*range1st/SOL; INFO << "range1st: " << range1st; INFO.print(); } if (readfiles_arg.sar_processor==SARPR_ATL) // end_added_by_don { datfile.seekg(startrec2+64,ios::beg);// datfile.read((char*)&range1st,sizeb4);// range to first pix range1st = ntohl(range1st);// Bert Kampes, 07-Apr-2005 datfile.seekg(startrec2+72,ios::beg);// datfile.read((char*)&rangelst,sizeb4);// range to last pix rangelst = ntohl(rangelst);// Bert Kampes, 07-Apr-2005 zd1strange = (range1stnumlines) { WARNING << "Specified input DBOW linehi > numlines: " << crop_arg.dbow.linehi << " > " << numlines << ". I set linehi = " << numlines; WARNING.print(); tempdbow.linehi=numlines; } if (crop_arg.dbow.pixhi>numpixels) { WARNING << "Specified input DBOW pixhi > numpixels: " << crop_arg.dbow.pixhi << " > " << numpixels << ". I set pixhi = " << numpixels; WARNING.print(); tempdbow.pixhi=numpixels; } // ______ Only hi values are possibly adapted, low is a constant ______ numlines = tempdbow.linehi - crop_arg.dbow.linelo + 1; numpixels = tempdbow.pixhi - crop_arg.dbow.pixlo + 1; linestart = crop_arg.dbow.linelo; lineend = tempdbow.linehi; pixelstart = crop_arg.dbow.pixlo; pixelend = tempdbow.pixhi; // only for resultfile } // ______ Note complex not in ANSI c ______ matrix LINE(1,2*numpixels); // size of short // ====== Process requested lines ====== ofstream datoutfile; openfstream(datoutfile,crop_arg.fileout1,generalinput.overwrit); bk_assert(datoutfile,crop_arg.fileout1,__FILE__,__LINE__); // ______ info on data, to avoid X86 problems ______ // ______ according to CEOS specs, byte 13-16 is first complex pixel, etc. ______ datfile.seekg(lenrec1+12,ios::beg); matrix TMPSHORT(1,2); datfile >> TMPSHORT; // read in first complex pixel for test real8 tmpmag = sqrt( real8(int16(ntohs(TMPSHORT(0,0)))*int16(ntohs(TMPSHORT(0,0)))) + real8(int16(ntohs(TMPSHORT(0,1)))*int16(ntohs(TMPSHORT(0,1))))); DEBUG << "First complex element in datafile: (" << int16(ntohs(TMPSHORT(0,0))) << "," << int16(ntohs(TMPSHORT(0,1))) << "); mag = " << tmpmag; DEBUG.print(); if (tmpmag > 10000.) { WARNING.print(DEBUG.get_str()); WARNING.print("this is a byteorder problem on X86? (use ntohs)"); } DEBUG << "TEST: (realpart): " << TMPSHORT(0,0) << ", (imagpart): " << TMPSHORT(0,1); DEBUG.print(); DEBUG << "TEST: htons(realpart): " << htons(TMPSHORT(0,0)) << ", htons(imagpart): " << htons(TMPSHORT(0,1)); DEBUG.print(); DEBUG << "TEST: ntohs(realpart): " << ntohs(TMPSHORT(0,0)) << ", ntohs(imagpart): " << ntohs(TMPSHORT(0,1)); DEBUG.print(); DEBUG << "TEST: short int(ntohs(realpart)): " << int16(ntohs(TMPSHORT(0,0))) << ", (imagpart): " << int16(ntohs(TMPSHORT(0,1))); DEBUG.print(); // ====== perline is faster than perbuffer, less memory etc. BK1998 ====== datfile.seekg(lenrec1+(linestart-1)*lendatarec2+8,ios::beg); datfile.read((char*)&lenrec2,sizeb4); // length of first record lenrec2 = ntohl(lenrec2); // bk 6 jul 2000, byteorder x86 machines. if (lenrec2 != lendatarec2) { ERROR << "code 904: Length of datarecords seems to be inconsistent in file: " << crop_arg.filein1 << ": " << lenrec2 << " != " << lendatarec2; WARNING.print(ERROR.get_str()); ERROR.reset(); } const int32 TEN = 10; const int32 TENPERCENT = int32((.5*TEN+numlines)/TEN); // number of lines int32 percentage = 0; // initialization const int32 tmpstart = lenrec1+12-lendatarec2+(pixelstart-1)*4; // sizeof=4 for (register int32 linecnt=linestart; linecnt<=lineend; linecnt++) { if (!((linecnt-linestart)%TENPERCENT)) { PROGRESS << "WRITESLC: " << setw(3) << percentage << "%"; PROGRESS.print(); percentage += TEN; } datfile.seekg(tmpstart+linecnt*lendatarec2,ios::beg); datfile >> LINE; // ______ BK 13 July 2000: swapbytes for X86 (intel) linux cpus ______ #ifdef __X86PROCESSOR__ for (int ii=0; iinumlines) { WARNING << "Specified input DBOW linehi > numlines: " << crop_arg.dbow.linehi << " > " << numlines << ". I set linehi = " << numlines; WARNING.print(); tempdbow.linehi=numlines; } if (crop_arg.dbow.pixhi>numpixels) { WARNING << "Specified input DBOW pixhi > numpixels: " << crop_arg.dbow.pixhi << " > " << numpixels << ". I set pixhi = " << numpixels; WARNING.print(); tempdbow.pixhi=numpixels; } // ______ Only hi values are possibly adapted, low is a constant ______ numlines = tempdbow.linehi - crop_arg.dbow.linelo + 1; numpixels = tempdbow.pixhi - crop_arg.dbow.pixlo + 1; linestart = crop_arg.dbow.linelo; lineend = tempdbow.linehi; pixelstart = crop_arg.dbow.pixlo; pixelend = tempdbow.pixhi; // only for resultfile } // ______ Note complex not in ANSI c ______ matrix LINE(1,2*numpixels); // size of short ifstream datfile; openfstream(datfile,crop_arg.filein1); bk_assert(datfile,crop_arg.filein1,__FILE__,__LINE__); // ====== Process requested lines ====== ofstream datoutfile; openfstream(datoutfile,crop_arg.fileout1,generalinput.overwrit); bk_assert(datoutfile,crop_arg.fileout1,__FILE__,__LINE__); // ______ info on data, to avoid X86 problems ______ // ______ go to the beginning of file to first complex pixel, etc. ______ datfile.seekg(0, ios::beg); matrix TMPSHORT(1,2); datfile >> TMPSHORT; // read in first complex pixel for test real8 tmpmag = sqrt( real8(int16(ntohs(TMPSHORT(0,0)))*int16(ntohs(TMPSHORT(0,0)))) + real8(int16(ntohs(TMPSHORT(0,1)))*int16(ntohs(TMPSHORT(0,1))))); DEBUG << "First complex element in datafile: (" << int16(ntohs(TMPSHORT(0,0))) << "," << int16(ntohs(TMPSHORT(0,1))) << "); mag = " << tmpmag; DEBUG.print(); if (tmpmag > 10000.) { WARNING.print(DEBUG.get_str()); WARNING.print("this is a byteorder problem on X86? (use ntohs)"); } DEBUG << "TEST: (realpart): " << TMPSHORT(0,0) << ", (imagpart): " << TMPSHORT(0,1); DEBUG.print(); DEBUG << "TEST: htons(realpart): " << htons(TMPSHORT(0,0)) << ", htons(imagpart): " << htons(TMPSHORT(0,1)); DEBUG.print(); DEBUG << "TEST: ntohs(realpart): " << ntohs(TMPSHORT(0,0)) << ", ntohs(imagpart): " << ntohs(TMPSHORT(0,1)); DEBUG.print(); DEBUG << "TEST: short int(ntohs(realpart)): " << int16(ntohs(TMPSHORT(0,0))) << ", (imagpart): " << int16(ntohs(TMPSHORT(0,1))); DEBUG.print(); // ====== perline is faster than perbuffer, less memory etc. BK1998 ====== const int32 TEN = 10; const int32 TENPERCENT = int32((.5*TEN+numlines)/TEN); // number of lines int32 percentage = 0; // initialization const int32 offset = (pixelstart-1)*4; // sizeof=4 for (register int32 linecnt=linestart; linecnt<=lineend; linecnt++) { if (!((linecnt-linestart)%TENPERCENT)) { PROGRESS << "WRITESLC: " << setw(3) << percentage << "%"; PROGRESS.print(); percentage += TEN; } datfile.seekg((linecnt-1)*lenOneLine+offset, ios::beg); datfile >> LINE; datoutfile << LINE; } datfile.close(); // close files datoutfile.close(); // ====== Write results to scratchfile ====== ofstream scratchresfile("scratchres2raw", ios::out | ios::trunc); bk_assert(scratchresfile,"writeslc: scratchres2raw",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************\n"; //<< "\n*_Start_crop:\t\t\t" //<< crop_arg.idcrop if (crop_arg.fileid == MASTERID) scratchresfile << "*_Start_" << processcontrol[pr_m_crop]; if (crop_arg.fileid == SLAVEID) scratchresfile << "*_Start_" << processcontrol[pr_s_crop]; scratchresfile << "\t\t\t" << crop_arg.idcrop << "\n*******************************************************************" << "\nData_output_file: \t\t\t\t" << crop_arg.fileout1 << "\nData_output_format: \t\t\t\t" << "complex_short" // ______ updateslcimage greps these ______ << "\nFirst_line (w.r.t. original_image): \t\t" << linestart << "\nLast_line (w.r.t. original_image): \t\t" << lineend << "\nFirst_pixel (w.r.t. original_image): \t\t" << pixelstart << "\nLast_pixel (w.r.t. original_image): \t\t" << pixelend << "\nNumber of lines (non-multilooked): \t\t" << lineend-linestart+1 << "\nNumber of pixels (non-multilooked): \t\t" << pixelend-pixelstart+1 << "\n*******************************************************************"; if (crop_arg.fileid == MASTERID) scratchresfile << "\n* End_" << processcontrol[pr_m_crop] << "_NORMAL"; if (crop_arg.fileid == SLAVEID) scratchresfile << "\n* End_" << processcontrol[pr_s_crop] << "_NORMAL"; scratchresfile << "\n*******************************************************************" << endl; scratchresfile.close(); PROGRESS.print("WRITESLC: 100%"); } // END gammaprocessor_crop /**************************************************************** * envisatdump_data * * * * Via a system call to the c-program envisat_dump_data, the * * SLC data is wrtten to file. The resfile is here created. * * envisatdumpdata writes SLC data out in host order. * * it is important that crop_arg.dbow is correctly filled. * * Bert Kampes, 16-JUN-2003 * ****************************************************************/ void envisat_dump_data( const input_crop &crop_arg) { // ______ Write some info ______ TRACE_FUNCTION("envisat_dump_data (BK 16-Jun-2003)") // ______ Build command ______ // ______ make sure l0 etc. are correctly defined ______ // ____ assume these are filled correctly ___ INFO.reset(); if (crop_arg.dbow.linehi!=0 && crop_arg.dbow.linelo!=0 && crop_arg.dbow.pixhi!=0 && crop_arg.dbow.pixlo!=0) INFO << "envisat_dump_data " << crop_arg.filein1 << " " << crop_arg.fileout1 << " " << crop_arg.dbow.linelo << " " << crop_arg.dbow.linehi << " " << crop_arg.dbow.pixlo << " " << crop_arg.dbow.pixhi << ends; else INFO << "envisat_dump_data " << crop_arg.filein1 << " " << crop_arg.fileout1 << ends; char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("With following command the envisat data was cropped."); INFO.print(cmd); PROGRESS.print("system call may take some time..."); system(cmd);// this does the work INFO.reset(); INFO.print(); // ====== Write results to scratchfile ====== ofstream scratchresfile("scratchres2raw", ios::out | ios::trunc); bk_assert(scratchresfile,"writeslc: scratchres2raw",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************\n"; if (crop_arg.fileid == MASTERID) scratchresfile << "*_Start_" << processcontrol[pr_m_crop]; if (crop_arg.fileid == SLAVEID) scratchresfile << "*_Start_" << processcontrol[pr_s_crop]; scratchresfile << "\t\t\t" << crop_arg.idcrop << "\n*******************************************************************" << "\nData_output_file: \t\t\t\t" << crop_arg.fileout1 << "\nData_output_format: \t\t\t\t" << "complex_short" // ______ updateslcimage greps these ______ << "\nFirst_line (w.r.t. original_image): \t\t" << crop_arg.dbow.linelo << "\nLast_line (w.r.t. original_image): \t\t" << crop_arg.dbow.linehi << "\nFirst_pixel (w.r.t. original_image): \t\t" << crop_arg.dbow.pixlo << "\nLast_pixel (w.r.t. original_image): \t\t" << crop_arg.dbow.pixhi << "\nNumber of lines (non-multilooked): \t\t" << crop_arg.dbow.linehi-crop_arg.dbow.linelo+1 << "\nNumber of pixels (non-multilooked): \t\t" << crop_arg.dbow.pixhi-crop_arg.dbow.pixlo+1 << "\n*******************************************************************"; if (crop_arg.fileid == MASTERID) scratchresfile << "\n* End_" << processcontrol[pr_m_crop] << "_NORMAL"; if (crop_arg.fileid == SLAVEID) scratchresfile << "\n* End_" << processcontrol[pr_s_crop] << "_NORMAL"; scratchresfile << "\n*******************************************************************" << endl; scratchresfile.close(); } // END envisat_dump_data // AP_VV functions, later migrate to above one with a switch void envisat_dump_VV( const input_crop &crop_arg) { // ______ Write some info ______ TRACE_FUNCTION("envisat_dump_VV (MCC 16-Jun-2003)") // ______ Build command ______ // ______ make sure l0 etc. are correctly defined ______ // ____ assume these are filled correctly ___ INFO.reset(); if (crop_arg.dbow.linehi!=0 && crop_arg.dbow.linelo!=0 && crop_arg.dbow.pixhi!=0 && crop_arg.dbow.pixlo!=0) INFO << "envisat_dump_VV " << crop_arg.filein1 << " " << crop_arg.fileout1 << " " << crop_arg.dbow.linelo << " " << crop_arg.dbow.linehi << " " << crop_arg.dbow.pixlo << " " << crop_arg.dbow.pixhi << ends; else INFO << "envisat_dump_VV " << crop_arg.filein1 << " " << crop_arg.fileout1 << ends; char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("With following command the envisat data was cropped."); INFO.print(cmd); PROGRESS.print("system call may take some time..."); system(cmd);// this does the work INFO.reset(); INFO.print(); // ====== Write results to scratchfile ====== ofstream scratchresfile("scratchres2raw", ios::out | ios::trunc); bk_assert(scratchresfile,"writeslc: scratchres2raw",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************\n"; if (crop_arg.fileid == MASTERID) scratchresfile << "*_Start_" << processcontrol[pr_m_crop]; if (crop_arg.fileid == SLAVEID) scratchresfile << "*_Start_" << processcontrol[pr_s_crop]; scratchresfile << "\t\t\t" << crop_arg.idcrop << "\n*******************************************************************" << "\nData_output_file: \t\t\t\t" << crop_arg.fileout1 << "\nData_output_format: \t\t\t\t" << "complex_short" // ______ updateslcimage greps these ______ << "\nFirst_line (w.r.t. original_image): \t\t" << crop_arg.dbow.linelo << "\nLast_line (w.r.t. original_image): \t\t" << crop_arg.dbow.linehi << "\nFirst_pixel (w.r.t. original_image): \t\t" << crop_arg.dbow.pixlo << "\nLast_pixel (w.r.t. original_image): \t\t" << crop_arg.dbow.pixhi << "\nNumber of lines (non-multilooked): \t\t" << crop_arg.dbow.linehi-crop_arg.dbow.linelo+1 << "\nNumber of pixels (non-multilooked): \t\t" << crop_arg.dbow.pixhi-crop_arg.dbow.pixlo+1 << "\n*******************************************************************"; if (crop_arg.fileid == MASTERID) scratchresfile << "\n* End_" << processcontrol[pr_m_crop] << "_NORMAL"; if (crop_arg.fileid == SLAVEID) scratchresfile << "\n* End_" << processcontrol[pr_s_crop] << "_NORMAL"; scratchresfile << "\n*******************************************************************" << endl; scratchresfile.close(); } // END envisat_dump_VV void envisat_dump_HH( const input_crop &crop_arg) { // ______ Write some info ______ TRACE_FUNCTION("envisat_dump_HH (BK 16-Jun-2003)") // ______ Build command ______ // ______ make sure l0 etc. are correctly defined ______ // ____ assume these are filled correctly ___ INFO.reset(); if (crop_arg.dbow.linehi!=0 && crop_arg.dbow.linelo!=0 && crop_arg.dbow.pixhi!=0 && crop_arg.dbow.pixlo!=0) INFO << "envisat_dump_HH " << crop_arg.filein1 << " " << crop_arg.fileout1 << " " << crop_arg.dbow.linelo << " " << crop_arg.dbow.linehi << " " << crop_arg.dbow.pixlo << " " << crop_arg.dbow.pixhi << ends; else INFO << "envisat_dump_HH " << crop_arg.filein1 << " " << crop_arg.fileout1 << ends; char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("With following command the envisat data was cropped."); INFO.print(cmd); PROGRESS.print("system call may take some time..."); system(cmd);// this does the work INFO.reset(); INFO.print(); // ====== Write results to scratchfile ====== ofstream scratchresfile("scratchres2raw", ios::out | ios::trunc); bk_assert(scratchresfile,"writeslc: scratchres2raw",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************\n"; if (crop_arg.fileid == MASTERID) scratchresfile << "*_Start_" << processcontrol[pr_m_crop]; if (crop_arg.fileid == SLAVEID) scratchresfile << "*_Start_" << processcontrol[pr_s_crop]; scratchresfile << "\t\t\t" << crop_arg.idcrop << "\n*******************************************************************" << "\nData_output_file: \t\t\t\t" << crop_arg.fileout1 << "\nData_output_format: \t\t\t\t" << "complex_short" // ______ updateslcimage greps these ______ << "\nFirst_line (w.r.t. original_image): \t\t" << crop_arg.dbow.linelo << "\nLast_line (w.r.t. original_image): \t\t" << crop_arg.dbow.linehi << "\nFirst_pixel (w.r.t. original_image): \t\t" << crop_arg.dbow.pixlo << "\nLast_pixel (w.r.t. original_image): \t\t" << crop_arg.dbow.pixhi << "\nNumber of lines (non-multilooked): \t\t" << crop_arg.dbow.linehi-crop_arg.dbow.linelo+1 << "\nNumber of pixels (non-multilooked): \t\t" << crop_arg.dbow.pixhi-crop_arg.dbow.pixlo+1 << "\n*******************************************************************"; if (crop_arg.fileid == MASTERID) scratchresfile << "\n* End_" << processcontrol[pr_m_crop] << "_NORMAL"; if (crop_arg.fileid == SLAVEID) scratchresfile << "\n* End_" << processcontrol[pr_s_crop] << "_NORMAL"; scratchresfile << "\n*******************************************************************" << endl; scratchresfile.close(); } // END envisat_dump_HH /**************************************************************** * tsxdump_data * * * * Via a system call to the python tsx_dump_data, the * * SLC data is written to file. The resfile is here created. * * tsxdumpdata writes SLC data out in host order. * * it is important that crop_arg.dbow is correctly filled. * * * * Dependencies: GDAL * ****************************************************************/ void tsx_dump_data( const input_crop &crop_arg) { // ______ Write some info ______ TRACE_FUNCTION("tsx_dump_data (PM 06-Apr-2009)") // ______ Build command ______ // ______ make sure l0 etc. are correctly defined ______ // ____ assume these are filled correctly ___ int16 status = 0; // [MA] check exit status of system calls for proper error handling INFO.reset(); if (crop_arg.dbow.linehi!=0 && crop_arg.dbow.linelo!=0 && crop_arg.dbow.pixhi!=0 && crop_arg.dbow.pixlo!=0) INFO << "tsx_dump_data.py " << crop_arg.filein1 << " " << crop_arg.fileout1 //<< " " << crop_arg.dbow.linelo - 1 << " " << crop_arg.dbow.linelo << " " << crop_arg.dbow.linehi //<< " " << crop_arg.dbow.pixlo - 1 << " " << crop_arg.dbow.pixlo << " " << crop_arg.dbow.pixhi << ends; else INFO << "tsx_dump_data.py " << crop_arg.filein1 << " " << crop_arg.fileout1 << ends; char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("With following command TSX cosar data was cropped."); INFO.print(cmd); PROGRESS.print("system call may take some time..."); status=system(cmd);// this does the work if (status != 0) // [MA] TODO make it a function { ERROR << "tsx_dump_data.py: failed with exit code: " << status; PRINT_ERROR(ERROR.get_str()) throw(some_error); } INFO.reset(); INFO.print(); // ====== Write results to scratchfile ====== ofstream scratchresfile("scratchres2raw", ios::out | ios::trunc); bk_assert(scratchresfile,"writeslc: scratchres2raw",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************\n"; if (crop_arg.fileid == MASTERID) scratchresfile << "*_Start_" << processcontrol[pr_m_crop]; if (crop_arg.fileid == SLAVEID) scratchresfile << "*_Start_" << processcontrol[pr_s_crop]; scratchresfile << "\t\t\t" << crop_arg.idcrop << "\n*******************************************************************" << "\nData_output_file: \t\t\t\t" << crop_arg.fileout1 << "\nData_output_format: \t\t\t\t" << "complex_short" // ______ updateslcimage greps these ______ << "\nFirst_line (w.r.t. original_image): \t\t" << crop_arg.dbow.linelo << "\nLast_line (w.r.t. original_image): \t\t" << crop_arg.dbow.linehi << "\nFirst_pixel (w.r.t. original_image): \t\t" << crop_arg.dbow.pixlo << "\nLast_pixel (w.r.t. original_image): \t\t" << crop_arg.dbow.pixhi << "\nNumber of lines (non-multilooked): \t\t" << crop_arg.dbow.linehi-crop_arg.dbow.linelo+1 << "\nNumber of pixels (non-multilooked): \t\t" << crop_arg.dbow.pixhi-crop_arg.dbow.pixlo+1 << "\n*******************************************************************"; if (crop_arg.fileid == MASTERID) scratchresfile << "\n* End_" << processcontrol[pr_m_crop] << "_NORMAL"; if (crop_arg.fileid == SLAVEID) scratchresfile << "\n* End_" << processcontrol[pr_s_crop] << "_NORMAL"; scratchresfile << "\n*******************************************************************" << endl; scratchresfile.close(); } // END tsx_dump_data /**************************************************************** * rs2dump_data * * * * Dump Radarsat-2 TIFF file to raw * * via a system call to the python rs2_dump_data, the * * SLC data is written to file. The resfile is here created. * * rs2dumpdata writes SLC data out in host order. * * it is important that crop_arg.dbow is correctly filled. * * * * Dependencies: GDAL, PYTHON * * * * * ****************************************************************/ void rs2_dump_data( const input_crop &crop_arg) { // ______ Write some info ______ TRACE_FUNCTION("rs2_dump_data (MA,PM 04-Oct-2009)") // ______ Build command ______ // ______ make sure l0 etc. are correctly defined ______ // ____ assume these are filled correctly ___ int16 status = 0; // [MA] check exit status of system calls for proper error handling INFO.reset(); if (crop_arg.dbow.linehi!=0 && crop_arg.dbow.linelo!=0 && crop_arg.dbow.pixhi!=0 && crop_arg.dbow.pixlo!=0) INFO << "rs2_dump_data.py " << crop_arg.filein1 << " " << crop_arg.fileout1 //<< " " << crop_arg.dbow.linelo - 1 << " " << crop_arg.dbow.linelo << " " << crop_arg.dbow.linehi //<< " " << crop_arg.dbow.pixlo - 1 << " " << crop_arg.dbow.pixlo << " " << crop_arg.dbow.pixhi << ends; else INFO << "rs2_dump_data.py " << crop_arg.filein1 << " " << crop_arg.fileout1 << ends; char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("With following command RS2 data was cropped."); INFO.print(cmd); PROGRESS.print("system call may take some time..."); status=system(cmd);// this does the work if (status != 0) // [MA] TODO make it a function { ERROR << "rs2_dump_data.py: failed with exit code: " << status; PRINT_ERROR(ERROR.get_str()) throw(some_error); } INFO.reset(); INFO.print(); // ====== Write results to scratchfile ====== ofstream scratchresfile("scratchres2raw", ios::out | ios::trunc); bk_assert(scratchresfile,"writeslc: scratchres2raw",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************\n"; if (crop_arg.fileid == MASTERID) scratchresfile << "*_Start_" << processcontrol[pr_m_crop]; if (crop_arg.fileid == SLAVEID) scratchresfile << "*_Start_" << processcontrol[pr_s_crop]; scratchresfile << "\t\t\t" << crop_arg.idcrop << "\n*******************************************************************" << "\nData_output_file: \t\t\t\t" << crop_arg.fileout1 << "\nData_output_format: \t\t\t\t" << "complex_short" // ______ updateslcimage greps these ______ << "\nFirst_line (w.r.t. original_image): \t\t" << crop_arg.dbow.linelo << "\nLast_line (w.r.t. original_image): \t\t" << crop_arg.dbow.linehi << "\nFirst_pixel (w.r.t. original_image): \t\t" << crop_arg.dbow.pixlo << "\nLast_pixel (w.r.t. original_image): \t\t" << crop_arg.dbow.pixhi << "\nNumber of lines (non-multilooked): \t\t" << crop_arg.dbow.linehi-crop_arg.dbow.linelo+1 << "\nNumber of pixels (non-multilooked): \t\t" << crop_arg.dbow.pixhi-crop_arg.dbow.pixlo+1 << "\n*******************************************************************"; if (crop_arg.fileid == MASTERID) scratchresfile << "\n* End_" << processcontrol[pr_m_crop] << "_NORMAL"; if (crop_arg.fileid == SLAVEID) scratchresfile << "\n* End_" << processcontrol[pr_s_crop] << "_NORMAL"; scratchresfile << "\n*******************************************************************" << endl; scratchresfile.close(); } // END rs2_dump_data /**************************************************************** * cskdump_data * * * * Dump Cosmo-Skymed HD5 file to raw * * via a system call to the python csk_dump_data, the * * SLC data is written to file. The resfile is here created. * * cskdumpdata writes SLC data out in host order. * * it is important that crop_arg.dbow is correctly filled. * * * * Dependencies: HD5, PYTHON * * * * * ****************************************************************/ void csk_dump_data( const input_crop &crop_arg) { // ______ Write some info ______ TRACE_FUNCTION("csk_dump_data (MA,PD 23-Jun-2010)") // ______ Build command ______ // ______ make sure l0 etc. are correctly defined ______ // ____ assume these are filled correctly ___ int16 status = 0; // [MA] check exit status of system calls for proper error handling INFO.reset(); if (crop_arg.dbow.linehi!=0 && crop_arg.dbow.linelo!=0 && crop_arg.dbow.pixhi!=0 && crop_arg.dbow.pixlo!=0) INFO << "csk_dump_data.py " << crop_arg.filein1 << " " << crop_arg.fileout1 //<< " " << crop_arg.dbow.linelo - 1 << " " << crop_arg.dbow.linelo << " " << crop_arg.dbow.linehi //<< " " << crop_arg.dbow.pixlo - 1 << " " << crop_arg.dbow.pixlo << " " << crop_arg.dbow.pixhi << ends; else INFO << "csk_dump_data.py " << crop_arg.filein1 << " " << crop_arg.fileout1 << ends; char cmd[512];// command string strcpy(cmd, INFO.get_str()); INFO.print("With following command CSK data was cropped."); INFO.print(cmd); PROGRESS.print("system call may take some time..."); status=system(cmd);// this does the work if (status != 0) // [MA] TODO make it a function { ERROR << "csk_dump_data.py: failed with exit code: " << status; PRINT_ERROR(ERROR.get_str()) throw(some_error); } INFO.reset(); INFO.print(); // ====== Write results to scratchfile ====== ofstream scratchresfile("scratchres2raw", ios::out | ios::trunc); bk_assert(scratchresfile,"writeslc: scratchres2raw",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************\n"; if (crop_arg.fileid == MASTERID) scratchresfile << "*_Start_" << processcontrol[pr_m_crop]; if (crop_arg.fileid == SLAVEID) scratchresfile << "*_Start_" << processcontrol[pr_s_crop]; scratchresfile << "\t\t\t" << crop_arg.idcrop << "\n*******************************************************************" << "\nData_output_file: \t\t\t\t" << crop_arg.fileout1 << "\nData_output_format: \t\t\t\t" << "complex_short" // ______ updateslcimage greps these ______ << "\nFirst_line (w.r.t. original_image): \t\t" << crop_arg.dbow.linelo << "\nLast_line (w.r.t. original_image): \t\t" << crop_arg.dbow.linehi << "\nFirst_pixel (w.r.t. original_image): \t\t" << crop_arg.dbow.pixlo << "\nLast_pixel (w.r.t. original_image): \t\t" << crop_arg.dbow.pixhi << "\nNumber of lines (non-multilooked): \t\t" << crop_arg.dbow.linehi-crop_arg.dbow.linelo+1 << "\nNumber of pixels (non-multilooked): \t\t" << crop_arg.dbow.pixhi-crop_arg.dbow.pixlo+1 << "\n*******************************************************************"; if (crop_arg.fileid == MASTERID) scratchresfile << "\n* End_" << processcontrol[pr_m_crop] << "_NORMAL"; if (crop_arg.fileid == SLAVEID) scratchresfile << "\n* End_" << processcontrol[pr_s_crop] << "_NORMAL"; scratchresfile << "\n*******************************************************************" << endl; scratchresfile.close(); } // END csk_dump_data /**************************************************************** * radarsat_dump_data * * * * Inputfile in ceos slc format is converted to * * raw format outputfile. * * image is flipped if time direction is not INCREASE,INCREASE * * crop is thus done either geometric correct, or if specified * #%// Bert Kampes, 04-Aug-2004 * DBOW a bit strange ... ? #%// Fix for DBOW for cropping radarsat images - Andy Mar,2009 ****************************************************************/ void radarsat_dump_data( const input_gen &generalinput, const input_crop &crop_arg) { const int16 sizeb4 = 4, // some constants for reading sizeb1 = 1, // binary fields. sizei4 = 4, // binary fields. sizei6 = 6, sizei8 = 8; uint lenrec1; // length of general record1 uint lenrec2; // (nominal) length of data records char c4[5], // correctly 5 for \0 c6[7], // correctly 7 for \0 c8[9]; // correctly 9 for \0 // --- Check for RSAT #%// Bert Kampes, 02-Aug-2004 --- uint rec_seq;// type B4 unsigned char rec_sub1, rec_type, rec_sub2, rec_sub3;// type B1 // ______ Write some info ______ TRACE_FUNCTION("radarsat_dump_data (Bert Kampes 04-Aug-2004)") PROGRESS.print("Start cropping slc data for RADARSAT."); #ifdef __X86PROCESSOR__ INFO.print("Swapping Big Endian (CEOS input) to Little Endian (your platform)."); #else INFO.print("NO byte swapping performed, you must be on Big Endian platform."); #endif // ______ Open files ______ ifstream datfile; openfstream(datfile,crop_arg.filein1); bk_assert(datfile,crop_arg.filein1,__FILE__,__LINE__); // ====== Get data such as recordlength ====== // --- RECORD 1 --- DEBUG.print("record 1 of data file (ERS and RSAT)."); datfile.seekg(0,ios::beg);// datfile.read((char*)&rec_seq,sizeb4);// record number rec_seq = ntohl(rec_seq); // bk 6 jul 2000, byteorder x86 machines. datfile.read((char*)&rec_sub1,sizeb1);// first record sub type code datfile.read((char*)&rec_type,sizeb1);// record type code datfile.read((char*)&rec_sub2,sizeb1);// second record sub type code datfile.read((char*)&rec_sub3,sizeb1);// third record sub type code DEBUG.print("RSAT: Expecting record 1 with code {63,192,18,18}"); DEBUG << "rec_seq: " << rec_seq << "; rec_sub1: " << int(rec_sub1) << "; rec_type: " << int(rec_type) << "; rec_sub2: " << int(rec_sub2) << "; rec_sub3: " << int(rec_sub3); DEBUG.print(); if (int(rec_sub1)==63 && int(rec_type)==192 && int(rec_sub2)==18 && int(rec_sub3)==18) DEBUG.print("This is the expected record with code {63,192,18,18}"); else WARNING.print("This is NOT the expected record with code {63,192,18,18}"); datfile.seekg(8,ios::beg);// datfile.read((char*)&lenrec1,sizeb4);// length of record lenrec1 = ntohl(lenrec1); // bk 6 jul 2000, byteorder x86 machines. DEBUG.print("RSAT: Expecting record 1 with length 16252"); DEBUG << "radarsat_dump_data::record 1: start at: " << 0 << "; length: " << lenrec1; DEBUG.print(); // --- Get some info in RECORD 1 --- datfile.seekg(180,ios::beg); datfile.read((char*)&c6,sizei6); // number of SAR DATA records (lines) c6[6]='\0'; const uint numdatarec = atoi(c6); DEBUG << "numdatarec: " << numdatarec; DEBUG.print(); //datfile.seekg(186,ios::beg); datfile.read((char*)&c6,sizei6); // SAR DATA record length c6[6]='\0'; const uint lendatarec2 = atoi(c6); DEBUG << "lendatarec2: " << lendatarec2; DEBUG.print(); datfile.seekg(232,ios::beg); // SAR Related data datfile.read((char*)&c4,4); c4[4]='\0'; const uint numchannels = atoi(c4); DEBUG << "numchannels: " << numchannels; DEBUG.print(); datfile.read((char*)&c8,sizei8); c8[8]='\0'; uint numlines = atoi(c8); DEBUG << "numlines: " << numlines; DEBUG.print(); datfile.read((char*)&c4,sizei4); c4[4]='\0'; const uint leftborder = atoi(c4); DEBUG << "leftborder: " << leftborder; DEBUG.print(); datfile.read((char*)&c8,sizei8); // number of pixels c8[8]='\0'; uint numpixels = atoi(c8); DEBUG << "numpixels: " << numpixels; DEBUG.print(); datfile.read((char*)&c4,sizei4); c4[4]='\0'; const uint rightborder = atoi(c4); DEBUG << "rightborder: " << rightborder; DEBUG.print(); datfile.read((char*)&c4,sizei4); c4[4]='\0'; const uint topborder = atoi(c4); DEBUG << "topborder: " << topborder; DEBUG.print(); datfile.read((char*)&c4,sizei4); c4[4]='\0'; const uint bottomborder = atoi(c4); DEBUG << "bottomborder: " << bottomborder; DEBUG.print(); datfile.seekg(280,ios::beg); // Record data datfile.read((char*)&c8,sizei8); c8[8]='\0'; const uint numbytesdata = atoi(c8); DEBUG << "numbytesdata: " << numbytesdata; DEBUG.print(); // ______ Check with previous section ______ if (numlines != numdatarec) { WARNING << "code 904: Number of lines seems not to be consistent in file: " << crop_arg.filein1 << " : " << numlines << " != " << numdatarec; WARNING.print(); WARNING.print("this means SLC FORMAT IS DIFFERENT THEN EXPECTED."); } if ((numbytesdata / 4) != numpixels) { WARNING << "code 904: Number of pixels seems to be inconsistent in file: " << crop_arg.filein1 << ": " << numpixels << " != " << (numbytesdata / 4); WARNING.print(); WARNING.print("this means SLC FORMAT IS DIFFERENT THEN EXPECTED."); } // ====== Start copy input to output (raw) format with buffer====== // ______ Check and process optional offset parameters______ // ______ Lcnlow is corner line, lcnhi is other corner, pcnlow, pixel coord. low etc. uint linestart = 1; // counters for loops, first=1; uint lineend = numlines; uint pixelstart = 1; // first pix is 1 uint pixelend = numpixels; // only for resultfile uint orig_numlines = numlines; uint orig_numpixels = numpixels; if (crop_arg.dbow.linehi!=0 && crop_arg.dbow.linelo!=0 && crop_arg.dbow.pixhi!=0 && crop_arg.dbow.pixlo!=0) { WARNING.print("cropping data may be difficult, due to INC/DECREASE storage"); window tempdbow(crop_arg.dbow.linelo, crop_arg.dbow.linehi, crop_arg.dbow.pixlo, crop_arg.dbow.pixhi); if (crop_arg.dbow.linehi>numlines) { WARNING << "Specified input DBOW linehi > numlines: " << crop_arg.dbow.linehi << " > " << numlines << ". I set linehi = " << numlines; WARNING.print(); tempdbow.linehi=numlines; } if (crop_arg.dbow.pixhi>numpixels) { WARNING << "Specified input DBOW pixhi > numpixels: " << crop_arg.dbow.pixhi << " > " << numpixels << ". I set pixhi = " << numpixels; WARNING.print(); tempdbow.pixhi=numpixels; } // ______ Only hi values are possibly adapted, low is a constant ______ numlines = tempdbow.linehi - crop_arg.dbow.linelo + 1; numpixels = tempdbow.pixhi - crop_arg.dbow.pixlo + 1; linestart = crop_arg.dbow.linelo; lineend = tempdbow.linehi; pixelstart = crop_arg.dbow.pixlo; pixelend = tempdbow.pixhi; // only for resultfile } // --- Find out if data is stored increasing in line/pix --- // --- RECORD 2 --- uint startrec2 = lenrec1; DEBUG.print("record 2 of data file (RSAT)."); datfile.seekg(startrec2,ios::beg);// datfile.read((char*)&rec_seq,sizeb4);// record number rec_seq = ntohl(rec_seq); // bk 6 jul 2000, byteorder x86 machines. datfile.read((char*)&rec_sub1,sizeb1);// first record sub type code datfile.read((char*)&rec_type,sizeb1);// record type code datfile.read((char*)&rec_sub2,sizeb1);// second record sub type code datfile.read((char*)&rec_sub3,sizeb1);// third record sub type code DEBUG.print("RSAT: Expecting record 2 with code {50,11,18,20}"); DEBUG << "rec_seq: " << rec_seq << "; rec_sub1: " << int(rec_sub1) << "; rec_type: " << int(rec_type) << "; rec_sub2: " << int(rec_sub2) << "; rec_sub3: " << int(rec_sub3); DEBUG.print(); if (int(rec_sub1)==50 && int(rec_type)==11 && int(rec_sub2)==18 && int(rec_sub3)==20) DEBUG.print("This is the expected record with code {50,11,18,20}"); else WARNING.print("This is NOT the expected record with code {50,11,18,20}"); datfile.seekg(startrec2+8,ios::beg);// datfile.read((char*)&lenrec2,sizeb4);// length of record lenrec2 = ntohl(lenrec2); // bk 6 jul 2000, byteorder x86 machines. DEBUG.print("RSAT: Expecting record 2 with length variable"); DEBUG << "radarsat_dump_data::record 2: start at: " << startrec2 << "; length: " << lenrec2; DEBUG.print(); uint startrec3 = lenrec1+lenrec2; uint startrecN = lenrec1+(numlines-1)*lenrec2;// start of last record // --- azimuth time to first line (depends on decrease/increase): --- uint zdmsecofday1 = 99999;// B4 uint zdmsecofday2 = 99999;// B4 uint zdmsecofdayN = 99999;// B4 datfile.seekg(startrec2+44,ios::beg);// datfile.read((char*)&zdmsecofday1,sizeb4);// range to first pix zdmsecofday1 = ntohl(zdmsecofday1); // bk 6 jul 2000, byteorder x86 machines. datfile.seekg(startrec3+44,ios::beg);// datfile.read((char*)&zdmsecofday2,sizeb4);// range to first pix zdmsecofday2 = ntohl(zdmsecofday2); // bk 6 jul 2000, byteorder x86 machines. datfile.seekg(startrecN+44,ios::beg);// datfile.read((char*)&zdmsecofdayN,sizeb4);// range to first pix zdmsecofdayN = ntohl(zdmsecofdayN); // bk 6 jul 2000, byteorder x86 machines. INFO << "zdmsecofday1: " << zdmsecofday1; INFO.print(); DEBUG << "zdmsecofday2: " << zdmsecofday2; DEBUG.print(); INFO << "zdmsecofdayN: " << zdmsecofdayN; INFO.print(); bool increasing_line = true;// assume this // --- I assume linestart is smaller than end, so swap them if required --- if (zdmsecofday1 < zdmsecofdayN)// increase, use ZD time of first line { INFO.print("INCREASE line direction detected (OK)."); } else // decreasing lines: flip up-down { WARNING.print("DECREASE line direction detected: I will flip up-down the RSAT data"); increasing_line = false; } // --- range time to first pixel is distance ------------------------- uint range1st = 99999;// uint rangelst = 99999; datfile.seekg(startrec2+64,ios::beg);// datfile.read((char*)&range1st,sizeb4);// range to first pix range1st = ntohl(range1st); // bk 6 jul 2000, byteorder x86 machines. datfile.seekg(startrec2+72,ios::beg);// datfile.read((char*)&rangelst,sizeb4);// range to last pix rangelst = ntohl(rangelst); // bk 6 jul 2000, byteorder x86 machines. INFO << "range1st: " << range1st; INFO.print(); INFO << "rangelst: " << rangelst; INFO.print(); bool increasing_pix = true;// assume this if (range1st < rangelst)// increase { INFO.print("INCREASE pixel direction detected (OK)."); } else // decrease: flip data left-right { WARNING.print("DECREASE pixel direction detected: I will flip left-right the RSAT data"); increasing_pix = false; } // ====== Process requested lines ====== ofstream datoutfile; openfstream(datoutfile,crop_arg.fileout1,generalinput.overwrit); bk_assert(datoutfile,crop_arg.fileout1,__FILE__,__LINE__); // ______ info on data, to avoid X86 problems ______ // ______ according to RSAT CEOS specs, byte 192-195 is first complex pixel, etc. ______ datfile.seekg(lenrec1+192,ios::beg); matrix TMPSHORT(1,2); datfile >> TMPSHORT; // read in first complex pixel for test real8 tmpmag = sqrt( real8(int16(ntohs(TMPSHORT(0,0)))*int16(ntohs(TMPSHORT(0,0)))) + real8(int16(ntohs(TMPSHORT(0,1)))*int16(ntohs(TMPSHORT(0,1))))); DEBUG << "First complex element in datafile: (" << int16(ntohs(TMPSHORT(0,0))) << "," << int16(ntohs(TMPSHORT(0,1))) << "); mag = " << tmpmag; DEBUG.print(); if (tmpmag > 10000.) { WARNING.print(DEBUG.get_str()); WARNING.print("this is a byteorder problem on X86? (use ntohs)"); } DEBUG << "TEST: (realpart): " << TMPSHORT(0,0) << ", (imagpart): " << TMPSHORT(0,1); DEBUG.print(); DEBUG << "TEST: htons(realpart): " << htons(TMPSHORT(0,0)) << ", htons(imagpart): " << htons(TMPSHORT(0,1)); DEBUG.print(); DEBUG << "TEST: ntohs(realpart): " << ntohs(TMPSHORT(0,0)) << ", ntohs(imagpart): " << ntohs(TMPSHORT(0,1)); DEBUG.print(); DEBUG << "TEST: short int(ntohs(realpart)): " << int16(ntohs(TMPSHORT(0,0))) << ", (imagpart): " << int16(ntohs(TMPSHORT(0,1))); DEBUG.print(); // --- Simple way pix by pix reading so we can easily flip if req. --- datfile.seekg(lenrec1+(linestart-1)*lendatarec2+8,ios::beg); datfile.read((char*)&lenrec2,sizeb4); // length of first record lenrec2 = ntohl(lenrec2); // bk 6 jul 2000, byteorder x86 machines. if (lenrec2 != lendatarec2) { ERROR << "code 904: Length of datarecords seems to be inconsistent in file: " << crop_arg.filein1 << ": " << lenrec2 << " != " << lendatarec2; WARNING.print(ERROR.get_str()); ERROR.reset(); } // ______ Note complex not in ANSI c ______ int32 percentage = 0; // initialization const int32 TENPERCENT = int32((5+numlines)/10); // number of lines for (register int32 linecnt=linestart; linecnt<=lineend; linecnt++) { // 03/2009 AH //int32 line2read = (increasing_line==true) ? linecnt : lineend-(linecnt-linestart); int32 line2read = (increasing_line==true) ? linecnt : orig_numlines-linecnt+1; for (register int32 pixcnt=pixelstart; pixcnt<=pixelend; pixcnt++) { // 03/2009 AH //int32 pix2read = (increasing_pix==true) ? pixcnt : pixelend-(pixcnt-pixelstart); int32 pix2read = (increasing_pix==true) ? pixcnt : orig_numpixels-pixcnt+1; // --- set pointer before complex pixel to read --- uint tmpstart = lenrec1+192+(line2read-1)*lendatarec2+(pix2read-1)*4; datfile.seekg(tmpstart,ios::beg); datfile >> TMPSHORT; // ______ BK 13 July 2000: swapbytes for X86 (intel) linux cpus ______ #ifdef __X86PROCESSOR__ TMPSHORT(0,0) = int16(ntohs(TMPSHORT(0,0)));// byteswap TMPSHORT(0,1) = int16(ntohs(TMPSHORT(0,1)));// byteswap #endif datoutfile << TMPSHORT; } if (!((linecnt-linestart)%TENPERCENT)) { PROGRESS << "radarsat_dump_data: " << setw(3) << percentage << "%"; PROGRESS.print(); percentage += 10; } } datfile.close(); // close files datoutfile.close(); // ====== Write results to scratchfile ====== ofstream scratchresfile("scratchres2raw", ios::out | ios::trunc); bk_assert(scratchresfile,"writeslc: scratchres2raw",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************\n"; if (crop_arg.fileid == MASTERID) scratchresfile << "*_Start_" << processcontrol[pr_m_crop]; if (crop_arg.fileid == SLAVEID) scratchresfile << "*_Start_" << processcontrol[pr_s_crop]; scratchresfile << "\t\t\t" << crop_arg.idcrop << "\n*******************************************************************" << "\nData_output_file: \t\t\t\t" << crop_arg.fileout1 << "\nData_output_format: \t\t\t\t" << "complex_short" // ______ updateslcimage greps these ______ << "\nFirst_line (w.r.t. original_image): \t\t" << linestart << "\nLast_line (w.r.t. original_image): \t\t" << lineend << "\nFirst_pixel (w.r.t. original_image): \t\t" << pixelstart << "\nLast_pixel (w.r.t. original_image): \t\t" << pixelend << "\nNumber of lines (non-multilooked): \t\t" << lineend-linestart+1 << "\nNumber of pixels (non-multilooked): \t\t" << pixelend-pixelstart+1 << "\n*******************************************************************"; if (crop_arg.fileid == MASTERID) scratchresfile << "\n* End_" << processcontrol[pr_m_crop] << "_NORMAL"; if (crop_arg.fileid == SLAVEID) scratchresfile << "\n* End_" << processcontrol[pr_s_crop] << "_NORMAL"; scratchresfile << "\n*******************************************************************" << endl; scratchresfile.close(); // ______ Tidy up do checks here ______ if (numchannels != 1) // ?? { WARNING << "code 904: Number of channels in file: " << crop_arg.filein1 << " = " << numchannels << " != 1 "; WARNING.print(); WARNING.print("this means SLC FORMAT IS DIFFERENT THEN EXPECTED."); } if (bottomborder != topborder != leftborder != rightborder != 0) { WARNING << "code 904: Not implemented: offset border: left,right,bottom,top: " << leftborder << "," << rightborder << "," << bottomborder << "," << topborder << " in file: " << crop_arg.filein1; WARNING.print(); WARNING.print("this means SLC FORMAT IS DIFFERENT THEN EXPECTED."); } PROGRESS.print("radarsat_dump_data: 100%"); } // END radarsat_dump_data //____RaffaeleNutricato START MODIFICATION SECTION 2 /**************************************************************** * OversampleSLC * * * * Oversamples the SLC by an integer factor. * * For now only range oversampling is performed. * * Raffaele Nutricato, 12-Jan-2004 * * Azimuth oversampling with factor 2 added. * * Bert Kampes, 30-Jul-2005 * ***************************************************************/ void OversampleSLC( const input_gen &generalinput, const slcimage &imageinfo, const input_oversample &oversampleinput, const int16 fileid) { TRACE_FUNCTION("OversampleSLC (Raffaele Nutricato 12-Jan-2004)") //char infile[EIGHTY]; // Input file which is master/slave.raw renamed as .old //char outfile[EIGHTY]; // Output file which is the oversampled version. char infile[2*ONE27]; // Input file which is master/slave.raw renamed as .old // MA char outfile[2*ONE27]; // Output file which is the oversampled version. strcpy(infile,imageinfo.file); strcpy(outfile,oversampleinput.fileoutovs); const int32 OsrRange = oversampleinput.OsrRange; // Range oversampling ratio. const int32 OsrAzimuth = oversampleinput.OsrAzimuth; // Azimuth oversampling ratio. const int32 FilterSize = oversampleinput.FilterSize; // Length of the kernel for the oversampling in range. if (OsrAzimuth!=1 && OsrAzimuth!=2) { ERROR.print("oversampling in azimuth: only factor 2"); throw(some_error); } // ______Open input file_____ ifstream ifile; openfstream(ifile,infile); bk_assert(ifile,infile,__FILE__,__LINE__); // ______Open output file_____ ofstream ofile; openfstream(ofile,outfile,generalinput.overwrit); bk_assert(ofile,outfile,__FILE__,__LINE__); // ______ Compute the size of original cropped image ______ //const int32 numlines = imageinfo.currentwindow.lines(); //const int32 numpixels = imageinfo.currentwindow.pixels(); const uint numlines = imageinfo.currentwindow.lines(); // MA const uint numpixels = imageinfo.currentwindow.pixels(); // ______ Define the accuracy of the digital signal processings ______ // ______ in range (in azimuth I use float, BK ______ #define RN_DSP_ACCURACY double #define RN_DSP_CPXACCURACY complr8 // ______ Interpolation kernel section ______ matrix LINE_IN(1,OsrRange*(numpixels-1)+1);// zero alternating matrix LINE_OUT(1,OsrRange*numpixels);// ovs line const int32 interp_size = FilterSize * OsrRange - 1; matrix INTERP_KERNEL(1,interp_size); // ______ Generate the range interpolator impulse response ______ const RN_DSP_ACCURACY invosr = 1.0/RN_DSP_ACCURACY(OsrRange); RN_DSP_ACCURACY interpsamplepos = invosr - RN_DSP_ACCURACY(FilterSize)/2.0; for (int32 i=0; i BUFFER_AZ(NP_kernel_az,LINE_OUT.pixels());// rotating buffer matrix KERNEL_AZ(NP_kernel_az,LINE_OUT.pixels());// raised cosine matrix LINE_OUT2(1,LINE_OUT.pixels());// interpolated in azi. if (OsrAzimuth!=1) { INFO.print("Initializing azimuth kernel"); const real4 CHI = imageinfo.prf/imageinfo.abw;// oversampling factor az matrix x_axis(NP_kernel_az,1); for (int32 i=0; i tmp_kernel = mat2cr4(rc_kernel(x_axis, CHI, NP_kernel_az)); DEBUG.print("Normalizing kernel"); real4 qsum = 0.0; for (int32 i=0; i bufferrreal4(1,1); matrix bufferrimag4(1,1); for (int32 ii=0; ii> bufferrreal4; ifile >> bufferrimag4; // ______Generate a zero filled copy of LINE______ // RN LINE_IN must be cleaned!!! LINE_IN(0,OsrRange*ii) = RN_DSP_CPXACCURACY(bufferrreal4(0,0),bufferrimag4(0,0)); } break; } // ______ Convert first to ci2 before writing to file ______ case FORMATCI2: { matrix bufferrealint16(1,1); matrix bufferimagint16(1,1); for (int32 ii=0; ii> bufferrealint16; ifile >> bufferimagint16; // ______Generate a zero filled copy of LINE______ // RN LINE_IN must be cleaned!!! LINE_IN(0,OsrRange*ii) = RN_DSP_CPXACCURACY(bufferrealint16(0,0),bufferimagint16(0,0)); } break; } default: PRINT_ERROR("Unknown input format for the cropped image."); throw(unhandled_case_error); }// end switch reading input line // ______Spatial convolution between LINE_IN and INTERP_KERNEL______ int jmin, jmax, RN_k, minpos, maxpos; RN_k = 0; minpos = (interp_size-1)/2; maxpos = (interp_size-1)/2 + (LINE_IN.pixels() - 1) + OsrRange - 1; for (int ii=minpos; ii<=maxpos; ii++) { LINE_OUT(0,RN_k) = 0; jmin = max(int32(0), int32(ii-interp_size+1)); jmax = min(int32(ii),int32(LINE_IN.pixels()-1)); for (int j=jmin; j<=jmax; j++) LINE_OUT(0,RN_k) += LINE_IN(0,j) * INTERP_KERNEL(0,ii-j); RN_k++; } // ______ Oversample in azimuth ______ // ______ e.g., kernel is 6 points, buffer is 6 lines ______ // ______ if linecnt==5, then buffer is filled with ______ // ______ first 6 lines of file. LINE_OUT2 is the ______ // ______ interpolated line at BUFFER[2.5,*], i.e., ______ // ______ to write in correct order each time we write ______ // ______ BUFFER[2,*] and LINE_OUT2[*]; not 5 and 5.5 ______ // ______ To correct for this offset, we do: ______ // ______ linecnt==0: do not write (add at end) // ______ linecnt==1: do not write (add at end) // ______ linecnt==2: do not write (add at end) // ______ linecnt==3: write 0 and 0.5 // ______ linecnt==4: write 1 and 1.5 // ______ linecnt==5: write 2 and 2.5 // ______ linecnt==6: write etc. // ______ linecnt==last: write last + 6 extra lines. if (OsrAzimuth!=1)//i.e., 2 { // ______ Rotating BUFFER_AZ ______ // ______ I dont trust shifting pointers so I copy lines ______ // ______ this is slower, but guarantees continuous in mem. ______ for (int32 x=0; x=NP_kernel_az/2) { // _____ write line 2.0 ______ for (int ii=0; ii=NP_kernel_az/2) { // _____ write line 2.0 ______ for (int ii=0; iinumlines) { WARNING << "Specified input DBOW linehi > numlines: " << crop_arg.dbow.linehi << " > " << numlines << ". I set linehi = " << numlines; WARNING.print(); tempdbow.linehi=numlines; } if (crop_arg.dbow.pixhi>numpixels) { WARNING << "Specified input DBOW pixhi > numpixels: " << crop_arg.dbow.pixhi << " > " << numpixels << ". I set pixhi = " << numpixels; WARNING.print(); tempdbow.pixhi=numpixels; } // ______ Only hi values are possibly adapted, low is a constant ______ numlines = tempdbow.linehi - crop_arg.dbow.linelo + 1; numpixels = tempdbow.pixhi - crop_arg.dbow.pixlo + 1; linestart = crop_arg.dbow.linelo; lineend = tempdbow.linehi; pixelstart = crop_arg.dbow.pixlo; pixelend = tempdbow.pixhi; // only for resultfile } // ______ Note complex not in ANSI c ______ // matrix LINE(1,2*numpixels); // size of real4 // ====== Process requested lines ====== ofstream datoutfile; openfstream(datoutfile,crop_arg.fileout1,generalinput.overwrit); bk_assert(datoutfile,crop_arg.fileout1,__FILE__,__LINE__); // ______ info on data, to avoid X86 problems ______ // ______ according to CEOS specs, byte 413 is first complex pixel, etc. ______ // 720 + 84124*linenum + 412 datfile.seekg(lenrec1 + 412,ios::beg); matrix TMPREAL4(1,2); datfile >> TMPREAL4; // read in first complex pixel for test real8 tmpmag = sqrt( real8(real4(ntohl(TMPREAL4(0,0)))*real4(ntohl(TMPREAL4(0,0)))) + real8(real4(ntohl(TMPREAL4(0,1)))*real4(ntohl(TMPREAL4(0,1))))); DEBUG << "First complex element in datafile: (" << real4(ntohl(TMPREAL4(0,0))) << "," << real4(ntohl(TMPREAL4(0,1))) << "); mag = " << tmpmag; DEBUG.print(); if (tmpmag > 10000.) { WARNING.print(DEBUG.get_str()); WARNING.print("this is a byteorder problem on X86? (use ntohs)"); } DEBUG << "TEST: (realpart): " << TMPREAL4(0,0) << ", (imagpart): " << TMPREAL4(0,1); DEBUG.print(); DEBUG << "TEST: htons(realpart): " << ntohl(TMPREAL4(0,0)) << ", htons(imagpart): " << ntohl(TMPREAL4(0,1)); DEBUG.print(); DEBUG << "TEST: ntohs(realpart): " << ntohl(TMPREAL4(0,0)) << ", ntohs(imagpart): " << ntohl(TMPREAL4(0,1)); DEBUG.print(); DEBUG << "TEST: short int(ntohs(realpart)): " << real4(ntohl(TMPREAL4(0,0))) << ", (imagpart): " << real4(ntohl(TMPREAL4(0,1))); DEBUG.print(); // ====== perline is faster than perbuffer, less memory etc. BK1998 ====== datfile.seekg(lenrec1+(linestart-1)*lendatarec2 + 8,ios::beg); datfile.read((char*)&lenrec2,sizeb4); // length of first record lenrec2 = ntohl(lenrec2); // bk 6 jul 2000, byteorder x86 machines. if (lenrec2 != lendatarec2) { ERROR << "code 904: Length of datarecords seems to be inconsistent in file: " << crop_arg.filein1 << ": " << lenrec2 << " != " << lendatarec2; WARNING.print(ERROR.get_str()); ERROR.reset(); } const int32 TEN = 10; const int32 TENPERCENT = int32((.5*TEN+numlines)/TEN); // number of lines int32 percentage = 0; // initialization const int32 tmpstart = lenrec1+412-lendatarec2+(pixelstart-1)*8; // sizeof=8 char pD,*pc; for (register int32 linecnt=linestart; linecnt<=lineend; linecnt++) { if (!((linecnt-linestart)%TENPERCENT)) { PROGRESS << "WRITESLC: " << setw(3) << percentage << "%"; PROGRESS.print(); percentage += TEN; } datfile.seekg(tmpstart+linecnt*lendatarec2,ios::beg); datfile >> LINE; // ______ LG 28 DEC 2005: swapbytes for X86 (intel) linux cpus ______ #ifdef __X86PROCESSOR__ for (int ii=0; ii 1000 #pragma once #endif // _MSC_VER > 1000 #include "constants.hh" // typedefs #include "readinput.hh" // input structs // ______prototypes______ void readvolume( input_readfiles &readfiles_arg, const char *chk1, const char *chk2, const char *chk3); void readleader( input_readfiles &readfiles_arg, const int32 check); // process leader file void readnull( const input_readfiles &readfiles_arg); // process null file void readdat( input_readfiles &readfiles_arg, const int32 check); // Modified by LG for reading ALOS Fine void palsar_fine_dump_data( const input_gen &generalinput, const input_crop &writeslc_arg, const int32 check); void writeslc( const input_gen &generalinput, // mem/ overwrite const input_crop &writeslc_arg, const int32 check); // process data file void envisat_dump_data( const input_crop &writeslc_arg); void envisat_dump_VV( const input_crop &writeslc_arg); void envisat_dump_HH( const input_crop &writeslc_arg); void tsx_dump_data( const input_crop &writeslc_arg); void rs2_dump_data( const input_crop &writeslc_arg); void csk_dump_data( const input_crop &writeslc_arg); void radarsat_dump_data( const input_gen &generalinput, // mem/ overwrite const input_crop &writeslc_arg); // BO.20100917 void gammaprocessor_crop( const input_gen &generalinput, // mem/ overwrite const slcimage &master, const input_crop &writeslc_arg); void OversampleSLC( const input_gen &generalinput, const slcimage &imageinfo, const input_oversample &oversampleinput, const int16 fileid); #endif // READDATA_H Doris-5.0.3Beta/doris_core/readinput.cc000077500000000000000000010755341312547014700200530ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/readinput.cc,v $ * $Revision: 3.36 $ * $Date: 2009/01/09 11:09:20 $ * $Author: TUDelft $ * * implementation of readinput. ****************************************************************/ #include "matrixbk.hh" #include "constants.hh" // global constants #include "ioroutines.hh" // ? #include "utilities.hh" // ispower2 #include "exceptions.hh" // my exceptions class #include // for file streams #include // for file streams #include // for setprecision etc. #include // for strcmp etc. #include // exit, atoi #include // isspace // ______ displevel used in ioroutines.h, changed here ______ char WARNS[6][ONE27]; // remember 6 last warnings in WARNS int32 beeplevel=1; // global variable for beeping. // 0: nobeep; BEEP OFF // -1: beep on error exit ; BEEP ERROR // 1: beep on error, warnings; BEEP WARNING // 2: beep on error, warnings, progress; // BEEP PROGRESS, BEEP [ON] int32 displevel=30000; // controls level of screen output // -100 only errors // 0: warnings and errors // 10000: progress, warn and err // 20000: info, pro, warn and err // 30000: debug, info, pro, warn, err // ______ Checks input prototypes (see below in this file) ______ void checkgeneral (input_gen &generalinput, const int16 onlyprocess); void checkreadfiles (const input_readfiles &readfilesinput, const int16 id); void checkcrop (const input_crop &cropinput, const int16 id); //____RaffaeleNutricato START MODIFICATION SECTION 1 void checkoversample (const input_oversample &oversampleinput, const int16 id); //____RaffaeleNutricato END MODIFICATION SECTION 1 void checkporbits (const input_pr_orbits &porbitsinput, const int16 id); void checksimamp (const input_simamp &simampinput); //[MA] ?nec. id check? void checkmtiming (const input_mtiming &mtiminginput); //[MA] ?nec. id check? void checkslant2h (const input_slant2h &slant2hinput); void checkunwrap (const input_unwrap &unwrapinput); void checkgeocode (const input_geocode &geocodeinput); void checkcoarsecorr (const input_coarsecorr &coarsecorrinput); void checkfine (const input_fine &fineinput); void checkreltiming (const input_reltiming &reltiminginput); //[FvL] void checkdemassist (const input_demassist &demassistinput); //[FvL] void checkcoregpm (const input_coregpm &coregpminput); void checkcomprefpha (const input_comprefpha &comprefphainput); void checksubtrrefpha (const input_subtrrefpha &subtrrefphainput); void checkresample (const input_resample &resampleinput); void checkinterfero (const input_interfero &interferoinput); void checkcoherence (const input_coherence &coherenceinput); void checkcomprefdem (const input_comprefdem &comprefdeminput); void checksubtrrefdem (const input_subtrrefdem &subtrrefdeminput); void checkfiltrange (const input_filtrange &filtrangeinput); void checkdinsar (const input_dinsar &dinsarinput); void checkfiltphase (const input_filtphase &filtphaseinput); void checkfiltazi (const input_filtazi &filtaziinput, const int16 id); /**************************************************************** * writearg * * echo arg to screen if debug defined * #%// BK 13-Jul-2000 * ****************************************************************/ template void writearg(const Type argument) { TRACE_FUNCTION("writearg"); DEBUG << "Read argument: " << argument; DEBUG.print(); } // END writearg /**************************************************************** * readinput * * * * Read and interpret * * "inputoptionsfile" (file in variable: logfile). * * Write to logfile (via "scratchreadinput") * * mandatory input is checked on presence by checksums (cs). * * If there are more methods, process card switches default * * methodselector (if present) is used later to correct * * see for example unwrap methodeselector * * linecounter only used in case of errors * * * * input: * * - struct: general input options * * - struct: master readfiles input options * * - struct: slave readfiles input options * * - struct: master crop input options * * - struct: slave crop input options * * - ... * * output: * * - (updated input structs) * * - (file copy of input) * * * * Bert Kampes, 11-Dec-1998 * * Mahmut Arikan, 09-Jan-2009 (code to fix linecnt bug * * G.J. van Zwieten, 09-Jan-2009 and line extend ) * * Mahmut Arikan, 29-Aug-2010 Fix: Read only those prms * * for processing * ****************************************************************/ void readinput( input_gen &generalinput, input_ell &ellipsinput, input_pr_orbits &porbitsinput, input_readfiles &m_readfilesinput, input_morbits &morbitsinputmaster, // [HB] input_crop &m_cropinput, //____RaffaeleNutricato START MODIFICATION SECTION 2 input_oversample &m_oversample, input_simamp &simampinput, // master simamp [FvL],[MA] input_mtiming &mtiminginput, // mtiming correl [MA] //____RaffaeleNutricato END MODIFICATION SECTION 2 input_readfiles &s_readfilesinput, input_morbits &morbitsinputslave, // [HB] input_crop &s_cropinput, //____RaffaeleNutricato START MODIFICATION SECTION 3 input_oversample &s_oversample, //____RaffaeleNutricato END MODIFICATION SECTION 3 input_filtazi &filtaziinput, input_coarsecorr &coarsecorrinput, // input_deramp &derampinput, //MCC input_fine &fineinput, input_reltiming &reltiminginput, //[FvL] input_demassist &demassistinput, //[FvL] input_coregpm &coregpminput, input_resample &resampleinput, input_filtrange &filtrangeinput, input_interfero &interferoinput, input_coherence &coherenceinput, input_comprefpha &comprefphainput, input_subtrrefpha &subtrrefphainput, input_comprefdem &comprefdeminput, input_subtrrefdem &subtrrefdeminput, input_filtphase &filtphaseinput, input_dinsar &dinsarinput, input_unwrap &unwrapinput, input_estorbits &estorbitsinput, // [HB] input_slant2h &slant2hinput, input_geocode &geocodeinput) { //TRACE_FUNCTION("readinput (BK 11-Dec-1998)"); TRACE_FUNCTION("readinput rev.5 (TUDelft 29-Aug-2010)"); // ______ Set ids ______ m_readfilesinput.fileid = MASTERID; m_cropinput.fileid = MASTERID; s_readfilesinput.fileid = SLAVEID; s_cropinput.fileid = SLAVEID; // ______ Misuse generalinput.logfile to store name: open file here! ______ //ifstream optionsfile(generalinput.logfile, ios::in | ios::nocreate); ifstream optionsfile(generalinput.logfile, ios::in); bk_assert(optionsfile,generalinput.logfile,__FILE__,__LINE__); string inputoptionsfile = generalinput.logfile; // [MA] keep input filename // later variable is updated // as logfile name. int16 onlyprocess = -1; // flag for ONLYPROCESS card int16 linecnt = 0; // counter const int16 BASE10 = 10; // [MA] base 10 defined for strtol //char keyword[EIGHTY]; //char filename[4*ONE27]; // string for filenames // [MA] changed EIGHTY --> 2*ONE27, due to comments line gets longer char eachline[4*ONE27]; // assuming maximum char lenght of the line is 4*ONE27. It should be sufficient. // ______ Check (multiple) occurence of cards ______ bool priorscreen = false; // no screen card present bool priormemory = false; // check if present for info bool priorbatch = false; // check if present for info bool prioroverwrite = false; // check if present for info bool priorlistinput = false; // check if present for info bool priorrs_fileout = false; // // ====== Initialization, defaults ====== input_ell WGS84; bool listinput = true; // default copy input to log bool ellipsoid = false; // set default if no card present ellipsinput = WGS84; // default register int32 i; for (i=0; i(10,2); // morbitsinputmaster.coeff = 0; // default: no modification setunspecified(morbitsinputmaster.reforbitfile); // morbitsinputslave.coeff = matrix(10,2); // morbitsinputslave.coeff = 0; // default: no modification setunspecified(morbitsinputslave.reforbitfile); // // ____ end added by HB ____ filtaziinput.oformatflag = FORMATCR4; // default filtaziinput.fftlength = 1024; // default filtaziinput.overlap = -1; // default to fftlength/8 filtaziinput.hammingalpha = 0.75; // default (slc) strcpy(filtaziinput.fomaster,"master.afilter"); // default strcpy(filtaziinput.foslave,"slave.afilter"); // default const int32 def_cc_nwin = 11; // default #windows setunspecified(coarsecorrinput.ifpositions); // check later, then set default coarsecorrinput.MasksizeL = 64; // default correlation size coarsecorrinput.MasksizeP = coarsecorrinput.MasksizeL;// default correlation size coarsecorrinput.AccL = 8; // default searching limit coarsecorrinput.AccP = coarsecorrinput.AccL; // default searching limit coarsecorrinput.initoffsetL = 0; // default initial offset coarsecorrinput.initoffsetP = 0; // default initial offset //deramp.filein1 setunspecified(fineinput.ifpositions); // check later, then set default const int32 def_fc_nwin = 601; // default #windows fineinput.MasksizeL = 64; // default correlation size fineinput.MasksizeP = fineinput.MasksizeL; // default correlation size fineinput.AccL = 8; // default searching limit fineinput.AccP = fineinput.AccL; // default searching limit fineinput.initoffsetL = 0; // default initial offset fineinput.initoffsetP = 0; // default initial offset fineinput.osfactor = 32; // default oversampling factor fineinput.plotoffsets = false; // default no plotting fineinput.plotmagbg = false; // default no plotting fineinput.plotthreshold = 0.3; // default no plotting fineinput.shiftazi = 1; // [1] shift spectrum to 0 //ADD by MCC for fine CCCoregistration setunspecified(fineinput.forefdem); setunspecified(fineinput.firefdem); fineinput.iformatflag = FORMATI2; // default gtopo30 fineinput.demrows = 6000; // default gtopo30 fineinput.demcols = 4800; // default gtopo30 fineinput.demnodata = -9999; // default gtopo30 fineinput.demdeltalat = deg2rad(0.00833333333333333333);// default gtopo30 fineinput.demdeltalon = deg2rad(0.00833333333333333333);// default gtopo30 fineinput.demlatleftupper = deg2rad(89.995833333333333333); // w020n90.DEM fineinput.demlonleftupper = deg2rad(-19.995833333333333333);// w020n90.DEM //added by MCC for fine CCCoregistration //____ added by FvL ____ reltiminginput.threshold = 0.4; // default threshold data reltiminginput.maxiter = 10000; // default max. 10000 outliers removed reltiminginput.k_alpha = 1.97; // critical value for outliers setunspecified(demassistinput.firefdem); // check later, mandatory setunspecified(demassistinput.fodemi); // check later, then set default setunspecified(demassistinput.forefdemhei); // check later, then set default strcpy(demassistinput.fodem,"demcrop.raw"); // default name demassistinput.iformatflag = FORMATI2; // default gtopo30 demassistinput.demrows = 6000; // default gtopo30 demassistinput.demcols = 4800; // default gtopo30 demassistinput.demnodata = -9999; // default gtopo30 demassistinput.demdeltalat = deg2rad(0.00833333333333333333);// default gtopo30 demassistinput.demdeltalon = deg2rad(0.00833333333333333333);// default gtopo30 demassistinput.demlatleftupper = deg2rad(89.995833333333333333); // w020n90.DEM demassistinput.demlonleftupper = deg2rad(-19.995833333333333333);// w020n90.DEM // ____ end added by FvL ____ coregpminput.threshold = 0.2; // default threshold data coregpminput.degree = 1; // default degree polynomial coregpminput.weightflag = 0; // default no weighting of data coregpminput.maxiter = 10000; // default max. 10000 outliers removed, changed by [FvL] coregpminput.k_alpha = 1.97; // critical value for outliers coregpminput.dumpmodel = false; // default no files coregpminput.plot = false; // default no plots coregpminput.plotmagbg = false; // default no plots filtrangeinput.method = rf_adaptive; // default filtrangeinput.terrainslope = 0.0; // default porbits filtrangeinput.fftlength = -999; // set default later filtrangeinput.overlap = 0; // default no overlap filtrangeinput.nlmean = 15; // default filtrangeinput.hammingalpha = 0.75; // default filtrangeinput.SNRthreshold = 5.0; // default filtrangeinput.oversample = 2; // default filtrangeinput.doweightcorrel = false; // default strcpy(filtrangeinput.fomaster,"master.rfilter"); // default strcpy(filtrangeinput.foslave,"slave.rfilter"); // default filtrangeinput.oformatflag = FORMATCR4; // default setunspecified(comprefphainput.ifpositions); // check later, then set default const int32 def_fe_Npoints = 501; // default const int32 def_fe_degree = 5; // default strcpy(resampleinput.fileout,"s_resampled.raw"); // default resampleinput.oformatflag = FORMATCR4; // default resampleinput.dbow.linelo = 0; // min. line coord. initialization resampleinput.dbow.linehi = 0; // max. line coord. initialization resampleinput.dbow.pixlo = 0; // min. pixel coord. initialization resampleinput.dbow.pixhi = 0; // max. pixel coord. initialization resampleinput.dbow_geo.linelo = 0; // min. line coord. initialization resampleinput.dbow_geo.linehi = 0; // max. line coord. initialization resampleinput.dbow_geo.pixlo = 0; // min. pixel coord. initialization resampleinput.dbow_geo.pixhi = 0; // max. pixel coord. initialization resampleinput.shiftazi = 1; // default [1] apply shift interferoinput.method = int_oldmethod; // default method setunspecified(interferoinput.focint); // check later, then set default setunspecified(interferoinput.foint); // use later if specified //setunspecified(interferoinput.foflatearth); // check later, then set default interferoinput.multilookL = 5; // default multilookfactor interferoinput.multilookP = 1; // default multilookfactor coherenceinput.method = coh_oldmethod; // default method setunspecified(coherenceinput.focoh); // check later, then set default setunspecified(coherenceinput.foccoh); // check later, then set default coherenceinput.multilookL = 10; // default multilookfactor coherenceinput.multilookP = 2; // default multilookfactor coherenceinput.cohsizeL = coherenceinput.multilookL; // default windowsize. coherenceinput.cohsizeP = coherenceinput.multilookP; // default windowsize. subtrrefphainput.method = srp_polynomial; // default method strcpy(subtrrefphainput.forefpha, "refphase.raw"); // default name strcpy(subtrrefphainput.focint,"cint.minrefpha.raw");// default subtrrefphainput.multilookL = 1; // default multilookfactor subtrrefphainput.multilookP = 1; // default multilookfactor subtrrefphainput.dumponlyrefpha = false; // default not //_____ added by FvL setunspecified(subtrrefphainput.foh2ph); // check later, then set default // ____ end added by FvL filtphaseinput.method = fp_goldstein; // default method filtphaseinput.alpha = 0.2; // default // ______ 32 blocks default for goldstein, kernel as large as possible, ______ // ______ 2Dkernel then specify ______ filtphaseinput.blocksize = 32; // default filtphaseinput.overlap = 3; // default // set default later with alpha in name setunspecified(filtphaseinput.fofiltphase); // check later, then set default setunspecified(filtphaseinput.fifiltphase); // if specified, use it setunspecified(filtphaseinput.fikernel2d); // if specified, use it filtphaseinput.finumlines = 0; // numlines. strcpy(dinsarinput.fodinsar,"differentialinterf.raw");// default setunspecified(dinsarinput.foscaleduint); // default no output // ______ set mastertopo file to same as master resfile if not specified ______ setunspecified(dinsarinput.topomasterresfile); // if specified, use 4 pass setunspecified(dinsarinput.toposlaveresfile); // check later, mandatory setunspecified(dinsarinput.topointresfile); // check later, mandatory setunspecified(comprefdeminput.firefdem); // check later, mandatory setunspecified(comprefdeminput.fodemi); // check later, then set default //_____ added by FvL setunspecified(comprefdeminput.foh2ph); // check later, then set default // ____ end added by FvL setunspecified(comprefdeminput.forefdemhei); // check later, then set default strcpy(comprefdeminput.forefdem,"refdem.raw"); // default name strcpy(comprefdeminput.fodem,"demcrop.raw"); // default name [FvL] comprefdeminput.iformatflag = FORMATI2; // default gtopo30 // comprefdeminput.method = crd_trilinear; // default method // comprefdeminput.extradense = 0.5; // default (now interpolated in l,p) comprefdeminput.demrows = 6000; // default gtopo30 comprefdeminput.demcols = 4800; // default gtopo30 comprefdeminput.demnodata = -9999; // default gtopo30 comprefdeminput.demdeltalat = deg2rad(0.00833333333333333333);// default gtopo30 comprefdeminput.demdeltalon = deg2rad(0.00833333333333333333);// default gtopo30 comprefdeminput.demlatleftupper = deg2rad(89.995833333333333333); // w020n90.DEM comprefdeminput.demlonleftupper = deg2rad(-19.995833333333333333);// w020n90.DEM comprefdeminput.isCCC =false; // MCC strcpy(subtrrefdeminput.focint,"cint.minrefdem.raw"); // default name subtrrefdeminput.offsetL = 0; // default no offset subtrrefdeminput.offsetP = 0; // default no offset strcpy(unwrapinput.fouint,"unwrapped_interferogram.raw"); // default name strcpy(unwrapinput.foregions,"regions_unwrapped.raw"); // default name setunspecified(unwrapinput.seedfile); // check later, then set default unwrapinput.deltaLseed = 100; // default 100 pixels; unwrapinput.deltaPseed = unwrapinput.deltaLseed; // default 100 pixels; setunspecified(unwrapinput.snaphu_log);// " " setunspecified(unwrapinput.snaphu_coh);// " " strcpy(unwrapinput.snaphu_mode,"DEFO"); // default to DEFO from TOPO strcpy(unwrapinput.snaphu_init,"MST"); // default method strcpy(unwrapinput.snaphu_verbose,"TRUE"); // default verbose unwrapinput.oformatflag = FORMATR4; // default to // REAL4 from FORMATHGT // block for Tile.CONTROL: only for SNAPHU; defaults for single CPU unwrapinput.ntilerow = 1; // number of tiles in range unwrapinput.ntilecol = 1; // number of tiles in azimuth unwrapinput.rowovrlp = 0; // overlap between tiles in rng unwrapinput.colovrlp = 0; // overlap between tiles in az unwrapinput.nproc = 1; // no.cpus or nodes on load // balancing cluster unwrapinput.tilecostthresh = 500; // cost threshold boundaries of reliable regions slant2hinput.Npoints = 200; // default 100 pixels; slant2hinput.degree1d = 2; // default 2 slant2hinput.degree2d = 5; // default 5 slant2hinput.Nheights = slant2hinput.degree1d+1;// minimum strcpy(slant2hinput.fohei,"hei.raw"); // default strcpy(slant2hinput.fophi,"phi.raw"); // default strcpy(slant2hinput.folam,"lam.raw"); // default strcpy(geocodeinput.fophi,"geo_phi.raw"); // default name strcpy(geocodeinput.folam,"geo_lambda.raw"); // default name // ____ start added by HB ____ estorbitsinput.method = eo_lsq; // default: least squares method setunspecified(estorbitsinput.fiheightmap); // default: use no heights setunspecified(estorbitsinput.foresiduals); // default: no output estorbitsinput.weighting = eo_noweighting; // default: unweighted const uint def_eo_nobs = 1000; // default value, apply later setunspecified(estorbitsinput.ifpositions); // default: no file input estorbitsinput.threshold = 0; // default: ignore coherence estimate estorbitsinput.maxiter = 0; // default: no iteration estorbitsinput.k_alpha = 3.29; // default: norminv(.9995) \approx tinv(.9995,redund) estorbitsinput.maxfringesaz = 15; // estorbitsinput.maxfringesrg = 15; // setunspecified(estorbitsinput.reforbitfile); // default: use master as reference setunspecified(estorbitsinput.foobsdata); // default: do not dump observation data estorbitsinput.poldegree = 1; // estorbitsinput.constrained = true; // default: constrain BPAR0 BPERP1 (define later) // end added by HB ____ // ====== (default) Methods ====== const int16 def_mte_method = cc_magspace; const int16 def_cc_method = cc_magfft; const int16 def_fc_method = fc_magfft; const int16 def_fe_method = fe_porbits; const int16 def_rs_method = rs_cc4p; const int16 def_uw_method = uw_method2;// snaphu, system call, see www const int16 def_s2h_method = s2h_ambiguity; // ______ To check later if default should be used ______ mtiminginput.method = def_mte_method - 999; // default method (repair later) mtiminginput.Nwin = def_mte_nwin + 999; // default #windows coarsecorrinput.method = def_cc_method - 999; // default method (repair later) coarsecorrinput.Nwin = def_cc_nwin + 999; // default #windows fineinput.method = def_fc_method - 999; // default method (repair later) fineinput.Nwin = def_fc_nwin + 999; // default #windows unwrapinput.method = def_uw_method - 999; // default method (repair later) comprefphainput.method = def_fe_method - 999; // default method (repair later) comprefphainput.degree = def_fe_degree - 999; // default degree polynomial comprefphainput.Npoints = def_fe_Npoints - 999; // default degree polynomial resampleinput.method = def_rs_method - 999; // default method (repair later) slant2hinput.method = def_s2h_method - 999; // default method (repair later) estorbitsinput.nobs = 0; // set default later // ====== Process "inputoptionsfile" ====== bool continuereading = true; //while (! optionsfile.eof()) // read file until end of file. //while (continuereading || ! optionsfile.eof()) // read file until STOP card or if fails exit at end of the file while (continuereading) // read file until STOP card { linecnt++; optionsfile.getline(eachline,4*ONE27,'\n'); // get line. [MA] if the line is longer than 4*ONE27 then loops forever. //cerr << "line: " << linecnt << " : " << eachline << endl; if ( optionsfile.eof() ) // && strcmp(keyword,"STOP") ) // [MA] STOP is missing { ERROR << "STOP: \t is missing" << " in file '" << inputoptionsfile << "'"; PRINT_ERROR(ERROR.get_str()) WARNING.print("Please make sure the inputfile line: STOP has ended with [eol] character"); throw(keyword_error); continuereading = false; // break while loop } const int maxwords = 8; // [GJ, MA] char *word[ maxwords ]; char *c = eachline; for ( int i = 0; i < maxwords; i++ ) { while ( *c == ' ' || *c == '\t' ) // get rid of leadin white space { c++; // next address } word[ i ] = c; // pass first char address of a word while ( *c != ' ' && *c != '\t' && *c != '\0' ) { c++; } if ( *c != '\0' ) // at last char { *c = '\0'; c++; } } char *keyword = word[0]; // start off with the card. // word[1] --> first argument // word[2] --> second argument and so on. toupper(keyword); DEBUG << linecnt << ": Read keyword: " << keyword; DEBUG.print(); // ******************************************************************* // *** GENERAL // ******************************************************************* if (!strcmp(keyword,"COMMENT") || !strcmp(keyword,"C")) { ; // comment: no action } else if (!strncmp(keyword,"//",2) || // assume user comments out !strncmp(keyword,"#",1)) // with // or '#' as delimiter { // but no blank after keyword ; // comment: no action } //else if (!strncmp(keyword,'\0',1)) // empty line? crashes else if (!strlen(keyword)) // empty line { ; // comment: no action } // ********************************************************************** else if (!strcmp(keyword,"BEEP")) // level of beep output (THE CARD) { // /progress/[warning]/error/ON/OFF //keyword = word[1] ; // pass keyword // argument //writearg((char*)keyword); keyword = word[1]; // pass next word (the argument) writearg(keyword); toupper(keyword); if (!strcmp(keyword,"ERROR")) { TRACE.bellrings(0); DEBUG.bellrings(0); INFO.bellrings(0); PROGRESS.bellrings(0); WARNING.bellrings(0); ERROR.bellrings(1); beeplevel = -1; INFO.print("BEEP: \tbeeping enabled at level: \tERROR"); } else if (!strcmp(keyword,"PROGRESS")) { TRACE.bellrings(0); DEBUG.bellrings(0); INFO.bellrings(0); PROGRESS.bellrings(1); WARNING.bellrings(2); ERROR.bellrings(3); beeplevel = 2; INFO.print("BEEP: \tbeeping enabled at level: \tPROGRESS"); } else if (!strcmp(keyword,"WARNING")) { TRACE.bellrings(0); DEBUG.bellrings(0); INFO.bellrings(0); PROGRESS.bellrings(0); WARNING.bellrings(1); ERROR.bellrings(2); beeplevel = 1; INFO.print("BEEP: \tbeeping enabled at level: \tWARNING"); } else if (!strcmp(keyword,"OFF")) { TRACE.bellrings(0); DEBUG.bellrings(0); INFO.bellrings(0); PROGRESS.bellrings(0); WARNING.bellrings(0); ERROR.bellrings(0); beeplevel = 0; INFO.print("BEEP: \tbeeping disabled"); } else if (!strcmp(keyword,"ON") || !strncmp(keyword,"//",2) || // comment !strncmp(keyword,"#",1) || // comment //!strcmp(keyword,\'\\0\')) !(keyword[0] == '\0')) // no keyword // !strcmp(keyword,"")) // no keyword { TRACE.bellrings(0); DEBUG.bellrings(0); INFO.bellrings(0); PROGRESS.bellrings(1); WARNING.bellrings(2); ERROR.bellrings(3); beeplevel = 2; INFO.print("BEEP: \tbeeping enabled for all levels: \tON"); } else { beeplevel = 1; TRACE.bellrings(0); DEBUG.bellrings(0); INFO.bellrings(0); PROGRESS.bellrings(0); WARNING.bellrings(1); ERROR.bellrings(2); WARNING << "BEEP: line " << linecnt << ": Argument " << keyword << " not recognized." << " [error/warning/progress/on/off] I used WARNING."; WARNING.print(); } } // BEEP key // ********************************************************************** else if (!strcmp(keyword,"SCREEN")) // level of screen output { // debug/info/progress/warning or error switch (priorscreen) { case true: WARNING << "SCREEN: line " << linecnt << ": stdout: " << " ignored due to prior occurence."; WARNING.print(); break; default: priorscreen = true; //keyword = word[1] ; // pass keyword // argument keyword = word[1]; // argument writearg(keyword); toupper(keyword); if (!strcmp(keyword,"INFO")) { TRACE.doprint(0); DEBUG.doprint(0); INFO.doprint(1); PROGRESS.doprint(1); WARNING.doprint(1); ERROR.doprint(1); displevel = 20000 + displevel%10000; // for cnt #warnings INFO.print("SCREEN: \tverboseness: \t\t\tINFO"); } else if (!strcmp(keyword,"PROGRESS")) { TRACE.doprint(0); DEBUG.doprint(0); INFO.doprint(1); PROGRESS.doprint(1); WARNING.doprint(1); ERROR.doprint(1); displevel = 10000 + displevel%10000; // for cnt #warnings INFO.print("SCREEN: \tverboseness: \t\t\tPROGRESS"); } else if (!strcmp(keyword,"DEBUG")) { TRACE.doprint(0); DEBUG.doprint(1); INFO.doprint(1); PROGRESS.doprint(1); WARNING.doprint(1); ERROR.doprint(1); displevel = 30000 + displevel%10000; // for cnt #warnings INFO.print("SCREEN: \tverboseness: \t\t\tDEBUG"); } else if (!strcmp(keyword,"TRACE")) { TRACE.doprint(1); DEBUG.doprint(1); INFO.doprint(1); PROGRESS.doprint(1); WARNING.doprint(1); ERROR.doprint(1); } else if (!strcmp(keyword,"WARNING")) { TRACE.doprint(0); DEBUG.doprint(0); INFO.doprint(0); PROGRESS.doprint(0); WARNING.doprint(1); ERROR.doprint(1); displevel = 0 + displevel%10000; // for cnt #warnings; INFO.print("SCREEN: \tverboseness: \t\t\tWARNING"); } else if (!strcmp(keyword,"ERROR")) { TRACE.doprint(0); DEBUG.doprint(0); INFO.doprint(0); PROGRESS.doprint(0); WARNING.doprint(0); ERROR.doprint(1); displevel = -100 + displevel%10000; // for cnt #warnings INFO.print("SCREEN: \tverboseness: \t\t\tERROR"); } else { TRACE.doprint(0); DEBUG.doprint(1); INFO.doprint(1); PROGRESS.doprint(1); WARNING.doprint(1); ERROR.doprint(1); WARNING << "SCREEN: line " << linecnt << ": Argument " << keyword << " not recognized." << " [error/warning/progress/info/debug] I used DEBUG."; WARNING.print(); displevel = 30000 + displevel%10000; // for cnt #warnings } } // switch } // SCREEN key // ********************************************************************** else if (!strcmp(keyword,"MEMORY")) // available mem in MB for processing in buffers { switch (priormemory) { case true: WARNING << "MEMORY: line " << linecnt << ": ignored due to prior occurence."; WARNING.print(); break; default: priormemory = true; //generalinput.memory = word[1] ; // pass keyword keyword = word[1]; char *pLast = NULL; //generalinput.memory = uint(strtod( keyword, &pLast )); // [MA] try strtoul( keyword, &pLast, 10 ) for uint generalinput.memory = strtod( keyword, &pLast ); if ( pLast == keyword ) // fail { ERROR << "memory argument: " << keyword << " is not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(generalinput.memory); if (generalinput.memory > real8(MEMORY_MAX)) WARNING << "MEMORY: > " << MEMORY_MAX << " MB seems unlikely."; //generalinput.memory *= 1000000; // in B generalinput.memory *= 1e6; // convert Mb --> b } // switch } // MEMORY card // ********************************************************************** else if (!strcmp(keyword,"BATCH")) // overrides interactive mode { switch (priorbatch) { case true: WARNING << "BATCH: line: " << linecnt << ": " << "ignored due to prior occurence."; WARNING.print(); break; default: priorbatch = true; // flag for occurence // keyword = word[1] ; // pass keyword // argument keyword = word[1]; // pass next word (the argument) writearg(keyword); toupper(keyword); if (!strcmp(keyword,"OFF")) generalinput.interactive = true; else if (!strcmp(keyword,"ON") || !strncmp(keyword,"//",2) || // comment !strncmp(keyword,"#",1) || // comment !(keyword[0] == '\0')) // no keyword generalinput.interactive = false; else { generalinput.interactive = true; WARNING << "BATCH: line: " << linecnt << ": " << "argument: " << keyword << " not recognized, interactive processing."; WARNING.print(); } } // switch } // BATCH key // ********************************************************************** else if (!strcmp(keyword,"OVERWRITE")) { switch (prioroverwrite) { case true: WARNING << "OVERWRITE: line: " << linecnt << ": " << "ignored due to prior occurence."; WARNING.print(); break; default: prioroverwrite = true; // flag for occurence keyword = word[1]; // pass next word (the argument) writearg(keyword); toupper(keyword); if (!strcmp(keyword,"OFF")) generalinput.overwrit = false; else if (!strcmp(keyword,"ON") || !strncmp(keyword,"//",2) || // comment !strncmp(keyword,"#",1) || // comment !(keyword[0] == '\0')) // no keyword generalinput.overwrit = true; else { generalinput.overwrit=false; // don't overwrite files WARNING << "OVERWRITE: line " << linecnt << ": argument: " << keyword << " not recognized, existing files are not overwritten."; WARNING.print(); } } // switch } // OVERWRITE key // ********************************************************************** else if (!strcmp(keyword,"LISTINPUT")) { switch (priorlistinput) { case true: WARNING << "LISTINPUT: line: " << linecnt << ": " << "ignored due to prior occurence."; WARNING.print(); break; default: priorlistinput = true; // flag for occurence keyword = word[1]; // pass next word (the argument) writearg(keyword); toupper(keyword); if (!strcmp(keyword,"OFF")) listinput = false; else if (!strcmp(keyword,"ON") || !strncmp(keyword,"//",2) || // comment !strncmp(keyword,"#",1) || // comment !(keyword[0] == '\0')) // no keyword listinput = true; else { listinput = true; // default list input WARNING << "LISTINPUT: line " << linecnt << ": argument: " << keyword << " not recognized, input will be appended to logfile."; WARNING.print(); } } // switch } // LISTINPUT key // ********************************************************************** else if (!strcmp(keyword,"ONLYPROCESS")) // process only one step { // Read argument and set onlyprocess to value for filling // the flag input array 'process[NUMPROCESSES]' after reading reset input // to avoid interference with PROCESS cards (ONLYPROCESS overrides) // if (onlyprocess == -1) // check multiple occurences { keyword = word[1]; // pass next word (the argument) writearg(keyword); toupper(keyword); if (!strcmp(keyword,"M_READFILES")) onlyprocess=pr_m_readfiles; else if (!strcmp(keyword,"M_CROP")) onlyprocess=pr_m_crop; //____RaffaeleNutricato START MODIFICATION SECTION 5 else if (!strcmp(keyword,"M_OVS")) onlyprocess=pr_m_oversample; //____RaffaeleNutricato END MODIFICATION SECTION 5 else if (!strcmp(keyword,"M_PORBITS")) onlyprocess=pr_m_porbits; else if (!strcmp(keyword,"M_MORBITS")) // [HB] onlyprocess=pr_m_morbits; else if (!strcmp(keyword,"M_SIMAMP")) // [MA] onlyprocess=pr_m_simamp; else if (!strcmp(keyword,"M_TIMING")) onlyprocess=pr_m_mtiming; else if (!strcmp(keyword,"M_FILTAZI")) onlyprocess=pr_m_filtazi; else if (!strcmp(keyword,"FILTRANGE")) { onlyprocess=pr_m_filtrange; onlyprocess=pr_s_filtrange; } else if (!strcmp(keyword,"M_EXTRA")) onlyprocess=pr_m_EXTRA; else if (!strcmp(keyword,"S_READFILES")) onlyprocess=pr_s_readfiles; else if (!strcmp(keyword,"S_MORBITS")) // [HB] onlyprocess=pr_s_morbits; else if (!strcmp(keyword,"S_CROP")) onlyprocess=pr_s_crop; //____RaffaeleNutricato START MODIFICATION SECTION 6 else if (!strcmp(keyword,"S_OVS")) onlyprocess=pr_s_oversample; //____RaffaeleNutricato END MODIFICATION SECTION 6 else if (!strcmp(keyword,"S_PORBITS")) onlyprocess=pr_s_porbits; else if (!strcmp(keyword,"S_FILTAZI")) onlyprocess=pr_s_filtazi; else if (!strcmp(keyword,"RESAMPLE")) onlyprocess=pr_s_resample; else if (!strcmp(keyword,"S_EXTRA")) onlyprocess=pr_s_EXTRA; else if (!strcmp(keyword,"COARSEORB")) onlyprocess=pr_i_coarse; else if (!strcmp(keyword,"COARSECORR")) onlyprocess=pr_i_coarse2; else if (!strcmp(keyword,"FINE")) onlyprocess=pr_i_fine; // see methodselector else if (!strcmp(keyword,"RELTIMING")) // [FvL] onlyprocess=pr_i_timing; else if (!strcmp(keyword,"DEMASSIST")) // [FvL] onlyprocess=pr_i_demassist; else if (!strcmp(keyword,"COREGPM")) onlyprocess=pr_i_coregpm; else if (!strcmp(keyword,"INTERFERO")) onlyprocess=pr_i_interfero; else if (!strcmp(keyword,"COHERENCE")) onlyprocess=pr_i_coherence; else if (!strcmp(keyword,"FILTPHASE")) onlyprocess=pr_i_filtphase; else if (!strcmp(keyword,"COMPREFPHA")) onlyprocess=pr_i_comprefpha; else if (!strcmp(keyword,"SUBTRREFPHA")) onlyprocess=pr_i_subtrrefpha; else if (!strcmp(keyword,"COMPREFDEM")) onlyprocess=pr_i_comprefdem; else if (!strcmp(keyword,"SUBTRREFDEM")) onlyprocess=pr_i_subtrrefdem; else if (!strcmp(keyword,"UNWRAP")) onlyprocess=pr_i_unwrap; // see methodselector else if (!strcmp(keyword,"ESTORBITS")) // [HB] onlyprocess=pr_i_estorbits; else if (!strcmp(keyword,"SLANT2H")) onlyprocess=pr_i_slant2h; else if (!strcmp(keyword,"GEOCODE")) onlyprocess=pr_i_geocoding; else if (!strcmp(keyword,"DINSAR")) onlyprocess=pr_i_dinsar; else if (!strcmp(keyword,"I_EXTRA2")) onlyprocess=pr_i_EXTRA2; else { ERROR << "ONLYPROCESS: line " << linecnt << ": Argument " << keyword << " not recognized."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } INFO << "ONLYPROCESS: \tonly processing step: \t\t" << keyword; INFO.print(); } else { WARNING << "ONLYPROCESS: more than one occurence of card, ignored line: " << linecnt << "."; WARNING.print(); } } // ********************************************************************** else if (!strcmp(keyword,"PROCESS")) // which routine to run { if (onlyprocess+1) // initialized to -1; { WARNING << "PROCESS card on line " << linecnt << " ignored due to presence of ONLYPROCESS card."; WARNING.print(); } else { keyword = word[1]; // pass next word (the argument) writearg(keyword); toupper(keyword); if (!strcmp(keyword,"M_READFILES")) generalinput.process[pr_m_readfiles] = 1; else if (!strcmp(keyword,"M_CROP")) generalinput.process[pr_m_crop] = 1; //____RaffaeleNutricato START MODIFICATION SECTION 7 else if (!strcmp(keyword,"M_OVS")) generalinput.process[pr_m_oversample] = 1; //____RaffaeleNutricato END MODIFICATION SECTION 7 else if (!strcmp(keyword,"M_PORBITS")) generalinput.process[pr_m_porbits] = 1; else if (!strcmp(keyword,"M_MORBITS")) // [HB] generalinput.process[pr_m_morbits] = 1; else if (!strcmp(keyword,"M_SIMAMP")) // [MA] generalinput.process[pr_m_simamp] = 1; else if (!strcmp(keyword,"M_TIMING")) generalinput.process[pr_m_mtiming] = 1; else if (!strcmp(keyword,"M_FILTAZI")) generalinput.process[pr_m_filtazi] = 1; else if (!strcmp(keyword,"FILTRANGE")) { generalinput.process[pr_m_filtrange] = 1; // use for s_ as well generalinput.process[pr_s_filtrange] = 1; } else if (!strcmp(keyword,"M_EXTRA")) generalinput.process[pr_m_EXTRA] = 1; else if (!strcmp(keyword,"S_READFILES")) generalinput.process[pr_s_readfiles] = 1; else if (!strcmp(keyword,"S_MORBITS")) // [HB] generalinput.process[pr_s_morbits] = 1; else if (!strcmp(keyword,"S_CROP")) generalinput.process[pr_s_crop] = 1; //____RaffaeleNutricato START MODIFICATION SECTION 8 else if (!strcmp(keyword,"S_OVS")) generalinput.process[pr_s_oversample] = 1; //____RaffaeleNutricato END MODIFICATION SECTION 8 else if (!strcmp(keyword,"S_PORBITS")) generalinput.process[pr_s_porbits] = 1; else if (!strcmp(keyword,"S_FILTAZI")) generalinput.process[pr_s_filtazi] = 1; else if (!strcmp(keyword,"RESAMPLE")) generalinput.process[pr_s_resample] = 1; else if (!strcmp(keyword,"S_EXTRA")) generalinput.process[pr_s_EXTRA] = 1; else if (!strcmp(keyword,"COARSEORB")) generalinput.process[pr_i_coarse] = 1; else if (!strcmp(keyword,"COARSECORR")) generalinput.process[pr_i_coarse2] = 1; else if (!strcmp(keyword,"FINE")) generalinput.process[pr_i_fine] = 1; else if (!strcmp(keyword,"RELTIMING")) // [FvL] generalinput.process[pr_i_timing] = 1; else if (!strcmp(keyword,"DEMASSIST")) // [FvL] generalinput.process[pr_i_demassist] = 1; else if (!strcmp(keyword,"COREGPM")) generalinput.process[pr_i_coregpm] = 1; else if (!strcmp(keyword,"COMPREFPHA")) generalinput.process[pr_i_comprefpha] = 1; else if (!strcmp(keyword,"SUBTRREFPHA")) generalinput.process[pr_i_subtrrefpha] = 1; else if (!strcmp(keyword,"COMPREFDEM")) generalinput.process[pr_i_comprefdem] = 1; else if (!strcmp(keyword,"SUBTRREFDEM")) generalinput.process[pr_i_subtrrefdem] = 1; else if (!strcmp(keyword,"INTERFERO")) generalinput.process[pr_i_interfero] = 1; else if (!strcmp(keyword,"COHERENCE")) generalinput.process[pr_i_coherence] = 1; else if (!strcmp(keyword,"FILTPHASE")) generalinput.process[pr_i_filtphase] = 1; else if (!strcmp(keyword,"UNWRAP")) generalinput.process[pr_i_unwrap] = 1; else if (!strcmp(keyword,"ESTORBITS")) // [HB] generalinput.process[pr_i_estorbits] = 1; else if (!strcmp(keyword,"SLANT2H")) generalinput.process[pr_i_slant2h] = 1; else if (!strcmp(keyword,"GEOCODE")) generalinput.process[pr_i_geocoding] = 1; else if (!strcmp(keyword,"DINSAR")) generalinput.process[pr_i_dinsar] = 1; else if (!strcmp(keyword,"I_EXTRA2")) generalinput.process[pr_i_EXTRA2] = 1; else { ERROR << "PROCESS: line " << linecnt << ": Argument " << keyword << " not recognized."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } INFO << "PROCESS: \tI will process step: \t\t" << keyword; INFO.print(); } } // ********************************************************************** else if (!strcmp(keyword,"ELLIPSOID")) // ref. system { // inputoptionsfile ellipsoid = true; // use below keyword = word[1]; char *keyword2 = word[2]; writearg(keyword); toupper(keyword); writearg(keyword2); if (!strcmp(keyword,"WGS84")) { ellipsinput = WGS84;// default } else if (!strcmp(keyword,"GRS80")) { WARNING.print("ELLIPS: not ok, sat. ephemerides should be in this system."); input_ell GRS80(6378137.0,6356752.3); GRS80.set_name("GRS80"); ellipsinput = GRS80;// copy } else if (!strcmp(keyword,"BESSEL")) { WARNING.print("ELLIPS: not ok, sat. ephemerides should be in this system."); input_ell BESSEL(6377397.155,6356078.963); BESSEL.set_name("BESSEL"); ellipsinput = BESSEL;// copy } else if (isdigit(keyword2[0])) // likely to be a,b { WARNING.print("ELLIPS: not ok, sat. ephemerides should be in this system."); input_ell ELL_USER_DEFINED(atof(keyword),atof(keyword2));// a,b ELL_USER_DEFINED.set_name("user_defined"); ellipsinput = ELL_USER_DEFINED;// copy if (ellipsinput.a 0)// atoi returns 0 if not convertible { generalinput.orb_interp = degree; INFO << "ORB_INTERP: second argument read: degree = " << degree; INFO.print(); } } else if (!strcmp(keyword,"SPLINE")) { INFO.print("ORB_INTERP: natural cubic splines used fit interpolation"); generalinput.orb_interp = ORB_SPLINE;// natural cubic splines } else { WARNING.print("argument ORB_INTERP not recognized, using polyfit"); generalinput.orb_interp = ORB_DEFAULT;// depends on number of points } } // ********************************************************************** else if (!strcmp(keyword,"ORB_PRM")) // orbit parameters { keyword = word[1]; // pass keyword // argument writearg(keyword); toupper(keyword); if (!strcmp(keyword,"POSITION") || !strcmp(keyword,"POS") ) { INFO.print("ORB_PRM: identified, using position state vectors for orbit interpolation"); generalinput.orb_prm = ORB_PRM_POS;// user positional state vectors only } else if (!strcmp(keyword,"POSVEL")) { INFO.print("ORB_PRM: identified, using positions and velocities for orbit interpolation"); generalinput.orb_prm = ORB_PRM_VEL;// include velocity vectors too } else { WARNING.print("argument ORB_PRM not identified, using position state vectors only (this ignores any velocity column.)"); generalinput.orb_prm = ORB_PRM_POS;// default positional. } } // ********************************************************************** else if (!strcmp(keyword,"DUMPBASELINE")) // eval on grid { // generalinput.dumpbaselineL >> generalinput.dumpbaselineP = word[1] ; // pass keyword keyword = word[1]; char *keyword2= word[2]; // in local scope generalinput.dumpbaselineL = atoi( keyword ) ; generalinput.dumpbaselineP = atoi( keyword2 ); writearg(generalinput.dumpbaselineL); writearg(generalinput.dumpbaselineP); if (generalinput.dumpbaselineL==0 || generalinput.dumpbaselineP==0) { ERROR << "DUMPBASELINE: " << generalinput.dumpbaselineL << " " << generalinput.dumpbaselineP << " line: " << linecnt << ": ==0.\n"; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"PREVIEW")) // system call to cpxfiddle to get SUNraster { //keyword = word[1] ; // pass keyword // argument keyword = word[1]; // argument writearg(keyword); toupper(keyword); if (!strcmp(keyword,"OFF")) { generalinput.preview = 0; INFO.print("PREVIEW: \tOFF: generation of SUNraster files disabled."); } else if (!strcmp(keyword,"XV")) { generalinput.preview = 2; INFO.print("PREVIEW: \tON: generation of SUNraster files enabled + XV sytem call."); } else if (!strcmp(keyword,"ON") || !strncmp(keyword,"//",2) || // comment !strncmp(keyword,"#",1) || // comment !(keyword[0] == '\0')) // no keyword { generalinput.preview = 1; INFO.print("PREVIEW: \tON: generation of SUNraster files enabled."); } else { generalinput.preview = 0; WARNING << "PREVIEW: line: " << linecnt << ": " << "argument: " << keyword << " not recognized, no preview generated."; WARNING.print(); } } // PREVIEW key // ********************************************************************** else if (!strcmp(keyword,"HEIGHT")) // mean height or for CROP { //generalinput.terrain_height = word[1] ; // pass keyword keyword = word[1]; char *pLast = NULL; generalinput.terrain_height = strtod( keyword, &pLast ); if ( pLast == keyword ) // fail { ERROR << "Height argument: " << keyword << " is not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(generalinput.terrain_height); } // ********************************************************************** else if (!strcmp(keyword,"TIEPOINT")) // lat/lon/hei dec.degrees { keyword = word[1]; char *pLast, *pLast2, *pLast3 = NULL; generalinput.tiepoint.x = strtod( keyword, &pLast ); generalinput.tiepoint.y = strtod( word[2], &pLast2 ); // 2nd arg generalinput.tiepoint.z = strtod( word[3], &pLast3 ); // 3rd arg if ( pLast == keyword || pLast2 == word[2] || pLast3 == word[3] ) // fail { ERROR << "Tiepoints: " << keyword << " " << word[2] << " " << word[3] << " are not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(generalinput.tiepoint.x); writearg(generalinput.tiepoint.y); writearg(generalinput.tiepoint.z); } // ********************************************************************** else if (!strcmp(keyword,"STOP")) // STOP interpreting input { INFO.print("STOP: \tEncountered."); DEBUG << "STOP card encountered at line " << linecnt << endl; DEBUG.print(); continuereading = false; // break while loop } // ******************************************************************* // *** ?_READFILES // ******************************************************************* else if (!strcmp(keyword,"M_IN_METHOD")) // ERS or ASAR ENVISAT { //filename = word[1] ; // pass keyword keyword = word[1]; writearg(keyword); toupper(keyword); if (!strcmp(keyword,"ERS")) m_readfilesinput.sensor_id=SLC_ERS; // default ers else if (!strcmp(keyword,"ERS-1")) // ers m_readfilesinput.sensor_id=SLC_ERS; else if (!strcmp(keyword,"ERS1")) // ers m_readfilesinput.sensor_id=SLC_ERS; else if (!strcmp(keyword,"ERS-2")) // ers m_readfilesinput.sensor_id=SLC_ERS; else if (!strcmp(keyword,"ERS2")) // ers m_readfilesinput.sensor_id=SLC_ERS; else if (!strcmp(keyword,"ERS_N1")) // ers in envisat file format [MA]; treat as ASAR //m_readfilesinput.sensor_id=SLC_ASAR; m_readfilesinput.sensor_id=SLC_ERS_N1; else if (!strcmp(keyword,"N1")) // envisat m_readfilesinput.sensor_id=SLC_ASAR; else if (!strcmp(keyword,"ASAR")) // envisat m_readfilesinput.sensor_id=SLC_ASAR; else if (!strcmp(keyword,"ENVISAT")) // envisat m_readfilesinput.sensor_id=SLC_ASAR; else if (!strcmp(keyword,"ASAR_AP_HH")) // envisat Alternating Pol. HH m_readfilesinput.sensor_id=SLC_ASAR_AP_HH; else if (!strcmp(keyword,"ASAR_AP_VV")) // envisat Alternating Pol. VV m_readfilesinput.sensor_id=SLC_ASAR_AP_VV; else if (!strcmp(keyword,"ATLANTIS")) // radarsat ceos reader m_readfilesinput.sensor_id=SLC_RSAT; else if (!strcmp(keyword,"RSAT")) // radarsat m_readfilesinput.sensor_id=SLC_RSAT; else if (!strcmp(keyword,"RADARSAT")) // radarsat m_readfilesinput.sensor_id=SLC_RSAT; else if (!strcmp(keyword,"RADARSAT-1")) // radarsat m_readfilesinput.sensor_id=SLC_RSAT; else if (!strcmp(keyword,"JERS")) // jers m_readfilesinput.sensor_id=SLC_JERS; else if (!strcmp(keyword,"J-ERS")) // jers m_readfilesinput.sensor_id=SLC_JERS; else if (!strcmp(keyword,"ALOS")) // alos FBS [DON] m_readfilesinput.sensor_id=SLC_ALOS; else if (!strcmp(keyword,"TSX")) // TSX [PM] m_readfilesinput.sensor_id=SLC_TSX; else if (!strcmp(keyword,"TERRASARX")) // TSX m_readfilesinput.sensor_id=SLC_TSX; else if (!strcmp(keyword,"TERRASAR-X")) // TSX m_readfilesinput.sensor_id=SLC_TSX; else if (!strcmp(keyword,"RS2")) // RS2 [MA] m_readfilesinput.sensor_id=SLC_RS2; else if (!strcmp(keyword,"RADARSAT-2")) // RS2 m_readfilesinput.sensor_id=SLC_RS2; else if (!strcmp(keyword,"CSK")) // CSK [PD] m_readfilesinput.sensor_id=SLC_CSK; else if (!strcmp(keyword,"CSX")) // CSK [PD] m_readfilesinput.sensor_id=SLC_CSK; else if (!strcmp(keyword,"GAMMA")) // GAMMA [BO] m_readfilesinput.sensor_id=SLC_GAMMA; else { ERROR << "M_IN_METHOD: method " << keyword << " not known for reading input files on line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"M_IN_VOL")) // volumefile filename { //m_readfilesinput.volfile = word[1] ; // pass keyword strcpy(m_readfilesinput.volfile, word[1]); // pass keyword writearg(m_readfilesinput.volfile); } // ********************************************************************** else if (!strcmp(keyword,"M_IN_LEA")) // leaderfile filename { strcpy(m_readfilesinput.leaderfile, word[1]); // pass keyword writearg(m_readfilesinput.leaderfile); } // ********************************************************************** else if (!strcmp(keyword,"M_IN_NULL")) // nullfile filename { strcpy(m_readfilesinput.nullfile, word[1]); // pass keyword writearg(m_readfilesinput.nullfile); } // ********************************************************************** else if (!strcmp(keyword,"M_IN_DAT")) // datafile filename { strcpy(m_readfilesinput.datfile, word[1]); // pass keyword writearg(m_readfilesinput.datfile); } // ********************************************************************** else if (!strcmp(keyword,"M_RG_T_ERROR")) // master timing error { keyword = word[1]; char *pLast = NULL; m_readfilesinput.rg_timing_error= strtod( keyword, &pLast ); if ( pLast == keyword ) // fail { ERROR << "M_RG_T_ERROR argument: " << keyword << " is not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(m_readfilesinput.rg_timing_error); } // ********************************************************************** else if (!strcmp(keyword,"M_AZ_T_ERROR")) // master timing error { keyword = word[1]; char *pLast = NULL; m_readfilesinput.az_timing_error = strtod( keyword, &pLast ); if ( pLast == keyword ) // fail { ERROR << "M_AZ_T_ERROR argument: " << keyword << " is not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(m_readfilesinput.az_timing_error); } // ******************************************************************* else if (!strcmp(keyword,"S_IN_METHOD")) // ERS or ASAR ENVISAT { keyword = word[1]; writearg(keyword); toupper(keyword); if (!strcmp(keyword,"ERS")) s_readfilesinput.sensor_id=SLC_ERS; // default else if (!strcmp(keyword,"ERS-1")) // ers s_readfilesinput.sensor_id=SLC_ERS; else if (!strcmp(keyword,"ERS1")) // ers s_readfilesinput.sensor_id=SLC_ERS; else if (!strcmp(keyword,"ERS-2")) // ers s_readfilesinput.sensor_id=SLC_ERS; else if (!strcmp(keyword,"ERS2")) // ers s_readfilesinput.sensor_id=SLC_ERS; else if (!strcmp(keyword,"ERS_N1")) // ers in envisat file format [MA]; treat as ASAR s_readfilesinput.sensor_id=SLC_ERS_N1; else if (!strcmp(keyword,"N1")) // envisat s_readfilesinput.sensor_id=SLC_ASAR; else if (!strcmp(keyword,"ASAR")) // envisat s_readfilesinput.sensor_id=SLC_ASAR; else if (!strcmp(keyword,"ENVISAT")) // envisat s_readfilesinput.sensor_id=SLC_ASAR; else if (!strcmp(keyword,"ATLANTIS")) // radarsat ceos reader s_readfilesinput.sensor_id=SLC_RSAT; else if (!strcmp(keyword,"RSAT")) // radarsat s_readfilesinput.sensor_id=SLC_RSAT; else if (!strcmp(keyword,"RADARSAT")) // radarsat s_readfilesinput.sensor_id=SLC_RSAT; else if (!strcmp(keyword,"RADARSAT-1")) // radarsat s_readfilesinput.sensor_id=SLC_RSAT; else if (!strcmp(keyword,"JERS")) // jers s_readfilesinput.sensor_id=SLC_JERS; else if (!strcmp(keyword,"J-ERS")) // jers s_readfilesinput.sensor_id=SLC_JERS; else if (!strcmp(keyword,"ALOS")) // [DON] s_readfilesinput.sensor_id=SLC_ALOS; else if (!strcmp(keyword,"TSX")) // TSX [PM] s_readfilesinput.sensor_id=SLC_TSX; else if (!strcmp(keyword,"TERRASARX")) // TSX s_readfilesinput.sensor_id=SLC_TSX; else if (!strcmp(keyword,"TERRASAR-X")) // TSX s_readfilesinput.sensor_id=SLC_TSX; else if (!strcmp(keyword,"RS2")) // RS2 [MA] s_readfilesinput.sensor_id=SLC_RS2; else if (!strcmp(keyword,"RADARSAT-2")) // RS2 s_readfilesinput.sensor_id=SLC_RS2; else if (!strcmp(keyword,"CSK")) // CSK [PD] s_readfilesinput.sensor_id=SLC_CSK; else if (!strcmp(keyword,"CSX")) // CSK [PD] s_readfilesinput.sensor_id=SLC_CSK; else if (!strcmp(keyword,"GAMMA")) // GAMMA [BO] s_readfilesinput.sensor_id=SLC_GAMMA; else { ERROR << "S_IN_METHOD: method " << keyword << " not known for reading input files on line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"S_IN_VOL")) // volumefile filename { strcpy(s_readfilesinput.volfile, word[1]); // pass keyword writearg(s_readfilesinput.volfile); } // ********************************************************************** else if (!strcmp(keyword,"S_IN_LEA")) // leaderfile filename { strcpy(s_readfilesinput.leaderfile, word[1]); // pass keyword writearg(s_readfilesinput.leaderfile); } // ********************************************************************** else if (!strcmp(keyword,"S_IN_NULL")) // nullfile filename { strcpy(s_readfilesinput.nullfile, word[1]); // pass keyword writearg(s_readfilesinput.nullfile); } // ********************************************************************** else if (!strcmp(keyword,"S_IN_DAT")) // datfile filename { strcpy(s_readfilesinput.datfile, word[1]); // pass keyword writearg(s_readfilesinput.datfile); } // ********************************************************************** else if (!strcmp(keyword,"S_RG_T_ERROR")) // slave timing error { keyword = word[1]; char *pLast = NULL; s_readfilesinput.rg_timing_error = strtod( keyword, &pLast ); if ( pLast == keyword ) // fail { ERROR << "S_RG_T_ERROR argument: " << keyword << " is not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(s_readfilesinput.rg_timing_error); } // ********************************************************************** else if (!strcmp(keyword,"S_AZ_T_ERROR")) // slave timing error { keyword = word[1]; char *pLast = NULL; s_readfilesinput.az_timing_error = strtod( keyword, &pLast ); if ( pLast == keyword ) // fail { ERROR << "S_AZ_T_ERROR argument: " << keyword << " is not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(s_readfilesinput.az_timing_error); } // ********************************************************************** // *** ?_PORBITS // ********************************************************************** else if (!strcmp(keyword,"M_ORBDIR")) // orbitfile filename { if (specified(porbitsinput.m_orbdir)) WARNING.print("Prior occurence of M_ORBDIR ignored."); strcpy(porbitsinput.m_orbdir, word[1] ); // pass keyword writearg(porbitsinput.m_orbdir); } // ********************************************************************** else if (!strcmp(keyword,"M_ORB_INTERVAL") || // time interval in sec !strcmp(keyword,"S_ORB_INTERVAL")) { keyword = word[1]; // pass keyword char *pLast = NULL; porbitsinput.timeinterval = strtol( keyword, &pLast , BASE10); // int32 if ( pLast == keyword ) // fail { ERROR << "[M|S]_ORB_INTERVAL argument: " << keyword << " is not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(porbitsinput.timeinterval); } // ********************************************************************** else if (!strcmp(keyword,"M_ORB_EXTRATIME") || // time before 1st line in sec !strcmp(keyword,"S_ORB_EXTRATIME")) { keyword = word[1]; // pass keyword char *pLast = NULL; porbitsinput.timebefore = strtol( keyword, &pLast , BASE10); // int32 if ( pLast == keyword ) // fail { ERROR << "[M|S]_ORB_EXTRATIME argument: " << keyword << " is not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(porbitsinput.timebefore); } // ********************************************************************** else if (!strcmp(keyword,"M_ORB_DUMP")) // dump orbit with dt { keyword = word[1]; // pass keyword char *pLast = NULL; porbitsinput.dumpmasterorbit = strtod( keyword, &pLast ); if ( pLast == keyword ) // fail { ERROR << "M_ORB_DUMP argument: " << keyword << " is not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(porbitsinput.dumpmasterorbit); INFO.print("dumping master orbit to ascii file: masterorbit.dat"); } // ********************************************************************** else if (!strcmp(keyword,"S_ORBDIR")) // orbitfile filename { if (specified(porbitsinput.s_orbdir)) WARNING.print("Prior occurence of S_ORBDIR ignored."); strcpy(porbitsinput.s_orbdir, word[1] ); // pass keyword writearg(porbitsinput.s_orbdir); } // ********************************************************************** else if (!strcmp(keyword,"S_ORB_DUMP")) // dump orbit with dt { keyword = word[1]; // pass keyword char *pLast = NULL; porbitsinput.dumpslaveorbit = strtod( keyword, &pLast ); if ( pLast == keyword ) // fail { ERROR << "S_ORB_DUMP argument: " << keyword << " is not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(porbitsinput.dumpslaveorbit); INFO.print("dumping slave orbit to ascii file: slaveorbit.dat"); } // ____ start added by HB ____ // ******************************************************************* // *** ?_MORBITS // ******************************************************************* else if (!strncmp(keyword,"M_MO_D",6)) { char *keywordpart = &keyword[6]; int16 component; if (!strncmp(keywordpart,"BH",2)) component = 0; else if (!strncmp(keywordpart,"BV",2)) component = 1; else { ERROR << "Unknown keyword: \"" << keyword << "\" at line: " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } int16 degree = int(keywordpart[2])-48; // char2int morbitsinputmaster.coeff(degree,component) = atof(word[1]); writearg(morbitsinputmaster.coeff(degree,component)); } // ******************************************************************* else if (!strcmp(keyword,"M_MO_REFORBIT")) { strcpy(morbitsinputmaster.reforbitfile, word[1]); writearg(morbitsinputmaster.reforbitfile); } // ******************************************************************* else if (!strncmp(keyword,"S_MO_D",6)) { char *keywordpart = &keyword[6]; int16 component; if (!strncmp(keywordpart,"BH",2)) component = 0; else if (!strncmp(keywordpart,"BV",2)) component = 1; else { ERROR << "Unknown keyword: \"" << keyword << "\" at line: " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } int16 degree = int(keywordpart[2])-48; // char2int morbitsinputslave.coeff(degree,component) = atof(word[1]); writearg(morbitsinputslave.coeff(degree,component)); } // ******************************************************************* else if (!strcmp(keyword,"S_MO_REFORBIT")) { strcpy(morbitsinputslave.reforbitfile, word[1]); writearg(morbitsinputslave.reforbitfile); } // ____ end added by HB ____ // ******************************************************************* // *** ?_CROP // ******************************************************************* else if (!strcmp(keyword,"M_CROP_ID")) // identifier of run { strcpy(m_cropinput.idcrop, word[1] ); // pass keyword writearg(m_cropinput.idcrop); } // ******************************************************************* CROP else if (!strcmp(keyword,"S_CROP_ID")) // identifier of run { strcpy(s_cropinput.idcrop, word[1] ); // pass keyword writearg(s_cropinput.idcrop); } // ********************************************************************** else if (!strcmp(keyword,"M_CROP_IN")) // SLC input image filename { strcpy(m_cropinput.filein1, word[1] ); // pass keyword writearg(m_cropinput.filein1); } // ********************************************************************** else if (!strcmp(keyword,"S_CROP_IN")) // SLC input image filename { strcpy(s_cropinput.filein1, word[1] ); // pass keyword writearg(s_cropinput.filein1); } // ********************************************************************** else if (!strcmp(keyword,"M_CROP_OUT")) // SLC output image filename { strcpy(m_cropinput.fileout1, word[1] ); // pass keyword writearg(m_cropinput.fileout1); } // ********************************************************************** else if (!strcmp(keyword,"S_CROP_OUT")) // SLC output image filename { strcpy(s_cropinput.fileout1, word[1] ); // pass keyword writearg(s_cropinput.fileout1); } // ********************************************************************** else if (!strcmp(keyword,"M_DBOW")) // min. line coord. { m_cropinput.dbow.linelo = atoi(word[1]); // pass keywords m_cropinput.dbow.linehi = atoi(word[2]); m_cropinput.dbow.pixlo = atoi(word[3]); m_cropinput.dbow.pixhi = atoi(word[4]); writearg(m_cropinput.dbow.linelo); writearg(m_cropinput.dbow.linehi); writearg(m_cropinput.dbow.pixlo); writearg(m_cropinput.dbow.pixhi); // ______initial check, later checked to #lines of image______ if (m_cropinput.dbow.linelo <= 0 || m_cropinput.dbow.pixlo <= 0 || m_cropinput.dbow.linelo > m_cropinput.dbow.linehi || m_cropinput.dbow.pixlo > m_cropinput.dbow.pixhi) { ERROR << "code 300: Arguments of M_DBOW card on line " << linecnt << " missing. [DBOW min_line max_line min_pixel max_pixel]."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"S_DBOW")) // min. line coord. { s_cropinput.dbow.linelo = atoi(word[1]); // pass keywords s_cropinput.dbow.linehi = atoi(word[2]); s_cropinput.dbow.pixlo = atoi(word[3]); s_cropinput.dbow.pixhi = atoi(word[4]); writearg(s_cropinput.dbow.linelo); writearg(s_cropinput.dbow.linehi); writearg(s_cropinput.dbow.pixlo); writearg(s_cropinput.dbow.pixhi); // ______initial check, later checked to #lines of image______ if (s_cropinput.dbow.linelo <= 0 || s_cropinput.dbow.pixlo <= 0 || s_cropinput.dbow.linelo > s_cropinput.dbow.linehi || s_cropinput.dbow.pixlo > s_cropinput.dbow.pixhi) { ERROR << "code 300: Arguments of S_DBOW card on line " << linecnt << " missing. [DBOW min_line max_line min_pixel max_pixel]."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** // BK 15-Dec-2003 else if (!strcmp(keyword,"M_DBOW_GEO")) // 1e6*lat_0 [deg], lon_0, height, width [pix] { // use dbow to store tmp, compute later in crop if not zero real8 tmp_lat_0, tmp_lon_0, tmp_height, tmp_width; tmp_lat_0 = atof(word[1]) ; // pass keyword tmp_lon_0 = atof(word[2]) ; // pass keyword tmp_height = atof(word[3]) ; // pass keyword tmp_width = atof(word[4]) ; // pass keyword writearg(tmp_lat_0); writearg(tmp_lon_0); writearg(tmp_height); writearg(tmp_width); m_cropinput.dbow_geo.linelo = uint((360.0+tmp_lat_0)*1e6); m_cropinput.dbow_geo.linehi = uint((360.0+tmp_lon_0)*1e6); m_cropinput.dbow_geo.pixlo = uint(tmp_height); m_cropinput.dbow_geo.pixhi = uint(tmp_width); } // ********************************************************************** // BK 15-Dec-2003 else if (!strcmp(keyword,"S_DBOW_GEO")) // 1e6*lat_0 [deg], lon_0, height, width [pix] { // use dbow to store tmp, compute later in crop if not zero real8 tmp_lat_0, tmp_lon_0, tmp_height, tmp_width; tmp_lat_0 = atof(word[1]) ; // pass keyword tmp_lon_0 = atof(word[2]) ; // pass keyword tmp_height = atof(word[3]) ; // pass keyword tmp_width = atof(word[4]) ; // pass keyword writearg(tmp_lat_0); writearg(tmp_lon_0); writearg(tmp_height); writearg(tmp_width); s_cropinput.dbow_geo.linelo = uint((360.0+tmp_lat_0)*1e6); s_cropinput.dbow_geo.linehi = uint((360.0+tmp_lon_0)*1e6); s_cropinput.dbow_geo.pixlo = uint(tmp_height); s_cropinput.dbow_geo.pixhi = uint(tmp_width); } //____RaffaeleNutricato START MODIFICATION SECTION 9 // ******************************************************************* // *** ?_OVS // ********************************************************************** else if (!strcmp(keyword,"M_OVS_OUT")) // oversampled SLC output image filename { strcpy(m_oversample.fileoutovs, word[1] ); // pass keyword writearg(m_oversample.fileoutovs); } // ********************************************************************** else if (!strcmp(keyword,"S_OVS_OUT")) // oversampled SLC output image filename { strcpy(s_oversample.fileoutovs, word[1] ); // pass keyword writearg(s_oversample.fileoutovs); } // ******************************************************************* else if (!strcmp(keyword,"M_OVS_FACT_RNG")) // Oversampling ratio in the master range direction. { m_oversample.OsrRange = strtol(word[1],NULL, BASE10); // pass keyword writearg(m_oversample.OsrRange); if (m_oversample.OsrRange < 1) { PRINT_ERROR( "(M_OVS_FACT_RNG < 1) Oversampling ratio must be at least 1."); throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"S_OVS_FACT_RNG")) // Oversampling ratio in the slave range direction. { s_oversample.OsrRange = strtol(word[1],NULL, BASE10) ; // pass keyword writearg(s_oversample.OsrRange); if (s_oversample.OsrRange < 1) { PRINT_ERROR( "(S_OVS_FACT_RNG < 1) Oversampling ratio must be at least 1."); throw(keyword_error); } } // ******************************************************************* else if (!strcmp(keyword,"M_OVS_FACT_AZI")) // Oversampling ratio in the master azimuth direction. { m_oversample.OsrAzimuth = strtol(word[1],NULL, BASE10) ; // pass keyword writearg(m_oversample.OsrAzimuth); if (m_oversample.OsrAzimuth < 1) { PRINT_ERROR( "(M_OVS_FACT_AZI < 1) Oversampling ratio must be at least 1."); throw(keyword_error); } if (m_oversample.OsrAzimuth > 2) { PRINT_ERROR( "(M_OVS_FACT_AZI > 2) Not implemented!"); throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"S_OVS_FACT_AZI")) // Oversampling ratio in the slave azimuth direction. { s_oversample.OsrAzimuth = strtol(word[1],NULL, BASE10) ; // pass keyword writearg(s_oversample.OsrAzimuth); if (s_oversample.OsrAzimuth < 1) { PRINT_ERROR("(S_OVS_FACT_AZI < 1) Oversampling ratio must be at least 1."); throw(keyword_error); } if (s_oversample.OsrAzimuth > 2) { PRINT_ERROR( "(S_OVS_FACT_AZI > 2) Not implemented!"); throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"M_OVS_KERNELSIZE")) // Length of the interpolation kernel. { m_oversample.FilterSize = strtol(word[1],NULL, BASE10) ; // pass keyword writearg(m_oversample.FilterSize); if (m_oversample.FilterSize < 2) { PRINT_ERROR("(M_OVS_KERNELSIZE < 2) Interpolation kernel length must be > 1."); throw(keyword_error); } if (m_oversample.FilterSize % 2) { PRINT_ERROR("(M_OVS_KERNELSIZE not even) Range Interpolation kernel length must be an even number."); throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"S_OVS_KERNELSIZE")) // Length of the interpolation kernel. { s_oversample.FilterSize = strtol(word[1],NULL, BASE10) ; // pass keyword writearg(s_oversample.FilterSize); if (s_oversample.FilterSize < 2) { PRINT_ERROR("code ???: (S_OVS_KERNELSIZE < 2) Interpolation kernel length must be > 1."); throw(keyword_error); } if (s_oversample.FilterSize % 2) { PRINT_ERROR( "code ???: (S_OVS_KERNELSIZE not even) Interpolation kernel length must be an even number."); throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"M_OVS_OUT_FORMAT")) // Output format [cr4] ci16, I suggest [cr4]. { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"CR4")) m_oversample.oformatflag = FORMATCR4; // default else if (!strcmp(keyword,"CI2")) m_oversample.oformatflag = FORMATCI2; else { ERROR << "M_OVS_OUT_FORMAT: output format " << keyword << " not known for master range oversampling. line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"S_OVS_OUT_FORMAT")) // Output format [cr4] ci16, I suggest [cr4]. { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"CR4")) s_oversample.oformatflag = FORMATCR4; // default else if (!strcmp(keyword,"CI2")) s_oversample.oformatflag = FORMATCI2; else { ERROR << "S_OVS_OUT_FORMAT: output format " << keyword << " not known for slave range oversampling. line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } //____RaffaeleNutricato END MODIFICATION SECTION 9 // ____ start added by MA ____ // ********************************************************************** // *** SIMULATE AMPLITUDE FOR MASTER // ********************************************************************** else if (!strcmp(keyword,"SAM_IN_DEM") && ( generalinput.process[pr_m_simamp] || onlyprocess == pr_m_simamp ) ) // input file // [MA] read parm only if there is (ONLY)PROCESS flag // default onlyprocess is -1 { strcpy(simampinput.firefdem, word[1] ); // pass keyword writearg(simampinput.firefdem); } // ********************************************************************** else if (!strcmp(keyword,"SAM_IN_FORMAT") && ( generalinput.process[pr_m_simamp] || onlyprocess == pr_m_simamp ) ) // format input file { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"R4") || !strcmp(keyword,"REAL4")) simampinput.iformatflag = FORMATR4; else if (!strcmp(keyword,"I2") || !strcmp(keyword,"SHORT")) simampinput.iformatflag = FORMATI2; // default else if (!strcmp(keyword,"I2_BIGENDIAN") || !strcmp(keyword,"SHORT_BIGENDIAN")) simampinput.iformatflag = FORMATI2_BIGENDIAN; // default else if (!strcmp(keyword,"R8") || !strcmp(keyword,"REAL8")) simampinput.iformatflag = FORMATR8; else { ERROR << "SAM_IN_FORMAT: input format " << keyword << " not known (R4 R8 I2 (native) SHORT_BIGENDIAN); line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"SAM_IN_SIZE") && ( generalinput.process[pr_m_simamp] || onlyprocess == pr_m_simamp ) ) // nrow ncols (lat lon) { char *pLast1, *pLast2 = NULL; simampinput.demrows = strtoul(word[1], &pLast1, BASE10); simampinput.demcols = strtoul(word[2], &pLast2, BASE10); if ( pLast1 == word[1] || pLast2 == word[2] ) // fails to convert one of them to double. { ERROR << "SAM_IN_SIZE: " << word[1] << " : " << word[2] << " are not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(simampinput.demrows); writearg(simampinput.demcols); } // ********************************************************************** else if (!strcmp(keyword,"SAM_IN_DELTA") && ( generalinput.process[pr_m_simamp] || onlyprocess == pr_m_simamp ) ) // degrees delta lat lon { simampinput.demdeltalat = atof(word[1]); // pass keyword keyword = word[2]; // pass keyword writearg(simampinput.demdeltalat); writearg(keyword); if (isdigit(keyword[0]) || keyword[0]=='.') // likely to be 2 numbers simampinput.demdeltalon = atof(keyword); else // default same gridsize simampinput.demdeltalon = simampinput.demdeltalat; // ______ Store as radians ______ simampinput.demdeltalat = deg2rad(simampinput.demdeltalat); simampinput.demdeltalon = deg2rad(simampinput.demdeltalon); } // ********************************************************************** else if (!strcmp(keyword,"SAM_IN_UL") && ( generalinput.process[pr_m_simamp] || onlyprocess == pr_m_simamp ) ) // upperleft coordinates { char *pLast1, *pLast2 = NULL; simampinput.demlatleftupper = strtod(word[1], &pLast1); simampinput.demlonleftupper = strtod(word[2], &pLast2); if ( pLast1 == word[1] || pLast2 == word[2] ) // fails to convert one of them to double. { ERROR << "SAM_IN_UL: " << word[1] << " : " << word[2] << " are not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(simampinput.demlatleftupper); writearg(simampinput.demlonleftupper); simampinput.demlatleftupper = deg2rad(simampinput.demlatleftupper); simampinput.demlonleftupper = deg2rad(simampinput.demlonleftupper); } // ********************************************************************** else if (!strcmp(keyword,"SAM_IN_NODATA") && ( generalinput.process[pr_m_simamp] || onlyprocess == pr_m_simamp ) ) // flag for no data { char *pLast = NULL; simampinput.demnodata = strtod(word[1], &pLast); if ( pLast == word[1] ) // fails to convert to double. { ERROR << "SAM_IN_NODATA: " << word[1] << " is not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(simampinput.demnodata); } // ********************************************************************** else if (!strcmp(keyword,"SAM_OUT_DEM") && ( generalinput.process[pr_m_simamp] || onlyprocess == pr_m_simamp ) ) // name of output file { strcpy(simampinput.fodem, word[1] ); // pass keyword writearg(simampinput.fodem); } // ********************************************************************** else if (!strcmp(keyword,"SAM_OUT_FILE") && ( generalinput.process[pr_m_simamp] || onlyprocess == pr_m_simamp ) ) // name of output file { strcpy(simampinput.fosimamp, word[1] ); // pass keyword writearg(simampinput.fosimamp); } // // ********************************************************************** // else if (!strcmp(keyword,"SAM_OUT_DEMI")) // name of output file // { // strcpy(demassistinput.fodemi, word[1] ); // pass keyword // writearg(demassistinput.fodemi); // } // // // ********************************************************************** else if (!strcmp(keyword,"SAM_OUT_DEM_LP") && ( generalinput.process[pr_m_simamp] || onlyprocess == pr_m_simamp ) ) // name of output file // MA enabled for SPT tracking. { strcpy(simampinput.fodemlp, word[1] ); // pass keyword writearg(simampinput.fodemlp); } else if (!strcmp(keyword,"SAM_OUT_THETA_LP") && ( generalinput.process[pr_m_simamp] || onlyprocess == pr_m_simamp ) ) // name of output file // MA enabled for SPT tracking. { strcpy(simampinput.fothetalp, word[1] ); // pass keyword writearg(simampinput.fothetalp); } // ********************************************************************** // *** MASTER TIMING ERROR ESTIMATION using COREGISTRATION // ********************************************************************** else if (!strcmp(keyword,"MTE_METHOD")) // method selector simamp coreg { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"MAGFFT")) { mtiminginput.method=cc_magfft; // default MTE_magfft } else if (!strcmp(keyword,"MAGSPACE")) { mtiminginput.method=cc_magspace; // MTE_magspace } else { ERROR << "MTE_METHOD: method " << keyword << " not known for simamp correlation coregistration on line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"MTE_NWIN")) // #windows for simamp correlation { char *pLast = NULL; mtiminginput.Nwin = strtoul(word[1], &pLast, BASE10); if ( pLast == word[1] ) // fails to convert to double. { ERROR << "MTE_NWIN: " << word[1] << " is not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(mtiminginput.Nwin); if (mtiminginput.Nwin > 10000) { PRINT_ERROR("Too many windows requested (MTE_NWIN > 10000).") throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"MTE_IN_POS")) // file with #windows positions { strcpy(mtiminginput.ifpositions, word[1] ); // pass keyword writearg(mtiminginput.ifpositions); } // ********************************************************************** else if (!strcmp(keyword,"MTE_WINSIZE")) // windowsize for simamp correlation { char *pLast1, *pLast2 = NULL; mtiminginput.MasksizeL = strtoul(word[1], &pLast1, BASE10); mtiminginput.MasksizeP = strtoul(word[2], &pLast2, BASE10); if ( pLast1 == word[1] || pLast2 == word[2] ) // fails to convert one of them to double. { ERROR << "MTE_WINSIZE: " << word[1] << " : " << word[2] << " are not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(mtiminginput.MasksizeL); writearg(mtiminginput.MasksizeP); if (mtiminginput.MasksizeL > 4096 || mtiminginput.MasksizeP > 4096) { PRINT_ERROR("Too large correlation window (MTE_WINSIZE > 4096)."); throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"MTE_ACC")) // Searchdomain for correlation { // simamp correlation char *pLast1, *pLast2 = NULL; mtiminginput.AccL = strtoul(word[1], &pLast1, BASE10); mtiminginput.AccP = strtoul(word[2], &pLast2, BASE10); if ( pLast1 == word[1] || pLast2 == word[2] ) // fails to convert one of them to double. { ERROR << "MTE_ACC: " << word[1] << " : " << word[2] << " are not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(mtiminginput.AccL); writearg(mtiminginput.AccP); if (mtiminginput.AccL > 1000 || mtiminginput.AccP > 1000) { PRINT_ERROR("Too large searchwindow (MTE_ACC > 1000)."); throw(keyword_error); } if (mtiminginput.AccL == 0 || mtiminginput.AccP == 0) { PRINT_ERROR("Acc = 0 ?(MTE_ACC)."); throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"MTE_INITOFF")) // Initial offset { keyword = word[1] ; // pass keyword char *keyword2 = word[2] ; // pass keyword writearg(keyword); writearg(keyword2); if (isdigit(keyword2[0]) || keyword2[0]=='-') // likely to be 2 numbers // BK19/1/00 thanks to m.goos for '-' { mtiminginput.initoffsetL = atoi(keyword); mtiminginput.initoffsetP = atoi(keyword2); } else { ERROR << "MTE_INITOFF: unknown input: " << keyword << ", " << keyword2 << " on line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ____ end added by MA ____ // ********************************************************************** // *** AZIMUTH FILTERING // ********************************************************************** else if (!strcmp(keyword,"AF_BLOCKSIZE")) { char *pLast = NULL; filtaziinput.fftlength = strtol(word[1], &pLast, BASE10); // int32 if ( pLast == word[1] ) // fails to convert to double. { ERROR << "AF_BLOCKSIZE: " << word[1] << " is not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(filtaziinput.fftlength); } // ********************************************************************** else if (!strcmp(keyword,"AF_HAMMING")) { char *pLast = NULL; filtaziinput.hammingalpha = strtod(word[1], &pLast); if ( pLast == word[1] ) // fails to convert to double. { ERROR << "AF_HAMMING: " << word[1] << " is not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(filtaziinput.hammingalpha); } // ********************************************************************** else if (!strcmp(keyword,"AF_OVERLAP")) { char *pLast = NULL; filtaziinput.overlap = strtol(word[1], &pLast, BASE10); // int32 if ( pLast == word[1] ) // fails to convert to double. { ERROR << "AF_OVERLAP: " << word[1] << " is not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(filtaziinput.overlap); } // ********************************************************************** else if (!strcmp(keyword,"AF_OUT_MASTER")) { strcpy(filtaziinput.fomaster, word[1] ); // pass keyword writearg(filtaziinput.fomaster); } // ********************************************************************** else if (!strcmp(keyword,"AF_OUT_SLAVE")) { strcpy(filtaziinput.foslave, word[1] ); // pass keyword writearg(filtaziinput.foslave); } // ********************************************************************** else if (!strcmp(keyword,"AF_OUT_FORMAT")) // output format { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"CR4")) filtaziinput.oformatflag = FORMATCR4; // default else if (!strcmp(keyword,"CI2")) filtaziinput.oformatflag = FORMATCI2; else { ERROR << "AF_OUT_FORMAT: output format " << keyword << " not known for azimuth filtering. line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** // *** COARSE CORR COREGISTRATION // ********************************************************************** else if (!strcmp(keyword,"CC_METHOD")) // method selector coarse coreg { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"MAGFFT")) coarsecorrinput.method=cc_magfft; // default else if (!strcmp(keyword,"MAGSPACE")) coarsecorrinput.method=cc_magspace; else { ERROR << "CC_METHOD: method " << keyword << " not known for coarse correlation coregistration on line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"CC_NWIN")) // #windows for coarse correlation { coarsecorrinput.Nwin = atoi(word[1]) ; // pass keyword writearg(coarsecorrinput.Nwin); if (coarsecorrinput.Nwin > 10000) { PRINT_ERROR("Too many windows requested (CC_NWIN > 10000).") throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"CC_IN_POS")) // file with #windows positions { strcpy(coarsecorrinput.ifpositions, word[1] ); // pass keyword writearg(coarsecorrinput.ifpositions); } // ********************************************************************** else if (!strcmp(keyword,"CC_WINSIZE")) // windowsize for coarse correlation { coarsecorrinput.MasksizeL = atoi(word[1]) ; // pass keyword coarsecorrinput.MasksizeP = atoi(word[2]) ; // pass keyword writearg(coarsecorrinput.MasksizeL); writearg(coarsecorrinput.MasksizeP); if (coarsecorrinput.MasksizeL > 10240 || coarsecorrinput.MasksizeP > 4096) // [TODO] move MAX constant values to constant.hh { PRINT_ERROR("Too large correlation window (CC_WINSIZE(l,p) > [10240,4096] )."); throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"CC_ACC")) // Searchdomain for correlation { // coarse correlation coarsecorrinput.AccL = atoi(word[1]) ; // pass keyword coarsecorrinput.AccP = atoi(word[2]) ; // pass keyword writearg(coarsecorrinput.AccL); writearg(coarsecorrinput.AccP); if (coarsecorrinput.AccL > 1000 || coarsecorrinput.AccP > 1000) { PRINT_ERROR("Too large searchwindow (CC_ACC > 1000)."); throw(keyword_error); } if (coarsecorrinput.AccL == 0 || coarsecorrinput.AccP == 0) { PRINT_ERROR("Acc = 0 ?(CC_ACC)."); throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"CC_INITOFF")) // Initial offset { keyword = word[1] ; // pass keyword char *keyword2 = word[2] ; // pass keyword writearg(keyword); writearg(keyword2); if (!strcmp(keyword,"ORBIT") || // use value of precise orbits !strcmp(keyword,"orbit")) { coarsecorrinput.initoffsetL = NaN; // flag used in main, see processor.cc coarsecorrinput.initoffsetP = NaN; // flag used in main INFO << "CC_INITOFF: \tInitial offsets from COARSEORB: " << generalinput.i_resfile; INFO.print(); } else if (isdigit(keyword2[0]) || keyword2[0]=='-') // likely to be 2 numbers // BK19/1/00 thanks to m.goos for '-' { //coarsecorrinput.initoffsetL = atof(keyword); //coarsecorrinput.initoffsetP = atof(keyword2); coarsecorrinput.initoffsetL = atoi(keyword); coarsecorrinput.initoffsetP = atoi(keyword2); } else { ERROR << "CC_INITOFF: unknown input: " << keyword << ", " << keyword2 << " on line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** // *** FINE COREGISTRATION // ********************************************************************** else if (!strcmp(keyword,"FC_NWIN")) // #windows for fine correlation { fineinput.Nwin = atoi(word[1]) ; // pass keyword writearg(fineinput.Nwin); if (fineinput.Nwin > 100000) // [MA] change this to a higher value for SPT { PRINT_ERROR("Too many windows requested (FC_NWIN).") throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"FC_IN_POS")) // file with #windows positions { strcpy(fineinput.ifpositions, word[1] ); // pass keyword writearg(fineinput.ifpositions); } // ********************************************************************** else if (!strcmp(keyword,"FC_WINSIZE")) // windowsize for fine correlation { fineinput.MasksizeL = atoi(word[1]) ; // pass keyword fineinput.MasksizeP = atoi(word[2]) ; // pass keyword writearg(fineinput.MasksizeL); writearg(fineinput.MasksizeP); if (fineinput.MasksizeL > 1024 || fineinput.MasksizeP > 1024) { PRINT_ERROR("Too large correlation window (FC_WINSIZE).") throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"FC_ACC")) // Searchdomain for correlation { // fine correlation fineinput.AccL = atoi(word[1]); // pass keyword fineinput.AccP = atoi(word[2]); // pass keyword writearg(fineinput.AccL); writearg(fineinput.AccP); if (fineinput.AccL > 1000 || fineinput.AccP > 1000) { PRINT_ERROR("Too large searchwindow (FC_ACC).") throw(keyword_error); } if (fineinput.AccL == 0 || fineinput.AccP == 0) { PRINT_ERROR("Acc = 0 ?(FC_ACC).") throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"FC_INITOFF")) // Initial offset { keyword = word[1] ; // pass keyword char *keyword2 = word[2] ; // pass keyword writearg(keyword); writearg(keyword2); if (!strcmp(keyword,"COARSECORR") || !strcmp(keyword,"coarsecorr")) // use value of coarse correlation { fineinput.initoffsetL = NaN; // flag used in main fineinput.initoffsetP = NaN; // flag used in main INFO << "FC_INITOFF: \tInitial offset from COARSECORR: " << generalinput.i_resfile; INFO.print(); } else if (isdigit(keyword2[0]) || keyword2[0]=='-') // likely to be 2 numbers // BK19/1/00 thanks to M.Goos for '-' { fineinput.initoffsetL = atoi(keyword); fineinput.initoffsetP = atoi(keyword2); } else { ERROR << "FC_INITOFF: unknown input: " << keyword << ", " << keyword2 << " on line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"FC_METHOD")) // method selector fine coreg { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"CMPLXFFT")) { //fineinput.method=fc_cmplxfft; // default PRINT_ERROR("CMPLXFFT not implemented in v1.0 of Doris.") throw(keyword_error); } else if (!strcmp(keyword,"CMPLXSPACE")) { //fineinput.method=fc_cmplxspace; PRINT_ERROR("CMPLXSPACE not implemented in v1.0 of Doris.") throw(keyword_error); } else if (!strcmp(keyword,"MAGFFT")) fineinput.method=fc_magfft; else if (!strcmp(keyword,"MAGSPACE")) fineinput.method=fc_magspace; else if (!strcmp(keyword,"OVERSAMPLE")) fineinput.method=fc_oversample; else if (!strcmp(keyword,"COHERENCE")) fineinput.method=fc_coherence; else if (!strcmp(keyword,"INTENSITY")) fineinput.method=fc_intensity; else { ERROR << "FC_METHOD: method " << keyword << " not known for fine coregistration on line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"FC_OSFACTOR")) // oversampling factor { fineinput.osfactor = atoi(word[1]) ; // pass keyword writearg(fineinput.osfactor); } // ********************************************************************** else if (!strcmp(keyword,"FC_PLOT")) // plotting results { fineinput.plotoffsets = true; fineinput.plotthreshold = atof(word[1]) ; // pass keyword keyword = word[2] ; // pass keyword writearg(fineinput.plotthreshold); writearg(keyword); toupper(keyword); if (!strcmp(keyword,"BG")) fineinput.plotmagbg = true; else if (!strcmp(keyword,"NOBG")) fineinput.plotmagbg = false; else if (!strcmp(keyword,"ON")) // actually not allowed... fineinput.plotoffsets = true; else if (!strcmp(keyword,"OFF")) // actually not allowed... fineinput.plotoffsets = false; else WARNING.print("FC_PLOT: missing argument(s). (default: 0.4 NOBG)"); } else if (!strcmp(keyword,"FC_DEM")) // input file { strcpy(fineinput.firefdem, word[1] ); // pass keyword writearg(fineinput.firefdem); } // ********************************************************************** else if (!strcmp(keyword,"FC_DEM_FORMAT")) // format input file { keyword = word[1]; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"R4") || !strcmp(keyword,"REAL4")) fineinput.iformatflag = FORMATR4; else if (!strcmp(keyword,"I2") || !strcmp(keyword,"SHORT")) fineinput.iformatflag = FORMATI2; // default else if (!strcmp(keyword,"I2_BIGENDIAN") || !strcmp(keyword,"SHORT_BIGENDIAN")) fineinput.iformatflag = FORMATI2_BIGENDIAN; // default else if (!strcmp(keyword,"R8") || !strcmp(keyword,"REAL8")) fineinput.iformatflag = FORMATR8; else { ERROR << "FC_IN_FORMAT: input format " << keyword << " not known (R4 R8 I2 (native) SHORT_BIGENDIAN); line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"FC_DEM_SIZE")) // nrow ncols (lat lon) { char *pLast1, *pLast2 = NULL; fineinput.demrows = strtoul(word[1], &pLast1, BASE10); fineinput.demcols = strtoul(word[2], &pLast2, BASE10); if ( pLast1 == word[1] || pLast2 == word[2] ) // fails to convert one of them to double. { ERROR << "FC_DEM_SIZE: " << word[1] << " : " << word[2] << " are not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(fineinput.demrows); writearg(fineinput.demcols); } // ********************************************************************** else if (!strcmp(keyword,"FC_DEM_DELTA")) // degrees delta lat lon { fineinput.demdeltalat = atof(word[1]) ; // pass keyword keyword = word[2] ; // update keyword writearg(fineinput.demdeltalat); writearg(keyword); // lon if (isdigit(keyword[0]) || keyword[0]=='.') // likely to be 2 numbers fineinput.demdeltalon = atof(keyword); else // default same gridsize fineinput.demdeltalon = fineinput.demdeltalat; // ______ Store as radians ______ fineinput.demdeltalat = deg2rad(fineinput.demdeltalat); fineinput.demdeltalon = deg2rad(fineinput.demdeltalon); } // ********************************************************************** else if (!strcmp(keyword,"FC_DEM_UL")) // upperleft coordinates { char *pLast1, *pLast2 = NULL; fineinput.demlatleftupper = strtod(word[1], &pLast1); fineinput.demlonleftupper = strtod(word[2], &pLast2); if ( pLast1 == word[1] || pLast2 == word[2] ) // fails to convert { ERROR << "FC_DEM_UL: " << word[1] << " : " << word[2] << " are not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(fineinput.demlatleftupper); writearg(fineinput.demlonleftupper); fineinput.demlatleftupper = deg2rad(fineinput.demlatleftupper); fineinput.demlonleftupper = deg2rad(fineinput.demlonleftupper); } // ********************************************************************** else if (!strcmp(keyword,"FC_DEM_NODATA")) // flag for no data { fineinput.demnodata = atof(word[1]) ; // pass keyword writearg(fineinput.demnodata); } //added by MCC for fine CCCoregistration // ********************************************************************** else if (!strcmp(keyword,"FC_SHIFTAZI")) // true: shift before rs. { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"ON") || // consistent with previous versions (keyword[0] == '\0') || // no keyword !strcmp(keyword,"DC")) // Doppler centroid polynomial fineinput.shiftazi = 1; else if (!strcmp(keyword,"DERAMP")) //Only for TOPS fineinput.shiftazi = 2; else if (!strcmp(keyword,"OFF") || !strncmp(keyword,"//",2) || // comment !strncmp(keyword,"#",1) || //comment !strcmp(keyword,"NONE")) // just in case fineinput.shiftazi = 0; else { fineinput.shiftazi = 1; WARNING << "FC_SHIFTAZI: line: " << linecnt << ": unknown argument: " << keyword << "; Set to ON (do shift azimuth spectrum)."; WARNING.print(); } } // *************************************** // ____ start added by FvL ____ // ********************************************************************** // *** RELATIVE TIMING ERROR // ********************************************************************** else if (!strcmp(keyword,"RTE_THRESHOLD")) // treshhold value { reltiminginput.threshold = atof(word[1]) ; // pass keyword writearg(reltiminginput.threshold); if (reltiminginput.threshold > 1) { PRINT_ERROR("RTE_THRESHOLD: threshold > 1.") throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"RTE_MAXITER")) // max number of offsets to reject { reltiminginput.maxiter = atoi(word[1]) ; // pass keyword writearg(reltiminginput.maxiter); if (reltiminginput.maxiter < 0) { WARNING.print("RTE_MAXITER: max. number of points to remove < 0? (using 0)"); reltiminginput.maxiter = 0; } } // ********************************************************************** else if (!strcmp(keyword,"RTE_K_ALPHA")) // critical value for outlier removal { reltiminginput.k_alpha = atof(word[1]) ; // pass keyword writearg(reltiminginput.k_alpha); if (reltiminginput.k_alpha < 0) { WARNING.print("RTE_K_ALPHA: critical value < 0.0?"); reltiminginput.k_alpha = 1.97; } } // ********************************************************************** // *** DEM ASSISTED COREGISTRATION // ********************************************************************** else if (!strcmp(keyword,"DAC_IN_DEM")) // input file { strcpy(demassistinput.firefdem, word[1] ); // pass keyword writearg(demassistinput.firefdem); } // ********************************************************************** else if (!strcmp(keyword,"DAC_IN_FORMAT")) // format input file { keyword = word[1]; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"R4") || !strcmp(keyword,"REAL4")) demassistinput.iformatflag = FORMATR4; else if (!strcmp(keyword,"I2") || !strcmp(keyword,"SHORT")) demassistinput.iformatflag = FORMATI2; // default else if (!strcmp(keyword,"I2_BIGENDIAN") || !strcmp(keyword,"SHORT_BIGENDIAN")) demassistinput.iformatflag = FORMATI2_BIGENDIAN; // default else if (!strcmp(keyword,"R8") || !strcmp(keyword,"REAL8")) demassistinput.iformatflag = FORMATR8; else { ERROR << "DAC_IN_FORMAT: input format " << keyword << " not known (R4 R8 I2 (native) SHORT_BIGENDIAN); line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"DAC_IN_SIZE")) // nrow ncols (lat lon) { char *pLast1, *pLast2 = NULL; demassistinput.demrows = strtoul(word[1], &pLast1, BASE10); demassistinput.demcols = strtoul(word[2], &pLast2, BASE10); if ( pLast1 == word[1] || pLast2 == word[2] ) // fails to convert one of them to double. { ERROR << "DAC_IN_SIZE: " << word[1] << " : " << word[2] << " are not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(demassistinput.demrows); writearg(demassistinput.demcols); } // ********************************************************************** else if (!strcmp(keyword,"DAC_IN_DELTA")) // degrees delta lat lon { demassistinput.demdeltalat = atof(word[1]) ; // pass keyword keyword = word[2] ; // update keyword writearg(demassistinput.demdeltalat); writearg(keyword); // lon if (isdigit(keyword[0]) || keyword[0]=='.') // likely to be 2 numbers demassistinput.demdeltalon = atof(keyword); else // default same gridsize demassistinput.demdeltalon = demassistinput.demdeltalat; // ______ Store as radians ______ demassistinput.demdeltalat = deg2rad(demassistinput.demdeltalat); demassistinput.demdeltalon = deg2rad(demassistinput.demdeltalon); } // ********************************************************************** else if (!strcmp(keyword,"DAC_IN_UL")) // upperleft coordinates { char *pLast1, *pLast2 = NULL; demassistinput.demlatleftupper = strtod(word[1], &pLast1); demassistinput.demlonleftupper = strtod(word[2], &pLast2); if ( pLast1 == word[1] || pLast2 == word[2] ) // fails to convert { ERROR << "DAC_IN_UL: " << word[1] << " : " << word[2] << " are not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(demassistinput.demlatleftupper); writearg(demassistinput.demlonleftupper); demassistinput.demlatleftupper = deg2rad(demassistinput.demlatleftupper); demassistinput.demlonleftupper = deg2rad(demassistinput.demlonleftupper); } // ********************************************************************** else if (!strcmp(keyword,"DAC_IN_NODATA")) // flag for no data { demassistinput.demnodata = atof(word[1]) ; // pass keyword writearg(demassistinput.demnodata); } // ********************************************************************** else if (!strcmp(keyword,"DAC_OUT_DEM")) // name of output file { strcpy(demassistinput.fodem, word[1] ); // pass keyword writearg(demassistinput.fodem); } // ********************************************************************** else if (!strcmp(keyword,"DAC_OUT_DEMI")) // name of output file { strcpy(demassistinput.fodemi, word[1] ); // pass keyword writearg(demassistinput.fodemi); } // ********************************************************************** else if (!strcmp(keyword,"DAC_OUT_DEM_LP")) // name of output file { strcpy(demassistinput.forefdemhei, word[1] ); // pass keyword writearg(demassistinput.forefdemhei); } // ____ end added by FvL ____ // ********************************************************************** // *** COMPUTATION OF COREGISTRATION PARAMETERS // ********************************************************************** else if (!strcmp(keyword,"CPM_THRESHOLD")) // treshhold value { coregpminput.threshold = atof(word[1]) ; // pass keyword writearg(coregpminput.threshold); if (coregpminput.threshold > 1) { PRINT_ERROR("CPM_THRESHOLD: threshold > 1.") throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"CPM_DEGREE")) // degree of polynomial { coregpminput.degree = atoi(word[1]) ; // pass keyword writearg(coregpminput.degree); if (coregpminput.degree > 4) WARNING.print("CPM_DEGREE: degree > 4 dangerous at edges?"); } // ********************************************************************** else if (!strcmp(keyword,"CPM_WEIGHT")) // weightmatrix { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"NONE")) coregpminput.weightflag = 0; // default else if (!strcmp(keyword,"LINEAR")) coregpminput.weightflag = 1; else if (!strcmp(keyword,"QUADRATIC")) coregpminput.weightflag = 2; else if (!strcmp(keyword,"BAMLER")) coregpminput.weightflag = 3; else { ERROR << "CPM_WEIGHT: data weighting option: " << keyword << " not known for computation of coregistration parameters on line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"CPM_MAXITER")) // max number of offsets to reject { coregpminput.maxiter = atoi(word[1]) ; // pass keyword writearg(coregpminput.maxiter); if (coregpminput.maxiter < 0) { WARNING.print("CPM_MAXITER: max. number of points to remove < 0? (using 0)"); coregpminput.maxiter = 0; } } // ********************************************************************** else if (!strcmp(keyword,"CPM_K_ALPHA")) // critical value for outlier removal { coregpminput.k_alpha = atof(word[1]) ; // pass keyword writearg(coregpminput.k_alpha); if (coregpminput.k_alpha < 0) { WARNING.print("CPM_K_ALPHA: critical value < 0.0?"); coregpminput.k_alpha = 1.97; } } // ********************************************************************** else if (!strcmp(keyword,"CPM_DUMP")) // boolean { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"OFF")) coregpminput.dumpmodel = false; else if (!strcmp(keyword,"ON") || !strncmp(keyword,"//",2) || // comment !strncmp(keyword,"#",1) || // comment !(keyword[0] == '\0')) // no keyword coregpminput.dumpmodel = true; else { WARNING << "CPM_DUMP: line " << linecnt << ": argument: " << keyword << " not recognized, no dumping to files."; WARNING.print(); } } // ********************************************************************** else if (!strcmp(keyword,"CPM_PLOT")) // plotting results { coregpminput.plot = true; keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"BG")) coregpminput.plotmagbg = true; else if (!strcmp(keyword,"NOBG")) coregpminput.plotmagbg = false; else if (!strcmp(keyword,"ON")) // actually not allowed... coregpminput.plot = true; else if (!strcmp(keyword,"OFF")) // actually not allowed... coregpminput.plot = false; else WARNING.print("CPM_PLOT: missing argument. (default NOBG magnitude background)"); } // ********************************************************************** // *** RANGE FILTERING // ********************************************************************** else if (!strcmp(keyword,"RF_METHOD")) // method range filtering { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"ADAPTIVE")) filtrangeinput.method = rf_adaptive; else if (!strcmp(keyword,"PORBITS")) filtrangeinput.method = rf_porbits; else { ERROR << "RF_METHOD: method " << keyword << " not known for range filtering. line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"RF_SLOPE")) // terrain method porbits { filtrangeinput.terrainslope = atof(word[1]) ; // pass keyword writearg(filtrangeinput.terrainslope); deg2rad(filtrangeinput.terrainslope); } // ********************************************************************** else if (!strcmp(keyword,"RF_THRESHOLD")) // threshhold value { filtrangeinput.SNRthreshold = atof(word[1]) ; // pass keyword writearg(filtrangeinput.SNRthreshold); } // ********************************************************************** else if (!strcmp(keyword,"RF_HAMMING")) // alpha { filtrangeinput.hammingalpha = atof(word[1]) ; // pass keyword writearg(filtrangeinput.hammingalpha); } // ********************************************************************** else if (!strcmp(keyword,"RF_WEIGHTCORR")) // boolean { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"OFF")) filtrangeinput.doweightcorrel = false; else if (!strcmp(keyword,"ON") || !strncmp(keyword,"//",2) || // comment !strncmp(keyword,"#",1) || // comment !(keyword[0] == '\0')) // no keyword filtrangeinput.doweightcorrel = true; else { filtrangeinput.doweightcorrel = false; // default already... WARNING << "RF_WEIGHTCORREL: line " << linecnt << ": argument: " << keyword << " not recognized, weighting correlation set to OFF."; WARNING.print(); } } // ********************************************************************** else if (!strcmp(keyword,"RF_OVERSAMPLE")) // int { filtrangeinput.oversample = atoi(word[1]) ; // pass keyword writearg(filtrangeinput.oversample); } // ********************************************************************** else if (!strcmp(keyword,"RF_NLMEAN")) // take mean over nlmean lines { filtrangeinput.nlmean = atoi(word[1]) ; // pass keyword if (!isodd(filtrangeinput.nlmean)) // check if ODD value [MA] { PRINT_ERROR("RF_NLMEAN value has to be odd.") throw(argument_error); } writearg(filtrangeinput.nlmean); } // ********************************************************************** else if (!strcmp(keyword,"RF_FFTLENGTH")) // adaptive length { filtrangeinput.fftlength = atoi(word[1]) ; // pass keyword writearg(filtrangeinput.fftlength); } // ********************************************************************** else if (!strcmp(keyword,"RF_OVERLAP")) // overlap blocks { filtrangeinput.overlap = atoi(word[1]) ; // pass keyword writearg(filtrangeinput.overlap); } // ********************************************************************** else if (!strcmp(keyword,"RF_OUT_MASTER")) // filename { strcpy(filtrangeinput.fomaster, word[1] ); // pass keyword writearg(filtrangeinput.fomaster); } // ********************************************************************** else if (!strcmp(keyword,"RF_OUT_SLAVE")) // filename { strcpy(filtrangeinput.foslave, word[1] ); // pass keyword writearg(filtrangeinput.foslave); } // ********************************************************************** else if (!strcmp(keyword,"RF_OUT_FORMAT")) // output format { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"CR4")) filtrangeinput.oformatflag = FORMATCR4; // default else if (!strcmp(keyword,"CI2")) filtrangeinput.oformatflag = FORMATCI2; else { ERROR << "RF_OUT_FORMAT: output format " << keyword << " not known for range filtering. line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** // *** FLAT EARTH CORRECTION == compute reference phase since Feb-2000 // ********************************************************************** else if (!strcmp(keyword,"FE_METHOD")) // method selector flatearth { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"PORBITS")) comprefphainput.method=fe_porbits; else if (!strcmp(keyword,"METHOD2")) comprefphainput.method=fe_method2; else { ERROR << "FE_METHOD: argument: " << keyword << " not recognized."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"FE_DEGREE")) // degree for flat earth correction { comprefphainput.degree = atoi(word[1]) ; // pass keyword writearg(comprefphainput.degree); } // ********************************************************************** else if (!strcmp(keyword,"FE_NPOINTS")) // number of points used { // for estimation of polynomial comprefphainput.Npoints = atoi(word[1]) ; // pass keyword // flat earth correction. writearg(comprefphainput.Npoints); } // ********************************************************************** else if (!strcmp(keyword,"FE_IN_POS")) // file with #windows positions { strcpy(comprefphainput.ifpositions, word[1] ); // pass keyword writearg(comprefphainput.ifpositions); } // ********************************************************************** // *** RESAMPLING (SLAVE) // ********************************************************************** else if (!strcmp(keyword,"RS_METHOD")) // method selector resampling { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"CC4P")) resampleinput.method = rs_cc4p; // default else if (!strcmp(keyword,"CC6P")) resampleinput.method = rs_cc6p; else if (!strcmp(keyword,"TS6P")) resampleinput.method = rs_ts6p; else if (!strcmp(keyword,"TS8P")) resampleinput.method = rs_ts8p; else if (!strcmp(keyword,"TS16P")) resampleinput.method = rs_ts16p; else if (!strcmp(keyword,"KNAB4P")) resampleinput.method = rs_knab4p; else if (!strcmp(keyword,"KNAB6P")) resampleinput.method = rs_knab6p; else if (!strcmp(keyword,"KNAB8P")) resampleinput.method = rs_knab8p; else if (!strcmp(keyword,"KNAB10P")) resampleinput.method = rs_knab10p; else if (!strcmp(keyword,"KNAB16P")) resampleinput.method = rs_knab16p; else if (!strcmp(keyword,"RC6P")) resampleinput.method = rs_rc6p; else if (!strcmp(keyword,"RC12P")) resampleinput.method = rs_rc12p; else if (!strcmp(keyword,"RECT")) resampleinput.method = rs_rect; else if (!strcmp(keyword,"TRI")) resampleinput.method = rs_tri; else { ERROR << "RS_METHOD: method " << keyword << " not known for resampling. line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"RS_DBOW")) // database output window { resampleinput.dbow.linelo = atoi(word[1]); resampleinput.dbow.linehi = atoi(word[2]); resampleinput.dbow.pixlo = atoi(word[3]); resampleinput.dbow.pixhi = atoi(word[4]); writearg(resampleinput.dbow.linelo); writearg(resampleinput.dbow.linehi); writearg(resampleinput.dbow.pixlo); writearg(resampleinput.dbow.pixhi); if (resampleinput.dbow.linelo <= 0 || resampleinput.dbow.pixlo <= 0 || resampleinput.dbow.linelo > resampleinput.dbow.linehi || resampleinput.dbow.pixlo > resampleinput.dbow.pixhi) { ERROR << "code 300: Arguments of RS_DBOW card on line " << linecnt << " missing. [RS_DBOW min_line max_line min_pixel max_pixel]."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"RS_DBOW_GEO")) // database output // window on GEO.LOCATION { // use dbow to store temp, compute later real8 tmp_lat_0; real8 tmp_lon_0; real8 tmp_height; // total height, not half.window real8 tmp_width; // total width, not half.windo char *pLast1, *pLast2, *pLast3, *pLast4 = NULL; tmp_lat_0 = strtod(word[1], &pLast1); tmp_lon_0 = strtod(word[2], &pLast2); tmp_height = strtod(word[3], &pLast2); tmp_width = strtod(word[4], &pLast2); if ( pLast1 == word[1] || pLast2 == word[2] || pLast3 == word[3] || pLast4 == word[4] ) // fails to convert one of them to double. { ERROR << "RS_DBOW_GEO: " << word[1] << " : " << word[2] << " : " << word[3] << " : " << word[4] << " are not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(tmp_lat_0); writearg(tmp_lon_0); writearg(tmp_height); writearg(tmp_width); resampleinput.dbow_geo.linelo = uint((360.0+tmp_lat_0)*1e6); resampleinput.dbow_geo.linehi = uint((360.0+tmp_lon_0)*1e6); resampleinput.dbow_geo.pixlo = uint(tmp_height); resampleinput.dbow_geo.pixhi = uint(tmp_width); } // ********************************************************************** else if (!strcmp(keyword,"RS_OUT_FILE")) // name of output file { switch (priorrs_fileout) { case true: WARNING << "RS_OUT_FILE: line: " << linecnt << ": " << "ignored due to prior occurence."; WARNING.print(); break; default: priorrs_fileout = true; strcpy(resampleinput.fileout, word[1] ); // pass keyword (filename) writearg(resampleinput.fileout); } } // ********************************************************************** else if (!strcmp(keyword,"RS_OUT_FORMAT")) // output format { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"CR4")) resampleinput.oformatflag = FORMATCR4; // default else if (!strcmp(keyword,"CI2")) resampleinput.oformatflag = FORMATCI2; else { ERROR << "RS_OUT_FORMAT: output format " << keyword << " not known for resampling. line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"RS_SHIFTAZI")) // true: shift before rs. { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"OFF") || !strncmp(keyword,"//",2) || // comment !strncmp(keyword,"#",1) || //comment !strcmp(keyword,"NONE")) // just in case resampleinput.shiftazi = 0; else if (!strcmp(keyword,"DERAMP")) //Only for TOPS resampleinput.shiftazi = 2; else if (!strcmp(keyword,"ON") || // consistent with previous versions !strcmp(keyword,"DC") || // Doppler centroid polynomial (keyword[0] == '\0')) // no keyword resampleinput.shiftazi = 1; else { resampleinput.shiftazi = 1; WARNING << "RS_SHIFTAZI: line: " << linecnt << ": unknown argument: " << keyword << "; Set to ON (do shift azimuth spectrum)."; WARNING.print(); } } // ********************************************************************** // *** COMPUTATION OF INTERFEROGRAM // ********************************************************************** else if (!strcmp(keyword,"INT_METHOD")) // method selector interfero { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"OLD")) interferoinput.method = int_oldmethod; else if (!strcmp(keyword,"OVERSAMPLE")) interferoinput.method = int_oversample; else { ERROR << "INT_METHOD: method " << keyword << " not known for interfero. line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"INT_OUT_INT")) // name of output file { strcpy(interferoinput.foint, word[1] ); // pass keyword writearg(interferoinput.foint); } // ********************************************************************** else if (!strcmp(keyword,"INT_OUT_CINT")) // name of output file { strcpy(interferoinput.focint, word[1] ); // pass keyword writearg(interferoinput.focint); } // ********************************************************************** // else if (!strcmp(keyword,"INT_OUT_FE")) // name of output file // interferoinput.foflatearth = word[1] ; // pass keyword // ********************************************************************** else if (!strcmp(keyword,"INT_MULTILOOK")) // multilookfactors { interferoinput.multilookL = atoi(word[1]); // pass keyword interferoinput.multilookP = atoi(word[2]); // pass keyword writearg(interferoinput.multilookL); writearg(interferoinput.multilookP); } // ********************************************************************** // *** COMPUTATION OF COHERENCE // ********************************************************************** else if (!strcmp(keyword,"COH_METHOD")) // method selector coherence { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"REFPHASE_ONLY")) // OLD coherenceinput.method = coh_oldmethod; else if (!strcmp(keyword,"INCLUDE_REFDEM")) // NEW coherenceinput.method = coh_newmethod; else { ERROR << "COH_METHOD: method " << keyword << " not known for coherence. line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"COH_OUT_COH")) // name of output file { strcpy(coherenceinput.focoh, word[1] ); // pass keyword writearg(coherenceinput.focoh); } // ********************************************************************** else if (!strcmp(keyword,"COH_OUT_CCOH")) // name of output file { strcpy(coherenceinput.foccoh, word[1] ); // pass keyword writearg(coherenceinput.foccoh); } // ********************************************************************** else if (!strcmp(keyword,"COH_MULTILOOK")) // multilookfactors { coherenceinput.multilookL = atoi(word[1]); // pass keyword coherenceinput.multilookP = atoi(word[2]); // pass keyword writearg(coherenceinput.multilookL); writearg(coherenceinput.multilookP); } // ********************************************************************** else if (!strcmp(keyword,"COH_WINSIZE")) // estimator winsize { coherenceinput.cohsizeL = atoi(word[1]); // pass keyword coherenceinput.cohsizeP = atoi(word[2]); // pass keyword writearg(coherenceinput.cohsizeL); writearg(coherenceinput.cohsizeP); } // ********************************************************************** // *** SUBTRACTION OF REFERENCE PHASE // ********************************************************************** else if (!strcmp(keyword,"SRP_METHOD")) // method selector ref. phase { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"POLYNOMIAL")) subtrrefphainput.method = srp_polynomial; else if (!strcmp(keyword,"EXACT")) subtrrefphainput.method = srp_exact; else { ERROR << "SRP_METHOD: method " << keyword << " not known for subtraction of ref. phase. line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"SRP_OUT_CINT")) // name of output file { strcpy(subtrrefphainput.focint, word[1] ); // pass keyword writearg(subtrrefphainput.focint); } // ********************************************************************** else if (!strcmp(keyword,"SRP_OUT_REFPHA")) // name of output file { strcpy(subtrrefphainput.forefpha, word[1] ); // pass keyword writearg(subtrrefphainput.forefpha); } // ********************************************************************** else if (!strcmp(keyword,"SRP_DUMPREFPHA")) // true: dump ref.pha { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"ON")) subtrrefphainput.dumponlyrefpha = true; else if (!strcmp(keyword,"OFF") || !strncmp(keyword,"//",2) || // comment !strncmp(keyword,"#",1) || // comment !(keyword[0] == '\0')) // no keyword subtrrefphainput.dumponlyrefpha = false; else { subtrrefphainput.dumponlyrefpha = false; WARNING << "SRP_DUMPREFPHA: line: " << linecnt << ": unknown argument: " << keyword << "; Set to OFF (no dump)."; WARNING.print(); } } // ********************************************************************** // ___________ added by FvL else if (!strcmp(keyword,"SRP_OUT_H2PH")) // name of output file { strcpy(subtrrefphainput.foh2ph, word[1] ); // pass keyword writearg(subtrrefphainput.foh2ph); } // ___________ end added by FvL // ********************************************************************** else if (!strcmp(keyword,"SRP_MULTILOOK")) // multilookfactors { subtrrefphainput.multilookL = atoi(word[1]) ; // pass keyword keyword = word[2] ; // pass keyword writearg(subtrrefphainput.multilookL); writearg(keyword); if (isdigit(keyword[0])) subtrrefphainput.multilookP = atoi(keyword); else // default same factor subtrrefphainput.multilookP = subtrrefphainput.multilookL; } // ********************************************************************** // *** PHASE FILTER // ********************************************************************** else if (!strcmp(keyword,"PF_METHOD")) // method selector phase filtering { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"GOLDSTEIN")) filtphaseinput.method = fp_goldstein; else if (!strcmp(keyword,"MODGOLDSTEIN")) filtphaseinput.method = fp_modgoldstein; else if (!strcmp(keyword,"SPATIALCONV")) filtphaseinput.method = fp_spatialconv; else if (!strcmp(keyword,"SPECTRAL")) filtphaseinput.method = fp_spectral; else { ERROR << "PF_METHOD: method " << keyword << " not known for phase filtering. line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"PF_OUT_FILE")) // filename { strcpy(filtphaseinput.fofiltphase, word[1] ); // pass keyword writearg(filtphaseinput.fofiltphase); } // ********************************************************************** else if (!strcmp(keyword,"PF_IN_FILE")) // filename { strcpy(filtphaseinput.fifiltphase , word[1] ); // pass keyword char *pLast = NULL; filtphaseinput.finumlines = strtoul(word[1], &pLast, BASE10); // pass numoflines if ( pLast == word[2] ) // fails to convert one of them to double. { ERROR << "PF_IN_FILE (numoflines): " << word[2] << " are not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(filtphaseinput.fifiltphase); writearg(filtphaseinput.finumlines); } // ********************************************************************** else if (!strcmp(keyword,"PF_BLOCKSIZE")) // buffersize { filtphaseinput.blocksize = atoi(word[1]) ; // pass keyword writearg(filtphaseinput.blocksize); } // ********************************************************************** else if (!strcmp(keyword,"PF_ALPHA")) // alpha { filtphaseinput.alpha = atof(word[1]) ; // pass keyword writearg(filtphaseinput.alpha); } // ********************************************************************** else if (!strcmp(keyword,"PF_OVERLAP")) // overlap { filtphaseinput.overlap = atoi(word[1]) ; // pass keyword writearg(filtphaseinput.overlap); } // ********************************************************************** else if (!strcmp(keyword,"PF_KERNEL")) // conv. kernel e.g. 3 1 1 1 { keyword = word[1] ; // pass keyword const int32 sizekernel = atoi(keyword); writearg(sizekernel); if (!(isodd(sizekernel))) { PRINT_ERROR("PF_KERNEL: size must be odd! (add 0, center around midpix)") throw(keyword_error); } filtphaseinput.kernel.resize(1,sizekernel); real4 sum=0.; for (int32 argnum=0; argnum Using hgt format"); unwrapinput.oformatflag = FORMATHGT;// default } else if (!strcmp(keyword,"HGT")) unwrapinput.oformatflag = FORMATHGT;// default else { unwrapinput.oformatflag = FORMATHGT;// default WARNING << "UW_OUT_FORMAT: output format " << keyword << " not known (R4 or HGT, using HGT); line " << linecnt << "."; WARNING.print(); } } // ********************************************************************** else if (!strcmp(keyword,"UW_OUT_REGIONS")) // filename output regions { strcpy(unwrapinput.foregions, word[1] ); // pass keyword writearg(unwrapinput.foregions); } // ********************************************************************** else if (!strcmp(keyword,"UW_SNAPHU_MODE")) // filename output regions { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"TOPO")) strcpy(unwrapinput.snaphu_mode,"TOPO"); // default TOPO else if (!strcmp(keyword,"DEFO")) strcpy(unwrapinput.snaphu_mode,"DEFO"); else if (!strcmp(keyword,"SMOOTH")) strcpy(unwrapinput.snaphu_mode,"SMOOTH"); else if (!strcmp(keyword,"NOSTATCOSTS")) strcpy(unwrapinput.snaphu_mode,"NOSTATCOSTS"); else { ERROR << "UW_SNAPHU_MODE: " << keyword << " not known for unwrapping on line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"UW_SNAPHU_INIT")) { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"MST")) strcpy(unwrapinput.snaphu_init,"MST"); // default mst else if (!strcmp(keyword,"MCF")) strcpy(unwrapinput.snaphu_init,"MCF"); else { WARNING << "UW_SNAPHU_INIT: " << keyword << " not known for unwrapping on line " << linecnt << " (using MST)."; WARNING.print(); } } // ********************************************************************** else if (!strcmp(keyword,"UW_SNAPHU_LOG")) { strcpy(unwrapinput.snaphu_log, word[1] ); // pass keyword writearg(unwrapinput.snaphu_log); //strcpy(unwrapinput.snaphu_log,"-l "); //strcat(unwrapinput.snaphu_log,keyword); } // ********************************************************************** else if (!strcmp(keyword,"UW_SNAPHU_COH")) { strcpy(unwrapinput.snaphu_coh, word[1] ); // pass keyword writearg(unwrapinput.snaphu_coh); } // ********************************************************************** else if (!strcmp(keyword,"UW_SNAPHU_VERBOSE")) { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"OFF")) strcpy(unwrapinput.snaphu_verbose,"FALSE"); else if (!strcmp(keyword,"ON") || !strncmp(keyword,"//",2) || // comment !strncmp(keyword,"#",1) || // comment !(keyword[0] == '\0')) // no keyword strcpy(unwrapinput.snaphu_verbose,"TRUE"); else { strcpy(unwrapinput.snaphu_verbose,"TRUE"); WARNING << "UW_SNAPHU_VERBOSE: line: " << linecnt << ": unknown argument: " << keyword << "; Set to ON."; WARNING.print(); } } else if (!strcmp(keyword,"UW_SNAPHU_NTILEROW")) { unwrapinput.ntilerow = atoi(word[1]) ; // pass keyword writearg(unwrapinput.ntilerow); if (unwrapinput.ntilerow > 50) { WARNING.print("UW_SNAPHU_NTILEROW > 100 tiles, is this okay? "); } INFO << "UW_SNAPHU_NTILEROW: \t " << unwrapinput.ntilerow; INFO.print(); } else if (!strcmp(keyword,"UW_SNAPHU_NTILECOL")) { unwrapinput.ntilecol = atoi(word[1]) ; // pass keyword writearg(unwrapinput.ntilecol); if (unwrapinput.ntilecol > 50) { WARNING.print("UW_SNAPHU_NTILECOL > 100 tiles, is this okay? "); } INFO << "UW_SNAPHU_NTILECOL: \t " << unwrapinput.ntilecol; INFO.print(); } else if (!strcmp(keyword,"UW_SNAPHU_ROWOVRLP")) { unwrapinput.rowovrlp = atoi(word[1]) ; // pass keyword writearg(unwrapinput.rowovrlp); INFO << "UW_SNAPHU_ROWOVRLP: \t " << unwrapinput.rowovrlp; INFO.print(); } else if (!strcmp(keyword,"UW_SNAPHU_COLOVRLP")) { unwrapinput.colovrlp = atoi(word[1]) ; // pass keyword writearg(unwrapinput.colovrlp); INFO << "UW_SNAPHU_COLOVRLP: \t " << unwrapinput.colovrlp; INFO.print(); } else if (!strcmp(keyword,"UW_SNAPHU_NPROC")) { unwrapinput.nproc = atoi(word[1]) ; // pass keyword writearg(unwrapinput.nproc); if (unwrapinput.ntilecol > 2) { WARNING.print("UW_SNAPHU_NPROC > 2CPUs, do you have a cluster?"); } INFO << "UW_SNAPHU_NPROC: \t " << unwrapinput.ntilecol; INFO.print(); } else if (!strcmp(keyword,"UW_SNAPHU_TILECOSTTHRESH")) { unwrapinput.tilecostthresh = atoi(word[1]) ; // pass keyword writearg(unwrapinput.tilecostthresh); if (unwrapinput.ntilecol > 500) { WARNING.print("UW_SNAPHU_TILECOSTTHRESH > 500, do you have a cluster?"); } INFO << "UW_SNAPHU_TILECOSTTHRESH: \t " << unwrapinput.tilecostthresh; INFO.print(); } else if (!strcmp(keyword,"UW_SNAPHU_DUMPONLYCONF")) // { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"OFF")) unwrapinput.snaphu_dumponlyconf=false; else if (!strcmp(keyword,"ON") || !strncmp(keyword,"//",2) || // comment !strncmp(keyword,"#",1) || // comment !(keyword[0] == '\0')) // no keyword unwrapinput.snaphu_dumponlyconf=true; else { unwrapinput.snaphu_dumponlyconf=true; WARNING << "UW_SNAPHU_DUMPONLYCONF: line: " << linecnt << ": unknown argument: " << keyword << "; Set to ON."; WARNING.print(); } } // ********************************************************************** // *** SLANT to HEIGHT CONVERSION // ********************************************************************** else if (!strcmp(keyword,"S2H_METHOD")) // method selector slant2height { keyword = word[1] ; // pass keyword writearg(keyword); toupper(keyword); if (!strcmp(keyword,"SCHWABISCH")) slant2hinput.method = s2h_schwabisch; else if (!strcmp(keyword,"AMBIGUITY")) slant2hinput.method = s2h_ambiguity; else if (!strcmp(keyword,"RODRIGUEZ")) slant2hinput.method = s2h_rodriguez; else { ERROR << "S2H_METHOD: method " << keyword << " not known for slant to height conversion, line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"S2H_NPOINTS")) // number of points to use { slant2hinput.Npoints = atoi(word[1]) ; // pass keyword writearg(slant2hinput.Npoints); } // ********************************************************************** else if (!strcmp(keyword,"S2H_DEGREE1D")) // degree of 1d polynomial { slant2hinput.degree1d = atoi(word[1]) ; // pass keyword writearg(slant2hinput.degree1d); } // ********************************************************************** else if (!strcmp(keyword,"S2H_DEGREE2D")) // degree of 2d polynomial { slant2hinput.degree2d = atoi(word[1]) ; // pass keyword writearg(slant2hinput.degree2d); } // ********************************************************************** else if (!strcmp(keyword,"S2H_NHEIGHTS")) // #heights to evaluate ref.pha { slant2hinput.Nheights = atoi(word[1]) ; // pass keyword writearg(slant2hinput.Nheights); } // ********************************************************************** else if (!strcmp(keyword,"S2H_OUT_HEI")) // filename output height { strcpy(slant2hinput.fohei, word[1] ); // pass keyword writearg(slant2hinput.fohei); } // ********************************************************************** else if (!strcmp(keyword,"S2H_OUT_PHI")) // filename output latitude { strcpy(slant2hinput.fophi, word[1] ); // pass keyword writearg(slant2hinput.fophi); } // ********************************************************************** else if (!strcmp(keyword,"S2H_OUT_LAM")) // filename output longitude { strcpy(slant2hinput.folam, word[1] ); // pass keyword writearg(slant2hinput.folam); } // ********************************************************************** // *** GEOCODING // ********************************************************************** // else if (!strcmp(keyword,"GEO_METHOD")) // { // geocodeinput.method = word[1] ; // pass keyword // } // ********************************************************************** else if (!strcmp(keyword,"GEO_OUT_PHI")) // output file latitude { strcpy(geocodeinput.fophi, word[1] ); // pass keyword writearg(geocodeinput.fophi); } // ********************************************************************** else if (!strcmp(keyword,"GEO_OUT_LAM")) // output file longitude { strcpy(geocodeinput.folam, word[1] ); // pass keyword writearg(geocodeinput.folam); } // ____ start added by HB ____ // ********************************************************************** // *** ESTORBITS // ********************************************************************** else if (!strcmp(keyword,"EO_METHOD")) { keyword = word[1]; writearg(keyword); toupper(keyword); if (!strcmp(keyword,"LSQ")) estorbitsinput.method = eo_lsq; else if (!strcmp(keyword,"GRIDSEARCH")) estorbitsinput.method = eo_gridsearch; else { ERROR << "EO_METHOD: unknown method " << keyword << ", line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"EO_IN_DEM_LP")) { strcpy(estorbitsinput.fiheightmap, word[1]); writearg(estorbitsinput.fiheightmap); } // ********************************************************************** else if (!strcmp(keyword,"EO_OUT_RES")) { strcpy(estorbitsinput.foresiduals, word[1]); writearg(estorbitsinput.foresiduals); } // ********************************************************************** else if (!strcmp(keyword,"EO_WEIGHTING")) { keyword = word[1]; writearg(keyword); toupper(keyword); if (!strcmp(keyword,"NONE")) estorbitsinput.weighting = eo_noweighting; else if (!strcmp(keyword,"COH")) estorbitsinput.weighting = eo_coh; else if (!strcmp(keyword,"COH2")) estorbitsinput.weighting = eo_coh2; else if (!strcmp(keyword,"PDF")) estorbitsinput.weighting = eo_pdf; else { ERROR << "EO_WEIGHTING: unknown weighting scheme " << keyword << ", line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"EO_NPOINTS")) { estorbitsinput.nobs = atoi(word[1]); writearg(estorbitsinput.nobs); } // ********************************************************************** else if (!strcmp(keyword,"EO_IN_POS")) { strcpy(estorbitsinput.ifpositions,word[1] ); writearg(estorbitsinput.ifpositions); } // ********************************************************************** else if (!strcmp(keyword,"EO_THRESHOLD")) { estorbitsinput.threshold = atof(word[1]); writearg(estorbitsinput.threshold); if (estorbitsinput.threshold > 1) { ERROR << "EO_THRESHOLD: threshold > 1, line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"EO_MAXITER")) { estorbitsinput.maxiter = atoi(word[1]); writearg(estorbitsinput.maxiter); } // ********************************************************************** else if (!strcmp(keyword,"EO_K_ALPHA")) { estorbitsinput.k_alpha = atof(word[1]); writearg(estorbitsinput.k_alpha); if (estorbitsinput.k_alpha < 0) { ERROR << "EO_K_ALPHA: critical value < 0, line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // ********************************************************************** else if (!strcmp(keyword,"EO_SEARCHSPACE")) { char *pLast1, *pLast2 = NULL; estorbitsinput.maxfringesaz = strtoul(word[1], &pLast1, BASE10); estorbitsinput.maxfringesrg = strtoul(word[2], &pLast2, BASE10); if ( pLast1 == word[1] || pLast2 == word[2] ) // fails to convert one of them to double. { ERROR << "EO_SEARCHSPACE: " << word[1] << " : " << word[2] << " are not valid."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } writearg(estorbitsinput.maxfringesaz); writearg(estorbitsinput.maxfringesrg); if (estorbitsinput.maxfringesaz > 500 || estorbitsinput.maxfringesrg > 500) { WARNING << "EO_SEARCHSPACE: Parameters (" << estorbitsinput.maxfringesaz << "," << estorbitsinput.maxfringesrg << ") appear to be very high."; WARNING.print(); } } // ********************************************************************** else if (!strcmp(keyword,"EO_REFORBIT")) { strcpy(estorbitsinput.reforbitfile, word[1]); writearg(estorbitsinput.reforbitfile); } // ********************************************************************** else if (!strcmp(keyword,"EO_OUT_DATA")) { strcpy(estorbitsinput.foobsdata, word[1]); writearg(estorbitsinput.foobsdata); } // ********************************************************************** else if (!strcmp(keyword,"EO_DEGREE")) { estorbitsinput.poldegree = atoi(word[1]); writearg(estorbitsinput.poldegree); } // ********************************************************************** else if (!strcmp(keyword,"EO_CONSTRAIN")) { int16 npar = atoi(word[1]); writearg(npar); if (npar==0) estorbitsinput.constrained = false; else { estorbitsinput.constraints = matrix(npar,2); for (uint i=0; i15) { ERROR << "EO_CONSTRAIN: degree of parameter " << keyword << " is too high, line " << linecnt << "."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } else { estorbitsinput.constraints(i,0) = component; estorbitsinput.constraints(i,1) = deriv; } } } } // ____ end added by HB ____ // ********************************************************************** // Assume wrong keyword, but if it starts with //, a c, or comment // then continue with a warning, no blank between key and arg // ********************************************************************** else if (!strncmp(keyword,"COMMENT",7) || // assume user wanted to comment out !strncmp(keyword,"C",1)) // but forgot a space { WARNING << "Obsolete or unknown keyword: \"" << keyword << "\" at line: " << linecnt << ". (Interpreted as comment, ignored)"; WARNING.print(); } // ______ Really cannot make anything from your input ______ else { //ERROR << "Unknown keyword: \"" << keyword // << "\" at line: " << linecnt << "."; //PRINT_ERROR(ERROR.get_str()) //throw(keyword_error); WARNING << "Unknown keyword: \"" << keyword << "\" at line: " << linecnt << "."; WARNING.print(); } //optionsfile.getline(eachline,4*ONE27,'\n'); // goto next line. [MA] needs debug if the line is long loops forever. } // end while (file) // ====== Check input/ info to screen ====== checkgeneral(generalinput, onlyprocess); // also repair onlyprocess INFO << "LISTINPUT: \tAppend input to logfile: \t" << listinput; INFO.print(); // ______ info ELLIPSOID card, compute and fill e2, e2b ______ ellipsinput.showdata(); // ====== Check input of step reading info from files ====== if (generalinput.process[pr_m_readfiles]) checkreadfiles(m_readfilesinput, MASTERID); // check mandatory cards if (generalinput.process[pr_s_readfiles]) checkreadfiles(s_readfilesinput, SLAVEID); // check mandatory cards // ====== Check input of step conversion slc to raw ====== if (generalinput.process[pr_m_crop]) { checkcrop(m_cropinput, MASTERID); if (!strcmp(s_cropinput.fileout1,m_cropinput.fileout1)) { PRINT_ERROR( "code 301: same name outputfile CROP_OUT for master and slave not allowed.") throw(keyword_error); } if (generalinput.overwrit) if (existed(m_cropinput.fileout1)) { INFO << "OVERWRIT: file " << m_cropinput.fileout1 << " will be overwritten."; INFO.print(); } } if (generalinput.process[pr_s_crop]) { checkcrop(s_cropinput, SLAVEID); if (!strcmp(s_cropinput.fileout1,m_cropinput.fileout1)) { PRINT_ERROR( "code 301: same name outputfile CROP_OUT for master and slave not allowed.") throw(keyword_error); } if (generalinput.overwrit) if (existed(s_cropinput.fileout1)) { INFO << "OVERWRIT: file " << s_cropinput.fileout1 << " will be overwritten."; INFO.print(); } } //____RaffaeleNutricato START MODIFICATION SECTION 10 // ====== Check input of step oversample master====== if (generalinput.process[pr_m_oversample]) { checkoversample(m_oversample, MASTERID); } // ====== Check input of step oversampling slave ====== if (generalinput.process[pr_s_oversample]) { checkoversample(s_oversample, SLAVEID); } //____RaffaeleNutricato END MODIFICATION SECTION 10 // ====== Check input of step porbits ====== if (generalinput.process[pr_m_porbits]) checkporbits(porbitsinput, MASTERID); if (generalinput.process[pr_s_porbits]) checkporbits(porbitsinput, SLAVEID); // ____ start added by HB ____ // ====== Check input of steps m_modorb and s_modorb ====== if (generalinput.process[pr_m_morbits]) { // ______ determine polynomial degree => number of parameters ______ uint npar=2; for (int16 i=9; i>=0; i--) { if (morbitsinputmaster.coeff(i,0)!=0 || morbitsinputmaster.coeff(i,1)!=0) { npar = 2*(i+1); break; } } // ______ resize coefficient matrices ______ morbitsinputmaster.coeff.setdata(npar/2,0,morbitsinputmaster.coeff.getdata(window(0,npar/2-1,1,1))); matrix temp = morbitsinputmaster.coeff.getdata(window(0,npar-1,0,0)); morbitsinputmaster.coeff.resize(npar,1); morbitsinputmaster.coeff = temp; for (int p=0; p number of parameters ______ uint npar=2; for (int16 i=9; i>=0; i--) if (morbitsinputslave.coeff(i,0)!=0 || morbitsinputslave.coeff(i,1)!=0) { npar = 2*(i+1); break; } // ______ resize coefficient matrices ______ morbitsinputslave.coeff.setdata(npar/2,0,morbitsinputslave.coeff.getdata(window(0,npar/2-1,1,1))); matrix temp = morbitsinputslave.coeff.getdata(window(0,npar-1,0,0)); morbitsinputslave.coeff.resize(npar,1); morbitsinputslave.coeff = temp; for (int p=0; p(2,2); estorbitsinput.constraints(0,0) = 0; estorbitsinput.constraints(0,1) = 0; estorbitsinput.constraints(1,0) = 1; estorbitsinput.constraints(1,1) = 1; } // ______ check selection method of observation points ______ if (specified(estorbitsinput.ifpositions)) // filename specified { if (estorbitsinput.nobs != 0) // something is specified { WARNING << "EO_NOBS: \t" << estorbitsinput.nobs << " ignored due to existence of input file (EO_IN_POS) " << estorbitsinput.ifpositions; WARNING.print(); } estorbitsinput.nobs = filelines(estorbitsinput.ifpositions); } else if (estorbitsinput.nobs == 0) // no inputfile, default { estorbitsinput.nobs = def_eo_nobs; INFO << "Default number of " << def_eo_nobs << " observations will be used for orbit error estimation."; INFO.print(); } } // ====== Check input of step slant2height ====== if (generalinput.process[pr_i_slant2h]) { if (slant2hinput.method == def_s2h_method-999) { slant2hinput.method = def_s2h_method; // default method INFO.print("Default method will be used for slant2h."); } if (slant2hinput.Nheights <= slant2hinput.degree1d) { WARNING << "S2H_NHEIGHTS: \t" << slant2hinput.Nheights << " is too large because S2H_DEGREE1D=" << slant2hinput.degree1d << "; set S2H_NHEIGHTS = " << slant2hinput.degree1d+1 << " (minimum)"; WARNING.print(); slant2hinput.Nheights = slant2hinput.degree1d + 1; } checkslant2h(slant2hinput); } // ====== Check input of step geocoding ====== if (generalinput.process[pr_i_geocoding]) { checkgeocode(geocodeinput); } // ====== Check input of dinsar step interferogram ====== if (generalinput.process[pr_i_dinsar]) { if (!strcmp(dinsarinput.topomasterresfile,generalinput.m_resfile)) setunspecified(dinsarinput.topomasterresfile); // used in check... checkdinsar(dinsarinput); if (!specified(dinsarinput.topomasterresfile)) strcpy(dinsarinput.topomasterresfile,generalinput.m_resfile); } // ====== Check input of reserved EXTRA step interferogram ====== if (generalinput.process[pr_i_EXTRA2]) { PRINT_ERROR("extra step2 interferogram not implemented.") throw(keyword_error); } // ====== Copy input to logfile (via scratchfile, update in main) ====== // to avoid problems with not existing file it is always opened here ofstream scratchreadinput("scratchreadinput", ios::out | ios::trunc); bk_assert(scratchreadinput,"readinput: scratchreadinput",__FILE__,__LINE__); if (listinput) { // ______Start writing______ linecnt=0; scratchreadinput << "\n----------------------------------------------------\n" << " BEGIN: copy of input (non-interpretive).\n" << "-line---keyword----argument-------------comment-----\n"; optionsfile.seekg(0,ios::beg); optionsfile.clear(); // clear eofbit optionsfile.getline(eachline,4*ONE27,'\n'); while (optionsfile) { linecnt++; scratchreadinput << setw(3) << linecnt << ": " << eachline << endl; optionsfile.getline(eachline,4*ONE27,'\n'); } scratchreadinput << "\n----------------------------------------------------\n" << " END: copy of input.\n" << "----------------------------------------------------\n\n"; DEBUG.print("Finished writing to scratchreadinput."); } // ______Tidy up______ PROGRESS.print("Interpretation inputoptionsfile finished."); scratchreadinput.close(); optionsfile.close(); } // END READINPUT /**************************************************************** * checkgeneral * * * * Checks general cards. * * Repair process card * * * * Bert Kampes, 06-Sep-1999 * ****************************************************************/ void checkgeneral( input_gen &generalinput, const int16 onlyprocess) { TRACE_FUNCTION("checkgeneral (BK 06-Sep-1999)") register int32 i; int32 cs_processcard = 0; // ______ Repair process control if ONLYPROCESS card was present ______ for (i=0; i 1) WARNING.print("PROCESS cards ignored due to presence ONLYPROCESS card."); for (i=0; i " << fineinput.plotthreshold; INFO.print(); } else { WARNING.print("It is highly recommended to use FC_PLOT to plot the computed FINE offset vectors."); } if (fineinput.plotmagbg) INFO.print("FC_PLOT: magnitude will be in background of plot."); INFO << "FC_WINSIZE for correlation: (l,p) = (" << fineinput.MasksizeL << ", " << fineinput.MasksizeP << ")."; INFO.print(); INFO.print("Max. estimable offset is half the window size"); INFO.print("If the offset varies a lot over the image, use larger winsize"); INFO << "FC_WINSIZE for oversampling (2*Acc): (l,p) = (" << 2*fineinput.AccL << ", " << 2*fineinput.AccP << ")."; INFO.print(); INFO << "FC_OSFACTOR: " << fineinput.osfactor << ". Oversampling factor for fine coregistration."; INFO.print(); if (!ispower2(fineinput.osfactor)) { ERROR << " no power of 2."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } } // END checkfine /**************************************************************** * checksimamp * * * * Checks cards for step simamp. * * * * Mahmut Arikan, 30-Oct-2008 * ****************************************************************/ void checksimamp( const input_simamp &simampinput) { TRACE_FUNCTION("checksimamp (MA 30-oct-2008)") INFO.print("\n\t*** Input for step SIMAMP ***"); INFO << "SAM_IN_DEM: \t" << simampinput.firefdem; INFO.print(); if (specified(simampinput.fothetalp)) // MA SPT { INFO << "SAM_OUT_THETA_LP: \t" << simampinput.fothetalp << "; output requested of incidence angle THETA [rad] in radar coordinates."; INFO.print(); } if (specified(simampinput.fodemlp)) // MA SPT { INFO << "SAM_OUT_DEM_LP: \t" << simampinput.fodemlp << "; output requested of DEM [m] in radar coordinates."; INFO.print(); } if (specified(simampinput.fodem)) { INFO << "SAM_OUT_DEM: \t" << simampinput.fodem << "; output requested of input DEM."; INFO.print(); if (!strcmp(simampinput.fosimamp,simampinput.fodem)) { PRINT_ERROR("OUT_DEM, OUT_FILE: Same output file name."); throw(keyword_error); } } if (specified(simampinput.fosimamp)) { INFO << "SAM_OUT_FILE: \t" << simampinput.fosimamp << "; output requested of simulated amplitude."; INFO.print(); if (!strcmp(simampinput.fosimamp,simampinput.fodem)) { PRINT_ERROR("OUT_DEM, OUT_FILE: Same output file name."); throw(keyword_error); } } INFO << "SAM_IN_SIZE: \t" << simampinput.demrows << " " << simampinput.demcols << "; number of rows (latitude), columns (lon) in DEM."; INFO.print(); INFO << "SAM_IN_UL: \t" << rad2deg(simampinput.demlatleftupper) << " " << rad2deg(simampinput.demlonleftupper) << "; coordinates of upper left corner (first row/col)."; INFO.print(); INFO << "SAM_IN_DELTA: \t" << rad2deg(simampinput.demdeltalat) << " " << rad2deg(simampinput.demdeltalon); INFO.print(); INFO << "SAM_IN_NODATA: \t" << simampinput.demnodata << "; this number in DEM will be set to 0 reference phase."; INFO.print(); INFO << "SAM_IN_FORMAT: \tinput format DEM: \t"; switch (simampinput.iformatflag) { case FORMATR4: INFO << "real4."; break; case FORMATR8: INFO << "real8."; break; case FORMATI2: INFO << "signed short."; break; case FORMATI2_BIGENDIAN: INFO << "signed short big endian."; break; default: PRINT_ERROR("totally impossible, checked input."); throw(keyword_error); } INFO.print(); // ______ Check some things ______ if (!existed(simampinput.firefdem)) { ERROR << "SAM_IN_DEM: \t" << simampinput.firefdem << " can not be opened."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } if (rad2deg(simampinput.demdeltalat)<.0002) // [MA] 1 arc secs = 1/3600=0.00027 : allow finer resolutions { WARNING << "SAM_IN_DELTA: \t" << rad2deg(simampinput.demdeltalat) << " [deg] seems very small (input in decimal degrees)."; WARNING.print(); } if (simampinput.demrows<1 || simampinput.demrows>100000) { WARNING << "SAM_DEM_SIZE: numrows: \t" << simampinput.demrows << " seems to be wrong."; WARNING.print(); } if (simampinput.demcols<1 || simampinput.demcols>100000) { WARNING << "SAM_DEM_SIZE: numcols: \t" << simampinput.demcols << " seems to be wrong."; WARNING.print(); } if (rad2deg(simampinput.demdeltalon)<.0002) { WARNING << "SAM_IN_DELTA: \t" << simampinput.demdeltalon << " seems very small (it should be in decimal degrees)."; WARNING.print(); } if (rad2deg(simampinput.demlatleftupper) < -90. || rad2deg(simampinput.demlatleftupper) > 90. ) { ERROR << "SAM_IN_LU: \t" << rad2deg(simampinput.demlatleftupper) << " out of range (-90:90)."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } if (rad2deg(simampinput.demlonleftupper) < -180. || rad2deg(simampinput.demlonleftupper) > 180. ) { WARNING << "SAM_IN_LU: \t" << rad2deg(simampinput.demlonleftupper) << " out of range (-180:180)."; WARNING.print(); } } // END simamp [MA] /**************************************************************** * checkmtiming * * * * Checks cards for step simamp corr. * * * * Mahmut Arikan, 11-Nov-2008 * ****************************************************************/ void checkmtiming( const input_mtiming &mtiminginput) { TRACE_FUNCTION("checkmtiming (MA, BO 11-Nov-2008)") INFO.print("\n\t*** Input for step MASTER TIMING ***"); switch (mtiminginput.method) { case cc_magfft: INFO.print("MTE_METHOD: \tMAGFFT is used for MASTER TIMING ERROR estimation."); break; case cc_magspace: INFO.print("MTE_METHOD: \tMAGSPACE is used for MASTER TIMING ERROR estimation."); break; default: PRINT_ERROR("panic."); throw(keyword_error); } if (specified(mtiminginput.ifpositions)) { INFO << "MTE_IN_POS: \tFile: " << mtiminginput.ifpositions << " containing " << mtiminginput.Nwin << " positions is used."; INFO.print(); } else // no input file { INFO << "MTE_NWIN: \tDistributing " << mtiminginput.Nwin << " windows for master timing error estimation (correlation)."; INFO.print(); } } // END checkmtiming // ____end added by MA ____ // ____start added by FvL ____ /**************************************************************** * checkreltiming * * * * Checks cards for step timing * * * * Freek van Leijen, 22-Aug-2007 * ****************************************************************/ void checkreltiming( const input_reltiming &timinginput) { TRACE_FUNCTION("checkreltiming (FvL 22-aug-2007)") INFO.print("\n\t*** Input for step REL_TIMING ***"); INFO << "RTE_THRESHOLD: \tThreshold correlation for model: \t" << timinginput.threshold; INFO.print(); INFO << "RTE_MAXITER: \tNumber of points to remove (max): \t" << timinginput.maxiter; INFO.print(); INFO << "RTE_K_ALPHA: \tCritical value for outlier test: \t" << timinginput.k_alpha; INFO.print(); } // END checkreltiming /**************************************************************** * checkdemassist * * * * Checks cards for step demassist. * * * * Freek van Leijen, 22-Aug-2007 * ****************************************************************/ void checkdemassist( const input_demassist &demassistinput) { TRACE_FUNCTION("checkdemassist (FvL 22-aug-2007)") INFO.print("\n\t*** Input for step DEMASSIST ***"); INFO << "DAC_IN_DEM: \t" << demassistinput.firefdem; INFO.print(); if (specified(demassistinput.forefdemhei)) { INFO << "DAC_OUT_DEM_LP: \t" << demassistinput.forefdemhei << "; output requested of DEM [m] in radar coordinates."; INFO.print(); } if (specified(demassistinput.fodem)) { INFO << "DAC_OUT_DEM: \t" << demassistinput.fodem << "; output requested of input DEM."; INFO.print(); if (!strcmp(demassistinput.fodemi,demassistinput.fodem)) { PRINT_ERROR("OUT_DEM, OUT_DEMI: Same output file name."); throw(keyword_error); } } if (specified(demassistinput.fodemi)) { INFO << "DAC_OUT_DEMI: \t" << demassistinput.fodemi << "; output requested of interpolated DEM."; INFO.print(); if (!strcmp(demassistinput.fodemi,demassistinput.fodem)) { PRINT_ERROR("OUT_DEM, OUT_DEMI: Same output file name."); throw(keyword_error); } } INFO << "DAC_IN_SIZE: \t" << demassistinput.demrows << " " << demassistinput.demcols << "; number of rows (latitude), columns (lon) in DEM."; INFO.print(); INFO << "DAC_IN_UL: \t" << rad2deg(demassistinput.demlatleftupper) << " " << rad2deg(demassistinput.demlonleftupper) << "; coordinates of upper left corner (first row/col)."; INFO.print(); INFO << "DAC_IN_DELTA: \t" << rad2deg(demassistinput.demdeltalat) << " " << rad2deg(demassistinput.demdeltalon); INFO.print(); INFO << "DAC_IN_NODATA: \t" << demassistinput.demnodata << "; this number in DEM will be set to 0 reference phase."; INFO.print(); INFO << "DAC_IN_FORMAT: \tinput format DEM: \t"; switch (demassistinput.iformatflag) { case FORMATR4: INFO << "real4."; break; case FORMATR8: INFO << "real8."; break; case FORMATI2: INFO << "signed short."; break; case FORMATI2_BIGENDIAN: INFO << "signed short big endian."; break; default: PRINT_ERROR("totally impossible, checked input."); throw(keyword_error); } INFO.print(); // ______ Check some things ______ if (!existed(demassistinput.firefdem)) { ERROR << "DAC_IN_DEM: \t" << demassistinput.firefdem << " can not be opened."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } if (rad2deg(demassistinput.demdeltalat)<.0002) //[MA] 1 arc secs = 1/3600=0.00027 : allow finer resolutions { WARNING << "DAC_IN_DELTA: \t" << rad2deg(demassistinput.demdeltalat) << " [deg] seems very small (input in decimal degrees)."; WARNING.print(); } if (demassistinput.demrows<1 || demassistinput.demrows>100000) { WARNING << "DAC_DEM_SIZE: numrows: \t" << demassistinput.demrows << " seems to be wrong."; WARNING.print(); } if (demassistinput.demcols<1 || demassistinput.demcols>100000) { WARNING << "DAC_DEM_SIZE: numcols: \t" << demassistinput.demcols << " seems to be wrong."; WARNING.print(); } if (rad2deg(demassistinput.demdeltalon)<.0002) { WARNING << "DAC_IN_DELTA: \t" << demassistinput.demdeltalon << " seems very small (it should be in decimal degrees)."; WARNING.print(); } if (rad2deg(demassistinput.demlatleftupper) < -90. || rad2deg(demassistinput.demlatleftupper) > 90. ) { ERROR << "DAC_IN_LU: \t" << rad2deg(demassistinput.demlatleftupper) << " out of range (-90:90)."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } if (rad2deg(demassistinput.demlonleftupper) < -180. || rad2deg(demassistinput.demlonleftupper) > 180. ) { WARNING << "DAC_IN_LU: \t" << rad2deg(demassistinput.demlonleftupper) << " out of range (-180:180)."; WARNING.print(); } } // END demassist // ____end added by FvL ____ /**************************************************************** * checkcoregpm * * * * Checks cards for step coregpm. * * * * Bert Kampes, 29-Sep-1999 * ****************************************************************/ void checkcoregpm( const input_coregpm &coregpminput) { TRACE_FUNCTION("checkcoregpm (BK 29-Sep-1999)") INFO.print("\n\t*** Input for step COREGPM ***"); INFO << "CPM_THRESHOLD: \tThreshold correlation for model: \t" << coregpminput.threshold; INFO.print(); INFO << "CPM_DEGREE: \tPolynomial for coregistration: \t" << coregpminput.degree; INFO.print(); INFO << "CPM_WEIGHT: \tData weighting option: \t" << coregpminput.weightflag << " (0 none, 1 linear, 2 quadratic, 3 bamler paper) is used."; INFO.print(); INFO << "CPM_MAXITER: \tNumber of points to remove (max): \t" << coregpminput.maxiter; INFO.print(); INFO << "CPM_K_ALPHA: \tCritical value for outlier test: \t" << coregpminput.k_alpha; INFO.print(); if (coregpminput.dumpmodel) INFO.print("CPM_DUMP: dumping model to files (see INFO)."); if (coregpminput.plot) INFO.print("CPM_PLOT: error vectors etc. will be plotted."); else WARNING.print("It is higly recommended to use CPM_PLOT to review the estimated model."); if (coregpminput.plotmagbg) INFO.print("CPM_PLOT: magnitude will be in background."); } // END checkcoregpm /**************************************************************** * checkcomprefpha * * * * Checks cards for step comprefpha. * * * * Bert Kampes, 29-Sep-1999 * ****************************************************************/ void checkcomprefpha( const input_comprefpha &comprefphainput) { TRACE_FUNCTION("checkcomprefpha (BK 29-Sep-1999)") INFO.print("\n\t*** Input for step COMPREFPHA ***"); switch (comprefphainput.method) { case fe_porbits: INFO.print("FE_METHOD: method for flatearth correction: PORBITS"); // ______ Check points from file or random distributed ______ if (specified(comprefphainput.ifpositions)) { INFO << "FE_IN_POS: file: " << comprefphainput.ifpositions << " containing " << comprefphainput.Npoints << " positions used for ref. phase estimation."; INFO.print(); } else // no input file { INFO << "FE_NPOINTS: Using " << comprefphainput.Npoints << " (random like) distributed points for estimation of refpha polynomial."; INFO.print(); } if (comprefphainput.Npoints > 5000) WARNING.print("FE_NPOINTS: Too many points requested?"); INFO << "FE_DEGREE: Using " << comprefphainput.degree << " order polynomial for flat Earth correction."; INFO.print(); if (comprefphainput.degree > 10) WARNING.print("FE_DEGREE: degree > 10?"); break; case fe_method2: INFO.print("FE_METHOD: method for flatearth correction: method2 :NOT IMPLEMENTED"); break; default: PRINT_ERROR("impossible, method name is checked while reading cards."); throw(keyword_error); } } // END checkcomprefpha /**************************************************************** * checksubtrrefpha * * * * Checks cards for step subtrrefpha. * * * * Bert Kampes, 09-Feb-2000 * ****************************************************************/ void checksubtrrefpha( const input_subtrrefpha &subtrrefphainput) { TRACE_FUNCTION("checksubtrrefpha (BK 09-Feb-2000)") INFO.print("\n\t*** Input for step SUBTRREFPHA ***"); // ______ Print info ______ switch (subtrrefphainput.method) { case srp_polynomial: INFO.print("SRP_METHOD: \tpolynomial: \tPolynomial from COMPREFPHA used."); break; case srp_exact: INFO.print("SRP_METHOD: \texact: \treference phase computed foreach pixel."); break; default: PRINT_ERROR("impossible, checked above."); throw(keyword_error); } if (subtrrefphainput.dumponlyrefpha==false) { INFO << "SRP_OUT_CINT: \toutputfile complex interferogram: \t" << subtrrefphainput.focint; INFO.print(); } INFO << "SRP_MULTILOOK: \tFactors (line pixel): \t" << subtrrefphainput.multilookL << " " << subtrrefphainput.multilookP; INFO.print(); if (subtrrefphainput.dumponlyrefpha==true) { WARNING.print("SRP_DUMPREFPHA: Only dumping reference phase, no subtraction."); INFO << "SRP_DUMPREFPHA: only dump refphase: " << subtrrefphainput.dumponlyrefpha; INFO.print(); INFO << "SRP_OUT_REFPHA: Output file reference phase: " << subtrrefphainput.forefpha; INFO.print(); } // __________ added by FvL if (specified(subtrrefphainput.foh2ph)) { INFO << "SRP_OUT_H2PH: \t" << subtrrefphainput.foh2ph << "; output requested of height-to-phase constant per resolution cell."; INFO.print(); } // ____________ end added by FvL // ______ Check ______ // [MA] increased from 100 to 1000 if (subtrrefphainput.multilookL > 1000 || subtrrefphainput.multilookP > 1000 || subtrrefphainput.multilookL < 1 || subtrrefphainput.multilookP < 1 ) WARNING.print("SRP_MULTILOOK: multilookfactor seems very high."); } // END checksubtrrefpha /**************************************************************** * checkresample * * * * Checks cards for step resample. * * * * Bert Kampes, 29-Sep-1999 * ****************************************************************/ void checkresample( const input_resample &resampleinput) { TRACE_FUNCTION("checkresample (BK 29-Sep-1999)") INFO.print("\n\t*** Input for step RESAMPLE ***"); INFO << "RS_OUT_FILE: \toutput filename: \t\t" << resampleinput.fileout; INFO.print(); INFO << "RS_OUT_FORMAT: output format: \t\t"; switch (resampleinput.oformatflag) { case FORMATCR4: INFO << "complex_real4."; break; case FORMATCI2: INFO << "complex_short."; break; default: PRINT_ERROR("totally impossible, checked input."); throw(keyword_error); } INFO.print(); if (resampleinput.dbow.linehi != 0 || resampleinput.dbow.pixhi != 0) { INFO << "RS_DBOW: \tOutput window: \t\t\t" << resampleinput.dbow.linelo << " " << resampleinput.dbow.linehi << " " << resampleinput.dbow.pixlo << " " << resampleinput.dbow.pixhi ; INFO.print(); } INFO << "RS_SHIFTAZI: \tshift azimuth spectrum: \t" << resampleinput.shiftazi ; INFO.print(); } // END checkresample /**************************************************************** * checkinterfero * * * * Checks cards for step interfero. * * * * Bert Kampes, 29-Sep-1999 * ****************************************************************/ void checkinterfero( const input_interfero &interferoinput) { TRACE_FUNCTION("checkinterfero (BK 29-Sep-1999)") INFO.print("\n\t*** Input for step INTERFERO ***"); bool filespecified = false; bool samefilename = false; if (specified(interferoinput.foint)) { filespecified = true; INFO << "INT_OUT_INT: \tOutputfile interferogram: \t" << interferoinput.foint; INFO.print(); if (!(strcmp(interferoinput.foint,interferoinput.focint))) samefilename = true; } if (specified(interferoinput.focint)) { filespecified = true; INFO << "INT_OUT_CINT: Outfile complex interferogram: \t" << interferoinput.focint; INFO.print(); if (!(strcmp(interferoinput.focint,interferoinput.foint))) samefilename = true; } // if (strcmp(interferoinput.foflatearth," ")) // something is specified // { // filespecified = true; // INFO << "INT_OUT_FE: data outputfile reference phase: \t" // << interferoinput.foflatearth; // INFO.print(); // if (!(strcmp(interferoinput.foflatearth,interferoinput.foint)) || // !(strcmp(interferoinput.foflatearth,interferoinput.focint))) // samefilename = true; // } INFO << "INT_MULTILOOK: \tFactor (line pixel): \t" << interferoinput.multilookL << " " << interferoinput.multilookP; INFO.print(); // [MA] increased from 100 to 1000 if (interferoinput.multilookL > 1000 || interferoinput.multilookP > 1000) { PRINT_ERROR("code ???: INT_MULTILOOK: > 1000."); throw(keyword_error); } if (interferoinput.multilookL < 1 || interferoinput.multilookP < 1) { PRINT_ERROR("code ???: INT_MULTILOOK: < 1."); throw(keyword_error); } if (!filespecified) { PRINT_ERROR("code ???: INT_OUT_*: at least one output file must be specified."); throw(keyword_error); } if (samefilename) { PRINT_ERROR("code ???: INT_OUT_*: same name output files."); throw(keyword_error); } } // END checkinterfero /**************************************************************** * checkcoherence * * * * Checks cards for step coherence. * * * * Bert Kampes, 29-Sep-1999 * ****************************************************************/ void checkcoherence( const input_coherence &coherenceinput) { TRACE_FUNCTION("checkcoherence (BK 29-Sep-1999)") INFO.print("\n\t*** Input for step COHERENCE ***"); bool filespecified = false; bool samefilename = false; if (specified(coherenceinput.foccoh)) { filespecified = true; INFO << "COH_OUT_CCOH: \tOutfile complex coherence: \t" << coherenceinput.foccoh; INFO.print(); if (!(strcmp(coherenceinput.foccoh,coherenceinput.focoh))) samefilename = true; } if (specified(coherenceinput.focoh)) { filespecified = true; INFO << "COH_OUT_COH: \tOutputfile coherence image: " << coherenceinput.focoh; INFO.print(); if (!(strcmp(coherenceinput.focoh,coherenceinput.foccoh))) samefilename = true; } INFO << "COH_MULTILOOK: \tFactor (line pixel): \t" << coherenceinput.multilookL << " " << coherenceinput.multilookP; INFO.print(); INFO << "COH_WINSIZE: \t window size coh. estimation (l/p): \t" << coherenceinput.cohsizeL << " " << coherenceinput.cohsizeP; INFO.print(); // [MA] increased from 100 to 1000 if (coherenceinput.multilookL > 1000 || coherenceinput.multilookP > 1000) { PRINT_ERROR("code ???: COH_MULTILOOK: > 1000."); throw(keyword_error); } if (coherenceinput.multilookL < 1 || coherenceinput.multilookP < 1) { PRINT_ERROR("code ???: COH_MULTILOOK: < 1."); throw(keyword_error); } if (coherenceinput.cohsizeL > 500 || coherenceinput.cohsizeP > 500) { PRINT_ERROR("code ???: COH_WINSIZE: > 500."); throw(keyword_error); } if (coherenceinput.cohsizeL < 1 || coherenceinput.cohsizeP < 1) { PRINT_ERROR("code ???: COH_WINSIZE: < 1."); throw(keyword_error); } if (!filespecified) { PRINT_ERROR("code ???: COH_OUT_*: at least one output file must be specified."); throw(keyword_error); } if (samefilename) { PRINT_ERROR("code ???: COH_OUT_*: same name output files."); throw(keyword_error); } } // END checkcoherence /**************************************************************** * checkcomprefdem * * * * Checks cards for step comprefdem. * * * * Bert Kampes, 14-Feb-2000 * ****************************************************************/ void checkcomprefdem( const input_comprefdem &comprefdeminput) { TRACE_FUNCTION("checkcomprefdem (BK 14-Feb-2000)") INFO.print("\n\t*** Input for step COMPREFDEM ***"); // switch (comprefdeminput.method) // { // case crd_nearest: // INFO.print("NEAREST_NEIGHBOR, use DENSE=2 or so."); // break; // case crd_trilinear: // INFO.print("TRI_LINEAR; use DENSE=0.2 for speed."); // break; // default: // PRINT_ERROR("totally impossible, checked input."); // throw(keyword_error); // } INFO << "CRD_IN_DEM: \t" << comprefdeminput.firefdem; INFO.print(); INFO << "CRD_OUT_FILE: \t" << comprefdeminput.forefdem; INFO.print(); if (specified(comprefdeminput.forefdemhei)) { INFO << "CRD_OUT_DEM_LP: \t" << comprefdeminput.forefdemhei << "; output requested of DEM [m] in radar coordinates."; INFO.print(); if (!strcmp(comprefdeminput.forefdem,comprefdeminput.forefdemhei)) { PRINT_ERROR("CRD_OUT_FILE, CRD_OUT_DEM_LP: Same output file name."); throw(keyword_error); } } if (specified(comprefdeminput.fodem)) { INFO << "CRD_OUT_DEM: \t" << comprefdeminput.fodem << "; output requested of input DEM."; INFO.print(); if (!strcmp(comprefdeminput.fodemi,comprefdeminput.fodem)) { PRINT_ERROR("OUT_DEM, OUT_DEMI: Same output file name."); throw(keyword_error); } } if (specified(comprefdeminput.fodemi)) { INFO << "CRD_OUT_DEMI: \t" << comprefdeminput.fodemi << "; output requested of interpolated DEM."; INFO.print(); if (!strcmp(comprefdeminput.fodemi,comprefdeminput.fodem)) { PRINT_ERROR("OUT_DEM, OUT_DEMI: Same output file name."); throw(keyword_error); } } // __________ added by FvL if (specified(comprefdeminput.foh2ph)) { INFO << "CRD_OUT_H2PH: \t" << comprefdeminput.foh2ph << "; output requested of height-to-phase constant per resolution cell."; INFO.print(); } // ____________ end added by FvL INFO << "CRD_IN_SIZE: \t" << comprefdeminput.demrows << " " << comprefdeminput.demcols << "; number of rows (latitude), columns (lon) in DEM."; INFO.print(); INFO << "CRD_IN_UL: \t" << rad2deg(comprefdeminput.demlatleftupper) << " " << rad2deg(comprefdeminput.demlonleftupper) << "; coordinates of upper left corner (first row/col)."; INFO.print(); INFO << "CRD_IN_DELTA: \t" << rad2deg(comprefdeminput.demdeltalat) << " " << rad2deg(comprefdeminput.demdeltalon); INFO.print(); INFO << "CRD_IN_NODATA: \t" << comprefdeminput.demnodata << "; this number in DEM will be set to 0 reference phase."; INFO.print(); // INFO << "CRD_DENSE: \t" << comprefdeminput.extradense // << "; this is the factor for oversampling DEM more than minimum."; // INFO.print(); if (comprefdeminput.includerefpha) INFO << "CRD_INCLUDE_FE: \tref. dem is computed including flat earth."; else INFO << "CRD_INCLUDE_FE: \tref. dem is computed w.r.t. ellipsoid (topo only)."; INFO.print(); INFO << "CRD_IN_FORMAT: \tinput format DEM: \t"; switch (comprefdeminput.iformatflag) { case FORMATR4: INFO << "real4."; break; case FORMATR8: INFO << "real8."; break; case FORMATI2: INFO << "signed short."; break; case FORMATI2_BIGENDIAN: INFO << "signed short big endian."; break; default: PRINT_ERROR("totally impossible, checked input."); throw(keyword_error); } INFO.print(); // ______ Check some things ______ if (!existed(comprefdeminput.firefdem)) { ERROR << "CRD_IN_DEM: \t" << comprefdeminput.firefdem << " can not be opened."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } if (rad2deg(comprefdeminput.demdeltalat)<.0002) //[MA] 1 arc secs = 1/3600=0.00027 : allow finer resolutions { WARNING << "CRD_IN_DELTA: \t" << rad2deg(comprefdeminput.demdeltalat) << " [deg] seems very small (input in decimal degrees)."; WARNING.print(); } if (comprefdeminput.demrows<1 || comprefdeminput.demrows>100000) { WARNING << "CRD_DEM_SIZE: numrows: \t" << comprefdeminput.demrows << " seems to be wrong."; WARNING.print(); } if (comprefdeminput.demcols<1 || comprefdeminput.demcols>100000) { WARNING << "CRD_DEM_SIZE: numcols: \t" << comprefdeminput.demcols << " seems to be wrong."; WARNING.print(); } // if (comprefdeminput.extradense>5.0) // { // WARNING << "CRD_DENSE: \t" << comprefdeminput.extradense // << " seems to be quite large."; // WARNING.print(); // } // if (comprefdeminput.extradense<0.2) // { // WARNING << "CRD_DENSE: \t" << comprefdeminput.extradense // << " seems too small."; // WARNING.print(); // } if (rad2deg(comprefdeminput.demdeltalon)<.0002) { WARNING << "CRD_IN_DELTA: \t" << comprefdeminput.demdeltalon << " seems very small (it should be in decimal degrees)."; WARNING.print(); } if (rad2deg(comprefdeminput.demlatleftupper) < -90. || rad2deg(comprefdeminput.demlatleftupper) > 90. ) { ERROR << "CRD_IN_LU: \t" << rad2deg(comprefdeminput.demlatleftupper) << " out of range (-90:90)."; PRINT_ERROR(ERROR.get_str()) throw(keyword_error); } if (rad2deg(comprefdeminput.demlonleftupper) < -180. || rad2deg(comprefdeminput.demlonleftupper) > 180. ) { WARNING << "CRD_IN_LU: \t" << rad2deg(comprefdeminput.demlonleftupper) << " out of range (-180:180)."; WARNING.print(); } if (!strcmp(comprefdeminput.fodem,comprefdeminput.forefdem)) { PRINT_ERROR("OUT_DEM, OUT_FILE: Same output file name."); throw(keyword_error); } if (!strcmp(comprefdeminput.firefdem,comprefdeminput.forefdem)) { PRINT_ERROR("OUT_FILE, IN_DEM: Same file name."); throw(keyword_error); } } // END comprefdem /**************************************************************** * checksubtrrefdem * * * * Checks cards for step subtrrefdem. * * * * Bert Kampes, 14-Feb-2000 * ****************************************************************/ void checksubtrrefdem( const input_subtrrefdem &subtrrefdeminput) { TRACE_FUNCTION("checksubtrrefdem (BK 14-Feb-2000)") INFO.print("\n\t*** Input for step SUBTRREFDEM ***"); INFO << "SRD_OUT_CINT: \t" << subtrrefdeminput.focint; INFO.print(); INFO << "SRD_OFFSET: \t" << subtrrefdeminput.offsetL << " " << subtrrefdeminput.offsetP; INFO.print(); if (abs(subtrrefdeminput.offsetL)>5) WARNING.print("Apply offset in azimuth larger than 5 pixels?"); if (abs(subtrrefdeminput.offsetP)>5) WARNING.print("Apply offset in range larger than 5 pixels?"); } // END checksubtrrefdem /**************************************************************** * checkfiltrange * * Checks cards for step filtrange. * * Bert Kampes, 14-Feb-2000 * ****************************************************************/ void checkfiltrange( const input_filtrange &filtrangeinput) { TRACE_FUNCTION("checkfiltrange (BK 14-Feb-2000)") INFO.print("\n\t*** Input for step FILTRANGE ***"); // ______ Give info ______ switch (filtrangeinput.method) { case rf_adaptive: INFO.print("RF_METHOD: ADAPTIVE \t(estimate fringe freq.)"); INFO << "RF_NLMEAN: " << filtrangeinput.nlmean; INFO.print(); INFO << "RF_THRESHOLD: " << filtrangeinput.SNRthreshold; INFO.print(); INFO << "RF_OVERSAMPLE: " << filtrangeinput.oversample; INFO.print(); INFO << "RF_WEIGHTCORR: " << filtrangeinput.doweightcorrel; INFO.print(); INFO << "RF_OVERLAP: " << filtrangeinput.overlap; INFO.print(); if (filtrangeinput.nlmean > 51) WARNING.print("RF_NLMEAN: mean over more than 51 lines (?)"); if (filtrangeinput.SNRthreshold<1.99) WARNING.print("RF_THRESHOLD: < 2"); if (filtrangeinput.SNRthreshold>10.01) WARNING.print("RF_THRESHOLD: > 10 ?"); if (filtrangeinput.oversample<=1) WARNING.print("RF_OVERSAMPLE: no oversampling."); if (filtrangeinput.oversample>8) WARNING.print("RF_OVERSAMPLE: >8 ?"); if (!ispower2(filtrangeinput.oversample)) WARNING.print("RF_OVERSAMPLE: not power of two."); if (filtrangeinput.doweightcorrel==true) WARNING.print("RF_WEIGHTCORR: weighting, not sure it has effect."); if (filtrangeinput.fftlength > 1024) WARNING.print("RF_FFTLENGTH: adaptive filterlength > 1024 ?"); if (filtrangeinput.SNRthreshold<0.) { PRINT_ERROR( "RF_THRESHOLD: < 0."); throw(keyword_error); } break; case rf_porbits: INFO.print("RF_METHOD: PORBITS \t(based on orbits.)"); INFO << "RF_SLOPE: " << rad2deg(filtrangeinput.terrainslope) << "\t[deg] terrainslope."; INFO.print(); if (filtrangeinput.fftlength < 256) WARNING.print("RF_FFTLENGTH: porbits filterlength < 256 (?)"); break; default: PRINT_ERROR("totally impossible, checked input."); throw(keyword_error); } // ______ Both methods cards ______ INFO << "RF_FFTLENGTH: " << filtrangeinput.fftlength; INFO.print(); INFO << "RF_HAMMING: " << filtrangeinput.hammingalpha; INFO.print(); INFO << "RF_OUT_MASTER: " << filtrangeinput.fomaster; INFO.print(); INFO << "RF_OUT_SLAVE: " << filtrangeinput.foslave; INFO.print(); INFO << "RF_OUT_FORMAT: output format: "; switch (filtrangeinput.oformatflag) { case FORMATCR4: INFO << "complex_real4."; break; case FORMATCI2: INFO << "complex_short."; break; default: PRINT_ERROR("totally impossible, checked input."); throw(keyword_error); } INFO.print(); // ______ Check input ______ if (filtrangeinput.hammingalpha>0.999) WARNING.print("RF_HAMMING: no hamming filtering."); if (existed(filtrangeinput.fomaster)) WARNING.print("RF_OUT_MASTER: file exists."); if (existed(filtrangeinput.foslave)) WARNING.print("RF_OUT_SLAVE: file exists."); if (!ispower2(filtrangeinput.fftlength)) { PRINT_ERROR( "RF_FFTLENGTH: not power of 2."); throw(keyword_error); } if (filtrangeinput.overlap >= 0.5*filtrangeinput.fftlength) { PRINT_ERROR( "RF_OVERLAP >= 0.5*RF_FFTLENGTH"); throw(keyword_error); } if (filtrangeinput.hammingalpha>1. || filtrangeinput.hammingalpha<0.) { PRINT_ERROR( "RF_HAMMING: not e[0,1]."); throw(keyword_error); } } // END checkfiltrange /**************************************************************** * checkdinsar * * * * Checks cards for step dinsar. * * * #%// BK 25-Sep-2000 ****************************************************************/ void checkdinsar( const input_dinsar &dinsarinput) { TRACE_FUNCTION("checkdinsar (BK 25-Sep-2000)") INFO.print("\n\t*** Input for step DINSAR ***"); if (!specified(dinsarinput.topomasterresfile)) { INFO.print("Using 3 pass differential (for 4 pass, see DI_IN_TOPOMASTER card)."); } else { INFO << "DI_IN_TOPOMASTER: \t" << dinsarinput.topomasterresfile << " (4 pass)"; INFO.print(); } INFO << "DI_IN_TOPOSLAVE: \t" << dinsarinput.toposlaveresfile; INFO.print(); INFO << "DI_IN_TOPOINT: \t" << dinsarinput.topointresfile; INFO.print(); INFO << "DI_OUT_FILE: \t" << dinsarinput.fodinsar; INFO.print(); if (!specified(dinsarinput.foscaleduint)) INFO << "DI_OUT_SCALED: \tNo (debug) output requested scaled topography interf."; else INFO << "DI_OUT_SCALED: \t" << dinsarinput.foscaleduint << "; debug output requested."; INFO.print(); if (!specified(dinsarinput.toposlaveresfile)) { PRINT_ERROR("DI_IN_TOPOSLAVE: result file topo slave not specified."); throw(keyword_error); } if (!specified(dinsarinput.topointresfile)) { PRINT_ERROR("DI_IN_TOPOINT: result file topo interferogram not specified."); throw(keyword_error); } if (!strcmp(dinsarinput.toposlaveresfile,dinsarinput.topointresfile)) { PRINT_ERROR("IN_TOPOSLAVE, IN_TOPOINT: Same input file name."); throw(keyword_error); } } // END checkdinsar /**************************************************************** * checkfiltphase * * * * Checks cards for step filtphase. * * * #%// BK 25-Sep-2000 ****************************************************************/ void checkfiltphase( const input_filtphase &filtphaseinput) { TRACE_FUNCTION("checkfiltphase (BK 25-Sep-2000)") INFO.print("\n\t*** Input for step FILTPHASE ***"); if (specified(filtphaseinput.fifiltphase)) { INFO << "PF_IN_FILE: \t" << filtphaseinput.fifiltphase << " " << filtphaseinput.finumlines << " (this cr4 file will be filtered)"; INFO.print(); if (!existed(filtphaseinput.fifiltphase)) WARNING.print("Impossible? PF input file does not exist?"); } INFO << "PF_OUT_FILE: \t" << filtphaseinput.fofiltphase << " (output filename)."; INFO.print(); // ______ Method goldstein filter ______ if (filtphaseinput.method==fp_goldstein) { INFO.print("FILTPHASE: Method goldstein."); INFO << "PF_ALPHA: \t" << filtphaseinput.alpha << " (weigthing parameter for spectrum)."; INFO.print(); INFO << "PF_BLOCKSIZE: " << filtphaseinput.blocksize << " (size of block to perform filtering on)."; INFO.print(); INFO << "PF_OVERLAP: \t" << filtphaseinput.overlap << " (half overlap between consequetive blocks)."; INFO.print(); // ______ Use 1d kernel to smooth amplitude, e.g. 12321 ______ // ______ Which is normalized by me ______ INFO << "PF_KERNEL: \t"; for (int32 ii=0; ii1.) WARNING.print("PF_ALPHA not 064 || filtphaseinput.blocksize<16) WARNING.print("PF_BLOCKSIZE very small or large?"); if (filtphaseinput.kernel.pixels()>11) WARNING.print("smoothing kernel > 11: very large?"); if (filtphaseinput.overlap<0) { PRINT_ERROR("PF_OVERLAP < 0"); throw(keyword_error); } if (2*filtphaseinput.overlap>filtphaseinput.blocksize) { PRINT_ERROR("2*PF_OVERLAP > PF_BLOCKSIZE"); throw(keyword_error); } if (filtphaseinput.kernel.pixels()>filtphaseinput.blocksize) { PRINT_ERROR("smoothing kernel > PF_BLOCKSIZE"); throw(keyword_error); } if (!ispower2(filtphaseinput.blocksize)) { PRINT_ERROR("PF_BLOCKSIZE not a power of 2"); throw(keyword_error); } } // ______ Method modified goldstein filter ______ else if (filtphaseinput.method==fp_modgoldstein) { INFO.print("FILTPHASE: Method modgoldstein."); INFO << "PF_ALPHA: \t" << -1 << " (Calculated based on coherence)."; INFO.print(); INFO << "PF_BLOCKSIZE: " << filtphaseinput.blocksize << " (size of block to perform filtering on)."; INFO.print(); INFO << "PF_OVERLAP: \t" << filtphaseinput.overlap << " (half overlap between consequetive blocks)."; INFO.print(); // ______ Use 1d kernel to smooth amplitude, e.g. 12321 ______ // ______ Which is normalized by me ______ INFO << "PF_KERNEL: \t"; for (int32 ii=0; ii1.) WARNING.print("PF_ALPHA not 064 || filtphaseinput.blocksize<16) WARNING.print("PF_BLOCKSIZE very small or large?"); if (filtphaseinput.kernel.pixels()>11) WARNING.print("smoothing kernel > 11: very large?"); if (filtphaseinput.overlap<0) { PRINT_ERROR("PF_OVERLAP < 0"); throw(keyword_error); } if (2*filtphaseinput.overlap>filtphaseinput.blocksize) { PRINT_ERROR("2*PF_OVERLAP > PF_BLOCKSIZE"); throw(keyword_error); } if (filtphaseinput.kernel.pixels()>filtphaseinput.blocksize) { PRINT_ERROR("smoothing kernel > PF_BLOCKSIZE"); throw(keyword_error); } if (!ispower2(filtphaseinput.blocksize)) { PRINT_ERROR("PF_BLOCKSIZE not a power of 2"); throw(keyword_error); } } // ______ Method spatial convolution ______ else if (filtphaseinput.method==fp_spatialconv) { INFO.print("FILTPHASE: Method spatial convolution."); if (!specified(filtphaseinput.fikernel2d)) { INFO.print("Using 1d kernel for spatial convolution (no PF_IN_KERNEL2D)."); INFO << "PF_KERNEL: used: \t"; for (int32 ii=0; iifiltphaseinput.blocksize) { PRINT_ERROR("2*PF_OVERLAP > PF_BLOCKSIZE"); throw(keyword_error); } if (!ispower2(filtphaseinput.blocksize)) { PRINT_ERROR("PF_BLOCKSIZE not a power of 2"); throw(keyword_error); } if (!specified(filtphaseinput.fikernel2d)) { PRINT_ERROR("method spectral needs card PF_IN_KERNEL2D"); throw(keyword_error); } } else { PRINT_ERROR("Method phasefiltering != {goldstein,modgolstein,spatialconv,spectral}."); throw(keyword_error); } } // END checkfiltphase /**************************************************************** * checkfiltazi * * Checks cards for step filtazi. * * Bert Kampes, 02-Nov-2000 * ****************************************************************/ void checkfiltazi( const input_filtazi &filtaziinput, const int16 id) // either master, slave, or m+s { TRACE_FUNCTION("checkfiltazi (BK 02-Nov-2000)") INFO.print("\n\t*** Input for step FILTAZI ***"); INFO << "AF_BLOCKSIZE: \t" << filtaziinput.fftlength; INFO.print(); INFO << "AF_OVERLAP: \t" << filtaziinput.overlap; INFO.print(); INFO << "AF_HAMMING: \t" << filtaziinput.hammingalpha; INFO.print(); if (filtaziinput.oformatflag==FORMATCR4) INFO.print("AF_OUT_FORMAT: \tcomplex_real4"); else if (filtaziinput.oformatflag==FORMATCI2) INFO.print("AF_OUT_FORMAT: \tcomplex_short"); else { PRINT_ERROR("formatflag not ok for output."); throw(keyword_error); } if (id!=SLAVEID) { INFO << "AF_OUT_MASTER: \t" << filtaziinput.fomaster; INFO.print(); } if (id!=MASTERID) { INFO << "AF_OUT_SLAVE: \t" << filtaziinput.foslave; INFO.print(); } if (filtaziinput.fftlength<256) WARNING.print("AF_BLOCKSIZE < 256 (too small?)"); if (2*filtaziinput.overlap>0.5*filtaziinput.fftlength) WARNING.print("2*AF_OVERLAP > .5*AF_BLOCKSIZE (very large?)"); if (filtaziinput.hammingalpha<0 || filtaziinput.hammingalpha>1) { PRINT_ERROR("AF_HAMMING not e[0,1]"); throw(keyword_error); } if (filtaziinput.overlap<0) { PRINT_ERROR("AF_BLOCKSIZE < 0"); throw(keyword_error); } if (2*filtaziinput.overlap>filtaziinput.fftlength) { PRINT_ERROR("AF_BLOCKSIZE < 2*AF_BLOCKSIZE"); throw(keyword_error); } if (!ispower2(filtaziinput.fftlength)) { PRINT_ERROR("AF_BLOCKSIZE must be power of 2."); throw(keyword_error); } } // END checkfiltazi Doris-5.0.3Beta/doris_core/readinput.hh000077500000000000000000001100711312547014700200460ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/readinput.hh,v $ * $Revision: 3.24 $ * $Date: 2006/05/18 10:03:18 $ * $Author: kampes $ * * Some constants for switching processing steps * Structs where input parameters are stored * Definition of readinput function. ****************************************************************/ #ifndef READINPUT_H #define READINPUT_H using namespace std; // BK 29-Mar-2003, new compiler? // Jia defined this for compilation under windows // Bert Kampes, 24-Aug-2005 #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "constants.hh" // typedefs // ______ only declare here ______ #include "matrixbk.hh" // my matrix class //____RaffaeleNutricato START MODIFICATION SECTION 1 // ______index for: input_gen: process[NUMPROCESSES] (arbitrary index)______ // const int16 // [MA] use enum instead // With Doris v4, we want to keep SLC processing controls the same for both master and slave result files. [MA] enum { pr_m_readfiles = 0, // 0 flag for reading leader etc master pr_m_crop , // 1 write slc data to raster format pr_m_oversample , // 2 oversample master image //____RaffaeleNutricato added this line pr_m_porbits , // 3 calling getorb master pr_m_morbits , // 4 modify orbits by correction parameters [HB] pr_m_simamp , // 5 simulate amplitude for master timing [MA] pr_m_mtiming , // 6 correlate simamp and master for master timing [MA] pr_m_filtazi , // 7 azimuth filtering master pr_m_filtrange , // 8 range filtering master pr_m_resample , // 9 resample fake entry [MA] 2009, see also ioroutines.cc pr_m_EXTRA , // 10 for future use pr_s_readfiles , // 11 flag for reading leader etc slave pr_s_crop , // 12 writing to raw slave pr_s_oversample , // 13 oversample slave image //____RaffaeleNutricato added this line pr_s_porbits , // 14 calling getorb slave pr_s_morbits , // 15 modify orbits by correction parameters [HB] pr_s_simamp , // 16 simulate amplitude, fake entry no processing is defined [MA] pr_s_mtiming , // 17 master timing, fake entry [MA] pr_s_filtazi , // 18 azimuth filtering slave pr_s_filtrange , // 19 range filtering slave pr_s_resample , // 20 resample slave, actually at slave. pr_s_EXTRA , // 21 for future use pr_i_coarse , // 22 coarse coregistration: orbits pr_i_coarse2 , // 23 coarse coregistration: correlation pr_i_fine , // 24 fine coregistration pr_i_timing , // 25 relative timing error [FvL] pr_i_demassist , // 26 dem assist coregistration [FvL] pr_i_coregpm , // 27 compute parameters coregistration pr_i_interfero , // 28 computation of interferogram pr_i_coherence , // 29 computation of coherence image pr_i_comprefpha , // 30 ref.phase (flat earth) pr_i_subtrrefpha , // 31 interferogram - refpha pr_i_comprefdem , // 32 ref.phase (flat earth) pr_i_subtrrefdem , // 33 interferogram - refpha pr_i_filtphase , // 34 filtering interferogram pr_i_unwrap , // 35 unwrapping interferogram pr_i_estorbits , // 36 estimate orbit error [HB] pr_i_slant2h , // 37 slant to height conversion pr_i_geocoding , // 38 geocoding pr_i_dinsar , // 39 3 pass differential pr_i_EXTRA2 , // 40 for future use pr_last_one // 41 not used; to indicate last one (==NUMPROCESSES-1) }; const int16 NUMPROCESSES = pr_last_one+1; // see above... //____RaffaeleNutricato END MODIFICATION SECTION 1 // ====== global processcontrol array ====== // BK should be one word (no spaces) // usage: resfile << "\n*_Start_" << processcontrol[pr_i_interfero] // usage: resfile << "\n* End_" << processcontrol[pr_i_coarse] << "_NORMAL" //____RaffaeleNutricato START MODIFICATION SECTION 2 const char processcontrol[NUMPROCESSES][ONE27] = { "readfiles:", // 0 pr_m_readfiles "crop:", // 1 pr_m_crop "oversample:", // 2 pr_m_oversample //____RaffaeleNutricato added this line "precise_orbits:", // 3 pr_m_porbits "modify_orbits:", // 4 pr_m_morbits [HB] "sim_amplitude:", // 5 pr_m_simamp "master_timing:", // 6 pr_m_mtiming + master timing error // was simamp_corr "filt_azi:", // 7 pr_m_filtazi "filt_range:", // 8 pr_m_filtrange "resample:", // 9 pr_m_resample [MA] 200903, fake entry "NOT_USED:", // 10 pr_m_EXTRA "readfiles:", // 11 pr_s_readfiles "crop:", // 12 pr_s_crop "oversample:", // 13 pr_s_oversample //____RaffaeleNutricato added this line "precise_orbits:", // 14 pr_s_porbits "modify_orbits:", // 15 pr_s_morbits [HB] "sim_amplitude:", // 16 pr_s_simamp [MA] 2009, fake entry "master_timing:", // 17 pr_s_mtiming [MA] 2009, fake entry "filt_azi:", // 18 pr_s_filtazi: must be same as m_ "filt_range:", // 19 pr_s_filtrange "resample:", // 20 pr_s_resample !slave "NOT_USED:", // 21 pr_s_EXTRA "coarse_orbits:", // 22 pr_i_coarse "coarse_correl:", // 23 pr_i_coarse2 "fine_coreg:", // 24 pr_i_fine "timing_error:", // 25 pr_i_timing [FvL] "dem_assist:", // 26 pr_i_demassist [FvL] "comp_coregpm:", // 27 pr_i_coregpm "interfero:", // 28 pr_i_interfero "coherence:", // 29 pr_i_coherence "comp_refphase:", // 30 pr_i_comprefpha "subtr_refphase:", // 31 pr_i_subtrrefpha "comp_refdem:", // 32 pr_i_comprefdem "subtr_refdem:", // 33 pr_i_subtrrefdem "filtphase:", // 34 pr_i_filtphase "unwrap:", // 35 pr_i_unwrap "est_orbits:", // 36 pr_i_estorbits [HB "slant2h:", // 37 pr_i_slant2h "geocoding:", // 38 pr_i_geocoding "dinsar:", // 39 pr_i_EXTRA "NOT_USED2:", // 40 pr_i_EXTRA2 "ERROR update this!"}; // 41 pr_last_one // strcpy(processcontrol[pr_m_readfiles],"readfiles:"); // strcpy(processcontrol[pr_m_crop] , "crop:"); //____RaffaeleNutricato END MODIFICATION SECTION 2 // ====== Constants, variables ====== // ======Method selectors====== //const int16 readfiles_ers = 151; // method for readfiles //const int16 readfiles_asar = 152; // method for readfiles const int16 cc_magfft = 21; // method for coarse corr. coreg const int16 cc_magspace = 22; // method for coarse corr. coreg const int16 fc_cmplxfft = 31; // method for fine coreg const int16 fc_cmplxspace = 32; // method for fine coreg const int16 fc_magfft = 33; // method for fine coreg const int16 fc_magspace = 34; // method for fine coreg const int16 fc_oversample = 35; // method oversample signal,not corr. const int16 fc_coherence = 36; // method oversample signal,CCC. const int16 fc_intensity = 37; //same as fc_oversample but with intensity instead of amplitude const int16 fe_porbits = 41; // method for flat earth correction const int16 fe_method2 = 42; // method for flat earth correction const int16 rs_rect = 102; // nearest neighbor, 1 or 2 points const int16 rs_tri = 202; // piecewize linear, 2 point const int16 rs_cc4p = 304; // cubic convolution, 4 point const int16 rs_cc6p = 306; // cubic convolution, 6 point const int16 rs_ts6p = 406; // truncated sinc, 6 point const int16 rs_ts8p = 408; // truncated sinc, 8 point const int16 rs_ts16p = 416; // truncated sinc, 16 point const int16 rs_knab4p = 504; // knab window, 4 point const int16 rs_knab6p = 506; // knab window, 6 point const int16 rs_knab8p = 508; // knab window, 8 point const int16 rs_knab10p = 510; // knab window, 10 point const int16 rs_knab16p = 516; // knab window, 12 point const int16 rs_rc6p = 606; // raised cosine, 6 point const int16 rs_rc12p = 612; // raised cosine, 12 point const int16 int_oldmethod = 91; // method no overs. interf. gen. const int16 int_oversample = 92; // method oversample for int. computation const int16 coh_oldmethod = 101; // coherence computation up to refphase const int16 coh_newmethod = 102; // coherence computation including refdem const int16 fp_goldstein = 81; // method goldstein const int16 fp_spatialconv = 82; // method spatial conv. with kernel const int16 fp_spectral = 83; // method spectral kernel const int16 fp_modgoldstein = 84; // method modified goldstein const int16 uw_method1 = 51; // TREEF (delft only) const int16 uw_method2 = 52; // SNAPHU Curtis Cheng const int16 uw_method3 = 53; // method for unwrapping const int16 s2h_schwabisch = 61; // schwabisch95 thesis const int16 s2h_rodriguez = 62; // see paper rodriguez92 const int16 s2h_ambiguity = 63; // exact method const int16 geo_nointerp = 70; // no interpolation in geocding const int16 geo_regular = 71; // ... ? not implemented // const int16 crd_nearest = 81; // nearest neighbor, not used anymore [MA] // const int16 crd_trilinear = 82; // trilinear const int16 srp_polynomial = 101; // eval poly from comp_refpha const int16 srp_exact = 102; // compute ref_pha on he fly const int16 rf_adaptive = 301; // range filter adaptive method const int16 rf_porbits = 302; // precise orbits const int16 eo_noweighting = 701; // estorbit no weithting [HB] const int16 eo_coh = 702; // estorbit weighting by coherence [HB] const int16 eo_coh2 = 703; // estorbit weighting by coherence^2 [HB] const int16 eo_pdf = 704; // estorbit weighting by pdf(coherence) [HB] const int16 eo_lsq = 751; // estorbit least squares method [HB] const int16 eo_gridsearch = 752; // estorbit gridsearch method [HB] // ======Define structs for storing/passing input options====== struct input_gen // general input { char logfile[4*ONE27]; char m_resfile[4*ONE27]; char s_resfile[4*ONE27]; char i_resfile[4*ONE27]; //uint memory; // available mem. in Bytes. For 32-bit platform above 4200MB (4.2e9) is a problem even if uint [MA] real8 memory; // available mem. in Bytes bool process[NUMPROCESSES]; // if .[i] != 0 => process step_(i+1) bool interactive; // if true, pause bool overwrit; // 0: don't overwrite existing data output files int16 orb_interp; // method for orbit interpolation int16 orb_prm; // orbit parameters: POSITION or POSITION and VELOCITY int32 dumpbaselineL; // #lines to dump baseline param. int32 dumpbaselineP; // #lines to dump baseline param. int32 preview; // generate sunraster preview file // 0: no; 1: sh files; 2: sh sh_files. real4 terrain_height; // mean terrain height, or of a point. cn tiepoint; // lat/lon/hei for e.g., integration const. }; // ______These structs are input, filled by readinput______ // ______ ______ struct input_readfiles // arguments of readinfo --> m_readfilesinput, --> s_readfilesinput { int16 sensor_id; // method selector ers/asar/rsat/jers/alos int16 sar_processor; // atlantis, vmp, set in routines. int16 fileid; char volfile[4*ONE27]; char leaderfile[4*ONE27]; char nullfile[4*ONE27]; char datfile[4*ONE27]; real8 rg_timing_error; // [BK 27-May-2004] real8 az_timing_error; // [BK 27-May-2004] }; // ______ ______ struct input_pr_orbits // precise orbits { char m_orbdir[4*ONE27]; char s_orbdir[4*ONE27]; int32 timeinterval; // time in sec. int32 timebefore; // sec before first line. real8 dumpmasterorbit; // dtime in sec. real8 dumpslaveorbit; // dtime in sec. }; // ______ ______ [HB] struct input_morbits { matrix coeff; // coefficients of correction polynomials char reforbitfile[4*ONE27]; // result file of supermaster }; // ______ ______ struct input_crop // arguments of m/s_crop { int16 fileid; int16 sar_processor; // atlantis, vmp, set in routines. char idcrop[EIGHTY]; char filein1[4*ONE27]; char fileout1[4*ONE27]; window dbow; // cut out of original window dbow_geo; // lat_0*1e6, lon_0*1e6, height, width }; // ______ ______ [BO, FvL, MA] struct input_simamp // arguments for simulation of amplitude from DEM [MA] { char firefdem[4*ONE27]; // input filename reference dem int16 iformatflag; // input format [signed short] uint demrows; // number of uint demcols; // number of real8 demdeltalat; // radians real8 demdeltalon; // radians real8 demlatleftupper; // radians real8 demlonleftupper; // radians real8 demnodata; // identifier/flag char fodem[4*ONE27]; // flag+name output of cropped dem char fodemlp[4*ONE27]; // output filename DEM in radarcoord. // [MA] the same size as master image // char fodemi[4*ONE27]; // flag+name output of interpolated dem char fosimamp[4*ONE27]; // flag+name output of simulated amp [MA] TODO define common struct for comprefdem demassist sim-amp char fothetalp[4*ONE27]; // output filename for theta incidence angle in radar coordinates. // MA }; // ______ ______ struct input_mtiming // arguments of correlation for master timing error { char ifpositions[4*ONE27]; // input file name for positions int16 method; // method selector, [MA] rm if not nec. uint Nwin; // #windows uint MasksizeL; // size of correlation window uint MasksizeP; // size of correlation window uint AccL; // #lines to be searched in 1 direction uint AccP; // #pixels to be searched in 1 direction int32 initoffsetL; // initial offset lines int32 initoffsetP; // initial offset pixels }; // ______ ______ [MA] //____RaffaeleNutricato START MODIFICATION SECTION 3 struct input_oversample // arguments of m/s_oversample { char fileoutovs[4*ONE27]; // Name of the oversampled image int32 OsrRange; // Oversampling ratio in range. int32 OsrAzimuth; // Oversampling ratio in azimuth. int32 FilterSize; // Length of the interpolation kernel. int32 oformatflag; // Output format [cr4] ci16, I suggest [cr4]. }; //____RaffaeleNutricato END MODIFICATION SECTION 3 // ______ azimuth filtering ______ struct input_filtazi // arguments for azimuth filter { int16 method; // method selector int32 fftlength; // length per buffer int32 overlap; // 0.5overlap each buffer real8 hammingalpha; // alpha for hamming, 1 is no char foname[4*ONE27]; // output filename passed to routine char fomaster[4*ONE27]; // output filename char foslave[4*ONE27]; // output filename int16 oformatflag; // output format [cr4] ci16 }; // ______ ______ struct input_coarsecorr // arguments for correlation { // char idcoarsecorr[EIGHTY]; char ifpositions[4*ONE27]; // input file name for positions int16 method; // method selector uint Nwin; // #windows uint MasksizeL; // size of correlation window uint MasksizeP; // size of correlation window uint AccL; // #lines to be searched in 1 direction uint AccP; // #pixels to be searched in 1 direction int32 initoffsetL; // initial offset lines int32 initoffsetP; // initial offset pixels }; // struct input_deramp // arguments of m/s_crop // { // // char filein1[4*ONE27]; //name input file // char fileout1[4*ONE27];// name output file // // }; struct input_reramp // arguments of m/s_crop { // char filein1[4*ONE27]; //name input file // char fileout1[4*ONE27];// name output file }; // ______ ______ struct input_fine // arguments for fine coreg. { char ifpositions[4*ONE27]; // input file name for positions int16 method; // method selector uint Nwin; // #windows uint MasksizeL; // size of correlation window uint MasksizeP; // size of correlation window uint AccL; // #lines to be searched in l direction uint AccP; // #pixels to be searched in p direction int32 initoffsetL; // initial offset lines int32 initoffsetP; // initial offset pixels uint osfactor; // oversampling factor bool plotoffsets; // call script bool plotmagbg; // call script real4 plotthreshold; // call script int32 shiftazi; // [true] shift spectrum to 0 // * added by MCC //For cohernece method only char firefdem[4*ONE27]; // input filename reference dem char forefdem[4*ONE27]; // output filename DEM in radarcoord. int16 iformatflag; // input format [signed short] uint demrows; // number of uint demcols; // number of real8 demdeltalat; // radians real8 demdeltalon; // radians real8 demlatleftupper; // radians real8 demlonleftupper; // radians real8 demnodata; // identifier/flag // * added by MCC }; // ______ ______ struct input_reltiming // arguments for timing [FvL] { real4 threshold; // threshold for correlation int32 maxiter; // max. #pnts to remove (wtests) real4 k_alpha; // critical value for automated outlier removal }; // ______ ______ struct input_demassist // arguments for DEM assisted coregistration [FvL] { char firefdem[4*ONE27]; // input filename reference dem int16 iformatflag; // input format [signed short] uint demrows; // number of uint demcols; // number of real8 demdeltalat; // radians real8 demdeltalon; // radians real8 demlatleftupper; // radians real8 demlonleftupper; // radians real8 demnodata; // identifier/flag char forefdemhei[4*ONE27]; // output filename DEM in radarcoord. char fodem[4*ONE27]; // flag+name output of cropped dem char fodemi[4*ONE27]; // flag+name output of interpolated dem }; // ______ ______ struct input_coregpm // arguments for coregpm. { char idcoregpm[EIGHTY]; real4 threshold; // threshold for correlation int32 degree; // degree of polynomial int32 weightflag; // 0: all same weight // 1: choice1: weigh with correlation ?? int32 maxiter; // max. #pnts to remove (wtests) real4 k_alpha; // critical value for automated outlier removal bool dumpmodel; // create float files with model bool plot; // plot e_hat etc. bool plotmagbg; // plot magnitude in background }; // ______ range filtering ______ struct input_filtrange // arguments for range filter { int16 method; // method selector int32 oversample; // factor bool doweightcorrel; // weighting of correlation values int32 nlmean; // number of lines to take mean of int32 fftlength; // length for adaptive int32 overlap; // half overlap between blocks of fftlength real8 hammingalpha; // alpha for hamming real8 SNRthreshold; // spectral peak estimation real8 terrainslope; // [rad] porbits method only char fomaster[4*ONE27]; // output filename char foslave[4*ONE27]; // output filename int16 oformatflag; // output format [cr4] ci16 }; // ______ ______ struct input_comprefpha // arguments for flatearth correction. { //char idflatearth[EIGHTY]; char ifpositions[4*ONE27]; // input file name for positions int16 method; // method selector int32 degree; // degree of polynomial int32 Npoints; // number of observations }; // ______ ______ struct input_resample // arguments for resampling slave { int16 method; // method selector (interpolator) (%100 == Npoints) char fileout[4*ONE27]; int16 oformatflag; // output format [cr4] ci16 window dbow_geo; // cut out of original master.geo window dbow; // cut out of original master.radar int32 shiftazi; // [1] center the spectrum around zero, if 0 do nothing if 2 deramp using Sentinel-1 params }; // ______ ______ struct input_interfero // arguments for computation interferogram { int16 method; // method selector char focint[4*ONE27]; // optional output filename complex interferogram. char foint[4*ONE27]; // ~ of interferogram (phase). // char foflatearth[EIGHTY]; // ~ of correction (flatearth) model (phase) // these are flags as well as arguments. // one is man (else no output) uint multilookL; // multilookfactor in line dir. uint multilookP; // multilookfactor in pixel dir. }; // ______ ______ struct input_coherence // arguments for computation coherence { int16 method; // method selector char focoh[4*ONE27]; // opt output filename of real coherence image. char foccoh[4*ONE27]; // ~ of complex coherence image. // these are flags as well as arguments. uint multilookL; // multilookfactor in line dir. uint multilookP; // multilookfactor in pixel dir. uint cohsizeL; // size of estimation window coherence uint cohsizeP; // size of estimation window coherence }; // ______ ______ struct input_filtphase // arguments for phase filter { int16 method; // method selector char fofiltphase[4*ONE27]; // output filename char fifiltphase[4*ONE27]; // input filename uint finumlines; // number of lines input // ______ method goldstein ______ real8 alpha; // weighting int32 blocksize; // blocksize filtered blocks int32 overlap; // half overlap // ______ method goldstein, spatial conv. and spectral ______ matrix kernel; // e.g. [1 1 1] // ______ method spatial conv. and spectral ______ char fikernel2d[4*ONE27]; // input filename }; // ______ ______ struct input_dinsar // 3 pass differntial { //int16 method; // method selector char fodinsar[4*ONE27]; // output filename complex interferogram char foscaleduint[4*ONE27]; // output filename scaled uint char topomasterresfile[4*ONE27];// input filename char toposlaveresfile[4*ONE27];// input filename char topointresfile[4*ONE27]; // input filename }; // ______ ______ struct input_subtrrefpha // arguments for subtract 'flat earth' { int16 method; // method selector uint multilookL; // multilookfactor in line dir. uint multilookP; // multilookfactor in pixel dir. char focint[4*ONE27]; // output filename complex interferogram char forefpha[4*ONE27]; // output filename complex refpha char foh2ph[4*ONE27]; // output filename h2ph, added by FvL bool dumponlyrefpha; // do nothing except dump refpha }; // ______ ______ struct input_comprefdem // arguments for reference phase from DEM { // int16 method; // method selector char firefdem[4*ONE27]; // input filename reference dem int16 iformatflag; // input format [signed short] uint demrows; // number of uint demcols; // number of real8 demdeltalat; // radians real8 demdeltalon; // radians real8 demlatleftupper; // radians real8 demlonleftupper; // radians real8 demnodata; // identifier/flag // real8 extradense; // extra interpolation factor (4) char forefdem[4*ONE27]; // output filename reference phase char foh2ph[4*ONE27]; // output perp. baseline, added by FvL char forefdemhei[4*ONE27]; // output filename DEM in radarcoord. bool includerefpha; // flag to include_flatearth correction char fodem[4*ONE27]; // flag+name output of cropped dem char fodemi[4*ONE27]; // flag+name output of interpolated dem bool isCCC; // if demassist is used for Coherent complex coregistration (CCC), then isCCC must be set to true. Default is false }; // ______ ______ struct input_subtrrefdem // arguments for subtract reference DEM { int16 method; // method selector int32 offsetL; // offset applied before subtraction int32 offsetP; // offset applied before subtraction char focint[4*ONE27]; // output filename complex interferogram }; // ______ ______ struct input_unwrap // arguments for unwrapping { char fouint[4*ONE27]; // output filename int16 oformatflag; // output format [hgt] real4 char foregions[4*ONE27]; // output filename char seedfile[4*ONE27]; // input file with seeds int32 deltaLseed; // seed delta line direction int32 deltaPseed; // seed delta pixel direction int16 method; // method selector char snaphu_mode[12]; // snaphu TOPO DEFO SMOOTH NOSTATCOSTS char snaphu_log[4*ONE27]; // log filename for snaphu char snaphu_coh[4*ONE27]; // coherence filename for snaphu opt char snaphu_verbose[6]; // snaphu TRUE or FALSE bool snaphu_dumponlyconf; // dump snaphu.conf but do not run [BO] char snaphu_init[4]; // snaphu MST or MCF int16 ntilerow; int16 ntilecol; int16 rowovrlp; int16 colovrlp; int16 nproc; int16 tilecostthresh; }; // ______ ______ [HB] struct input_estorbits // arguments for orbit error estimation { int16 method; // method selector char fiheightmap[4*ONE27]; // file with heightmap in radar coordinates, obtained with CRD_OUT_DEM_LP char foresiduals[4*ONE27]; // outfile with observation pixels and (in case of lsq method) residuals int16 weighting; // weighting scheme uint nobs; // approximate number of observations to be used char ifpositions[4*ONE27]; // file with (l,p) for observations to be used real4 threshold; // min. coherence for a pixel to be used uint maxiter; // max. number of iterations for data snooping real4 k_alpha; // critical value for data snooping uint maxfringesaz; // maximum expected number of orbital fringes in azimuth uint maxfringesrg; // maximum expected number of orbital fringes in range char reforbitfile[4*ONE27]; // resfile of reference acquisition char foobsdata[4*ONE27]; // file with dumped observation data, estimation design, ... uint poldegree; // degree of orbit error polynomial bool constrained; // flag indicating if solution is constained of not matrix constraints; // k x 2 matrix defining k constraints. // 1st column: component. =0 for Bpar, =1 for Bperp // 2nd column: derivative. =0 for constant, =1 for linear, ... }; // ______ ______ struct input_slant2h // arguments for slant2height conversion { int16 method; // method selector char fohei[4*ONE27]; // output filename height char folam[4*ONE27]; // output filename lambda char fophi[4*ONE27]; // output filename phi int32 Npoints; // int32 degree1d; // only {1,2} possible now due to solve33 int32 degree2d; // int32 Nheights; // }; // ______ ______ struct input_geocode // arguments for geocode { // int16 method; // method selector not used right now char fophi[4*ONE27]; // output filename phi char folam[4*ONE27]; // output filename lambda }; // ______ ______ struct input_m_EXTRA // extra step { int16 method; // method selector }; // ______ ______ struct input_s_EXTRA // extra step { int16 method; // method selector }; // ______ ______ struct input_i_EXTRA2 // extra step { int16 method; // method selector }; // ====== Inline functions ====== // ______ to get/set derfaults ______ inline void setunspecified(char *s) {strcpy(s," ");} // better use string "unspecified" inline bool specified(const char *s) {return bool(strcmp(s," "));} // return true if specified // ====== Prototypes ====== //____RaffaeleNutricato START MODIFICATION SECTION 4 // ______ Reads and interprets "inputoptionsfile" ______ // ______ Fills input structs. ______ void readinput( input_gen &generalinput, input_ell &inputellips, input_pr_orbits &porbitsinput, input_readfiles &readfilesmaster, input_morbits &morbitsinputmaster, // [HB] input_crop &cropinputmaster, input_oversample &oversamplemaster, //____RaffaeleNutricato added this line input_simamp &simampmaster, // master amplitude simulation, related to master timing [FvL],[MA] TODO: do it flexible if we want for slave also input_mtiming &mtiming, // [MA] input_readfiles &readfilesslave, input_morbits &morbitsinputslave, // [HB] input_crop &cropinputslave, input_oversample &oversampleslave, //____RaffaeleNutricato added this line input_filtazi &filtaziinput, input_coarsecorr &coarsecorrinput, input_fine &fineinput, input_reltiming &timinginput, //[FvL] input_demassist &demassistinput, //[FvL] input_coregpm &coregpminput, input_resample &resampleinput, input_filtrange &filtrangeinput, input_interfero &interferoinput, input_coherence &coherenceinput, input_comprefpha &comprefphainput, input_subtrrefpha &subtrrefphainput, input_comprefdem &comprefdeminput, input_subtrrefdem &subtrrefdeminput, input_filtphase &filtphaseinput, input_dinsar &dinsarinput, input_unwrap &unwrapinput, input_estorbits &estorbitsinput, // [HB] input_slant2h &slant2hinput, input_geocode &geocodeinput); //____RaffaeleNutricato END MODIFICATION SECTION 4 #endif // READINPUT_H Doris-5.0.3Beta/doris_core/referencephase.cc000077500000000000000000003265721312547014700210370ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/referencephase.cc,v $ * * $Revision: 3.22 $ * * $Date: 2006/05/18 11:09:20 $ * * $Author: kampes $ * * * * -computation flat earth correction. * * -computation radarcoding dem + interpolation to (1,1) grid * ****************************************************************/ #include "matrixbk.hh" #include "orbitbk.hh" #include "slcimage.hh" // my slc image class #include "productinfo.hh" // my 'products' class #include "constants.hh" #include "referencephase.hh" // proto types #include "ioroutines.hh" // error etc. #include "utilities.hh" // isodd; ones(), etc. #include "coregistration.hh" // distribute points #include "exceptions.hh" // my exceptions class #include // setw only for test.. #include // system #include // max #ifdef WIN32 // Jia defined this. // Bert Kampes, 24-Aug-2005 #include "winsock2.h" #else #include // ntohl byteorder x86-HP unix #endif // Using A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator // from Jonathan Richard Shewchuk // Some definition for triangulate call #define VOID int #define REAL double #define ANSI_DECLARATORS #include "triangle.h" /**************************************************************** * flatearth * * * * Compute polynomial model for 'flat earth' correction. * * fie(l,p) = sumj=0:d sumk=0:d Ajk l^j p^k (NOT bert 8sept99) * * precise orbits are used to compute delta range for Npoints * * after which the polynomial model is fitted (LS). * * * * input: * * - inputoptions * * - info structs * * - platform data points * * output: * * - void (result to file "scratchresflat") * * - coefficients normalized wrt. original window of master * * * * Bert Kampes, 09-Mar-1999 * * Bert Kampes, 26-Oct-1999 normalization of coeff., * * dump to logfile: var(unknowns) == diag(inv(AtA)) * ****************************************************************/ void flatearth( const input_comprefpha &comprefphainput, const input_ell &ellips, const slcimage &master, const slcimage &slave, const productinfo &interferogram, orbit &masterorbit, orbit &slaveorbit) { TRACE_FUNCTION("flatearth (BK 26-Oct-1999)") const int32 MAXITER = 10; const real8 CRITERPOS = 1e-6; const real8 CRITERTIM = 1e-10; char dummyline[2*ONE27]; INFO << "FLATEARTH: MAXITER: " << MAXITER << "; " << "CRITERPOS: " << CRITERPOS << " m; " << "CRITERTIM: " << CRITERTIM << " s"; INFO.print(); // ______ Normalization factors for polynomial ______ const real8 minL = master.originalwindow.linelo; const real8 maxL = master.originalwindow.linehi; const real8 minP = master.originalwindow.pixlo; const real8 maxP = master.originalwindow.pixhi; INFO << "flatearth: polynomial normalized by factors: " << minL << " " << maxL << " " << minP << " " << maxP << " to [-2,2]"; INFO.print(); // ______Handling of input______ const real8 m_minpi4cdivlam = (-4.0*PI*SOL)/master.wavelength; const real8 s_minpi4cdivlam = (-4.0*PI*SOL)/slave.wavelength; DEBUG << "master wavelength = " << master.wavelength; DEBUG.print(); DEBUG << "slave wavelength = " << slave.wavelength; DEBUG.print(); const int32 DEGREE = comprefphainput.degree; const int32 Nunk = Ncoeffs(DEGREE); // Number of unknowns bool pointsrandom = true; if (specified(comprefphainput.ifpositions)) pointsrandom = false; // only use those points // ______ Distribute points wel distributed over win ______ // ______ or read from ascii file ______ // ______(i,0): line, (i,1): pixel, (i,2) flagfromdisk______ //matrix Position; // [FvL] for correct folding of points outside overlap window when inserted by file matrix Position; const uint Npoints = comprefphainput.Npoints; register int32 i,j,k,index; if (pointsrandom) // no filename specified { Position = distributepoints(Npoints,interferogram.win); } else // read from file { Position.resize(Npoints,3); //ifstream ifpos(comprefphainput.ifpositions, ios::in); ifstream ifpos; openfstream(ifpos,comprefphainput.ifpositions); bk_assert(ifpos,comprefphainput.ifpositions,__FILE__,__LINE__); uint ll,pp; for (i=0; i> ll >> pp; //Position(i,0) = uint(ll); //Position(i,1) = uint(pp); //Position(i,2) = uint(1); // flag from file // [FvL] Position(i,0) = int(ll); Position(i,1) = int(pp); Position(i,2) = int(1); // flag from file ifpos.getline(dummyline,2*ONE27,'\n'); // goto next line. } ifpos.close(); // ______ Check last point ivm. EOL after last position in file ______ if (Position(Npoints-1,0) == Position(Npoints-2,0) && Position(Npoints-1,1) == Position(Npoints-2,1)) { Position(Npoints-1,0) = uint(.5*(minL + maxL) + 27); // random Position(Npoints-1,1) = uint(.5*(minP + maxP) + 37); // random WARNING << "refpha: there should be no EOL after last point in file: " << comprefphainput.ifpositions; WARNING.print(); } // ______ Check if points are in overlap ______ // ______ no check for uniqueness of points ______ } matrix y(Npoints,1); // observation matrix y_h2ph(Npoints,1); // observation, h2ph factors, added by FvL matrix A(Npoints,Nunk); // designmatrix // ______Check redundancy______ if (Npoints < Nunk) { PRINT_ERROR("flatearth: Number of points is smaller than parameters solved for."); throw(input_error); } // ======Compute delta r for all points====== for (i=0; iSP) then S is to the right of slant line, then B perp is positive. cn r1 = Psat_master.min(P); cn r2 = Psat_slave.min(P); // real8 theta = Psat_master.angle(r1); // look angle real8 theta = P.angle(r1); // incidence angle real8 theta_slave = P.angle(r2); // incidence angle slave real8 Bperp = (theta > theta_slave ) ? // sign ok sqrt(sqr(B)-sqr(Bpar)) : -sqrt(sqr(B)-sqr(Bpar)) ; y_h2ph(i,0) = Bperp/(m_trange*SOL*sin(theta)); // ____________________________________________________________________________________ // _____________ End added part by FvL ________________________________________________ //_____________________________________________________________________________________ // ______Set up system of equations______ // ______Order unknowns: A00 A10 A01 A20 A11 A02 A30 A21 A12 A03 for degree=3______ // ______ normalize data [-2,2] ______ real8 posL = normalize(line,minL,maxL); real8 posP = normalize(pixel,minP,maxP); index = 0; for (j=0; j<=DEGREE; j++) { for (k=0; k<=j; k++) { A(i,index) = pow(posL,real8(j-k)) * pow(posP,real8(k)); index++; } } } // ======Compute polynomial for these phases (LS)====== // ______Compute Normalmatrix, rghthandside______ matrix N = matTxmat(A,A); matrix rhs = matTxmat(A,y); matrix rhs_h2ph = matTxmat(A,y_h2ph); // Added by FvL, same A matrix can be used // ______Compute solution______ matrix Qx_hat = N; choles(Qx_hat); // Cholesky factorisation normalmatrix solvechol(Qx_hat,rhs); // Estimate of unknowns in rhs solvechol(Qx_hat,rhs_h2ph); // Estimate of unknowns in rhs_h2ph, added by FvL invertchol(Qx_hat); // Covariance matrix // ______Test inverse______ for (i=0; i .001) { WARNING << "Deviation quite large. Decrease degree or number of points?"; WARNING.print(); } else { INFO.print("Deviation is OK."); } // ______Some other stuff, scale is ok______ // matrix Qy_hat = A * (matxmatT(Qx_hat,A)); matrix y_hat = A * rhs; matrix y_hat_h2ph = A * rhs_h2ph; // added by FvL matrix e_hat = y - y_hat; matrix e_hat_h2ph = y_h2ph - y_hat_h2ph; // added by FvL // ______Overall model test (variance factor)______ // ... ? // ______ Wrap offset ______ // BK 30/9/99 do not do this, later absolute ref. phase is used. // in s2h rodriguez for example. // it does not change anything for compinterfero etc. // rhs(0,0) = remainder(rhs(0,0),2*PI); // ______Write results to file______ ofstream scratchlogfile("scratchlogflat", ios::out | ios::trunc); bk_assert(scratchlogfile,"flatearth: scratchlogflat",__FILE__,__LINE__); scratchlogfile << "\n\n*******************************************************************" << "\n* FLATEARTH: " //<< "\n*_Start_" << processcontrol[pr_i_comprefpha] << "\n*******************************************************************" << "\nDegree_flat:\t" << DEGREE << "\nEstimated coefficients:\n" << "\nx_hat \tstd:\n"; for (i=0; i= lat0file)// largest latitude at first line of file { ERROR << "master crop outside DEM: most North latitude: " << rad2deg(lat0file) << " [deg]; master crop requires: " << rad2deg(phimax) << " [deg]"; PRINT_ERROR(ERROR.get_str()) //throw(some_error); } if (lambdamax <= lon0file) { ERROR << "master crop outside DEM: most West longitude: " << rad2deg(lon0file) << " [deg]; master crop window requires: " << rad2deg(lambdamax) << " [deg]"; PRINT_ERROR(ERROR.get_str()) //throw(some_error); } if (lambdamin >= lonNfile) { ERROR << "master crop outside DEM: most East longitude: " << rad2deg(lonNfile) << " [deg]; master crop window requires: " << rad2deg(lambdamin) << " [deg]"; PRINT_ERROR(ERROR.get_str()) //throw(some_error); } //=================================================================== //============ First loop: radarcode DEM ============================ //============ (DEM geometry) ============================ //=================================================================== int32 numvalid = 0;// number of good values, not NODATA in buffer int32 numNODATA = 0;// number of NODATA values in buffer real8 meancroppedDEM = 0.0;// to detect byte order problems, formats real8 min_input_dem = 100000.0;// stats real8 max_input_dem = -100000.0;// stats // ______ Compute buffer size radarcoding DEM______ const real8 BUFFERMEMSIZE = generalinput.memory;// Bytes int32 NcolsDEM = indexlambdaNDEM-indexlambda0DEM+1; int32 NrowsDEM = indexphiNDEM-indexphi0DEM+1; const uint32 NcolsDEMlog = NcolsDEM; // since NcolsDEM updated after getcorners() call. const uint32 NrowsDEMlog = NrowsDEM; const real8 Nrows_possible_DEM = BUFFERMEMSIZE / (5*8*NcolsDEM); int32 bufferlines = int32(ceil(Nrows_possible_DEM)); // [MA] checked ok. Sinces SLC is not multilooked, see comprefdem for solution if (bufferlines>NrowsDEM) bufferlines=NrowsDEM; int32 numfullbuffers = NrowsDEM / bufferlines; int32 restlines = NrowsDEM % bufferlines; int32 extrabuffer = (restlines == 0) ? 0 : 1; // ______ Extra info ______ INFO << "DEM output total pixels: " << NcolsDEM; INFO.print(); INFO << "DEM output total lines : " << NrowsDEM; INFO.print(); INFO << "Radar coding of DEM in: " << numfullbuffers << " buffers of " << bufferlines << " lines and " << extrabuffer << " extra buffer of " << restlines << " lines."; INFO.print(); // ______ Open (temporary) output files ______ // DEM heights ofstream demofile; openfstream(demofile,demassistinput.fodem,generalinput.overwrit); // dem_crop radarcoded bk_assert(demofile,demassistinput.fodem,__FILE__,__LINE__); // master line coordinates of DEM ofstream masterdemlineoutfile("dac_m_demline.temp", ios::out | ios::trunc); bk_assert(masterdemlineoutfile,"dac_m_demline.temp",__FILE__,__LINE__); // master pixel coordinates of DEM ofstream masterdempixeloutfile("dac_m_dempixel.temp", ios::out | ios::trunc); bk_assert(masterdempixeloutfile,"dac_m_dempixel.temp",__FILE__,__LINE__); // delta line coordinates of DEM ( slave-master ) ofstream deltademlineoutfile("dac_delta_demline.temp", ios::out | ios::trunc); bk_assert(deltademlineoutfile,"dac_delta_demline.temp",__FILE__,__LINE__); // delta pixel coordinates of DEM ofstream deltadempixeloutfile("dac_delta_dempixel.temp", ios::out | ios::trunc); bk_assert(deltadempixeloutfile,"dac_delta_dempixel.temp",__FILE__,__LINE__); // ______ DEM loop per buffer ______ register int32 j,i;// DEM index grid counter, register j first to ensure allocation for (register int32 buffer=0; buffer DEM(blines,NcolsDEM); // ______ Extra info ______ PROGRESS << STEP << "Buffer# [l0:lN, p0:pN]: " << buffer+1 << " [" << indexphi0BUFFER << ": " << indexphiNBUFFER << ", " << indexlambda0DEM << ": " << indexlambdaNDEM << "]"; PROGRESS.print(); // ______ lat/lon for first pixel in matrix read from file ______ // ______ upper is max. latitude, left is min. longitude ______ const real8 upperleftphi = lat0file-indexphi0BUFFER*DEMdeltalat; const real8 upperleftlambda = lon0file+indexlambda0DEM*DEMdeltalon; window zerooffset (0,0,0,0); window winfromfile (indexphi0BUFFER,indexphiNBUFFER, indexlambda0DEM,indexlambdaNDEM); // ______ Read in grdfile of DEM in matrix R4 (raw data, no header) _______ // ______ added formats (BK 4-May-2001) ______ PROGRESS << STEP << "Reading crop of DEM for buffer: " << buffer+1; PROGRESS.print(); DEBUG.print("Reading input DEM into real4 matrix (buffer)."); switch (demassistinput.iformatflag) { // ______ Read as short BE, then convert to host order ______ case FORMATI2_BIGENDIAN: { matrix DEMi2(blines,NcolsDEM); readfile(DEMi2,demassistinput.firefdem,numberoflatpixels,winfromfile,zerooffset); for (int32 iii=0; iii DEMi2(blines,NcolsDEM); readfile(DEMi2,demassistinput.firefdem,numberoflatpixels,winfromfile,zerooffset); for (int32 iii=0; iii DEMr8(blines,NcolsDEM); readfile(DEMr8,demassistinput.firefdem,numberoflatpixels,winfromfile,zerooffset); for (int32 iii=0; iiimax_dem_buffer) max_dem_buffer=DEM(i,j);// stats } else { numNODATA++; } }//loop dem for stats }//loop dem for stats min_input_dem = min(min_input_dem,min_dem_buffer);//global stats max_input_dem = max(max_input_dem,max_dem_buffer);//global stats // ====== Radarcoding DEM ============================== // ______ DEM contains values from leftupper with ______ // ______ spacing (DEMdeltalat,DEMdeltalon) ______ // ______ Transform DEM to l,p,refphase ______ PROGRESS.print("Converting DEM to radar system for this buffer."); const int32 NpointsDEM = DEM.size(); const int32 NpixelsDEM = DEM.pixels(); // ______ Extra info ______ INFO << "Number of points in DEM: " << NpointsDEM; INFO.print(); matrix masterDEMline(DEM.lines(),DEM.pixels()); matrix masterDEMpixel(DEM.lines(),DEM.pixels()); matrix deltaDEMline(DEM.lines(),DEM.pixels()); matrix deltaDEMpixel(DEM.lines(),DEM.pixels()); // --- Loop DEM --- real8 phi,lambda,height,m_l,m_p,s_l,s_p; phi = upperleftphi; for (i=0; i Nlinesml) bufferlines=Nlinesml; numfullbuffers = Nlinesml / bufferlines; restlines = Nlinesml % bufferlines; // the number of lines in extra buffer extrabuffer = (restlines == 0) ? 0 : 1; // ______ Extra info ______ INFO << "Interpolation in: " << numfullbuffers << " buffers of " << bufferlines << " lines and " << extrabuffer << " extra buffer of " << restlines << " lines."; INFO.print(); // ______ Open output files ______ ofstream deltalineofile("dac_delta_line.raw", ios::out | ios::trunc); bk_assert(deltalineofile,"dac_delta_line.raw",__FILE__,__LINE__); ofstream deltapixelofile("dac_delta_pixel.raw", ios::out | ios::trunc); bk_assert(deltapixelofile,"dac_delta_pixel.raw",__FILE__,__LINE__); // if request for height in radar coordinates l,p ofstream refdemheiofile; if (outputrefdemhei==true) { openfstream(refdemheiofile,demassistinput.forefdemhei,generalinput.overwrit); bk_assert(refdemheiofile,demassistinput.forefdemhei,__FILE__,__LINE__); } // ______ interpolation loop per buffer ______ for (register int32 buffer = 0; buffer < numfullbuffers + extrabuffer; ++buffer) { // Determine indices for buffer const int32 blines = (buffer == numfullbuffers) ? restlines : bufferlines; const real8 firstline_buffer = veryfirstline+buffer*bufferlines; const real8 lastline_buffer = firstline_buffer+blines-1; // ______ Extra info ______ PROGRESS << STEP << "Interpolation buffer: " << buffer+1 << "of" << numfullbuffers + extrabuffer << " [l0:lN, p0:pN]: " << " [" << firstline_buffer << ": " << lastline_buffer << ", " << firstpixel << ": " << lastpixel << "]"; PROGRESS.print(); // Get corners of buffer real8 phimin_az; real8 phimax_az; real8 lambdamin_az; real8 lambdamax_az; getcorners(firstline_buffer,lastline_buffer, firstpixel,lastpixel, extralat,extralong,phimax,lambdamin, DEMdeltalat,DEMdeltalon,NrowsDEM,NcolsDEM, ellips,master,masterorbit,phimin_az,phimax_az,lambdamin_az,lambdamax, indexphi0DEM,indexphiNDEM,indexlambda0DEM,indexlambdaNDEM); window zerooffset (0,0,0,0); window winfromfile (indexphi0DEM,indexphiNDEM, indexlambda0DEM,indexlambdaNDEM); const int32 NrowsDEM_buffer = indexphiNDEM-indexphi0DEM+1; const int32 NcolsDEM_buffer = indexlambdaNDEM-indexlambda0DEM+1; PROGRESS << STEP << "Reading input for interpolation buffer: " << buffer+1 << "of" << numfullbuffers + extrabuffer; PROGRESS.print(); // read x,y matrix DEMline_buffer(NrowsDEM_buffer,NcolsDEM_buffer); matrix DEMpixel_buffer(NrowsDEM_buffer,NcolsDEM_buffer); readfile(DEMline_buffer,"dac_m_demline.temp",NrowsDEM,winfromfile,zerooffset); readfile(DEMpixel_buffer,"dac_m_dempixel.temp",NrowsDEM,winfromfile,zerooffset); // read z (multiple, number can easily be increased, e.g. simulated intensity) int32 Nz = 2; //number of z matrix input_buffer(NrowsDEM_buffer *Nz ,NcolsDEM_buffer); matrix temp_input_buffer(NrowsDEM_buffer,NcolsDEM_buffer); if (outputrefdemhei==true) { Nz += 1; input_buffer.resize(NrowsDEM_buffer *Nz ,NcolsDEM_buffer); } readfile(temp_input_buffer,"dac_delta_demline.temp",NrowsDEM,winfromfile,zerooffset); input_buffer.setdata(0, 0, temp_input_buffer); readfile(temp_input_buffer,"dac_delta_dempixel.temp",NrowsDEM,winfromfile,zerooffset); input_buffer.setdata(NrowsDEM_buffer, 0, temp_input_buffer); Nz = 2; if (outputrefdemhei==true) { Nz += 1; /// i would like to use real4, test later on matrix dem_input(NrowsDEM_buffer,NcolsDEM_buffer); readfile(dem_input,demassistinput.fodem,NrowsDEM,winfromfile,zerooffset); for (register int32 i =0 ; i < NrowsDEM_buffer ; i ++) for(register int32 j = 0; j < NcolsDEM_buffer; j++) temp_input_buffer(i,j) = real8(dem_input(i,j)); input_buffer.setdata(NrowsDEM_buffer * (Nz-1), 0, temp_input_buffer); } // initialize output array Nz = 2; matrix output_buffer(blines * Nz, Npixelsml); if (outputrefdemhei==true) { Nz += 1; output_buffer.resize(blines * Nz, Npixelsml); } // interpolation griddatalinear(DEMline_buffer,DEMpixel_buffer,input_buffer, firstline_buffer,lastline_buffer,firstpixel,lastpixel, 1,1,r_az_ratio,0,NODATA,output_buffer); deltalineofile << output_buffer(window(0, blines - 1, 0, Npixelsml -1 )); deltapixelofile << output_buffer(window(blines , 2 * blines - 1, 0, Npixelsml -1 )); Nz = 2; if (outputrefdemhei==true) { Nz += 1; refdemheiofile << output_buffer(window((Nz-1) * blines,Nz * blines - 1, 0, Npixelsml -1 )); } DEMline_buffer.resize(1,1); DEMpixel_buffer.resize(1,1); input_buffer.resize(1,1); temp_input_buffer.resize(1,1); output_buffer.resize(1,1); } // end loop azimuth direction INFO << "Closing output files"; INFO.print(); deltalineofile.close(); deltapixelofile.close(); if (outputrefdemhei==true) // Radarcoded DEM refdemheiofile.close(); //=================================================================== //============ End second loop: interpolation ============= //============ (radar geometry) ============= //=================================================================== //=================================================================== //============ Determine inverse transformation ============= //============ (slave corners only, needed for overlap) ============= //=================================================================== real8 line, pixel; real8 deltaline_slave00,deltapixel_slave00, deltaline_slave0N,deltapixel_slave0N, deltaline_slaveN0,deltapixel_slaveN0, deltaline_slaveNN,deltapixel_slaveNN; real8 phimin_az,phimax_az,lambdamin_az,lambdamax_az; for (register int16 corner = 0 ; corner < 4 ; corner ++) { PROGRESS << "Radarcoding slave corner: " << corner+1; PROGRESS.print(); switch (corner) { case 0: { line=slave.currentwindow.linelo; pixel=slave.currentwindow.pixlo; break; } case 1: { line=slave.currentwindow.linelo; pixel=slave.currentwindow.pixhi; break; } case 2: { line=slave.currentwindow.linehi; pixel=slave.currentwindow.pixlo; break; } case 3: { line=slave.currentwindow.linehi; pixel=slave.currentwindow.pixhi; break; } default: PRINT_ERROR("totally impossible, checked input."); } //use getcorners with line,line,pixel,pixel for single point getcorners(line,line,pixel,pixel, extralat,extralong,lat0file,lon0file, DEMdeltalat,DEMdeltalon,numberoflatpixels,numberoflonpixels, ellips,slave,slaveorbit, phimin_az,phimax_az,lambdamin_az,lambdamax, indexphi0DEM,indexphiNDEM,indexlambda0DEM,indexlambdaNDEM); NcolsDEM = indexlambdaNDEM-indexlambda0DEM+1; NrowsDEM = indexphiNDEM-indexphi0DEM+1; const real8 upperleftphi = lat0file-indexphi0DEM*DEMdeltalat; const real8 upperleftlambda = lon0file+indexlambda0DEM*DEMdeltalon; window zerooffset (0,0,0,0); window winfromfile (indexphi0DEM,indexphiNDEM, indexlambda0DEM,indexlambdaNDEM); // ______ Read in DEM in matrix R4 (raw data, no header) _______ matrix DEM(NrowsDEM,NcolsDEM); switch (demassistinput.iformatflag) { // ______ Read as short BE, then convert to host order ______ case FORMATI2_BIGENDIAN: { matrix DEMi2(NrowsDEM,NcolsDEM); readfile(DEMi2,demassistinput.firefdem,numberoflatpixels,winfromfile,zerooffset); for (int32 iii=0; iii DEMi2(NrowsDEM,NcolsDEM); readfile(DEMi2,demassistinput.firefdem,numberoflatpixels,winfromfile,zerooffset); for (int32 iii=0; iii DEMr8(NrowsDEM,NcolsDEM); readfile(DEMr8,demassistinput.firefdem,numberoflatpixels,winfromfile,zerooffset); for (int32 iii=0; iii slaveDEMline(DEM.lines(),DEM.pixels()); matrix slaveDEMpixel(DEM.lines(),DEM.pixels()); matrix deltaDEMline(DEM.lines(),DEM.pixels()); matrix deltaDEMpixel(DEM.lines(),DEM.pixels()); // --- Loop DEM --- real8 phi,lambda,height,m_l,m_p,s_l,s_p; phi = upperleftphi; for (i=0; i input_buffer(DEM.lines()*2,DEM.pixels()); input_buffer.setdata(0, 0, deltaDEMline); input_buffer.setdata(DEM.lines(), 0, deltaDEMpixel); matrix output_buffer(2,1); griddatalinear(slaveDEMline,slaveDEMpixel,input_buffer, line,line,pixel,pixel, 1,1,r_az_ratio,0,NODATA,output_buffer); switch (corner) { case 0: { deltaline_slave00 = output_buffer(0,0); deltapixel_slave00 = output_buffer(1,0); INFO << "Deltaline_slave00: " << deltaline_slave00; INFO.print(); INFO << "Deltapixel_slave00: " << deltapixel_slave00; INFO.print(); break; } case 1: { deltaline_slave0N = output_buffer(0,0); deltapixel_slave0N = output_buffer(1,0); INFO << "Deltaline_slave0N: " << deltaline_slave0N; INFO.print(); INFO << "Deltapixel_slave0N: " << deltapixel_slave0N; INFO.print(); break; } case 2: { deltaline_slaveN0 = output_buffer(0,0); deltapixel_slaveN0 = output_buffer(1,0); INFO << "Deltaline_slaveN0: " << deltaline_slaveN0; INFO.print(); INFO << "Deltapixel_slaveN0: " << deltapixel_slaveN0; INFO.print(); break; } case 3: { deltaline_slaveNN = output_buffer(0,0); deltapixel_slaveNN = output_buffer(1,0); INFO << "Deltaline_slaveNN: " << deltaline_slaveNN; INFO.print(); INFO << "Deltapixel_slaveNN: " << deltapixel_slaveNN; INFO.print(); break; } default: PRINT_ERROR("totally impossible, checked input."); } } //=================================================================== //============ End determine inverse transformation ============= //============ (slave corners only, needed for overlap) ============= //=================================================================== // ====== Write output information ====== char croppeddemi[4*ONE27]; strcpy(croppeddemi,"NO output requested"); if (outputdemi) strcpy(croppeddemi,demassistinput.fodemi); INFO << "Min. value of input DEM covering master: " << min_input_dem; INFO.print(); INFO << "Max. value of input DEM covering master: " << max_input_dem; INFO.print(); ofstream scratchlogfile("scratchlogdemassist", ios::out | ios::trunc); bk_assert(scratchlogfile,"demassist: scratchlogdemassist",__FILE__,__LINE__); scratchlogfile << "\n*******************************************************************" << "\n* " << processcontrol[pr_i_demassist] << "\n*******************************************************************" << "\n1) DEM source file: \t" << demassistinput.firefdem << "\nFormat: \t"; switch (demassistinput.iformatflag) { case FORMATI2: { scratchlogfile << "SHORT SIGNED INTEGER (HOST ENDIANNESS)"; break; } case FORMATI2_BIGENDIAN: { scratchlogfile << "SHORT SIGNED INTEGER, BIG ENDIAN"; break; } case FORMATR4: { scratchlogfile << "REAL4 SIGNED FLOAT"; break; } case FORMATR8: { scratchlogfile << "REAL8 SIGNED DOUBLE"; break; } default: { scratchlogfile << "UNKNOWN? IMPOSSIBLE..."; break; } } scratchlogfile << "\nByte order: \t" << "check it yourself..." << "\nNumber of lines: \t" << numberoflatpixels << "\nNumber of pixels: \t" << numberoflonpixels << "\nResolution latitude: \t" << rad2deg(DEMdeltalat) << " [deg]" << "\nResolution longitude: \t" << rad2deg(DEMdeltalon) << " [deg]" << "\nMost West point in input DEM: \t" << rad2deg(lon0file) << "\nMost East point in input DEM: \t" << rad2deg(lonNfile) << "\nMost South point in input DEM: \t" << rad2deg(latNfile) << "\nMost North point in input DEM: \t" << rad2deg(lat0file) << "\nMin. value of input DEM covering master: " << min_input_dem << "\nMax. value of input DEM covering master: " << max_input_dem << "\n2) Output file cropped DEM: \t" << demassistinput.fodem //[FVL << "\nFormat: \t" << "REAL4" << "\nByte order: \t" << "(same as host)" << "\nNumber of lines : \t" << NrowsDEMlog << "\nNumber of pixels : \t" << NcolsDEMlog << "\nDEM extend w/e/s/n : \t" << rad2deg(lambdamin) << "/" << rad2deg(lambdamax) << "/" << rad2deg(phimin) << "/" << rad2deg(phimax) // << "\nMean value: \t" << meancroppedDEM << "\n3) Output file interpolated crop DEM: \t" << croppeddemi << "\nFormat: \t" << "REAL4" << "\nByte order: \t" << "(same as host)" << "\nNumber of lines (multilooked): \t" << Nlinesml << "\nNumber of pixels (multilooked): \t" << Npixelsml << "\nDeltaline_slave00_dem: \t" << deltaline_slave00 << "\nDeltapixel_slave00_dem: \t" << deltapixel_slave00 << "\nDeltaline_slave0N_dem: \t" << deltaline_slave0N << "\nDeltapixel_slave0N_dem: \t" << deltapixel_slave0N << "\nDeltaline_slaveN0_dem: \t" << deltaline_slaveN0 << "\nDeltapixel_slaveN0_dem: \t" << deltapixel_slaveN0 << "\nDeltaline_slaveNN_dem: \t" << deltaline_slaveNN << "\nDeltapixel_slaveNN_dem: \t" << deltapixel_slaveNN << "\n*******************************************************************\n\n"; scratchlogfile.close(); ofstream scratchresfile("scratchresdemassist", ios::out | ios::trunc); bk_assert(scratchresfile,"demassist: scratchresdemassist",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************" << "\n*_Start_" << processcontrol[pr_i_demassist] << "\n*******************************************************************"; scratchresfile << "\nDEM source file: \t" << demassistinput.firefdem << "\nMin. of input DEM: \t" << min_input_dem << "\nMax. of input DEM: \t" << max_input_dem << "\nFirst_line (w.r.t. original_master): \t" << master.currentwindow.linelo << "\nLast_line (w.r.t. original_master): \t" << master.currentwindow.linehi << "\nFirst_pixel (w.r.t. original_master): \t" << master.currentwindow.pixlo << "\nLast_pixel (w.r.t. original_master): \t" << master.currentwindow.pixhi << "\nNumber of lines: \t" << Nlinesml << "\nNumber of pixels: \t" << Npixelsml << "\nDeltaline_slave00_dem: \t" << deltaline_slave00 << "\nDeltapixel_slave00_dem: \t" << deltapixel_slave00 << "\nDeltaline_slave0N_dem: \t" << deltaline_slave0N << "\nDeltapixel_slave0N_dem: \t" << deltapixel_slave0N << "\nDeltaline_slaveN0_dem: \t" << deltaline_slaveN0 << "\nDeltapixel_slaveN0_dem: \t" << deltapixel_slaveN0 << "\nDeltaline_slaveNN_dem: \t" << deltaline_slaveNN << "\nDeltapixel_slaveNN_dem: \t" << deltapixel_slaveNN << "\n*******************************************************************" << "\n* End_" << processcontrol[pr_i_demassist] << "_NORMAL" << "\n*******************************************************************\n"; scratchresfile.close(); } // END demassist /**************************************************************** * radarcodedem (a.k.a comprefdem) * * * * Compute reference phase based on DEM (SRTM) * * DEM on equiangular grid (lat/lon) assumed * * DEM seems stored from North to South * * * * Freek van Leijen, 26-Sep-2007 * ****************************************************************/ void radarcodedem( const input_gen &generalinput, const input_ell &ellips, const input_comprefdem &refdeminput, const slcimage &master, const slcimage &slave, const productinfo &interferogram, orbit &masterorbit, orbit &slaveorbit) { TRACE_FUNCTION("radarcodedem (FvL 26-Sep-2007)") const string STEP="CRD: "; const int32 MAXITER = 10; const real8 CRITERPOS = 1e-6; const real8 CRITERTIM = 1e-10; const real8 lat0file = refdeminput.demlatleftupper; // first pix on disk w02090 const real8 lon0file = refdeminput.demlonleftupper; // first pix on disk const real8 DEMdeltalat = refdeminput.demdeltalat; // in radians const real8 DEMdeltalon = refdeminput.demdeltalon; // in radians const int32 numberoflonpixels = refdeminput.demcols; // NCOLS on file const int32 numberoflatpixels = refdeminput.demrows; // NROWS on file const real8 NODATA = refdeminput.demnodata; // (BK 4 may 2001) bool onlyrefphasetopo = !refdeminput.includerefpha; // true: phase DEM w.r.t. ellipsoid const bool outputdemi = specified(refdeminput.fodemi); // if spec. then output const bool outputh2ph = specified(refdeminput.foh2ph); // if spec. then output, added by FvL const bool outputrefdemhei = specified(refdeminput.forefdemhei); // _____ start added by MA _____ bool mlookedIFG = false; // true: ifg is multilooked int32 mlL = interferogram.multilookL; // initialize multilookfactor int32 mlP = interferogram.multilookP; const int32 &ifgmlL = interferogram.multilookL; // multilookfactor of interferogram const int32 &ifgmlP = interferogram.multilookP; // multilookfactor of interferogram if ( ifgmlL != 1 || ifgmlP != 1 ) // [MA] additional entry for Coherence comptation using refdem. { // always do computation without multilooking mlL = 1; // set multilookfactor for interpolation mlP = 1; // set multilookfactor for interpolation mlookedIFG = true; // dealing with mlooked ifg. } // _____ end added by MA _____ const real8 m_min4picdivlam = (-4.0*PI*SOL)/master.wavelength; const real8 s_min4picdivlam = (-4.0*PI*SOL)/slave.wavelength; DEBUG << "master wavelength = " << master.wavelength; DEBUG.print(); DEBUG << "slave wavelength = " << slave.wavelength; DEBUG.print(); const real8 latNfile = lat0file-DEMdeltalat*(numberoflatpixels-1); // upper=max. lat value const real8 lonNfile = lon0file+DEMdeltalon*(numberoflonpixels-1); // left=min. lon value // ______ Extra info ______ INFO << "DEM input: w/e/s/n: \t" << rad2deg(lon0file) << "/" << rad2deg(lonNfile) << "/" << rad2deg(latNfile) << "/" << rad2deg(lat0file); INFO.print(); // ______ Get corners of interferogram (approx) to select DEM ______ // ______ in radians (if height were zero)______ real8 extralat = (1.5*DEMdeltalat + deg2rad(4.0/25.0)); real8 extralong = (1.5*DEMdeltalon + deg2rad(4.0/25.0)); real8 phimin; real8 phimax; real8 lambdamin; real8 lambdamax; int32 indexphi0DEM; int32 indexphiNDEM; int32 indexlambda0DEM; int32 indexlambdaNDEM; const uint &ifglinelo = interferogram.win.linelo; // [MA] win no-mlooked master coords const uint &ifglinehi = interferogram.win.linehi; const uint &ifgpixlo = interferogram.win.pixlo; const uint &ifgpixhi = interferogram.win.pixhi; getcorners(ifglinelo,ifglinehi, ifgpixlo,ifgpixhi, extralat,extralong,lat0file,lon0file, DEMdeltalat,DEMdeltalon,numberoflatpixels,numberoflonpixels, ellips,master,masterorbit,phimin,phimax,lambdamin,lambdamax, indexphi0DEM,indexphiNDEM,indexlambda0DEM,indexlambdaNDEM); // ______ Extra info ______ INFO << "DEM input required: w/e/s/n: \t" << rad2deg(lambdamin) << "/" << rad2deg(lambdamax) << "/" << rad2deg(phimin) << "/" << rad2deg(phimax); INFO.print(); INFO << "For window (l0,lN,p0,pN): \t" << ifglinelo << " " << ifglinehi << " " << ifgpixlo << " " << ifgpixhi; INFO.print(); // ______ Check corners of DEM ______ // check if DEM is appropriate for interferogram // DEM should at least partially cover IFG // note: phi is [90:-90] if (phimax <= latNfile)// DEM is more north than IFG { ERROR << "IFG outside DEM: most South latitude: " << rad2deg(latNfile) << " [deg]; IFG requires: " << rad2deg(phimax) << " [deg]"; PRINT_ERROR(ERROR.get_str()) throw(some_error); } // DEM is more south than IFG if (phimin >= lat0file)// largest latitude at first line of file { ERROR << "IFG outside DEM: most North latitude: " << rad2deg(lat0file) << " [deg]; IFG requires: " << rad2deg(phimax) << " [deg]"; PRINT_ERROR(ERROR.get_str()) throw(some_error); } if (lambdamax <= lon0file) { ERROR << "IFG outside DEM: most West longitude: " << rad2deg(lon0file) << " [deg]; IFG window requires: " << rad2deg(lambdamax) << " [deg]"; PRINT_ERROR(ERROR.get_str()) throw(some_error); } if (lambdamin >= lonNfile) { ERROR << "IFG outside DEM: most East longitude: " << rad2deg(lonNfile) << " [deg]; IFG window requires: " << rad2deg(lambdamin) << " [deg]"; PRINT_ERROR(ERROR.get_str()) throw(some_error); } //=================================================================== //============ First loop: radarcode DEM ============================ //============ (DEM geometry) ============================ //=================================================================== int32 numvalid = 0;// number of good values, not NODATA in buffer int32 numNODATA = 0;// number of NODATA values in buffer real8 meancroppedDEM = 0.0;// to detect byte order problems, formats real8 min_input_dem = 100000.0;// stats real8 max_input_dem = -100000.0;// stats // ______ Compute buffer size radarcoding DEM______ const real8 BUFFERMEMSIZE = generalinput.memory;// Bytes const int32 NcolsDEM = indexlambdaNDEM-indexlambda0DEM+1; const int32 NrowsDEM = indexphiNDEM-indexphi0DEM+1; const real8 Nrows_possible_DEM = BUFFERMEMSIZE / (5*8*NcolsDEM); int32 bufferlines = int32(ceil(Nrows_possible_DEM)); INFO << "Possible max. buffer lines: " << bufferlines << " for " << BUFFERMEMSIZE << " memory size."; INFO.print(); if (bufferlines>NrowsDEM) bufferlines=NrowsDEM; int32 numfullbuffers = NrowsDEM / bufferlines; int32 restlines = NrowsDEM % bufferlines; int32 extrabuffer = (restlines == 0) ? 0 : 1; // ______ Extra info ______ INFO << "DEM output total pixels: " << NcolsDEM; INFO.print(); INFO << "DEM output total lines : " << NrowsDEM; INFO.print(); INFO << "Radar coding of DEM in: " << numfullbuffers << " buffers of " << bufferlines << " lines and " << extrabuffer << " extra buffer of " << restlines << " lines."; INFO.print(); // ______ Open (temporary) output files ______ // DEM heights INFO< DEM(blines,NcolsDEM); // ______ Extra info ______ PROGRESS << STEP << "Buffer# [l0:lN, p0:pN]: " << buffer+1 << " [" << indexphi0BUFFER << ": " << indexphiNBUFFER << ", " << indexlambda0DEM << ": " << indexlambdaNDEM << "]"; PROGRESS.print(); // ______ lat/lon for first pixel in matrix read from file ______ // ______ upper is max. latitude, left is min. longitude ______ const real8 upperleftphi = lat0file-indexphi0BUFFER*DEMdeltalat; const real8 upperleftlambda = lon0file+indexlambda0DEM*DEMdeltalon; window zerooffset (0,0,0,0); window winfromfile (indexphi0BUFFER,indexphiNBUFFER, indexlambda0DEM,indexlambdaNDEM); // ______ Read in grdfile of DEM in matrix R4 (raw data, no header) _______ // ______ added formats (BK 4-May-2001) ______ PROGRESS << STEP << "Reading crop of DEM for buffer: " << buffer+1; PROGRESS.print(); DEBUG.print("Reading input DEM into real4 matrix (buffer)."); INFO<< "file info: name: " << refdeminput.firefdem <<", nof flat pixels, " << numberoflatpixels << endl; INFO<< "file info, Format : " << refdeminput.iformatflag< DEMi2(blines,NcolsDEM); readfile(DEMi2,refdeminput.firefdem,numberoflatpixels,winfromfile,zerooffset); for (int32 iii=0; iii DEMi2(blines,NcolsDEM); readfile(DEMi2,refdeminput.firefdem,numberoflatpixels,winfromfile,zerooffset); for (int32 iii=0; iii DEMr8(blines,NcolsDEM); readfile(DEMr8,refdeminput.firefdem,numberoflatpixels,winfromfile,zerooffset); for (int32 iii=0; iiimax_dem_buffer) max_dem_buffer=DEM(i,j);// stats } else { numNODATA++; } }//loop dem for stats }//loop dem for stats min_input_dem = min(min_input_dem,min_dem_buffer);//global stats max_input_dem = max(max_input_dem,max_dem_buffer);//global stats // ====== Radarcoding DEM ============================== // ______ DEM contains values from leftupper with ______ // ______ spacing (DEMdeltalat,DEMdeltalon) ______ // ______ Transform DEM to l,p,refphase ______ PROGRESS.print("Converting DEM to radar system for this buffer."); const int32 NpointsDEM = DEM.size(); const int32 NpixelsDEM = DEM.pixels(); // ______ Extra info ______ INFO << "Number of points in DEM: " << NpointsDEM; INFO.print(); matrix masterDEMline(DEM.lines(),DEM.pixels()); matrix masterDEMpixel(DEM.lines(),DEM.pixels()); matrix ref_phase_array(DEM.lines(),DEM.pixels()); matrix h2ph_array(DEM.lines(),DEM.pixels()); // --- Loop DEM --- cn P; real8 phi,lambda,height,l,p,ref_phase; phi = upperleftphi; for (i=0; i theta_slave ) ? // sign ok sqrt(sqr(B)-sqr(Bpar)) : -sqrt(sqr(B)-sqr(Bpar)) ; h2ph_array(i,j) = Bperp/(t_range_master*SOL*sin(theta)); } if (onlyrefphasetopo) // do not include flat earth phase { lp2xyz(l,p,ellips, // h==0 master, masterorbit, P,MAXITER,CRITERPOS); // P returned real8 t_range_flatearth,t_azi_dummy; xyz2t(t_azi_dummy,t_range_flatearth, slave,slaveorbit, P,MAXITER,CRITERTIM); // P on h=0 ref_phase = s_min4picdivlam*t_range_flatearth- s_min4picdivlam*t_range_slave; } else // include flatearth, ref.pha = phi_topo+phi_flatearth { ref_phase = m_min4picdivlam*master.pix2tr(p)- s_min4picdivlam*t_range_slave; } ref_phase_array(i,j) = ref_phase; lambda += DEMdeltalon; } // loop DEM pixels // ______ update latitude of next line ______ phi -= DEMdeltalat; // upper left is max. value } // loop DEM lines // Write results to output files PROGRESS << STEP << "Writing radar coded DEM to file, buffer: " << buffer+1 << " of " << numfullbuffers + extrabuffer ; PROGRESS.print(); demofile << DEM; masterdemlineoutfile << masterDEMline; masterdempixeloutfile << masterDEMpixel; demrefphaseoutfile << ref_phase_array; if (outputh2ph==true) demh2phoutfile << h2ph_array; masterDEMline.resize(1,1); //deallocate masterDEMpixel.resize(1,1); //deallocate DEM.resize(1,1); //deallocate ref_phase_array(1,1); //deallocate h2ph_array(1,1); //deallocate } // buffer loop demofile.close(); masterdemlineoutfile.close(); masterdempixeloutfile.close(); demrefphaseoutfile.close(); if (outputh2ph==true) demh2phoutfile.close(); //=================================================================== //============ End first loop: radarcode DEM ======================== //============ (DEM geometry) ============================ //=================================================================== //=================================================================== //============ Second loop: interpolation ============= //============ (radar geometry) ============= //=================================================================== INFO << STEP << "Start interpolation..."; INFO.print(); // ______ Line/pixel of first point in original master coordinates ______ // ______ maybe this should be changed to be x+(ml/2) ?? but depends on // ______ definition of range_to_first_bin is to center or start.. // Bert Kampes, 08-Apr-2005: chose center by adding ml/2 const int32 Nlinesml = interferogram.win.lines() / mlL; // ifg lines when mlL = 1 (no multilooking) const int32 Npixelsml = interferogram.win.pixels() / mlP; const int32 ifgNlinesml = interferogram.win.lines() / ifgmlL; // for the result file when mlL != 1 const int32 ifgNpixelsml = interferogram.win.pixels() / ifgmlP; const real8 offset = 0; //cerr << "xNFO: linesnoml: " << Nlinesml << " pixnoml: " << Npixelsml << endl; //cerr << "xNFO: ifglinesml: " << ifgNlinesml << " ifgpixml: " << ifgNpixelsml << endl; const real8 veryfirstline = real8(ifglinelo) + (real8(mlL)-1.0)/2.0; const real8 verylastline = veryfirstline + real8((Nlinesml-1)*mlL); const real8 firstpixel = real8(ifgpixlo) + (real8(mlP)-1.0)/2.0; const real8 lastpixel = firstpixel + real8((Npixelsml-1)*mlP); //cerr << "xNFO: vl0:vlN " << veryfirstline << ":" << verylastline << " p1:pN " << firstpixel << ":" << lastpixel << endl; //Determine range-azimuth spacing ratio, needed for proper triangulation cn P1, P2 , P3, P4; lp2xyz(veryfirstline,firstpixel,ellips,master,masterorbit, P1,MAXITER,CRITERPOS); lp2xyz(veryfirstline,lastpixel,ellips,master,masterorbit, P2,MAXITER,CRITERPOS); lp2xyz(verylastline,firstpixel,ellips,master,masterorbit, P3,MAXITER,CRITERPOS); lp2xyz(verylastline,lastpixel,ellips,master,masterorbit, P4,MAXITER,CRITERPOS); const real8 r_spacing = ( (P1.min(P2)).norm() + (P3.min(P4)).norm() ) / 2 /(lastpixel - firstpixel) ; const real8 az_spacing = ( (P1.min(P3)).norm() + (P2.min(P4)).norm() ) /2 /(verylastline - veryfirstline); const real8 r_az_ratio = r_spacing/az_spacing; INFO << "Interferogram azimuth spacing: " << az_spacing; INFO.print(); INFO << "Interferogram range spacing: " << r_spacing; INFO.print(); INFO << "Range-azimuth spacing ratio: " << r_az_ratio; INFO.print(); // ______ Compute buffer size interpolation______ const real8 Nlinesml_possible = BUFFERMEMSIZE / (6*8*Npixelsml); bufferlines = int32(ceil(Nlinesml_possible)); // initialized if ( mlookedIFG == true) // if ifg is multilooked by a factor { bufferlines = int32( floor(Nlinesml_possible/ifgmlL) * ifgmlL ); // [HB] Hermann provided the fix: // Successive bufferlines must have a size which is multiple of multilooking factor // unless data can fit completely to an initial single buffer. // Extra buffer will scale correctly and rounding due to multilooking // will yield correct number lines for the output file. // Ex: floor(2097/25)*2 + floor(1578/25) = 229 lines (wrong) (bufferlines/mlL)*Nbuffers+extrabufferlines/mlL } // Ex: floor(2075/25)*25*2 + floor(1622/25) = 230 lines (correct) else // no-multilooking { bufferlines = int32( floor(Nlinesml_possible) ); // [MA] instead of ceil, prefered floor to use less mem } if (bufferlines > Nlinesml) bufferlines=Nlinesml; // if bufferlines > Nlines then shrink bufferlines to Nlines, no extra buffer requested. INFO << "Possible max. buffer lines: " << bufferlines << " for " << BUFFERMEMSIZE << " memory size."; INFO.print(); numfullbuffers = Nlinesml / bufferlines; restlines = Nlinesml % bufferlines; // the number of lines in extra buffer extrabuffer = (restlines == 0) ? 0 : 1; // ______ Extra info ______ INFO << "Interpolation in: " << numfullbuffers << " buffers of " << bufferlines << " lines and " << extrabuffer << " extra buffer of " << restlines << " lines."; INFO.print(); INFO << "OutputFile forefdem: "<< refdeminput.forefdem; INFO.print(); // ______ Open output files ______ ofstream refdemofile; // refdem phase openfstream(refdemofile,refdeminput.forefdem,generalinput.overwrit); bk_assert(refdemofile,refdeminput.forefdem,__FILE__,__LINE__); // _____ start added by MA _____ ofstream refdemofilenoML; // [MA] refdem phase no-multilooked { // local scope practice string fname = string(refdeminput.forefdem) + ".noML"; // new name as m_s_refdemphase.raw.noML if ( mlookedIFG == true) // if ifg is multilooked by a factor { openfstream(refdemofilenoML,fname.c_str(),generalinput.overwrit); bk_assert(refdemofilenoML,fname.c_str(),__FILE__,__LINE__); } else // no-multilooking { if(!remove(fname.c_str())) // when success report removed. { WARNING << "Removed existing " << fname << "file."; WARNING.print(); } } } // _____ end added by MA _____ // if request for height in radar coordinates l,p ofstream refdemheiofile;// Radarcoded DEM (Z.Perski) if (outputrefdemhei==true) { INFO << "OutputFile forefdemhei: "<< refdeminput.forefdemhei; INFO.print(); openfstream(refdemheiofile,refdeminput.forefdemhei,generalinput.overwrit); bk_assert(refdemheiofile,refdeminput.forefdemhei,__FILE__,__LINE__); } // if request for h2ph in radar coordinates l,p ofstream h2phofile; if (outputh2ph==true) { openfstream(h2phofile,refdeminput.foh2ph,generalinput.overwrit); bk_assert(h2phofile,refdeminput.foh2ph,__FILE__,__LINE__); } // ______ interpolation loop per buffer ______ for (register int32 buffer = 0; buffer < numfullbuffers + extrabuffer; ++buffer) { // Determine indices for buffer const int32 blines = (buffer == numfullbuffers) ? restlines : bufferlines; const real8 firstline_buffer = veryfirstline+buffer*bufferlines*mlL; const real8 lastline_buffer = firstline_buffer+(blines-1)*mlL; // ______ Extra info ______ PROGRESS << STEP << "Interpolation buffer: " << buffer+1 << "of" << numfullbuffers + extrabuffer << " [l0:lN, p0:pN]: " << " [" << firstline_buffer << ": " << lastline_buffer << ", " << firstpixel << ": " << lastpixel << "]"; PROGRESS.print(); // Get corners of buffer real8 phimin_az; real8 phimax_az; real8 lambdamin_az; real8 lambdamax_az; getcorners(firstline_buffer+offset,lastline_buffer+offset, firstpixel+offset,lastpixel+offset, extralat,extralong,phimax,lambdamin, DEMdeltalat,DEMdeltalon,NrowsDEM,NcolsDEM, ellips,master,masterorbit,phimin_az,phimax_az,lambdamin_az,lambdamax, indexphi0DEM,indexphiNDEM,indexlambda0DEM,indexlambdaNDEM); window zerooffset (0,0,0,0); window winfromfile (indexphi0DEM,indexphiNDEM, indexlambda0DEM,indexlambdaNDEM); const int32 NrowsDEM_buffer = indexphiNDEM-indexphi0DEM+1; const int32 NcolsDEM_buffer = indexlambdaNDEM-indexlambda0DEM+1; PROGRESS << STEP << "Reading input for interpolation buffer: " << buffer+1 << "of" << numfullbuffers + extrabuffer; PROGRESS.print(); // read x,y matrix DEMline_buffer(NrowsDEM_buffer,NcolsDEM_buffer); matrix DEMpixel_buffer(NrowsDEM_buffer,NcolsDEM_buffer); readfile(DEMline_buffer,"crd_m_demline.temp",NrowsDEM,winfromfile,zerooffset); readfile(DEMpixel_buffer,"crd_m_dempixel.temp",NrowsDEM,winfromfile,zerooffset); // read z (multiple, number can easily be increased, e.g. simulated intensity) int32 Nz = 1; //number of z matrix input_buffer(NrowsDEM_buffer *Nz ,NcolsDEM_buffer); matrix temp_input_buffer(NrowsDEM_buffer,NcolsDEM_buffer); if (outputrefdemhei==true) { Nz += 1; input_buffer.resize(NrowsDEM_buffer *Nz ,NcolsDEM_buffer); } if (outputh2ph==true) { Nz += 1; input_buffer.resize(NrowsDEM_buffer *Nz ,NcolsDEM_buffer); } readfile(temp_input_buffer,"crd_dem_refphase.temp",NrowsDEM,winfromfile,zerooffset); input_buffer.setdata(0, 0, temp_input_buffer); Nz = 1; if (outputrefdemhei==true) { Nz += 1; /// i would like to use real4, test later on matrix dem_input(NrowsDEM_buffer,NcolsDEM_buffer); readfile(dem_input,refdeminput.fodem,NrowsDEM,winfromfile,zerooffset); for (register int32 i =0 ; i < NrowsDEM_buffer ; i ++) for(register int32 j = 0; j < NcolsDEM_buffer; j++) temp_input_buffer(i,j) = real8(dem_input(i,j)); input_buffer.setdata(NrowsDEM_buffer * (Nz-1), 0, temp_input_buffer); } if (outputh2ph==true) { Nz += 1; readfile(temp_input_buffer,"crd_dem_h2ph.temp",NrowsDEM,winfromfile,zerooffset); input_buffer.setdata(NrowsDEM_buffer * (Nz-1) , 0, temp_input_buffer); } // initialize output array Nz = 1; matrix output_buffer(blines * Nz, Npixelsml); if (outputrefdemhei==true) { Nz += 1; output_buffer.resize(blines * Nz, Npixelsml); } if (outputh2ph==true) { Nz += 1; output_buffer.resize(blines * Nz, Npixelsml); } // interpolation griddatalinear(DEMline_buffer,DEMpixel_buffer,input_buffer, firstline_buffer,lastline_buffer,firstpixel,lastpixel, mlL,mlP,r_az_ratio,offset,NODATA,output_buffer); //MA multilooking will start here. //MA cast all output files to type real4 matrix output_layer(blines,Npixelsml); Nz = 1; // matrix 3rd dimension counter, 1 --> PHASE for (register int32 i =0 ; i < blines ; i++) for(register int32 j = 0; j < Npixelsml; j++) output_layer(i,j) = real4(output_buffer(i,j)); // real8 --> real4 // convert_type(output_buffer,output_layer); // TODO MA, should replace above 3 lines but this one doesn't work properly yet cerr << "refphase: blines: " << blines << " Npixelsml " << Npixelsml << endl; INFO << "size buffer: lines: " << output_layer.lines()<< ", " << output_layer.pixels() < real4 //refdemheiofile << output_layer; // output reference dem heights (mlookedIFG == true) ? refdemheiofile << multilook(output_layer, ifgmlL, ifgmlP) // [MA] : refdemheiofile << output_layer ; //refdemheiofile << output_buffer(window((Nz-1) * blines,Nz * blines - 1, 0, Npixelsml -1 )); } if (outputh2ph==true) { Nz += 1; for (register int32 i = blines * (Nz-1) ; i < blines * Nz ; i++) for(register int32 j = 0; j < Npixelsml; j++) output_layer(i-(blines * (Nz-1)),j) = real4(output_buffer(i,j)); // real8 --> real4 //h2phofile << output_layer; // output h2ph matrix (mlookedIFG == true) ? h2phofile << multilook(output_layer, ifgmlL, ifgmlP) // [MA] : h2phofile << output_layer; //h2phofile << output_buffer(window((Nz-1) * blines,Nz * blines - 1, 0, Npixelsml -1 )); } DEMline_buffer.resize(1,1); // deallocate DEMpixel_buffer.resize(1,1); input_buffer.resize(1,1); temp_input_buffer.resize(1,1); output_buffer.resize(1,1); } // end loop azimuth direction INFO << "Closing output files"; INFO.print(); refdemofile.close(); // has the same multilook as interferrogram if (mlookedIFG==true) refdemofilenoML.close(); // [MA] if interferogram is mlooked then this is // generated as non-multilooked for coherence estimation. if (outputrefdemhei==true) // For Zbigniew Perski refdemheiofile.close(); if (outputh2ph==true) h2phofile.close(); //=================================================================== //============ End second loop: interpolation ============= //============ (radar geometry) ============= //=================================================================== // === Clean up temporary outfiles === [MA] if (remove("crd_m_demline.temp")) // remove files WARNING.print("code 101: could not remove file: crd_m_demline.temp."); if (remove("crd_m_dempixel.temp")) WARNING.print("code 101: could not remove file: crd_m_dempixel.temp."); if (remove("crd_dem_refphase.temp")) WARNING.print("code 101: could not remove file: crd_dem_refphase.temp."); if ( outputh2ph==true && remove("crd_dem_h2ph.temp")) // output available WARNING.print("code 101: could not remove file: crd_dem_h2ph.temp."); // === Clean up Done. === // ====== Write output information ====== char croppeddemi[4*ONE27]; strcpy(croppeddemi,"NO output requested"); if (outputdemi) strcpy(croppeddemi,refdeminput.fodemi); INFO << "Min. value of input DEM covering interferogram: " << min_input_dem; INFO.print(); INFO << "Max. value of input DEM covering interferogram: " << max_input_dem; INFO.print(); ofstream scratchlogfile("scratchlogcomprefdem", ios::out | ios::trunc); bk_assert(scratchlogfile,"comprefdem: scratchlogcomprefdem",__FILE__,__LINE__); scratchlogfile << "\n*******************************************************************" << "\n* " << processcontrol[pr_i_comprefdem] << "\n*******************************************************************" << "\n1) DEM source file: \t" << refdeminput.firefdem << "\nFormat: \t"; switch (refdeminput.iformatflag) { case FORMATI2: { scratchlogfile << "SHORT SIGNED INTEGER (HOST ENDIANNESS)"; break; } case FORMATI2_BIGENDIAN: { scratchlogfile << "SHORT SIGNED INTEGER, BIG ENDIAN"; break; } case FORMATR4: { scratchlogfile << "REAL4 SIGNED FLOAT"; break; } case FORMATR8: { scratchlogfile << "REAL8 SIGNED DOUBLE"; break; } default: { scratchlogfile << "UNKNOWN? IMPOSSIBLE..."; break; } } scratchlogfile << "\nByte order: \t" << "check it yourself..." << "\nNumber of lines: \t" << numberoflatpixels << "\nNumber of pixels: \t" << numberoflonpixels << "\nResolution latitude: \t" << rad2deg(DEMdeltalat) << " [deg]" << "\nResolution longitude: \t" << rad2deg(DEMdeltalon) << " [deg]" << "\nMost West point in input DEM: \t" << rad2deg(lon0file) << "\nMost East point in input DEM: \t" << rad2deg(lonNfile) << "\nMost South point in input DEM: \t" << rad2deg(latNfile) << "\nMost North point in input DEM: \t" << rad2deg(lat0file) << "\nMin. value of input DEM covering interferogram: " << min_input_dem << "\nMax. value of input DEM covering interferogram: " << max_input_dem << "\n2) Output file cropped DEM: \t" << refdeminput.fodem //[FVL << "\nFormat: \t" << "REAL4" << "\nByte order: \t" << "(same as host)" << "\nNumber of lines (multilooked): \t" << NcolsDEM << "\nNumber of pixels (multilooked): \t" << NrowsDEM << "\nDEM extend w/e/s/n : \t" << rad2deg(lambdamin) << "/" << rad2deg(lambdamax) << "/" << rad2deg(phimin) << "/" << rad2deg(phimax) // << "\nMean value: \t" << meancroppedDEM << "\n3) Output file interpolated crop DEM: \t" << croppeddemi << "\nFormat: \t" << "REAL4" << "\nByte order: \t" << "(same as host)" << "\n4) Output file synthetic phase: \t" << refdeminput.forefdem << "\nFormat: \t" << "REAL4" << "\nByte order: \t" << "(same as host)" << "\nNumber of lines (multilooked): \t" << ifgNlinesml << "\nNumber of pixels (multilooked): \t" << ifgNpixelsml // this is not correct, only stats per buffer... // << "\n\n----- Other STATS -----" // << "\nTotal points in cropped DEM: \t" << numpoints // << "\nNumber of valid points in DEM: \t" << numvalid // << " (" << 100*numvalid/numpoints << "%)" // << "\nNumber of NODATA points in DEM: \t" << numNODATA // << " (" << 100*numNODATA/numpoints << "%)" // << "\nMean height in meters at valid points:\t" << meancroppedDEM << "\n*******************************************************************\n\n"; scratchlogfile.close(); ofstream scratchresfile("scratchrescomprefdem", ios::out | ios::trunc); bk_assert(scratchresfile,"comprefdem: scratchrescomprefdem",__FILE__,__LINE__); scratchresfile << "\n\n*******************************************************************" << "\n*_Start_" << processcontrol[pr_i_comprefdem] << "\n*******************************************************************"; if (onlyrefphasetopo==true) scratchresfile // [don] << "\nInclude_flatearth: \tNo"; else scratchresfile << "\nInclude_flatearth: \tYes"; scratchresfile << "\nDEM source file: \t" << refdeminput.firefdem << "\nMin. of input DEM: \t" << min_input_dem << "\nMax. of input DEM: \t" << max_input_dem << "\nData_output_file: \t" << refdeminput.forefdem << "\nData_output_format: \t" << "real4" << "\nFirst_line (w.r.t. original_master): \t" << interferogram.win.linelo << "\nLast_line (w.r.t. original_master): \t" << interferogram.win.linehi << "\nFirst_pixel (w.r.t. original_master): \t" << interferogram.win.pixlo << "\nLast_pixel (w.r.t. original_master): \t" << interferogram.win.pixhi << "\nMultilookfactor_azimuth_direction: \t" << ifgmlL << "\nMultilookfactor_range_direction: \t" << ifgmlP << "\nNumber of lines (multilooked): \t" << ifgNlinesml << "\nNumber of pixels (multilooked): \t" << ifgNpixelsml << "\n*******************************************************************" << "\n* End_" << processcontrol[pr_i_comprefdem] << "_NORMAL" << "\n*******************************************************************\n"; scratchresfile.close(); } // END radarcodedem /**************************************************************** * getcorners * * * * Get corners of window (approx) to select DEM in radians (if * * height were zero) * * * * Implementation: * * 1) calculate phi, lambda of corners * * 2) select the extreme values * * 3) add extra overlap * * 4) determine the indices in the file * * * * Freek van Leijen, 07-AUG-2006 * * * ****************************************************************/ void getcorners( const real8 &l0, // master.currentwindow.linelo const real8 &lN, // master.currentwindow. const real8 &p0, // master.currentwindow. const real8 &pN, // master.currentwindow. const real8 &extralat, // const real8 &extralong, // const real8 &lat0, // lat0file const real8 &long0, // lon0file const real8 &DEMdeltalat, // const real8 &DEMdeltalong, // const int32 &Nlatpixels, // numberoflatpixels const int32 &Nlongpixels, // numberoflonpixels const input_ell &ellips, const slcimage &master, orbit &masterorbit, real8 &phimin, real8 &phimax, real8 &lambdamin, real8 &lambdamax, int32 &indexphi0DEM, // returned int32 &indexphiNDEM, // returned int32 &indexlambda0DEM, // returned int32 &indexlambdaNDEM) // returned { TRACE_FUNCTION("getcorners (FvL 07-AUG-2006)") DEBUG << "(getcorners) l0 :" << l0; DEBUG.print(); DEBUG << "(getcorners) lN :" << lN; DEBUG.print(); DEBUG << "(getcorners) p0 :" << p0; DEBUG.print(); DEBUG << "(getcorners) pN :" << pN; DEBUG.print(); DEBUG << "(getcorners) extralat :" << extralat; DEBUG.print(); DEBUG << "(getcorners) extralong :" << extralong; DEBUG.print(); DEBUG << "(getcorners) lat0 :" << lat0; DEBUG.print(); DEBUG << "(getcorners) long0 :" << long0; DEBUG.print(); DEBUG << "(getcorners) DEMdeltalat :" << DEMdeltalat; DEBUG.print(); DEBUG << "(getcorners) DEMdeltalong :" << DEMdeltalong; DEBUG.print(); DEBUG << "(getcorners) Total Nlatpixels :" << Nlatpixels; DEBUG.print(); DEBUG << "(getcorners) Total Nlongpixels :" << Nlongpixels; DEBUG.print(); real8 phi; real8 lambda; real8 height; lp2ell(l0,p0, ellips, master, masterorbit, phi, lambda, height); // returned real8 phil0p0 = phi; real8 lambdal0p0 = lambda; lp2ell(lN,p0, ellips, master, masterorbit, phi, lambda, height); // returned real8 philNp0 = phi; real8 lambdalNp0 = lambda; lp2ell(lN,pN, ellips, master, masterorbit, phi, lambda, height); // returned real8 philNpN = phi; real8 lambdalNpN = lambda; lp2ell(l0,pN, ellips, master, masterorbit, phi, lambda, height); // returned real8 phil0pN = phi; real8 lambdal0pN = lambda; // ______ Select DEM values based on rectangle outside l,p border ______ phimin = min(min(min(phil0p0,philNp0),philNpN),phil0pN); phimax = max(max(max(phil0p0,philNp0),philNpN),phil0pN); lambdamin = min(min(min(lambdal0p0,lambdalNp0),lambdalNpN),lambdal0pN); lambdamax = max(max(max(lambdal0p0,lambdalNp0),lambdalNpN),lambdal0pN); // ______ a little bit extra at edges to be sure ______ // TODO this should change based on ascending or descending [MA] phimin -= extralat; phimax += extralat; lambdamax += extralong; lambdamin -= extralong; DEBUG << "(getcorners) phimin :" << phimin; DEBUG.print(); DEBUG << "(getcorners) phimax :" << phimax; DEBUG.print(); DEBUG << "(getcorners) lambdamin :" << lambdamin; DEBUG.print(); DEBUG << "(getcorners) lambdamax :" << lambdamax; DEBUG.print(); // ______ Get indices of DEM needed ______ // ______ Index boundary: [0:numberofx-1] ______ indexphi0DEM = int32(floor((lat0-phimax)/DEMdeltalat)); if (indexphi0DEM < 0) { WARNING << "(getcorners) indexphi0DEM: " << indexphi0DEM; WARNING.print(); indexphi0DEM=0; // default start at first WARNING.print("DEM does not cover entire interferogram."); WARNING.print("input DEM should be extended to the North."); } indexphiNDEM = int32(ceil((lat0-phimin)/DEMdeltalat)); if (indexphiNDEM > Nlatpixels-1) { WARNING << "(getcorners) indexphiNDEM: " << indexphiNDEM; WARNING.print(); indexphiNDEM=Nlatpixels-1; WARNING.print("DEM does not cover entire interferogram."); WARNING.print("input DEM should be extended to the South."); } indexlambda0DEM = int32(floor((lambdamin-long0)/DEMdeltalong)); if (indexlambda0DEM < 0) { WARNING << "(getcorners) indexlambda0DEM: " << indexlambda0DEM; WARNING.print(); indexlambda0DEM=0; // default start at first WARNING.print("DEM does not cover entire interferogram."); WARNING.print("input DEM should be extended to the West."); } indexlambdaNDEM = int32(ceil((lambdamax-long0)/DEMdeltalong)); if (indexlambdaNDEM > Nlongpixels-1) { WARNING << "(getcorners) indexlambdaNDEM: " << indexlambdaNDEM; WARNING.print(); indexlambdaNDEM=Nlongpixels-1; WARNING.print("DEM does not cover entire interferogram."); WARNING.print("input DEM should be extended to the East."); } DEBUG << "(getcorners) indexphi0DEM :" << indexphi0DEM; DEBUG.print(); DEBUG << "(getcorners) indexphiNDEM :" << indexphiNDEM; DEBUG.print(); DEBUG << "(getcorners) indexlambda0DEM :" << indexlambda0DEM; DEBUG.print(); DEBUG << "(getcorners) indexlambdaNDEM :" << indexlambdaNDEM; DEBUG.print(); } // END getcorners /**************************************************************** * griddatalinear (naming after Matlab function) * * * * Implementation after GMT function triangulate.c * ****************************************************************/ void griddatalinear( const matrix &x_in, const matrix &y_in, const matrix &z_in, const real8 &x_min, const real8 &x_max, const real8 &y_min, const real8 &y_max, const int32 &x_inc, const int32 &y_inc, const real8 &r_az_ratio, const real8 &offset, const real8 &NODATA, matrix &grd ) { TRACE_FUNCTION("griddatalinear (LG&FvL 13-AUG-2006)") INFO << "griddataLinear interpolation."; INFO.print(); int32 i, j, k, ij, p, i_min, i_max, j_min, j_max; int32 n, nx, ny, zLoops, zLoop, zBlockSize,indexFirstPoint,zInterpolateBlockSize; real8 vx[4], vy[4], xkj, xlj, ykj, ylj, zj, zk, zl, zlj, zkj, xp, yp; real8 f, *a = NULL , *b = NULL , *c = NULL ; // linear interpolation parameters struct triangulateio In, Out, vorOut; // Initialize variables n = zBlockSize = x_in.size(); // block size of x and y coordination /* How many groups of z value should be interpolated */ if (( z_in.size() % zBlockSize ) != 0) { INFO << "The input of the DEM buffer and z is not the same..."; INFO.print(); return; } else zLoops = z_in.size()/x_in.size(); a = new real8[zLoops]; b = new real8[zLoops]; c = new real8[zLoops]; if (a == NULL || b == NULL || c == NULL) { ERROR << "Memory ERROR in source file: " << __FILE__ << " at line: " << __LINE__; PRINT_ERROR(ERROR.get_str()); throw(memory_error); } nx = grd.lines()/zLoops; ny = grd.pixels(); zInterpolateBlockSize = grd.size()/zLoops; /* Set everything to 0 and NULL */ memset ((void *)&In, 0, sizeof (struct triangulateio)); memset ((void *)&Out, 0, sizeof (struct triangulateio)); memset ((void *)&vorOut, 0, sizeof (struct triangulateio)); /* Allocate memory for input points */ In.numberofpoints = n ; In.pointlist = new real8 [2 * n]; /* Copy x,y points to In structure array */ for (i = j = 0; i < n; i++) { In.pointlist[j++] = *(x_in[0] + i); In.pointlist[j++] = (*(y_in[0] + i)) * r_az_ratio ; // to eliminate the effect of difference in range and azimuth spacing; } /* Call Jonathan Shewchuk's triangulate algorithm. This is 64-bit safe since * all the structures use 4-byte ints (longs are used internally). */ triangulate ("zIQB", &In, &Out, &vorOut); //triangulate ("zIBV", &In, &Out, &vorOut); // [MA] for verbosing int32 *link = Out.trianglelist; /* List of node numbers to return via link */ int32 np = Out.numberoftriangles; for (k = ij = 0; k < np; k++) { DEBUG << "k of np, ij: " << k << " of " << np << ", :" << ij; DEBUG.print(); //Store the Index of the first Point of this triangle. indexFirstPoint = ij; vx[0] = vx[3] = *(x_in[0] + link[ij]); vy[0] = vy[3] = *(y_in[0] + link[ij]); ij++; vx[1] = *(x_in[0] + link[ij]); vy[1] = *(y_in[0]+link[ij]); ij++; vx[2] = *(x_in[0] + link[ij]); vy[2] = *(y_in[0]+link[ij]); ij++; if ( vx[0] == NODATA || vx[1] == NODATA || vx[2] == NODATA ) continue; if ( vy[0] == NODATA || vy[1] == NODATA || vy[2] == NODATA ) continue; /* Compute grid indices the current triangle may cover.*/ xp = min (min (vx[0], vx[1]), vx[2]); i_min = x_to_i (xp, x_min, x_inc, offset, nx); //INFO << "xp: " << xp; //INFO.print(); xp = max (max (vx[0], vx[1]), vx[2]); i_max = x_to_i (xp, x_min, x_inc, offset, nx); //INFO << "xp: " << xp; //INFO.print(); yp = min (min (vy[0], vy[1]), vy[2]); j_min = y_to_j (yp, y_min, y_inc, offset, ny); //INFO << "yp: " << yp; //INFO.print(); yp = max (max (vy[0], vy[1]), vy[2]); j_max = y_to_j (yp, y_min, y_inc, offset, ny); //INFO << "yp: " << yp; //INFO.print(); /* Adjustments for triangles outside -R region. */ /* Triangle to the left or right. */ if ((i_max < 0) || (i_min >= nx)) continue; /* Triangle Above or below */ if ((j_max < 0) || (j_min >= ny)) continue; /* Triangle covers boundary, left or right. */ if (i_min < 0) i_min = 0; if (i_max >= nx) i_max = nx - 1; /* Triangle covers boundary, top or bottom. */ if (j_min < 0) j_min = 0; if (j_max >= ny) j_max = ny - 1; // for (kk = 0; kk ((x - xt[0]) * ( yt[2] - yt[0])) ? 1:-1; int iRet1 = ((xt[0] - xt[1]) * (y - yt[1])) > ((x - xt[1]) * ( yt[0] - yt[1])) ? 1:-1; int iRet2 = ((xt[1] - xt[2]) * (y - yt[2])) > ((x - xt[2]) * ( yt[1] - yt[2])) ? 1:-1; if ((iRet0 >0 && iRet1 > 0 && iRet2 > 0 ) || (iRet0 <0 && iRet1 < 0 && iRet2 < 0 )) return 1; else return 0; } //END pointintriangle Doris-5.0.3Beta/doris_core/referencephase.hh000077500000000000000000000144351312547014700210410ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/referencephase.hh,v $ * $Revision: 3.8 $ * $Date: 2005/08/24 10:03:18 $ * $Author: kampes $ * * Routines for reference phase computation * - flatearth * - radarcodedem * - interpolation routines delaunay? ****************************************************************/ #ifndef REFERENCEPHASE_H #define REFERENCEPHASE_H using namespace std; // BK 29-Mar-2003, new compiler? // Jia defined this for compilation under windows // Bert Kampes, 24-Aug-2005 #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "constants.hh" // typedefs #include "readinput.hh" // input structs #include "orbitbk.hh" // my orbit class #include "slcimage.hh" // my slc image class #include "productinfo.hh" // my 'products' class // ====== Prototypes ====== // ______ Compute reference phase ______ void flatearth( const input_comprefpha &flatearthinput, const input_ell &ellips, const slcimage &master, const slcimage &slave, const productinfo &interferogram, orbit &masterorbit, orbit &slaveorbit); // ______ DEM assisted coregistration ______ void demassist( const input_gen &generalinput, const input_ell &ellips, const input_demassist &demassistinput, const slcimage &master, const slcimage &slave, orbit &masterorbit, orbit &slaveorbit); // ______ Compute reference phase ______ void radarcodedem( const input_gen &generalinput, const input_ell &ellips, const input_comprefdem &comprefdeminput, const slcimage &master, const slcimage &slave, const productinfo &interferogram, orbit &masterorbit, orbit &slaveorbit); // ______ Get indices of corners DEM ________________ void getcorners( const real8 &l0, const real8 &lN, const real8 &p0, const real8 &pN, const real8 &extralat, const real8 &extralong, const real8 &lat0, const real8 &long0, const real8 &DEMdeltalat, const real8 &DEMdeltalong, const int32 &Nlatpixels, const int32 &Nlongpixels, const input_ell &ellips, const slcimage &master, orbit &masterorbit, real8 &phimin, real8 &phimax, real8 &lambdamin, real8 &lambdamax, int32 &indexphi0DEM, int32 &indexphiNDEM, int32 &indexlambda0DEM, int32 &indexlambdaNDEM); // _______ griddatalinear ______________________ void griddatalinear( const matrix &x_in, // line values const matrix &y_in, // pixel values const matrix &z_in, // z. hei, amp in dem coords const real8 &x_min, const real8 &x_max, const real8 &y_min, // pixel extend min const real8 &y_max, // pixel extend max const int32 &x_inc, // increment based on mlL const int32 &y_inc, const real8 &r_az_ratio, const real8 &offset, const real8 &NODATA, matrix &grd ); // _______ pointintriangle ______________________ int pointintriangle( double *xt, double *yt, double x , double y); #define rint(x) (floor((x)+0.5)) #define irint(x) ((int)rint(x)) #define x_to_i(x,x0,dx,off,nx) (irint(((((x) - (x0)) / (dx)) - (off)))) #define y_to_j(y,y0,dy,off,ny) (irint(((((y) - (y0)) / (dy)) - (off)))) #define i_to_x(i,x0,x1,dx,off,nx) ((x0) + (i) * (dx) + (off)) #define j_to_y(j,y0,y1,dy,off,ny) ((y0) + (j) * (dy) + (off)) // // ______ Return true if P(l,p) is inside triangle P1P2P3 ______ // // ______ newtriangle is true if last call was for same P1P2P3 ______ // bool pointintriangle( // real4 l, // real4 p, // real4 l1, // real4 p1, // real4 l2, // real4 p2, // real4 l3, // real4 p3, // bool newtriangle); // ______ Return true if P(l,p) is inside triangle P1P2P3 ______ // ______ newtriangle is true if last call was for same P1P2P3 ______ // ______ if not real8 then totally wrong... (or eps = AP1P2P3/1e6) ______ bool pointintriangle( real8 l, real8 p, real8 l1, real8 p1, real8 l2, real8 p2, real8 l3, real8 p3, bool newtriangle); #endif // REFERENCEPHASE_H Doris-5.0.3Beta/doris_core/slcimage.cc000077500000000000000000001462601312547014700176360ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/slcimage.cc,v $ * * $Revision: 3.31 $ * * $Date: 2005/10/06 11:09:20 $ * * $Author: kampes $ * * * * implementation of slc image class. * * - data filling/updating. * * - reading in matrices. * * - etc. * #%// BK 14-Aug-2000 * ****************************************************************/ #include "constants.hh" // typedefs #include "slcimage.hh" // declarations, constants.h #include "ioroutines.hh" // ? #include "utilities.hh" // deg2rad() #include "ioroutines.hh" // filesize #include "matrixbk.hh" // matrix #include "exceptions.hh" // my exceptions class #include // some compilers, remove function #include // for memory stream #include // strcat? #include // time #ifdef WIN32 // Jia defined this here, I put it in constants.hh // Bert Kampes, 24-Aug-2005 //#define max _MAX //#define min _MIN #endif char *strptime(const char *s, const char *format, struct tm *tm); /**************************************************************** * slcimage::constructor * #%// Bert Kampes, 08-Apr-2005 ****************************************************************/ slcimage::slcimage() { TRACE_FUNCTION("slcimage() (BK 14-Aug-2000)") DEBUG.print("initializing slcimage with ERS defaults"); // ______Initialize______ strcpy(file,"unknown"); strcpy(utc1,"unknown"); sensor = SLC_ERS; // default (vs. SLC_ASAR, JERS, RSAT) sar_processor = SARPR_VMP; // (VMP (esa paf) or ATLANTIS or TUDELFT) // TODO PGS update? approxcentreoriginal.x = 0.0; approxcentreoriginal.y = 0.0; approxcentreoriginal.z = 0.0; wavelength = 0.0565646; // [m] default ERS2 t_azi1 = 0.0; // [s] sec of day t_range1 = 5.5458330/2.0e3; // [s] one way, default ERS2 prf = 1679.902; // [Hz] default ERS2 abw = 1378.0; // [Hz] default ERS2 f_DC_a0 = 0.0; // [Hz] default ERS2 f_DC_a1 = 0.0; f_DC_a2 = 0.0; f_DC_t_ref_az = 0.0; // DC_reference_azimuth_time f_DC_t_ref_rn = 0.0; // DC_reference range time // ________________ TOPS ONLY__________________ // FM polynomial FM_t_ref_az = 0.0 ; // azimuth time reference for frequency modulation rate FM_t_ref_rn = 0.0 ; // range time reference for frequency modulation rate FM_a0 = 0.0 ; // constant term Hz FM_a1 = 0.0 ; // linear term Hz/s FM_a2 = 0.0 ; // quadratic term Hz/s/s Ks = 0.0 ; // azimuth steering rate [deg/s] dt_az = 0.0 ; //Azimuth_time_interval [s]] rsr2x = 18.9624680*2.0e6; // [Hz] default ERS2 rbw = 15.55e6; // [Hz] default ERS2 currentwindow.linelo = 1; currentwindow.linehi = 25000; // set for normalization? currentwindow.pixlo = 1; currentwindow.pixhi = 5000; // set for normalization? formatflag = 0; // format of file on disk originalwindow.linelo = 1; // by default originalwindow.linehi = 25000; // set for normalization? originalwindow.pixlo = 1; // by default originalwindow.pixhi = 5000; // set for normalization? coarseoffsetL = 0; // by default coarseoffsetP = 0; // by default coarseorbitoffsetL = 0; // by default, [FvL] coarseorbitoffsetP = 0; // by default, [FvL] ovs_rg = 1; // by default ovs_az = 1; // by default az_timing_error = 0; // by default, [FvL] unit lines r_timing_error = 0; // by default, [FvL] unit pixels see slcimage.hh timingerror_flag = false; // by default, [MA] slavemasteroffsets.l00 = 0; // window in master coordinates [FvL] slavemasteroffsets.p00 = 0; slavemasteroffsets.l0N = 0; slavemasteroffsets.p0N = 0; slavemasteroffsets.lN0 = 0; slavemasteroffsets.pN0 = 0; slavemasteroffsets.lNN = 0; slavemasteroffsets.pNN = 0; } // END slcimage::slcimage() /**************************************************************** * slcimage::fillslcimage * * Fills data of slscimage object, read from resultfile after * * step readfiles. * * Expects certain strings in outpfile. * * Break loop and warn if not found but do not exit. * * Look in first 100 lines for strings, or return sooner. * * Use SI units (Hz,s,m) for internal representation. * #%// BK 14-Aug-2000 * * added INFO for fDC. * #%// BK 06-Nov-2000 * * added sarprocessor and check for NORMAL termination * #%// Bert Kampes, 29-Jul-2005 * ****************************************************************/ void slcimage::fillslcimage(const char* file) { TRACE_FUNCTION("fillslcimage (BK 14-Aug-2000)") INFO << "Reading parameters from: " << file; INFO.print(); // ______Open file______ ifstream resfile(file, ios::in); bk_assert(resfile,file,__FILE__,__LINE__); // ______ Lookfor identifiers (strings) ______ char dummyline[6*ONE27]; real8 latitude; real8 longitude; char word[6*ONE27] = " "; int32 linecounter = 0; // ______ check all fields are found _______________ bool found_lat = false; bool found_lon = false; bool found_wavelength = false; bool found_t_range1 = false; bool found_t_azi1 = false; bool found_prf = false; bool found_rsr = false; bool found_nlines = false; bool found_npixels = false; bool found_abw = false; bool found_rbw = false; bool found_fdc_a0 = false; bool found_fdc_a1 = false; bool found_fdc_a2 = false; bool found_f_DC_t_ref = false; bool found_f_DC_t_ref_rn = false; bool found_FM_t_ref = false; // azimuth time reference for frequency modulation rate bool found_FM_t_ref_rn = false; // range time reference for frequency modulation rate bool found_FM_a0 = false; // constant term Hz bool found_FM_a1 = false; // linear term Hz/s bool found_FM_a2 = false; // quadratic term Hz/s/s bool found_Ks = false; // azimuth steering rate [deg/s] bool found_dt_az = false; //Azimuth_time_interval [s]] bool found_sarp = false; bool found_product = false; // ______ BK test if this help for DEBUG etc. ______ DEBUG << setiosflags(ios::fixed) << setprecision(8) << setiosflags(ios::showpoint); while(resfile && linecounter<1000) { ++linecounter; resfile.getline(dummyline,4*ONE27,'\n'); // next line TRACE << "dummyline: " << dummyline; TRACE.print(); // ___ Check if we are at end of section already ____ char *pchq; pchq = strstr(dummyline,":_NORMAL");// section terminator if (pchq != NULL) { char *pchqq; pchqq = strstr(dummyline,"leader_datapoints");// but ignore this one... if (pchqq != NULL) { DEBUG.print("Ignoring leader data points terminator."); } else { DEBUG.print("Section terminator found (string \":_NORMAL\")."); break;// section ends } } // ______ Check if all parameters are read ______ // if (found_lat == true && // found_lon == true && // found_wavelength == true && // found_t_range1 == true && // found_t_azi1 == true && // found_prf == true && // found_rsr == true && // found_nlines == true && // found_npixels == true && // found_abw == true && // found_rbw == true && // found_fdc_a0 == true && // found_fdc_a1 == true && // found_fdc_a2 == true && // found_sarp == true && // found_product == true) break; // ___ read parameters ___ resfile >> word; // read word if (!strcmp(word,"Scene_centre_latitude:")) { found_lat = true; resfile >> latitude; DEBUG << "[" << linecounter << "]: string: \"Scene_centre_latitude:\", (derived) value: " << latitude; DEBUG.print(); if (abs(latitude) > 90) WARNING.print("latitude larger than 90 degees?"); } else if (!strcmp(word,"Scene_centre_longitude:")) { found_lon = true; resfile >> longitude; DEBUG << "[" << linecounter << "]: string: \"Scene_centre_longitude:\", (derived) value: " << longitude; DEBUG.print(); if (abs(longitude) > 360) WARNING.print("longitude larger than 360 degees?"); } else if (!strcmp(word,"Radar_wavelength")) // (m): { found_wavelength = true; resfile >> word >> wavelength; DEBUG << "[" << linecounter << "]: string: \"Radar_wavelength\", (derived) value: " << wavelength; DEBUG.print(); if (wavelength > 0.50) WARNING.print("wavelength is larger than 50 centimeter?"); if (wavelength < 0.01) WARNING.print("wavelength is smaller than 1 centimeter?"); } else if (!strcmp(word,"Range_time_to_first_pixel")) { found_t_range1 = true; resfile >> word >> word >> t_range1; // (2way) (ms): t_range1 /= 2000.; // 1 way, s DEBUG << "[" << linecounter << "]: string: \"Range_time_to_first_pixel\", (derived) value: " << t_range1; DEBUG.print(); } else if (!strcmp(word,"First_pixel_azimuth_time")) { found_t_azi1 = true; struct tm tijdstart; char c12tijd0[20]; char c12tijd0_tmp[20];// allow for .123456 ms ASAR in reading resfile >> word >> utc1 >> c12tijd0_tmp; // (UTC): 26-JUL-1995 09:49:23.394 // ______ utc1 should be including time ______ // ______ make sure not to put in ms since what are the consequenses // ______ for getorb, strptime, etc. ______ strncpy(c12tijd0,c12tijd0_tmp,12); c12tijd0[12]='\0'; DEBUG << "Extracted first azimuth time string: " << c12tijd0; DEBUG.print(); strcat(utc1," "); strcat(utc1,c12tijd0); // ______ Compute sec. of day for this date ______ strptime(c12tijd0,"%T",&tijdstart); char c12frac0[20]="0."; register int32 i; for (i=0; i<20; i++) if (c12tijd0_tmp[i]=='.') break; int32 j = 2; while (c12tijd0_tmp[i] != '\0') // use old value of i { i++; c12frac0[j]=c12tijd0_tmp[i]; j++; } t_azi1 = tijdstart.tm_sec + atof(c12frac0) + 60 * tijdstart.tm_min + 3600 * tijdstart.tm_hour; DEBUG << "[" << linecounter << "]: string: \"First_pixel_azimuth_time\", (derived) value: " << t_azi1; DEBUG.print(); } else if (!strcmp(word,"Pulse_Repetition_Frequency")) { found_prf = true; resfile >> word >> word >> prf; // (computed, Hz): DEBUG << "[" << linecounter << "]: string: \"Pulse_Repetition_Frequency\", (derived) value: " << prf; DEBUG.print(); } else if (!strcmp(word,"Range_sampling_rate")) { found_rsr = true; resfile >> word >> word >> rsr2x; // (computed, MHz): rsr2x *= 2000000.; // 2 times in Hz DEBUG << "[" << linecounter << "]: string: \"Range_sampling_rate\", (derived) value: " << rsr2x; DEBUG.print(); } else if (!strcmp(word,"Number_of_lines_original:")) { found_nlines = true; resfile >> originalwindow.linehi; DEBUG << "[" << linecounter << "]: string: \"Number_of_lines_original:\", (derived) value: " << originalwindow.linehi; DEBUG.print(); if (originalwindow.linehi > 200000) WARNING.print("more than 200000 lines, very long-strip?"); // [MA] 100k --> 200k } else if (!strcmp(word,"Number_of_pixels_original:")) { found_npixels = true; resfile >> originalwindow.pixhi; DEBUG << "[" << linecounter << "]: string: \"Number_of_pixels_original:\", (derived) value: " << originalwindow.pixhi; DEBUG.print(); if (originalwindow.pixhi > 100000) WARNING.print("more than 100000 range pixels?"); } else if (!strcmp(word,"Total_azimuth_band_width")) // (Hz): { found_abw = true; resfile >> word >> abw; DEBUG << "[" << linecounter << "]: string: \"Total_azimuth_band_width\", (derived) value: " << abw; DEBUG.print(); } else if (!strcmp(word,"Total_range_band_width")) // (MHz): { found_rbw = true; resfile >> word >> rbw; rbw *= 1000000.; // (Hz) DEBUG << "[" << linecounter << "]: string: \"Total_range_band_width\", (derived) value: " << rbw; DEBUG.print(); } else if (!strcmp(word,"Xtrack_f_DC_constant")) // (Hz, early edge): { found_fdc_a0 = true; resfile >> word >> word >> word >> f_DC_a0;// also works for ATL: 1.0E+02 DEBUG << "[" << linecounter << "]: string: \"Xtrack_f_DC_constant\", (derived) value: " << f_DC_a0; DEBUG.print(); } else if (!strcmp(word,"Azimuth_steering_rate")) // (TOPS only): { found_Ks= true; resfile >> word >>word; Ks = atof(word); DEBUG << "[" << linecounter << "]: string: \"Azimuth_steering_rate\", (derived) value: " << word << ", " << Ks; DEBUG.print(); } else if (!strcmp(word,"Xtrack_f_DC_linear")) // (Hz/s, early edge): { found_fdc_a1 = true; //resfile >> word >> word >> word >> f_DC_a1; resfile >> word >> word >> word >>word; f_DC_a1 = atof(word); if (abs(f_DC_a1)<1.0) { WARNING << "Strange value for f_DC_a1: " << f_DC_a1 << "; setting f_DC_a1=0 (expected ~1e7)"; WARNING.print(); WARNING.print("other definition of ATLANTIS? or Focused SLC?"); if (!found_Ks)//do not change anything for TOPS f_DC_a1 = 0.0; } DEBUG << "[" << linecounter << "]: string: \"Xtrack_f_DC_linear\", (derived) value: " << f_DC_a1; DEBUG.print(); } else if (!strcmp(word,"Xtrack_f_DC_quadratic")) // (Hz/s/s, early edge): { found_fdc_a2 = true; resfile >> word >> word >> word >> f_DC_a2; if (abs(f_DC_a2)<1.0) { WARNING << "strange value for f_DC_a2: " << f_DC_a2 << "; setting f_DC_a2=0 (expected ~1e12)"; WARNING.print(); WARNING.print("other definition of ATLANTIS? or Focused SLC?"); if (!found_Ks)//do not change anything for TOPS f_DC_a2 = 0.0; } DEBUG << "[" << linecounter << "]: string: \"Xtrack_f_DC_quadratic\", (derived) value: " << f_DC_a2; DEBUG.print(); } else if (!strcmp(word,"DC_reference_azimuth_time:")) // (TOPS only): { found_f_DC_t_ref = true; struct tm tijdstart; char c12tijd0[20]; char c12tijd0_tmp[20];// allow for .123456 ms ASAR in reading resfile >> utc1 >> c12tijd0_tmp; // (UTC): 26-JUL-1995 09:49:23.394 // ______ utc1 should be including time ______ // ______ make sure not to put in ms since what are the consequences // ______ for getorb, strptime, etc. ______ strncpy(c12tijd0,c12tijd0_tmp,12); c12tijd0[12]='\0'; strcat(utc1," "); strcat(utc1,c12tijd0); // ______ Compute sec. of day for this date ______ strptime(c12tijd0,"%T",&tijdstart); char c12frac0[20]="0."; register int32 i; for (i=0; i<20; i++) if (c12tijd0_tmp[i]=='.') break; int32 j = 2; while (c12tijd0_tmp[i] != '\0') // use old value of i { i++; c12frac0[j]=c12tijd0_tmp[i]; j++; } f_DC_t_ref_az = tijdstart.tm_sec + atof(c12frac0) + 60 * tijdstart.tm_min + 3600 * tijdstart.tm_hour; DEBUG << "[" << linecounter << "]: string: \"DC_reference_azimuth_time:\", (derived) value: " << f_DC_t_ref_az; DEBUG.print(); } else if (!strcmp(word,"DC_reference_range_time:")) // (TOPS only): { found_f_DC_t_ref_rn = true; resfile >> f_DC_t_ref_rn; DEBUG << "[" << linecounter << "]: string: \"DC_reference_range_time:\", (derived) value: " << f_DC_t_ref_rn; DEBUG.print(); } else if (!strcmp(word,"FM_reference_azimuth_time:")) // (TOPS only): { found_FM_t_ref = true; resfile >> FM_t_ref_az; DEBUG << "[" << linecounter << "]: string: \"FM_reference_azimuth_time\", (derived) value: " << FM_t_ref_az; DEBUG.print(); } else if (!strcmp(word,"FM_reference_range_time:")) // (TOPS only): { found_FM_t_ref_rn = true; resfile >> FM_t_ref_rn; DEBUG << "[" << linecounter << "]: string: \"FM_reference_range_time\", (derived) value: " << FM_t_ref_rn; DEBUG.print(); } else if (!strcmp(word,"FM_polynomial_constant_coeff")) // (TOPS only): { found_FM_a0= true; resfile >> word >> word >> word >> FM_a0; DEBUG << "[" << linecounter << "]: string: \"FM_polynomial_constant_coeff\", (derived) value: " << FM_a0; DEBUG.print(); } else if (!strcmp(word,"FM_polynomial_linear_coeff")) // (TOPS only): { found_FM_a1= true; resfile >> word >> word >> word >> FM_a1; DEBUG << "[" << linecounter << "]: string: \"FM_polynomial_linear_coeff\", (derived) value: " << FM_a1; DEBUG.print(); } else if (!strcmp(word,"FM_polynomial_quadratic_coeff")) // (TOPS only): { found_FM_a2= true; resfile >> word >> word >> word >> FM_a2; DEBUG << "[" << linecounter << "]: string: \"FM_polynomial_quadratic_coeff\", (derived) value: " << FM_a2; DEBUG.print(); } else if (!strcmp(word,"Azimuth_time_interval")) // (TOPS only): { found_dt_az= true; resfile >> word >> dt_az; DEBUG << "[" << linecounter << "]: string: \"Azimuth_time_interval\", (derived) value: " << dt_az; DEBUG.print(); } //TODO UPDATE and ADD the FM rate // ___ SAR_PROCESSOR key added, written in readleader() ___ // ___ if you want to force behavior, change this in master.res ___ else if (!strcmp(word,"SAR_PROCESSOR:")) // VMP ATLANTIS TUD { found_sarp = true; resfile >> word; DEBUG << "[" << linecounter << "]: string: \"SAR_PROCESSOR:\", (derived) value: " << word; DEBUG.print(); // ______ default processor ______ if (!strcmp(word,"VMP")) { DEBUG.print("SAR_PROCESSOR: ESA VMP identified."); sar_processor = SARPR_VMP; } // ______ envisat, written by envisat_dump_header2doris.csh ______ else if (!strcmp(word,"ASAR")) { DEBUG.print("SAR_PROCESSOR: ESA ASAR identified."); sar_processor = SARPR_VMP; } // ______ Data focussed by user using Atlantis ______ else if (!strcmp(word,"ATLANTIS")) { sar_processor = SARPR_ATL; DEBUG.print("SAR_PROCESSOR: ATLANTIS identified."); } else if (!strcmp(word,"TUD")) { sar_processor = SARPR_TUD; DEBUG.print("SAR_PROCESSOR: TUD identified."); } // Modified by LG for reading ALOS Fine else if (!strcmp(word,"JAX")) { sar_processor = SARPR_JAX; DEBUG.print("SAR_PROCESSOR: JAX identified."); } else if (!strcmp(word,"TSX")) { sar_processor = SARPR_TSX; DEBUG.print("SAR_PROCESSOR: TSX identified."); } else if ( strstr(word,"TX") != NULL ) // maybe not supported { sar_processor = SARPR_TSX; DEBUG.print("SAR_PROCESSOR: TSX identified."); } else if ( strstr(word,"TDX") != NULL ) // TandemX { sar_processor = SARPR_TSX; DEBUG.print("SAR_PROCESSOR: TSX identified."); } else if (!strcmp(word,"RN")) { sar_processor = SARPR_RS2; DEBUG.print("SAR_PROCESSOR: RADARSAT-2 identified."); } else if (!strcmp(word,"CSK")) // CSK verify { sar_processor = SARPR_CSK; DEBUG.print("SAR_PROCESSOR: Cosmo-skymed identified."); } else if (!strcmp(word, "GAMMA")) { sar_processor = SARPR_GAM; // 20100916.BO.Gamma support. DEBUG.print("SAR_PROCESSOR: GAMMA identified."); } else { sar_processor = SARPR_VMP; WARNING.print("SAR_PROCESSOR: not identified, using VMP (ESA)."); } } // ______ 11.08.2002 BK, sensor specifier ers or asar? _____ // ______ Product type specifier: "PRODUCT:ERS-2.SAR.SLC" // ______ Product type specifier: "ASAR" (forced by me) // ______ Product type specifier: "JERS" (???) // ______ Product type specifier: "RSAT" (???) else if (!strcmp(word,"Product")) { found_product = true; resfile >> word >> word >> word; DEBUG << "[" << linecounter << "]: string: \"Product\", (derived) value: " << word; DEBUG.print(); // Best find substring ERS, but don't know if strstr is standard. // We force ASAR as sensor string for this goal. // but now with JERS, ERS, RSAT, ASAR, we search a bit... assume caps char *pch; pch = strstr (word,"PRODUCT");// Atlantis seems to put "PRODUCT:" or "PRODUCT" if (pch != NULL) { sensor = SLC_ERS;// Atlantis processor; also ERS... assume this DEBUG.print("Substring \"PRODUCT\" (radarsat?) found in Product type specifier."); char next_word[4*ONE27] = " "; // [PM]: for ALOS something goes wrong here resfile >> next_word; // strcpy(next_word,word); char *next_pch; next_pch = strstr (next_word,"ERS"); if (next_pch != NULL) { DEBUG.print("Substring \"PRODUCT ERS\" found in Product type specifier."); sensor = SLC_ERS;// Atlantis processor; also ERS... // assume reader for cropping is not as for RSAT... } // for ALOS Fine [PM] next_pch = strstr (next_word,"ALOS"); // without this // line,pixs not dumped if (next_pch != NULL) { DEBUG.print("Substring \"PRODUCT ALOS\" found in Product type specifier."); sensor = SLC_ALOS; } next_pch = strstr (next_word,"RSAT"); if (next_pch != NULL) { DEBUG.print("Substring \"PRODUCT RSAT\" found in Product type specifier."); sensor = SLC_RSAT;// Atlantis processor; also does RSAT WARNING.print("Assuming Atlantis processor was used/format of SLC."); WARNING.print("If you don;t want this, change line in res file to:"); WARNING.print("Product type specifier: ERS"); } } // pch = strstr (word,"RSAT"); // MA moved below TODO remove // if (pch != NULL) // { // DEBUG.print("Substring \"RSAT\" found in Product type specifier."); // sensor = SLC_RSAT; // WARNING.print("Assuming Atlantis processor was used/format of SLC."); // WARNING.print("If you don;t want this, change line in res file to:"); // WARNING.print("Product type specifier: ERS"); // } // pch = strstr (word,"RADARSAT"); // if (pch != NULL) // { // DEBUG.print("Substring \"RADARSAT\" found in Product type specifier."); // sensor = SLC_RSAT; // WARNING.print("Assuming Atlantis processor was used/format of SLC."); // WARNING.print("If you don;t want this, change line in res file to:"); // WARNING.print("Product type specifier: ERS"); // } pch = strstr (word,"ES");// envisat official abbrev? if (pch != NULL) { DEBUG.print("Substring \"ES\" found in Product type specifier."); sensor = SLC_ASAR; } pch = strstr (word,"ASAR"); if (pch != NULL) { DEBUG.print("Substring \"ASAR\" found in Product type specifier."); sensor = SLC_ASAR; } pch = strstr (word,"ENVISAT"); if (pch != NULL) { DEBUG.print("Substring \"ENVISAT\" found in Product type specifier."); sensor = SLC_ASAR; } pch = strstr (word,"ERS");// first ERS since ERS is substring of JERS if (pch != NULL) { DEBUG.print("Substring \"ERS\" found in Product type specifier."); sensor = SLC_ERS; } pch = strstr (word,"JERS"); if (pch != NULL) { DEBUG.print("Substring \"JERS\" found in Product type specifier."); sensor = SLC_JERS; } pch = strstr (word,"ERS_SAR");// ERS in N1 envisat format if (pch != NULL) { DEBUG.print("Substring \"ERS_SAR\" found in Product type specifier."); sensor = SLC_ERS_N1; } pch = strstr (word,"TSX"); if (pch != NULL) { DEBUG.print("Substring \"TSX\" found in Product type specifier."); sensor = SLC_TSX; } pch = strstr (word,"TDX"); // TandemX if (pch != NULL) { DEBUG.print("Substring \"TDX\" found in Product type specifier."); sensor = SLC_TSX; } pch = strstr (word,"RADARSAT-2"); if (pch != NULL) { DEBUG.print("Substring \"Radarsat-2\" found in Product type specifier."); sensor = SLC_RS2; continue; } pch = strstr (word,"S1A"); if (pch != NULL) { DEBUG.print("Substring \"Sentinel-1A\" found in Product type specifier."); sensor = SLC_S1A; continue; } pch = strstr (word,"RSAT"); if (pch != NULL) { DEBUG.print("Substring \"RSAT\" found in Product type specifier."); sensor = SLC_RSAT; WARNING.print("Assuming Atlantis processor was used/format of SLC."); WARNING.print("If you don;t want this, change line in res file to:"); WARNING.print("Product type specifier: ERS"); } pch = strstr (word,"RADARSAT"); if (pch != NULL) { DEBUG.print("Substring \"RADARSAT\" found in Product type specifier."); sensor = SLC_RSAT; WARNING.print("Assuming Atlantis processor was used/format of SLC."); WARNING.print("If you don;t want this, change line in res file to:"); WARNING.print("Product type specifier: ERS"); } pch = strstr (word,"CSK"); // CSK verify if (pch != NULL) { DEBUG.print("Substring \"CSK\" found in Product type specifier."); sensor = SLC_CSK; } DEBUG << "Product/sensor: " << sensor; DEBUG.print(); } } // while file and < 1000 lines resfile.close(); // --- Check if all parameters are found --- INFO << "Checking file: " << file; INFO.print(); if (found_lat == false) WARNING.print("found_lat==false"); if (found_lon == false) WARNING.print("found_lon==false"); if (found_wavelength == false) WARNING.print("found_wavelength==false"); if (found_t_range1 == false) WARNING.print("found_t_range1==false"); if (found_t_azi1 == false) WARNING.print("found_t_azi1==false"); if (found_prf == false) WARNING.print("found_prf==false"); if (found_rsr == false) WARNING.print("found_rsr==false"); if (found_nlines == false) WARNING.print("found_nlines==false"); if (found_npixels == false) WARNING.print("found_npixels==false"); if (found_abw == false) WARNING.print("found_abw==false"); if (found_rbw == false) WARNING.print("found_rbw==false"); if (found_fdc_a0 == false) WARNING.print("found_fdc_a0==false"); if (found_fdc_a1 == false) WARNING.print("found_fdc_a1==false"); if (found_fdc_a2 == false) WARNING.print("found_fdc_a2==false"); if (found_sarp == false) WARNING.print("found_sarp==false"); if (found_product == false) WARNING.print("found_product==false"); // ____ ____ DEBUG << "sensor id: " << sensor; DEBUG.print(); if (sensor==SLC_ERS || sensor==SLC_ERS_N1 ) { DEBUG.print("ERS 1 or 2 sensor detected."); if (abs(wavelength-0.0565646) > 0.01) WARNING.print("wavelength seems to deviates more than 1 cm from ERS2 nominal."); if (abs(prf - 1680) > 100.0) WARNING.print("prf deviates more than 100 Hz from ERS2 nominal."); if (abs(rsr2x - 18.9624680*2.0e6) > 100000.0) WARNING.print("rsr deviates more than 0.1 MHz from ERS2 nominal."); if (abs(abw-1378.0) > 100) WARNING.print("ABW deviates more than 100 Hz from ERS2 nominal?"); if (abs(rbw-15.55e6) > 1000) WARNING.print("RBW deviates more than 1 kHz from ERS2 nominal?"); } if (sensor==SLC_ASAR) { INFO.print("Yeah, EnviSAT!"); if (abs(wavelength-0.0562356) > 0.01) WARNING.print("wavelength seems to deviates more than 1 cm from ASAR nominal."); if (abs(prf-1652.0) > 100.0) WARNING.print("prf deviates more than 100 Hz from ASAR nominal."); if (abs(rsr2x - 19.207680*2.0e6) > 100000.0) WARNING.print("rsr deviates more than 0.1 MHz from ASAR nominal."); if (abs(abw-1316.0) > 100) WARNING.print("ABW deviates more than 100 Hz from ASAR nominal?"); if (abs(rbw-16.0e6) > 1000) WARNING.print("RBW deviates more than 1 kHz from ASAR nominal?"); } if (sensor==SLC_JERS) { WARNING.print("JERS detected: still in testing phase."); if (abs(wavelength-0.23076920) > 0.01) WARNING.print("wavelength seems to deviates more than 1 cm from JERS nominal."); if (abs(prf-1555.0) > 100.0) WARNING.print("prf deviates more than 100 Hz from JERS nominal."); if (abs(rsr2x - 17.075998*2.0e6) > 100000.0) WARNING.print("rsr deviates more than 0.1 MHz from JERS nominal."); if (abs(abw-1555.0) > 100) WARNING.print("ABW deviates more than 100 Hz from JERS nominal?"); if (abs(rbw-17.075998*2.0e6) > 1000) WARNING.print("RBW deviates more than 1 kHz from JERS nominal?"); } if (sensor==SLC_RSAT) { WARNING.print("RSAT detected: this is still in development."); WARNING.print(" +main difficulty with orbit in earth fixed system; doppler."); WARNING.print(" +but it seems to work with polyfit(max) for orbit interp."); } if (sensor==SLC_ALOS) { INFO.print("Yeah, ALOS!"); WARNING.print("ALOS detected: this is still in development."); WARNING.print(" +main difficulty coregistering actual doppler focused data."); } if (sensor==SLC_TSX) { INFO.print("Yeah, TerraSAR-X!"); if (abs(wavelength-0.031) > 0.01) WARNING.print("wavelength seems to deviates more than 1 cm from TSX nominal."); } if (sensor==SLC_RS2) { INFO.print("Yeah, Radarsat-2!"); } if (sensor==SLC_CSK) { INFO.print("Really!, Cosmo-SkyMed!"); if (abs(wavelength-0.031) > 0.01) WARNING.print("wavelength seems to deviates more than 1 cm from CSK nominal."); } // ______ Some info for range ______ INFO << setiosflags(ios::fixed) << setiosflags(ios::showpoint) << setprecision(3); INFO << "Range to pixel 1 = " << pix2range(1.0) << " m"; INFO.print(); INFO << "Range to pixel " << originalwindow.pixhi << " = " << pix2range(originalwindow.pixhi) << " m"; INFO.print(); // ______ Give some info on Doppler centroid frequency fDC ______ // ______ x=pixelnumber/RSR [s]; fDC=a0+a1x+a2x^2 [Hz] ______ const real8 earlyedgefDC = f_DC_a0;// tau=0.0 // ______ extreme of: y=ax^2+bx+c, dy/dx=0 at -b/2a ______ const real8 extremepix = (abs(f_DC_a2)<1e-9) ? 0.0: f_DC_a1/(-2.0*f_DC_a2); const real8 extremefDC = f_DC_a0 + extremepix * f_DC_a1 + sqr(extremepix) * f_DC_a2; const real8 faredgefDC = f_DC_a0 + real8(originalwindow.pixhi-1)/(rsr2x/2.0) * f_DC_a1 + sqr(real8(originalwindow.pixhi-1)/(rsr2x/2.0)) * f_DC_a2; DEBUG << setiosflags(ios::scientific) << setprecision(8) << setiosflags(ios::showpos); DEBUG << "fDC(col) = " << f_DC_a0 << f_DC_a1 << "*(col-1)/" << rsr2x/2 << f_DC_a2 << "*((col-1)/" << rsr2x/2 << ")^2" << ends; DEBUG.print(); DEBUG << "fDC(col) = " << f_DC_a0 << f_DC_a1/(rsr2x/2) << "*(col-1)" << f_DC_a2/sqr(rsr2x/2) << "*(col-1)^2" << ends; DEBUG.print(); // --- --- INFO << "Doppler centroid frequency: at pixel 1 (early edge): \t\t" << earlyedgefDC << " Hz"; INFO.print(); INFO << "Doppler centroid frequency: at pixel " << originalwindow.pixhi << " (far edge): \t" << faredgefDC << " Hz"; INFO.print(); INFO << "Doppler centroid frequency: at pixel " << extremepix*rsr2x/2.; // better if b<0 then max or somthinfg like that (extremefDC >= earlyedgefDC) ? INFO << " (maximum): " : INFO << " (minimum): "; INFO << "\t" << extremefDC << " Hz"; INFO.print(); //const real8 minfDC = min(min(earlyedgefDC,faredgefDC),); //mean fDC = ... (integral, decide max or min, etc., reshape to rectangle) INFO << "sensor: " << sensor; INFO.print(); // ====== Tidy up ====== //pol2xyz(approxcentreoriginal, // convert lat/lon to xyz // deg2rad(latitude),deg2rad(longitude),0.); // on sphere input_ell wgs84ellips; approxcentreoriginal = wgs84ellips.ell2xyz( deg2rad(latitude),deg2rad(longitude),0.0); currentwindow.linelo = originalwindow.linelo; currentwindow.linehi = originalwindow.linehi; currentwindow.pixlo = originalwindow.pixlo; currentwindow.pixhi = originalwindow.pixhi; #ifdef __DEBUG DEBUG.print("Finished fillslcimage"); DEBUG.print("content of struct:"); showdata(); #endif DEBUG.print(""); DEBUG.reset(); INFO.reset(); } // END slcimage::fillslcimage /**************************************************************** * updateslcimage * * * * Fills struct slcimage after step identified by iden * * and read information upto string ":_NORMAL" (i.e., only * * read appropriate section * * * * input: * * - resultfilename * * - identifier * * - struct slcimage * * output: * * - (updated) struct slcimage * * current size of image * * * * Bert Kampes, 22-Dec-1998 * * put in class. * #%// BK 14-Aug-2000 * * added check for "Multilookfactor_azimuth_direction" * * added check for "Multilookfactor_range_direction" * * make sure this does not happen recursively * * added reading upto ":_NORMAL" termination substring * #%// Bert Kampes, 29-Jul-2005 * #%// Mahmut Arikan, 19-May-2009 * * minor update to file size check * ****************************************************************/ void slcimage::updateslcimage( const char *resultfile, const char *iden) { TRACE_FUNCTION("updateslcimage (BK 14-Aug-2000)") char word[4*ONE27]=" "; char dummyline[4*ONE27]; // ______Open file______ ifstream resfile(resultfile, ios::in); bk_assert(resfile,resultfile,__FILE__,__LINE__); bool foundiden = false; while(resfile) { if (strcmp(word,iden)) // Lookfor identifier { resfile.getline(dummyline,4*ONE27,'\n'); // next line resfile >> word; // read word } else { foundiden = true; DEBUG << "updateslcimage: found identifier: \"" << iden << "\" in file: \"" << resultfile << "\"."; DEBUG.print(); break; } } // ______Check if section has been found______ if (!foundiden) { ERROR << "(updateslcimage). identifier: " << iden << " not found in file: " << resultfile; PRINT_ERROR(ERROR.get_str()) throw(file_error); } // ======Extract info (filename and window size)====== bool found_file = false; bool found_format = false; bool found_line1 = false; bool found_lineN = false; bool found_pixel1 = false; bool found_pixelN = false; bool found_mlL = false;// optional for oversampled data: adapt prf etc. if present. bool found_mlP = false;// optional for oversampled data: adapt prf etc. if present. float tmpmultilookL = 1.0;// default float tmpmultilookP = 1.0;// default while(resfile) // i.e. rest of file { resfile.getline(dummyline,4*ONE27,'\n'); // next line TRACE << "dummyline: " << dummyline; TRACE.print(); // ___ Check if we are at end of section already ____ char *pch; pch = strstr(dummyline,":_NORMAL");// section terminator if (pch != NULL) { DEBUG.print("Section terminator found (string \":_NORMAL\")."); break;// section ends } // ___ Check if all parameters are found ______ if (found_file == true && found_format == true && found_line1 == true && found_lineN == true && found_pixel1 == true && found_pixelN == true && found_mlL == true && found_mlP == true) break; // ___ Check for strings with parameters ___ resfile >> word; // read word if (!strcmp(word,"Data_output_file:")) { found_file = true; resfile >> file; DEBUG << "string: \"Data_output_file:\", \t\tvalue: " << file; DEBUG.print(); } else if (!strcmp(word,"Data_output_format:")) { found_format = true; resfile >> word; if (!strcmp(word,"complex_short")) formatflag = FORMATCI2; else if (!strcmp(word,"complex_real4")) formatflag = FORMATCR4; else { PRINT_ERROR("wrong format specifier (impossible?)") throw(file_error); } DEBUG << "string: \"Data_output_format:\", \t\tvalue: " << formatflag; DEBUG.print(); } else if (!strcmp(word,"First_line")) // (w.r.t. original): { found_line1 = true; resfile >> word >> word >> currentwindow.linelo; DEBUG << "string: \"First_line\", \t\tvalue: " << currentwindow.linelo; DEBUG.print(); } else if (!strcmp(word,"Last_line")) // (w.r.t. original): { found_lineN = true; resfile >> word >> word >> currentwindow.linehi ; DEBUG << "string: \"Last_line\", \t\tvalue: " << currentwindow.linehi; DEBUG.print(); } else if (!strcmp(word,"First_pixel")) // (w.r.t. original): { found_pixel1 = true; resfile >> word >> word >> currentwindow.pixlo ; DEBUG << "string: \"First_pixel\", \t\tvalue: " << currentwindow.pixlo; DEBUG.print(); } else if (!strcmp(word,"Last_pixel")) // (w.r.t. original): { found_pixelN = true; resfile >> word >> word >> currentwindow.pixhi ; DEBUG << "string: \"Last_pixel\", \t\tvalue: " << currentwindow.pixhi; DEBUG.print(); } // --- Only present in OVS section --- else if (!strcmp(word,"Multilookfactor_azimuth_direction:")) { resfile >> tmpmultilookL; found_mlL = true; ovs_az = int32(1.0/tmpmultilookL+0.5);// round to integer // ovs_az = (tmpmultilookL > 1.0) ? (1.0/tmpmultilookL) : int32(1.0/tmpmultilookL+0.5);// round to integer // comment below error msg and edit slcimage.hh to define real8 ovs_az [TODO] multilook test DEBUG << "String: \"Multilookfactor_azimuth_direction:\", value: " << tmpmultilookL; DEBUG.print(); if (tmpmultilookL > 1.0) { PRINT_ERROR("Decimation of slc along azimuth direction not implemented yet."); throw(file_error); } } // --- Only present in OVS section --- else if (!strcmp(word,"Multilookfactor_range_direction:")) { resfile >> tmpmultilookP; found_mlP = true; ovs_rg = int32(1.0/tmpmultilookP+0.5);// round to integer DEBUG << "String: \"Multilookfactor_range_direction:\", \tvalue: " << tmpmultilookP; DEBUG.print(); if (tmpmultilookP > 1.0) { PRINT_ERROR("Decimation of slc along range direction not implemented yet."); throw(file_error); } } } // while file // ___ Check if all required strings are found ______ INFO << "Checking file: " << file; INFO.print(); showdata(); if (found_file == false) {ERROR.print("found_file==false"); throw(some_error);} if (found_format == false) {ERROR.print("found_format==false"); throw(some_error);} if (found_line1 == false) {ERROR.print("found_line1==false"); throw(some_error);} if (found_lineN == false) {ERROR.print("found_lineN==false"); throw(some_error);} if (found_pixel1 == false) {ERROR.print("found_pixel1==false"); throw(some_error);} if (found_pixelN == false) {ERROR.print("found_pixelN==false"); throw(some_error);} // ___ Check oversampling factor of SLC image ___ if (found_mlL == false) DEBUG.print("found_mlL==false (OK if not oversampled)"); if (found_mlP == false) DEBUG.print("found_mlP==false (OK if not oversampled)"); // ___ Make changes to image parameters ___ // ___ Be careful not to do this recursive, e.g., if new sections ___ // ___ also report this parameter ___ // // [BK]: seems incorrect to change window parameters; // [BK]: Doris always stays with original master coordinates. // How is now after azimuth filter the settings, etc. ?? // How is function like get_fdc(pix) ? // I suspect that for now the interferogram is bigger // because it says ifg.win=master.win after this ? // this gives incorrect info in ifg.res file, i.e. // last line is 50000 not 25000, i.e., problems? // but correct number of files must be known to // read data from file, etc. // For now I will leave it. (the code by RN) // // -- only present in one section; then update for following steps -- if (found_mlL==true && found_mlP==true)//prevent recursion { prf *= ovs_az;// adapt az sampling freq. rsr2x *= ovs_rg;// adapt rg sampling freq. // ___ originalwindow only used for normalization ___ originalwindow.linelo = ovs_az*(originalwindow.linelo-1) + 1; originalwindow.linehi *= ovs_az;// for normalization? originalwindow.pixlo = ovs_rg*(originalwindow.pixlo-1) + 1; originalwindow.pixhi *= ovs_rg;// for normalization? //// ___ currentwindow passed and changed ___ ////currentwindow.linelo = ovs_az*(currentwindow.linelo-1) + 1; ////currentwindow.linehi *= ovs_az; ////currentwindow.pixlo = ovs_rg*(currentwindow.pixlo-1) + 1; ////currentwindow.pixhi *= ovs_rg; // ___ give info ___ DEBUG.print("Do not update abw and rbw: OK."); DEBUG.print("Do not update currentwindow, annotated is larger size"); //DEBUG.print("Do not update originalwindow; normalization unstable for small crops"); INFO << "Updated the following parameters: "; INFO.print(); INFO << "Pulse_Repetition_Frequency (actual, Hz): " << prf; INFO.print(); INFO << "Range_sampling_rate (leaderfile, MHz): " << rsr2x/2.0; INFO.print(); INFO << "Number_of_lines_original: " << originalwindow.linehi; INFO.print(); INFO << "Number_of_pixels_original: " << originalwindow.pixhi; INFO.print(); //INFO << "First_line (w.r.t. original_image): " << currentwindow.linelo; //INFO.print(); //INFO << "Last_line (w.r.t. original_image): " << currentwindow.linehi; //INFO.print(); //INFO << "First_pixel (w.r.t. original_image): " << currentwindow.pixlo; //INFO.print(); //INFO << "Last_pixel (w.r.t. original_image): " << currentwindow.pixhi; //INFO.print(); } // ______ Check filesize with format/dimensions (BK 08-Mar-2001) ______ ifstream tmpfile(file, ios::in); // ex: files is name.cint ... etc if (tmpfile) { tmpfile.seekg(0,ios::end); // internal filesize, normal one exits if not exists // uint filesizetrue = tmpfile.tellg(); const streamoff &filesizetrue = tmpfile.tellg(); // [MA] file > 4GB upport, this fix eliminates wrong warning // ___ not ok, error in bk_assert: uint filesizetrue = filesize(file); ___ int32 bytesperelem = 4; if (formatflag==FORMATCI2) bytesperelem=4; if (formatflag==FORMATCR4) bytesperelem=8; if (formatflag==FORMATR4) bytesperelem=4; if (formatflag==FORMATI2) bytesperelem=2; if (formatflag==FORMATI2_BIGENDIAN) bytesperelem=2; if (formatflag==FORMATR8) bytesperelem=8; if (formatflag==FORMATHGT) bytesperelem=8; //int32 filesizecomp = currentwindow.lines()*currentwindow.pixels()*bytesperelem; uint64 filesizecomp = (uint64)currentwindow.lines() * currentwindow.pixels() * bytesperelem; DEBUG << "Checking format/dimensions file=" << file; DEBUG.print(); if (filesizecomp != filesizetrue) { WARNING << "File: \'" << file << "\' has wrong fileformat or dimensions" // [MA] reorganized + add file << ": bytesperpix=" << bytesperelem << ", #l=" << currentwindow.lines() << ", #p=" << currentwindow.pixels() << "; size_computed=" << filesizecomp << "B" << " v." << " size_ondisk=" << filesizetrue << "B"; WARNING.print(); } else { DEBUG.print("SLC Fileformat and dimensions are checked and ok."); } tmpfile.close(); } // if file stream is OK else { WARNING << "File: " << file << " does not seem to exist (may not be a problem)."; WARNING.print(); } // ______Tidy up______ DEBUG.print(""); resfile.close(); #ifdef __DEBUG DEBUG.print("Finished updateslcimage"); DEBUG.print("content of struct:"); showdata(); #endif } // END updateslcimage /**************************************************************** * slcimage::readdata * * read data from file in a complr4 matrix * * file may be complex short or complex real4 format * * stored in row major order, pixel interleaved * %// BK 14-Aug-2000 * ****************************************************************/ matrix slcimage::readdata( window win) const // window to be read { // --- Log debug info --- TRACE_FUNCTION("readdata (BK 14-Aug-2000)") DEBUG << "Reading file: " << file; DEBUG.print(); DEBUG << "Formatflag: " << formatflag; DEBUG.print(); DEBUG << "Currentwindow: "; currentwindow.disp();// appends to DEBUG and prints DEBUG << "Window from file: "; win.disp();// appends to DEBUG and prints // // --- Read data in complex real4 matrix --- matrix Result(win.lines(),win.pixels()); switch (formatflag) { case FORMATCI2: { DEBUG.print("Format complex short integer (pixel interleaved)."); fileci2tomatcr4(Result,file,currentwindow.lines(),win,currentwindow); break; } case FORMATCR4: { DEBUG.print("Format complex float (pixel interleaved)."); readfile(Result,file,currentwindow.lines(),win,currentwindow); break; } default: PRINT_ERROR("readdata::not correct format on file.") throw(file_error); } return Result; } // END readdata Doris-5.0.3Beta/doris_core/slcimage.hh000077500000000000000000000302671312547014700176470ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/slcimage.hh,v $ * * $Revision: 3.15 $ * * $Date: 2005/08/24 10:03:18 $ * * $Author: kampes $ * * * * The slcimage class contains the definition of the data and * * functions for slc images. * * Data mainly public because this used to be a struct and I * * did not want to change the other code. * * functions for updating the data like prf, reading data into * * a matrix, etc. * #%// BK 14-Aug-2000 * ****************************************************************/ #ifndef SLCIMAGE_H #define SLCIMAGE_H using namespace std; // BK 29-Mar-2003, new compiler? // Jia defined this for compilation under windows // Bert Kampes, 24-Aug-2005 #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "constants.hh" // typedefs // ====== Define template functions (no member no friend) ====== // ______ (matrix class is declared way below) ______ template class matrix; // ====== Struct slcimage: information on master/slave ====== class slcimage // info per image { private: // copy constructor; copy matrices etc as public. slcimage(const slcimage& img) {};// prevent copy constructor usage by privatizing public: char file[EIGHTY]; // current filename char utc1[25]; // string for getorb int16 sensor; // flag for ers/asar/rsat/jers [BK 21.08.2002] int16 sar_processor; // VMP or ATLANTIS or TUDELFT [BK 04.2005] int16 formatflag; // flag for current file format cn approxcentreoriginal; // wgs84? sphere x,y,z window originalwindow; // linelo etc. for normalization (master only). window currentwindow; // linelo etc. of current on file. real8 prf; // pulse repetition frequency (Hz) real8 abw; // azimuth band width (Hz) real8 rsr2x; // 2 times range sampling rate (Hz) real8 rbw; // range band width (Hz) real8 t_azi1; // sec. of day of first pixel azimuth time real8 t_range1; // one way time (s) to first range pixel real8 wavelength; // meters // real8 hamming_azi; // weighting function designator/alpha // real8 hamming_range; // weighting function // ______ Xtrack f_DC coefficients from leader, not used for now, ______ // ______ better use matrix for polyval? real8 f_DC_a0; // constant term Hz real8 f_DC_a1; // linear term Hz/s real8 f_DC_a2; // quadratic term Hz/s/s // ________________ TOPS ONLY__________________ real8 f_DC_t_ref_az; // DC_reference_azimuth_time real8 f_DC_t_ref_rn; // range time reference // ________________ TOPS ONLY__________________ // FM polynomial real8 FM_t_ref_az; // azimuth time reference for frequency modulation rate real8 FM_t_ref_rn; // azimuth time reference for frequency modulation rate real8 FM_a0; // constant term (Hz) for polynomial of FM rate real8 FM_a1; // linear term (Hz/s) for polynomial of FM rate real8 FM_a2; // quadratic term (Hz/s/s) for polynomial of FM rate real8 Ks; // azimuth steering rate real8 dt_az; // Azimuth time interval , for most systems this is the same as 1/PRF // ______ offset = X(l,p) - X(L,P) ______ // ______ Where l,p are in the local slave coordinate system and ______ // ______ where L,P are in the local master coordinate system ______ // ______ These variables are stored in the slaveinfo variable only ______ int32 coarseoffsetL; // offset in line (azimuth) direction int32 coarseoffsetP; // offset in pixel (range) direction int32 coarseorbitoffsetL; // orbit offset in line (azimuth) direction [FvL] int32 coarseorbitoffsetP; // orbit offset in pixel (range) direction [FvL] real4 slopeP; // initial slope pixels real4 slopeL; // initial slope lines real4 realoffsetL; // initial offset pixels real4 realoffsetP; // initial offset lines int32 ovs_az; // oversampling of SLC //real8 ovs_az; // oversampling of SLC, multilook test [TODO] int32 ovs_rg; // oversampling of SLC int32 az_timing_error; // [FvL] // azimuth timing error in // lines with respect to // master (therefore used for slave only) // [MA] additionally used for master during master timing error int32 r_timing_error; //[FvL] // range timing error in // pixel with respect to // master (therefore used for slave only) bool timingerror_flag; //[MA] 0 if master time is not updated // 1 if updated slavewindow slavemasteroffsets; // window in master coordinates [FvL] // ______ Public functions of class ______ // ___Constructor/Destructor___ slcimage();// set defaults ~slcimage() { TRACE_FUNCTION("~slcimage() (BK 06-Mar-2005)"); ;// nothing to destruct ? }// dealloc // ---- Helper ---- inline void showdata() const { DEBUG << "current file: " << file; DEBUG.print(); DEBUG << "formatflag: " << formatflag; DEBUG.print(); DEBUG << "current win: " << currentwindow.linelo << " " << currentwindow.linehi << " " << currentwindow.pixlo << " " << currentwindow.pixhi; DEBUG.print(); DEBUG << "original win: " << originalwindow.linelo << " " << originalwindow.linehi << " " << originalwindow.pixlo << " " << originalwindow.pixhi; DEBUG.print(); DEBUG << "approxcentreoriginal: " << approxcentreoriginal.x << " " << approxcentreoriginal.y << " " << approxcentreoriginal.z; DEBUG.print(); DEBUG << "utc1: " << utc1; DEBUG.print(); DEBUG << "sensor: " << sensor; DEBUG.print(); DEBUG << "sar_processor: " << sar_processor; DEBUG.print(); DEBUG << "prf: " << prf; DEBUG.print(); DEBUG << "abw: " << abw; DEBUG.print(); DEBUG << "rsr: " << rsr2x/2.0; DEBUG.print(); DEBUG << "rbw: " << rbw; DEBUG.print(); DEBUG << "t_azi1: " << t_azi1; DEBUG.print(); DEBUG << "t_range1: " << t_range1; DEBUG.print(); DEBUG << "wavelength: " << wavelength; DEBUG.print(); DEBUG << "f_DC_a0: " << f_DC_a0; DEBUG.print(); DEBUG << "f_DC_a1: " << f_DC_a1; DEBUG.print(); DEBUG << "f_DC_a2: " << f_DC_a2; DEBUG.print(); DEBUG << "coarseoffsetL: " << coarseoffsetL; DEBUG.print(); DEBUG << "coarseoffsetP: " << coarseoffsetP; DEBUG.print(); DEBUG << "coarseorbitoffsetL: " << coarseoffsetL; DEBUG.print(); //[FvL] DEBUG << "coarseorbitoffsetP: " << coarseoffsetP; DEBUG.print(); //[FvL] DEBUG << "ovs_rg: " << ovs_rg; DEBUG.print(); DEBUG << "ovs_az: " << ovs_az; DEBUG.print(); DEBUG << "az_timing_error: " << az_timing_error; DEBUG.print(); //[FvL] DEBUG << "r_timing_error: " << r_timing_error; DEBUG.print(); //[FvL] DEBUG << "slave_master_offsets: " << slavemasteroffsets.l00 << " " << slavemasteroffsets.p00 << " " << slavemasteroffsets.l0N << " " << slavemasteroffsets.p0N << " " << slavemasteroffsets.lN0 << " " << slavemasteroffsets.pN0 << " " << slavemasteroffsets.lNN << " " << slavemasteroffsets.pNN; //[FvL] } // ______ Add a bias 1 way time range ______ inline void add_rg_t_error(const real8 dt) {t_range1+=dt;} inline void add_az_t_error(const real8 dt) {t_azi1+=dt;} inline void add_offsetL2az_t_error(const int32 dL) {t_azi1+=real8(dL/prf);} // [MA] inline void add_offsetP2rg_t_error(const int32 dP) {t_range1+=real8(dP/rsr2x);} // ______ Add slave master offsets [FvL] _____ inline void add_offsetl00(const real8 dl) {slavemasteroffsets.l00+=dl;} inline void add_offsetp00(const real8 dp) {slavemasteroffsets.p00+=dp;} inline void add_offsetl0N(const real8 dl) {slavemasteroffsets.l0N+=dl;} inline void add_offsetp0N(const real8 dp) {slavemasteroffsets.p0N+=dp;} inline void add_offsetlN0(const real8 dl) {slavemasteroffsets.lN0+=dl;} inline void add_offsetpN0(const real8 dp) {slavemasteroffsets.pN0+=dp;} inline void add_offsetlNN(const real8 dl) {slavemasteroffsets.lNN+=dl;} inline void add_offsetpNN(const real8 dp) {slavemasteroffsets.pNN+=dp;} // ______ Read readfiles section from resultfile ______ void fillslcimage(const char *file); void updateslcimage(const char *file, const char *iden); // //____RaffaeleNutricato START MODIFICATION SECTION 1 // void updateslcimageML(const char *file, const char *iden); // //____RaffaeleNutricato END MODIFICATION SECTION 1 // ______ Read matrix from file (all FORMATS) ______ //void readdata(matrix &Result,window win); //void readdata(matrix &Result,window win) const; matrix readdata(window win) const; // ______ Convert line number to azimuth time (1 is first line) ______ inline real8 line2ta(const real8 line) const {return t_azi1+(line-1.0)/prf;} // ______ Convert pixel number to range time (1 is first pixel) ______ inline real8 pix2tr(const real8 pixel) const {return t_range1+(pixel-1.0)/rsr2x;} // ______ Convert pixel number to range (1 is first pixel) ______ inline real8 pix2range(const real8 pixel) const {return SOL*pix2tr(pixel);} // ______ Convert azimuth time to line number (1 is first line) ______ inline real8 ta2line(const real8 azitime) const {return 1.0+prf*(azitime-t_azi1);} // ______ Convert range time to pixel number (1 is first pixel) ______ inline real8 tr2pix(const real8 rangetime) const {return 1.0+rsr2x*(rangetime-t_range1);} // ______ Convert range pixel to fDC (1 is first pixel, can be ovs) ______ // Bert Kampes, 03-Mar-2005 inline real8 pix2fdc(const real8 pixel) const {const real8 tau=(pixel-1.0)/(rsr2x/2.0);// two-way time return f_DC_a0+f_DC_a1*tau+f_DC_a2*sqr(tau);} }; // END class slcimage #endif // SLCIMAGE_H Doris-5.0.3Beta/doris_core/tmp_strptime.cc000077500000000000000000000703131312547014700205740ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ #ifdef __NO_STRPTIME /* The function "strptime" was unknown on my linux system. I downloaded the source, made small changes in order to compile it with g++, and include it with the Doris software. I did not perform a good check. DO NOT USE THIS, unless you cannot compile the doris software otherwise. in that case, define __NO_STRPTIME, in the makefile. That will use this code. Bert Kampes, November 2000. */ /* time/strptime.c compile: g++ strptime.cc teststrptime.c FUNCTIONS This source file includes following functions. localtime_r match_char match_string match_string get_number get_alt_number get_alt_number recursive strncasecmp __isleap day_of_the_week day_of_the_year strptime_internal strptime */ /* Convert a string representation of time to a time value. Copyright (C) 1996, 1997, 1998, 1999 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper , 1996. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The GNU C Library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with the GNU C Library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* XXX This version of the implementation is not really complete. Some of the fields cannot add information alone. But if seeing some of them in the same format (such as year, week and weekday) this is enough information for determining the date. */ #ifdef HAVE_CONFIG_H # include #endif //#include // BK 03-Nov-2002: changed include files to cctype etc. not ctype.h #include // commented this out, BK, seems not required and fails under cygwin. // #include #include #include #include #ifdef _LIBC //# include "../locale/localeinfo.h" # include #endif #ifndef __P # if defined (__GNUC__) || (defined (__STDC__) && __STDC__) # define __P(args) args # else # define __P(args) () # endif /* GCC. */ #endif /* Not __P. */ #if ! HAVE_LOCALTIME_R && ! defined localtime_r # ifdef _LIBC # define localtime_r __localtime_r # else /* Approximate localtime_r as best we can in its absence. */ # define localtime_r my_localtime_r static struct tm * localtime_r __P ((const time_t *t, struct tm *tp)) { struct tm *l = localtime (t); if (! l) return 0; *tp = *l; return tp; } # endif /* ! _LIBC */ #endif /* ! HAVE_LOCALTIME_R && ! defined (localtime_r) */ #ifdef WIN32 // Jia defined this for windows. // Bert Kampes, 24-Aug-2005 #define strncasecmp _strnicmp #endif #define match_char(ch1, ch2) if (ch1 != ch2) return NULL #if defined __GNUC__ && __GNUC__ >= 2 # define match_string(cs1, s2) \ ({ size_t len = strlen (cs1); \ int result = strncasecmp ((cs1), (s2), len) == 0; \ if (result) (s2) += len; \ result; }) #else /* Oh come on. Get a reasonable compiler. */ # define match_string(cs1, s2) \ (strncasecmp ((cs1), (s2), strlen (cs1)) ? 0 : ((s2) += strlen (cs1), 1)) #endif /* We intentionally do not use isdigit() for testing because this will lead to problems with the wide character version. */ #define get_number(from, to) \ do { \ val = 0; \ while (*rp == ' ') \ ++rp; \ if (*rp < '0' || *rp > '9') \ return NULL; \ do { \ val *= 10; \ val += *rp++ - '0'; \ } while (val * 10 <= to && *rp >= '0' && *rp <= '9'); \ if (val < from || val > to) \ return NULL; \ } while (0) #ifdef _NL_CURRENT # define get_alt_number(from, to) \ do { \ if (*decided != raw) \ { \ const char *alts = _NL_CURRENT (LC_TIME, ALT_DIGITS); \ val = 0; \ while (*alts != '\0') \ { \ size_t len = strlen (alts); \ if (strncasecmp (alts, rp, len) == 0) \ break; \ alts = strchr (alts, '\0') + 1; \ ++val; \ } \ if (*alts == '\0') \ { \ if (*decided == loc && val != 0) \ return NULL; \ } \ else \ { \ *decided = loc; \ break; \ } \ } \ get_number (from, to); \ } while (0) #else # define get_alt_number(from, to) \ /* We don't have the alternate representation. */ \ get_number(from, to) #endif #define recursive(new_fmt) \ (*(new_fmt) != '\0' \ && (rp = strptime_internal (rp, (new_fmt), tm, decided)) != NULL) #ifdef _LIBC /* This is defined in locale/C-time.c in the GNU libc. */ extern const struct locale_data _nl_C_LC_TIME; extern const unsigned short int __mon_yday[2][13]; # define weekday_name (&_nl_C_LC_TIME.values[_NL_ITEM_INDEX (DAY_1)].string) # define ab_weekday_name \ (&_nl_C_LC_TIME.values[_NL_ITEM_INDEX (ABDAY_1)].string) # define month_name (&_nl_C_LC_TIME.values[_NL_ITEM_INDEX (MON_1)].string) # define ab_month_name (&_nl_C_LC_TIME.values[_NL_ITEM_INDEX (ABMON_1)].string) # define HERE_D_T_FMT (_nl_C_LC_TIME.values[_NL_ITEM_INDEX (D_T_FMT)].string) # define HERE_D_FMT (_nl_C_LC_TIME.values[_NL_ITEM_INDEX (D_FMT)].string) # define HERE_AM_STR (_nl_C_LC_TIME.values[_NL_ITEM_INDEX (AM_STR)].string) # define HERE_PM_STR (_nl_C_LC_TIME.values[_NL_ITEM_INDEX (PM_STR)].string) # define HERE_T_FMT_AMPM \ (_nl_C_LC_TIME.values[_NL_ITEM_INDEX (T_FMT_AMPM)].string) # define HERE_T_FMT (_nl_C_LC_TIME.values[_NL_ITEM_INDEX (T_FMT)].string) # define strncasecmp(s1, s2, n) __strncasecmp (s1, s2, n) #else static char const weekday_name[][10] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; static char const ab_weekday_name[][4] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static char const month_name[][10] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; static char const ab_month_name[][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; # define HERE_D_T_FMT "%a %b %e %H:%M:%S %Y" # define HERE_D_FMT "%m/%d/%y" # define HERE_AM_STR "AM" # define HERE_PM_STR "PM" # define HERE_T_FMT_AMPM "%I:%M:%S %p" # define HERE_T_FMT "%H:%M:%S" /* Bert Kampes... = */ /* const unsigned short int __mon_yday[1][13] = */ const unsigned short int __mon_yday[][13] = { /* Normal years. */ { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }, /* Leap years. */ { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 } }; #endif /* Status of lookup: do we use the locale data or the raw data? */ enum locale_status { notyet, loc, raw }; #ifndef __isleap /* Nonzero if YEAR is a leap year (every 4 years, except every 100th isn't, and every 400th is). */ # define __isleap(year) \ ((year) % 4 == 0 && ((year) % 100 != 0 || (year) % 400 == 0)) #endif /* Compute the day of the week. */ static void day_of_the_week (struct tm *tm) { /* We know that January 1st 1970 was a Thursday (= 4). Compute the the difference between this data in the one on TM and so determine the weekday. */ int corr_year = 1900 + tm->tm_year - (tm->tm_mon < 2); int wday = (-473 + (365 * (tm->tm_year - 70)) + (corr_year / 4) - ((corr_year / 4) / 25) + ((corr_year / 4) % 25 < 0) + (((corr_year / 4) / 25) / 4) + __mon_yday[0][tm->tm_mon] + tm->tm_mday - 1); tm->tm_wday = wday % 7; } /* Compute the day of the year. */ static void day_of_the_year (struct tm *tm) { tm->tm_yday = (__mon_yday[__isleap (1900 + tm->tm_year)][tm->tm_mon] + (tm->tm_mday - 1)); } static char * #ifdef _LIBC internal_function #endif strptime_internal __P (( const char *buf, const char *format, struct tm *tm, enum locale_status *decided)) { const char *rp; const char *fmt; int cnt; size_t val; int have_I, is_pm; int century, want_century; int have_wday, want_xday; int have_yday; rp = buf; fmt = format; have_I = is_pm = 0; century = -1; want_century = 0; have_wday = want_xday = have_yday = 0; while (*fmt != '\0') { /* A white space in the format string matches 0 more or white space in the input string. */ if (isspace (*fmt)) { while (isspace (*rp)) ++rp; ++fmt; continue; } /* Any character but `%' must be matched by the same character in the iput string. */ if (*fmt != '%') { match_char (*fmt++, *rp++); continue; } ++fmt; #ifndef _NL_CURRENT /* We need this for handling the `E' modifier. */ start_over: #endif switch (*fmt++) { case '%': /* Match the `%' character itself. */ match_char ('%', *rp++); break; case 'a': case 'A': /* Match day of week. */ for (cnt = 0; cnt < 7; ++cnt) { #ifdef _NL_CURRENT if (*decided !=raw) { if (match_string (_NL_CURRENT (LC_TIME, DAY_1 + cnt), rp)) { if (*decided == notyet && strcmp (_NL_CURRENT (LC_TIME, DAY_1 + cnt), weekday_name[cnt])) *decided = loc; break; } if (match_string (_NL_CURRENT (LC_TIME, ABDAY_1 + cnt), rp)) { if (*decided == notyet && strcmp (_NL_CURRENT (LC_TIME, ABDAY_1 + cnt), ab_weekday_name[cnt])) *decided = loc; break; } } #endif if (*decided != loc && (match_string (weekday_name[cnt], rp) || match_string (ab_weekday_name[cnt], rp))) { *decided = raw; break; } } if (cnt == 7) /* Does notyet match a weekday name. */ return NULL; tm->tm_wday = cnt; have_wday = 1; break; case 'b': case 'B': case 'h': /* Match month name. */ for (cnt = 0; cnt < 12; ++cnt) { #ifdef _NL_CURRENT if (*decided !=raw) { if (match_string (_NL_CURRENT (LC_TIME, MON_1 + cnt), rp)) { if (*decided == notyet && strcmp (_NL_CURRENT (LC_TIME, MON_1 + cnt), month_name[cnt])) *decided = loc; break; } if (match_string (_NL_CURRENT (LC_TIME, ABMON_1 + cnt), rp)) { if (*decided == notyet && strcmp (_NL_CURRENT (LC_TIME, ABMON_1 + cnt), ab_month_name[cnt])) *decided = loc; break; } } #endif if (match_string (month_name[cnt], rp) || match_string (ab_month_name[cnt], rp)) { *decided = raw; break; } } if (cnt == 12) /* Does notyet match a month name. */ return NULL; tm->tm_mon = cnt; want_xday = 1; break; case 'c': /* Match locale's date and time format. */ #ifdef _NL_CURRENT if (*decided != raw) { if (!recursive (_NL_CURRENT (LC_TIME, D_T_FMT))) { if (*decided == loc) return NULL; } else { if (*decided == notyet && strcmp (_NL_CURRENT (LC_TIME, D_T_FMT), HERE_D_T_FMT)) *decided = loc; want_xday = 1; break; } *decided = raw; } #endif if (!recursive (HERE_D_T_FMT)) return NULL; want_xday = 1; break; case 'C': /* Match century number. */ get_number (0, 99); century = val; want_xday = 1; break; case 'd': case 'e': /* Match day of month. */ get_number (1, 31); tm->tm_mday = val; want_xday = 1; break; case 'F': if (!recursive ("%Y-%m-%d")) return NULL; want_xday = 1; break; case 'x': #ifdef _NL_CURRENT if (*decided != raw) { if (!recursive (_NL_CURRENT (LC_TIME, D_FMT))) { if (*decided == loc) return NULL; } else { if (decided == notyet && strcmp (_NL_CURRENT (LC_TIME, D_FMT), HERE_D_FMT)) *decided = loc; want_xday = 1; break; } *decided = raw; } #endif /* Fall through. */ case 'D': /* Match standard day format. */ if (!recursive (HERE_D_FMT)) return NULL; want_xday = 1; break; case 'k': case 'H': /* Match hour in 24-hour clock. */ get_number (0, 23); tm->tm_hour = val; have_I = 0; break; case 'I': /* Match hour in 12-hour clock. */ get_number (1, 12); tm->tm_hour = val % 12; have_I = 1; break; case 'j': /* Match day number of year. */ get_number (1, 366); tm->tm_yday = val - 1; have_yday = 1; break; case 'm': /* Match number of month. */ get_number (1, 12); tm->tm_mon = val - 1; want_xday = 1; break; case 'M': /* Match minute. */ get_number (0, 59); tm->tm_min = val; break; case 'n': case 't': /* Match any white space. */ while (isspace (*rp)) ++rp; break; case 'p': /* Match locale's equivalent of AM/PM. */ #ifdef _NL_CURRENT if (*decided != raw) { if (match_string (_NL_CURRENT (LC_TIME, AM_STR), rp)) { if (strcmp (_NL_CURRENT (LC_TIME, AM_STR), HERE_AM_STR)) *decided = loc; break; } if (match_string (_NL_CURRENT (LC_TIME, PM_STR), rp)) { if (strcmp (_NL_CURRENT (LC_TIME, PM_STR), HERE_PM_STR)) *decided = loc; is_pm = 1; break; } *decided = raw; } #endif if (!match_string (HERE_AM_STR, rp)) if (match_string (HERE_PM_STR, rp)) is_pm = 1; else return NULL; break; case 'r': #ifdef _NL_CURRENT if (*decided != raw) { if (!recursive (_NL_CURRENT (LC_TIME, T_FMT_AMPM))) { if (*decided == loc) return NULL; } else { if (*decided == notyet && strcmp (_NL_CURRENT (LC_TIME, T_FMT_AMPM), HERE_T_FMT_AMPM)) *decided = loc; break; } *decided = raw; } #endif if (!recursive (HERE_T_FMT_AMPM)) return NULL; break; case 'R': if (!recursive ("%H:%M")) return NULL; break; case 's': { /* The number of seconds may be very high so we cannot use the `get_number' macro. Instead read the number character for character and construct the result while doing this. */ time_t secs = 0; if (*rp < '0' || *rp > '9') /* We need at least one digit. */ return NULL; do { secs *= 10; secs += *rp++ - '0'; } while (*rp >= '0' && *rp <= '9'); if (localtime_r (&secs, tm) == NULL) /* Error in function. */ return NULL; } break; case 'S': get_number (0, 61); tm->tm_sec = val; break; case 'X': #ifdef _NL_CURRENT if (*decided != raw) { if (!recursive (_NL_CURRENT (LC_TIME, T_FMT))) { if (*decided == loc) return NULL; } else { if (strcmp (_NL_CURRENT (LC_TIME, T_FMT), HERE_T_FMT)) *decided = loc; break; } *decided = raw; } #endif /* Fall through. */ case 'T': if (!recursive (HERE_T_FMT)) return NULL; break; case 'u': get_number (1, 7); tm->tm_wday = val % 7; have_wday = 1; break; case 'g': get_number (0, 99); /* XXX This cannot determine any field in TM. */ break; case 'G': if (*rp < '0' || *rp > '9') return NULL; /* XXX Ignore the number since we would need some more information to compute a real date. */ do ++rp; while (*rp >= '0' && *rp <= '9'); break; case 'U': case 'V': case 'W': get_number (0, 53); /* XXX This cannot determine any field in TM without some information. */ break; case 'w': /* Match number of weekday. */ get_number (0, 6); tm->tm_wday = val; have_wday = 1; break; case 'y': /* Match year within century. */ get_number (0, 99); /* The "Year 2000: The Millennium Rollover" paper suggests that values in the range 69-99 refer to the twentieth century. */ tm->tm_year = val >= 69 ? val : val + 100; /* Indicate that we want to use the century, if specified. */ want_century = 1; want_xday = 1; break; case 'Y': /* Match year including century number. */ get_number (0, 9999); tm->tm_year = val - 1900; want_century = 0; want_xday = 1; break; case 'Z': /* XXX How to handle this? */ break; case 'E': #ifdef _NL_CURRENT switch (*fmt++) { case 'c': /* Match locale's alternate date and time format. */ if (*decided != raw) { const char *fmt = _NL_CURRENT (LC_TIME, ERA_D_T_FMT); if (*fmt == '\0') fmt = _NL_CURRENT (LC_TIME, D_T_FMT); if (!recursive (fmt)) { if (*decided == loc) return NULL; } else { if (strcmp (fmt, HERE_D_T_FMT)) *decided = loc; want_xday = 1; break; } *decided = raw; } /* The C locale has no era information, so use the normal representation. */ if (!recursive (HERE_D_T_FMT)) return NULL; want_xday = 1; break; case 'C': case 'y': case 'Y': /* Match name of base year in locale's alternate representation. */ /* XXX This is currently not implemented. It should use the value _NL_CURRENT (LC_TIME, ERA). */ break; case 'x': if (*decided != raw) { const char *fmt = _NL_CURRENT (LC_TIME, ERA_D_FMT); if (*fmt == '\0') fmt = _NL_CURRENT (LC_TIME, D_FMT); if (!recursive (fmt)) { if (*decided == loc) return NULL; } else { if (strcmp (fmt, HERE_D_FMT)) *decided = loc; break; } *decided = raw; } if (!recursive (HERE_D_FMT)) return NULL; break; case 'X': if (*decided != raw) { const char *fmt = _NL_CURRENT (LC_TIME, ERA_T_FMT); if (*fmt == '\0') fmt = _NL_CURRENT (LC_TIME, T_FMT); if (!recursive (fmt)) { if (*decided == loc) return NULL; } else { if (strcmp (fmt, HERE_T_FMT)) *decided = loc; break; } *decided = raw; } if (!recursive (HERE_T_FMT)) return NULL; break; default: return NULL; } break; #else /* We have no information about the era format. Just use the normal format. */ if (*fmt != 'c' && *fmt != 'C' && *fmt != 'y' && *fmt != 'Y' && *fmt != 'x' && *fmt != 'X') /* This is an illegal format. */ return NULL; goto start_over; #endif case 'O': switch (*fmt++) { case 'd': case 'e': /* Match day of month using alternate numeric symbols. */ get_alt_number (1, 31); tm->tm_mday = val; want_xday = 1; break; case 'H': /* Match hour in 24-hour clock using alternate numeric symbols. */ get_alt_number (0, 23); tm->tm_hour = val; have_I = 0; break; case 'I': /* Match hour in 12-hour clock using alternate numeric symbols. */ get_alt_number (1, 12); tm->tm_hour = val - 1; have_I = 1; break; case 'm': /* Match month using alternate numeric symbols. */ get_alt_number (1, 12); tm->tm_mon = val - 1; want_xday = 1; break; case 'M': /* Match minutes using alternate numeric symbols. */ get_alt_number (0, 59); tm->tm_min = val; break; case 'S': /* Match seconds using alternate numeric symbols. */ get_alt_number (0, 61); tm->tm_sec = val; break; case 'U': case 'V': case 'W': get_alt_number (0, 53); /* XXX This cannot determine any field in TM without further information. */ break; case 'w': /* Match number of weekday using alternate numeric symbols. */ get_alt_number (0, 6); tm->tm_wday = val; have_wday = 1; break; case 'y': /* Match year within century using alternate numeric symbols. */ get_alt_number (0, 99); tm->tm_year = val >= 69 ? val : val + 100; want_xday = 1; break; default: return NULL; } break; default: return NULL; } } if (have_I && is_pm) tm->tm_hour += 12; if (want_century && century != -1) tm->tm_year = tm->tm_year % 100 + (century - 19) * 100; if (want_xday && !have_wday) day_of_the_week (tm); if (want_xday && !have_yday) day_of_the_year (tm); return (char *) rp; } char * strptime (const char *buf, const char *format, struct tm *tm) { enum locale_status decided; #ifdef _NL_CURRENT decided = notyet; #else decided = raw; #endif return strptime_internal (buf, format, tm, &decided); } #endif // __NO_STRPTIME Doris-5.0.3Beta/doris_core/unwrap.cc000077500000000000000000001054671312547014700173720ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/unwrap.cc,v $ * * $Revision: 3.18 $ * * $Date: 2005/10/06 11:09:20 $ * * $Author: kampes $ * * * * implementation of unwrapping routines * * -unwrapramon (stanford) * * -snaphu_unwrap (Curtis Cheng, SU) * ****************************************************************/ #include "matrixbk.hh" #include "constants.hh" // global constants #include "productinfo.hh" // my 'products' class #include "exceptions.hh" // my exceptions class #include "unwrap.hh" // header file #include "ioroutines.hh" // error messages #include "coregistration.hh" // distributepoints #include "readinput.hh" // "specified" function #include "orbitbk.hh" // getxyz etc. #include "utilities.hh" // getBhBv etc. #include // isspace #include // some compilers, remove function // #include // rint function /**************************************************************** * unwraptreeframon * * * * unwrap with code howard from ramon: * * this will not work if executable treef_ramon is not in * * path. * * Place seeds over IFG, and start unwrapping there. Compose * * a map of totally unwrapped regions. With matlab program * * we can check these regions on consistency and adapt them. * * Input: * * - * * Output: * * - * * * * Bert Kampes, 07-Jun-1999 * ****************************************************************/ void unwraptreeframon( const input_gen &generalinput, const input_unwrap &unwrapinput, const productinfo &interferogram) { TRACE_FUNCTION("unwraptreeframon (BK 07-Jun-1999)") // char prog[ONE27]="/home/hanssen/projects/cerroprieto/matlab/manuw/treef_ramon "; char prog[ONE27] = "treef_ramon "; char fileouttreeframon[ONE27] = "ramon.uw"; char dummyline[4*ONE27]; const int32 dL = unwrapinput.deltaLseed; const int32 dP = unwrapinput.deltaPseed; // const int32 dL = 100; // const int32 dP = dL; // char unwrapinput.foregions[ONE27]="REGIONS"; // char fileoutuint[ONE27]="UWPHASE"; // ______ Number of lines/pixels on file (complex interferogram) ______ const int32 fileliness = (interferogram.win.linehi - interferogram.win.linelo + 1) / interferogram.multilookL; const int32 filepixels = (interferogram.win.pixhi - interferogram.win.pixlo + 1) / interferogram.multilookP; // ______ Allocate matrices ______ // BAND INTERLEAVED !! output of treef_ramon.f (hgt format...) // matrix AMP_PHA(fileliness,filepixels); // read from file ramon.uw matrix AMP(fileliness,filepixels); // read from file ramon.uw matrix PHA(fileliness,filepixels); // read from file ramon.uw matrix REGIONS(fileliness,filepixels); // initialize to 0 DEBUG.print("only for now like this, maak matrix allocation with setdata??"); // matrix PHASE(fileliness,filepixels,NaN); // initialize to NaN matrix PHASE(fileliness,filepixels); PHASE.setdata(NaN); // ______ Make commandstring ______ char basecmdstring[3*ONE27]; ostrstream basecmdstr(basecmdstring,3*ONE27); // to convert int to char basecmdstr.seekp(0); basecmdstr << prog << interferogram.file << " " // << filepixels << " " << fileliness << " 1 0 "; // FIRSTLINE = 0 ! (see source) << filepixels << " " << fileliness << " 0 0 "; // no ends!! const int32 posbasecmdstr = basecmdstr.tellp(); // ______ Windows for band interleaved file loading, cmp readhgt ______ const uint dummy = 999999; // large to force error if not ok window winamp(1, fileliness, 1, filepixels); window winpha(1, fileliness, filepixels+1, 2*filepixels); window offsetbuffer(1,dummy,1,dummy); // dummy not used in readfile, no offset register int32 regionnumber = 0; register int32 line, pixel; register int32 npoints = 0; uint seedL,seedP; matrix SEEDS; if (isspace(unwrapinput.seedfile[0])) // no filename specified { // ______ First determine size of matrix the easy way (just counting) ______ for (seedL=4; seedL<=fileliness-4; seedL=seedL+dL) { for (seedP=4; seedP<=filepixels-4; seedP=seedP+dP) { npoints++; } } // ______ Then fill the matrix ______ SEEDS.resize(npoints,2); register int32 cnt = 0; for (seedL=4; seedL<=fileliness-4; seedL=seedL+dL) { for (seedP=4; seedP<=filepixels-4; seedP=seedP+dP) { SEEDS(cnt,0) = seedL; SEEDS(cnt,1) = seedP; cnt++; } } } else // read in file + check { INFO.print("Using seedfile for unwrapping seeds."); if (!existed(unwrapinput.seedfile)) { PRINT_ERROR("UW_SEED seedfile: does not exist.") throw(input_error); } npoints = filelines(unwrapinput.seedfile); // number of enters INFO << "Number of points in seedfile (should be an enter after last one): " << npoints; INFO.print(); ifstream ifile(unwrapinput.seedfile, ios::in); // not binary SEEDS.resize(npoints,2); #ifdef __DEBUG bk_assert(ifile,unwrapinput.seedfile,__FILE__,__LINE__); #endif // ______ Read in data ______ for (line=0; line> seedL >> seedP; SEEDS(line,0) = seedL; SEEDS(line,1) = seedP; ifile.getline(dummyline,4*ONE27,'\n'); } // ______ Check input (wrapped interferogram starts at (1,1)) ______ if (max(SEEDS.getcolumn(0)) > fileliness) { PRINT_ERROR("max line in seedfile exceeds number of lines on file (complex interferogram).") throw(input_error); } if (max(SEEDS.getcolumn(1)) > filepixels) { PRINT_ERROR("max pixel in seedfile exceeds number of pixels on file (complex interferogram).") throw(input_error); } } // seedfile specified for (npoints=0; npoints= SEVENTY) break; // break inner loop for (pixel=0; pixel 1000 #pragma once #endif // _MSC_VER > 1000 #include "constants.hh" // typedefs #include "readinput.hh" // input structs #include "orbitbk.hh" // my orbit class #include "slcimage.hh" // my slc image class #include "productinfo.hh" // my 'products' class // ______ Use stanford software through unix calls _____ void unwraptreeframon( const input_gen &generalinput, const input_unwrap &unwrapinput, const productinfo &interferogram); // ______ Use snaphu software through unix calls _____ void snaphu_unwrap( const input_gen &generalinput, const input_unwrap &unwrapinput, const productinfo &interferogram, const slcimage &master, const slcimage &slave, orbit &masterorbit, orbit &slaveorbit, const input_ell &ellips); #endif // UNWRAP_H Doris-5.0.3Beta/doris_core/utilities.cc000077500000000000000000002235341312547014700200650ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/utilities.cc,v $ * * $Revision: 3.17 $ * * $Date: 2005/10/06 11:09:20 $ * * $Author: kampes $ * * * * implementation of utility routines. * * - math utils * * - solving small linear system * * - polynomial evaluation * * - getorb call * * - tiepoint computation * ****************************************************************/ #include "matrixbk.hh" // my matrix class #include "slcimage.hh" // my slc image class #include "constants.hh" // global constants #include "utilities.hh" // header file #include "ioroutines.hh" // error messages #include "exceptions.hh" // my exceptions class #include // for memory stream #include // setw #include // for strcat etc. #include // system #include // sqrt etc. #include // some compilers, remove function #include // time functions char *strptime(const char *s, const char *format, struct tm *tm); #ifndef NO_FASTTRIG // ___ // ___ globals for lookuptable fast_sin() and fast_cos() // ___ time for 10000000 std::sin(x): 2.73 sec. // ___ time for LUT of lengths 128:65536 = 0.12sec // ___ max_error is 1 bin (not 0.5 since we do not check for sign), // ___ i.e., max slope =1--> maxerror=2pi/65536=0.0001 const uint32 LUT_LENGHT = 65536; // memory req: 65536*sizeof(Type=real8)= 524288 Bytes. check fast_sin definition before changing this value. const uint16 LUT_ATAN_MAX = 128; const real8 LUT_DX_SIN = real8(LUT_LENGHT/(2.0*PI)); // idx=int(x*LUT_STEP) const real8 LUT_DX_ATAN = real8(LUT_LENGHT)/real8(2*LUT_ATAN_MAX); // idx=int(x*DX+0.5) real8 LUT_SIN[LUT_LENGHT]; // lookup table for sin [0:2PI) real8 LUT_ATAN[LUT_LENGHT]; // lookup table for atan [-ATAN_MAX:dx:ATAN_MAX-dx] #endif /**************************************************************** * getorb * * * * Calls getorb program to generate precise orbit file * * scratchorbit. * * Datapoints with INTERVAL seconds in between. * * time1-BEFOREFIRST to timeN+BEFOREFIRST * * time1 in format as: 15-AUG-1996 09:49:16.913 * * * * Bert Kampes, 11-Dec-1998 * ****************************************************************/ void getorb( const slcimage &image, const input_pr_orbits &inputorb, int16 ID) { TRACE_FUNCTION("getorb (BK 11-Dec-1998)") const int32 INTERVAL = inputorb.timeinterval; const int32 BEFOREFIRST = inputorb.timebefore; char orbdir[EIGHTY]; char dummyline[2*ONE27]; char startt[13]; char endt[13]; char *pstartt = startt; char *pendt = endt; if (ID==MASTERID) strcpy(orbdir,inputorb.m_orbdir); else if (ID==SLAVEID) strcpy(orbdir,inputorb.s_orbdir); else { PRINT_ERROR("panic, impossible."); throw(unhandled_case_error); } // ______ Convert times to struct tm ______ struct tm tijdstart; strptime(image.utc1,"%d-%b-%Y %T",&tijdstart); DEBUG << "value of image.utc1: " << image.utc1; DEBUG.print(); // ______ Adjust interval ______ int32 t1seconds = tijdstart.tm_sec + 60*tijdstart.tm_min + 3600*tijdstart.tm_hour; int32 t2seconds = t1seconds + BEFOREFIRST + int32(0.5+(image.originalwindow.linehi-image.originalwindow.linelo+1)/image.prf); t1seconds -= BEFOREFIRST; // adjust; if (t1seconds < 0) // check 0:00'00" utc { WARNING.print("getorb: couldn't adjust time lower bound, using old value."); t1seconds += BEFOREFIRST; } tijdstart.tm_hour = t1seconds / 3600; tijdstart.tm_min = (t1seconds-3600*tijdstart.tm_hour) / 60; tijdstart.tm_sec = (t1seconds-3600*tijdstart.tm_hour) % 60; DEBUG << "start time: tm struct: hour=" << tijdstart.tm_hour << "; min=" << tijdstart.tm_min << "; sec=" << tijdstart.tm_sec; DEBUG.print(); if (t2seconds / 3600 > 23) // hours + 1 day { WARNING.print("getorb: couldn't adjust time upper bound, using old value."); t2seconds -= BEFOREFIRST; } struct tm tijdend = tijdstart; // copy year, month, day tijdend.tm_hour = t2seconds / 3600; tijdend.tm_min = (t2seconds-3600*tijdend.tm_hour) / 60; tijdend.tm_sec = (t2seconds-3600*tijdend.tm_hour) % 60; DEBUG << "end time: tm struct: hour=" << tijdend.tm_hour << "; min=" << tijdend.tm_min << "; sec=" << tijdend.tm_sec; DEBUG.print(); // ______ Check timedifference ______ //if (tijdend.tm_min - tijdstart.tm_min != 0 && // tijdend.tm_min - tijdstart.tm_min != 1 ) if (tijdend.tm_min-tijdstart.tm_min > 10 || tijdend.tm_min-tijdstart.tm_min < -50) WARNING.print("getorb: > 10 minutes of orbit ephemerides?"); // ______convert time to strings[12] YYMMDDHHMMSS(.S)______ strftime(pstartt,13,"%y%m%d%H%M%S",&tijdstart); // including \0 strftime(pendt,13,"%y%m%d%H%M%S",&tijdend); // including \0 // ====== Get precise orbits ====== // ______ Call getorb (unix) ______ // ______Make string starttime YYMMDDHHMMSS(.S)______ char strgetorb[2*ONE27]; // unix system call ostrstream omemgetorb(strgetorb,2*ONE27); // combine types in string omemgetorb.seekp(0); omemgetorb << "getorb " << startt << "," << endt << "," << INTERVAL << " " << orbdir << ">scratchorbit" << ends; // BK 4 july 2000: assume ODR files are already untarred //omemgetorb << "getorb " << startt << "," << endt << "," << INTERVAL << " "; //if (removeuntarred == false) // .ODR file is in archive directory // omemgetorb << orbdir << ">scratchorbit" << ends; //else // file is untarred to current dir // omemgetorb << ". > scratchorbit" << ends; // 1. The # of bits *captured* from a return code varies. // Here are some examples: // some notes on status code: // shell scripts - capture 8-bits // tcl/expect scripts - capture 8-bits // perl scripts - capture 16-bits // c binaries - capture 16-bits // see http://www.etpenguin.com/cgi-bin/index2file.cgi?/pub/Reference/DOC_exit-codes.txt int32 status = 3*NaN; // [MA] keep int32 due to 65280 value. for (register int32 i=0;i<3;i++) // try a few times. { DEBUG.print(strgetorb); status=(system(strgetorb)); // run getorb / return positive values -1 --> 65280 DEBUG << "status of getorb: " << status; DEBUG.print(); if (status == 0) { // ______Check really ok______ DEBUG.print("Checking getorb result for errors."); //ifstream scratchorbit("scratchorbit",ios::in | ios::nocreate); // by getorb ifstream scratchorbit("scratchorbit",ios::in); // by getorb bk_assert(scratchorbit,"getorb: scratchorbit",__FILE__,__LINE__); int32 err=0; real8 dsec; bool getorbok=true; while(scratchorbit) { scratchorbit >> dsec >> err; DEBUG << "time: " << dsec << " err: " << err; DEBUG.print(); if (err) { getorbok=false; WARNING.print("seems a problem with getorb, can you repair?"); getanswer(); break; // file? } scratchorbit.getline(dummyline,2*ONE27,'\n'); } scratchorbit.close(); if (getorbok) { PROGRESS.print("getorb: program finished ok."); break; // break try few times } } else if (status == -1 || status==-256 || status == 65280 ) // [MA] [-1] --> 65280 { WARNING.print(strgetorb); WARNING.print("getorb: exit(-1): time within ODR, but outside precise part."); break; } else if (status == 1 || status==256) { WARNING.print(strgetorb); WARNING.print("getorb: exit(1): error opening ODR file.\n\tPerhaps file is tarred?"); getanswer(); } else if (status == 2 || status==512) { WARNING.print(strgetorb); PRINT_ERROR("code 905: getorb: exit(2): no ODR for requested epoch.") throw(some_error); } else if (status == 3 || status==768) { WARNING.print(strgetorb); PRINT_ERROR("code 905: getorb: exit(3): too many records.") throw(some_error); } else { WARNING.print(strgetorb); ERROR << "code 905: utilities.c: getorb: unknown exit code: " << status; PRINT_ERROR(ERROR.get_str()) throw(some_error); } } // ______Tidy up______ } // END getorb /**************************************************************** * convertgetorbout * * * * converts output of getorb (in "scratchorbit") to format: * * secsofday X Y Z * * input: * * - scratchorbit * * output: * * - scratchdatapoints, this file * * might already exist due to readleader * * - file is removed * * * * Bert Kampes, 11-Dec-1998 * ****************************************************************/ void convertgetorbout( int16 FILEID, const char* file) // default=scratchorbit { TRACE_FUNCTION("convertgetorbout (BK 11-Dec-1998)") if (FILEID != MASTERID && FILEID!=SLAVEID) { PRINT_ERROR("fileid not ok.") throw(some_error); } char dummyline[2*ONE27]; // ______ Open files ______ ifstream infile(file, ios::in); bk_assert(infile,file,__FILE__,__LINE__); ofstream outfile("scratchdatapoints", ios::out | ios::trunc); // do replace bk_assert(outfile,"convertgetorbout: scratchdatapoints",__FILE__,__LINE__); // ______Read line: sec85 err fie lambda h x y z______ int32 err; real8 sec; real8 fie; real8 lam; real8 hei; char x[25]; // to be sure no round off char y[25]; // to be sure no round off char z[25]; // to be sure no round off // ______ Get number of points ______ int32 numdatapoints = -1; int32 numerr = 0; DEBUG.print("Counting number of lines in tmp file with orbit; checking err parameter"); while(infile) { infile >> sec >> err >> fie >> lam >> hei >> x >> y >> z; infile.getline(dummyline,2*ONE27,'\n'); DEBUG << "scratchfile: sec=" << sec << " err=" << err << " x=" << x << " y=" << y << " z=" << z; DEBUG.print(); if (err!=0) numerr++; if (err==0) numdatapoints++; } infile.clear();// g++v3.2 has a problem if you don't to read it again //infile.close();// seems problem with g++v3.2 if stream is closed and opened? INFO << "Number of orbit ephemerides found: " << numdatapoints+1 << ends; INFO.print(); INFO << "Number of erroneous orbit ephemerides found: " << numerr << ends; if (numerr==0) INFO.print(); if (numerr>0) WARNING.print(INFO.get_str()); if ( numdatapoints == -1 ) // [MA] -1 --> no good pts] { //WARNING.print(INFO.get_str()); infile.close(); if (remove("scratchdatapoints")) // remove scratchdatapoints but keep scratchorbit WARNING.print("code 101: could not remove file."); ERROR << "No valid number of orbit ephemeris found! exiting..."; PRINT_ERROR(ERROR.get_str()) throw(some_error); } INFO.reset();// rewind // ___ Write results in parameter file via 2nd tmpfile ___ outfile << "\n\n*******************************************************************" << "\n*_Start_"; //<< "\n*_Start_precise_datapoints" if (FILEID==MASTERID) outfile << processcontrol[pr_m_porbits]; if (FILEID==SLAVEID) outfile << processcontrol[pr_s_porbits]; outfile << "\n*******************************************************************" << "\n\tt(s)\tX(m)\tY(m)\tZ(m)" << "\nNUMBER_OF_DATAPOINTS: \t\t\t" << numdatapoints << endl; // ______Set outfile in correct digits______ int32 secint; // integer part real8 secfrac; // fractional part outfile.setf(ios::fixed); outfile.setf(ios::showpoint); //infile.open(file); infile.seekg(0, ios::beg);// rewind file to read again DEBUG.print("Rewinding file and reading orbit ephemerides again"); for (register int32 i=0;i> sec >> err >> fie >> lam >> hei >> x >> y >> z; infile.getline(dummyline,2*ONE27,'\n'); // go to next line DEBUG << "scratchfile2: sec=" << sec << " err=" << err << " x=" << x << " y=" << y << " z=" << z; DEBUG.print(); // ______Convert time sec85 to sec of day______ secint = int32(sec)%86400; // 60*60*24 integer part secfrac = sec - int32(sec); // fractional part if (err!=0) { WARNING << "err == "<< err << " " << "err!=0: something went wrong in getorb? (skipping point)"; WARNING.print(); } if (err==0) outfile << secint+secfrac << "\t" << x << "\t" << y << "\t" << z << endl; } outfile << "\n*******************************************************************" //<< "\n* End_precise_datapoints:_NORMAL" << "\n* End_"; if (FILEID==MASTERID) outfile << processcontrol[pr_m_porbits]; if (FILEID==SLAVEID) outfile << processcontrol[pr_s_porbits]; outfile << "_NORMAL" << "\n*******************************************************************\n"; // ______Tidy up______ infile.close(); outfile.close(); if (remove(file)) // remove file WARNING.print("code 101: could not remove file."); } // END convertgetorbout /**************************************************************** * solve33 * * * * Solves setof 3 equations by straightforward (no pivotting) LU* * y=Ax (unknown x) * * * * input: * * - matrix righthandside 3x1 (y) * * - matrix partials 3x3 (A) * * * * output: * * - matrix result 3x1 unknown * * * * Bert Kampes, 22-Dec-1998 * ****************************************************************/ void solve33( matrix &RESULT, const matrix &rhs, const matrix &A) { TRACE_FUNCTION("solve33 (BK 22-Dec-1998)") #ifdef __DEBUG if (RESULT.lines() != 3 || RESULT.pixels() != 1) { PRINT_ERROR("solve33: input: size RES not 3x1.") throw(input_error); } if (A.lines() != 3 || A.pixels() != 3) { PRINT_ERROR("solve33: input: size of A not 33.") throw(input_error); } if (rhs.lines() != 3 || rhs.pixels() != 1) { PRINT_ERROR("solve33: input: size rhs not 3x1.") throw(input_error); } #endif // ______ real8 L10, L20, L21: used lower matrix elements // ______ real8 U11, U12, U22: used upper matrix elements // ______ real8 b0, b1, b2: used Ux=b const real8 L10 = A(1,0)/A(0,0); const real8 L20 = A(2,0)/A(0,0); const real8 U11 = A(1,1)-L10*A(0,1); const real8 L21 = (A(2,1)-(A(0,1)*L20))/U11; const real8 U12 = A(1,2)-L10*A(0,2); const real8 U22 = A(2,2)-L20*A(0,2)-L21*U12; // ______ Solution: forward substitution ______ const real8 b0 = rhs(0,0); const real8 b1 = rhs(1,0)-b0*L10; const real8 b2 = rhs(2,0)-b0*L20-b1*L21; // ______ Solution: backwards substitution ______ RESULT(2,0) = b2/U22; RESULT(1,0) = (b1-U12*RESULT(2,0))/U11; RESULT(0,0) = (b0-A(0,1)*RESULT(1,0)-A(0,2)*RESULT(2,0))/A(0,0); } // END solve33 /**************************************************************** * solve22 * * * * Solves setof 2 equations by straightforward substitution * * y=Ax (unknown x) * * * * input: * * - matrix righthandside 2x1 (y) * * - matrix partials 2x2 (A) * * output: * * - matrix result 2x1 unknown dx,dy,dz * * * * Future: LaTeX software doc. * * Future: this has been tested * * * * Bert Kampes, 22-Dec-1998 * ****************************************************************/ matrix solve22( const matrix &y, const matrix &A) { TRACE_FUNCTION("solve22 (BK 22-Dec-1998)") #ifdef __DEBUG // ______ Check input ______ if (A.lines() != 2 || A.pixels() != 2) { PRINT_ERROR("error...") throw(input_error); } if (y.lines() != 2 || y.pixels() != 1) { PRINT_ERROR("error...") throw(input_error); } #endif matrix Result(2,1); Result(1,0)= (y(0,0) - ((A(0,0)/A(1,0))*y(1,0))) / (A(0,1) - ((A(0,0)*A(1,1))/A(1,0))); Result(0,0)= (y(0,0) - A(0,1)*Result(1,0)) / A(0,0); return Result; } // END solve22 /**************************************************************** * nextpow2 * * * * Returns 32 for 31.3 etc. * * * * Bert Kampes, 03-Feb-1999 * * AFter bug report from Bruno who discover bug. b-1 instead * * of b. Did not * * have effect on Doris since this function was effectively not * * used. * #%// BK 16-Apr-2002 * ****************************************************************/ uint nextpow2( real8 w) { TRACE_FUNCTION("nextpow2 (BK 03-Feb-1999)") int32 b = 0; int32 *pnt = &b; real8 f = frexp(w,pnt); if (f==0.5) return uint(w); return (uint(pow(real8(2),b))); } // END nextpow2 /**************************************************************** * polyval * * * * evaluates polynomial at (x,y) * * input: * * - x,y: point * * - polynomial coefficients * * (a00 | 01 10 | 20 11 02 | 30 21 12 03 | ...) * * * * output: * * - real8 functional value at (x,y). * * * * Bert Kampes, 15-Mar-1999 * ****************************************************************/ real8 polyval( real8 x, real8 y, const matrix &coeff) { const int32 degreee = degree(coeff.size()); #ifdef __DEBUG TRACE_FUNCTION("polyval (BK 15-Mar-1999)") if (coeff.size() != coeff.lines()) { PRINT_ERROR("polyval: require standing data vector.") throw(input_error); } if (degreee<0 || degreee > 1000) { PRINT_ERROR("polyval: degreee < 0") throw(input_error); } #endif // ______Check default arguments______ // if (degreee==-1) // default applies // const int32 degreee = degree(coeff.size()); // ______Speed up______ // ______Evaluate polynomial______ real8 sum = coeff(0,0); if (degreee == 1) { sum += ( coeff(1,0) * x + coeff(2,0) * y ); } else if (degreee == 2) { sum += ( coeff(1,0) * x + coeff(2,0) * y + coeff(3,0) * sqr(x) + coeff(4,0) * x*y + coeff(5,0) * sqr(y) ); } else if (degreee == 3) { register real8 xx = sqr(x); register real8 yy = sqr(y); sum += ( coeff(1,0) * x + coeff(2,0) * y + coeff(3,0) * xx + coeff(4,0) * x*y + coeff(5,0) * yy + coeff(6,0) * xx*x + coeff(7,0) * xx*y + coeff(8,0) * x*yy + coeff(9,0) * yy*y ); } else if (degreee == 4) { register real8 xx = sqr(x); register real8 xxx = xx*x; register real8 yy = sqr(y); register real8 yyy = yy*y; sum += ( coeff(1,0) * x + coeff(2,0) * y + coeff(3,0) * xx + coeff(4,0) * x*y + coeff(5,0) * yy + coeff(6,0) * xxx + coeff(7,0) * xx*y + coeff(8,0) * x*yy + coeff(9,0) * yyy + coeff(10,0)* xx*xx + coeff(11,0)* xxx*y + coeff(12,0)* xx*yy + coeff(13,0)* x*yyy + coeff(14,0)* yy*yy ); } else if (degreee == 5) { register real8 xx = sqr(x); register real8 xxx = xx*x; register real8 xxxx = xxx*x; register real8 yy = sqr(y); register real8 yyy = yy*y; register real8 yyyy = yyy*y; sum += ( coeff(1,0) * x + coeff(2,0) * y + coeff(3,0) * xx + coeff(4,0) * x*y + coeff(5,0) * yy + coeff(6,0) * xxx + coeff(7,0) * xx*y + coeff(8,0) * x*yy + coeff(9,0) * yyy + coeff(10,0)* xxxx + coeff(11,0)* xxx*y + coeff(12,0)* xx*yy + coeff(13,0)* x*yyy + coeff(14,0)* yyyy + coeff(15,0)* xxxx*x + coeff(16,0)* xxxx*y + coeff(17,0)* xxx*yy + coeff(18,0)* xx*yyy + coeff(19,0)* x*yyyy + coeff(20,0)* yyyy*y ); } else if (degreee != 0) // degreee > 5 { sum = 0.0; register int32 coeffindex = 0; for (register int32 l=0; l<=degreee; l++) { for (register int32 k=0; k<=l ;k++) { sum += coeff(coeffindex,0) * pow(x,real8(l-k)) * pow(y,real8(k)); coeffindex++; } } } return sum; } // END polyval /**************************************************************** * polyval * * * * evaluates polynomial at (x,y) * * input: * * - x,y: point * * - polynomial coefficients * * (a00 | 01 10 | 20 11 02 | 30 21 12 03 | ...) * * * * output: * * - real8 functional value at (x,y). * * * * Bert Kampes, 15-Mar-1999 * ****************************************************************/ real8 polyval( real8 x, real8 y, const matrix &coeff, int32 degreee) { #ifdef __DEBUG TRACE_FUNCTION("polyval (BK 15-Mar-1999)") if (coeff.size() != coeff.lines()) { PRINT_ERROR("polyval: require standing data vector.") throw(input_error); } if (degreee<0 || degreee > 1000) { PRINT_ERROR("polyval: degreee < 0") throw(input_error); } #endif // ______Check default arguments______ // if (degreee==-1) // default applies // degreee = degree(coeff.size()); // ______Speed up______ // ______Evaluate polynomial______ real8 sum = coeff(0,0); if (degreee == 1) { sum += ( coeff(1,0) * x + coeff(2,0) * y ); } else if (degreee == 2) { sum += ( coeff(1,0) * x + coeff(2,0) * y + coeff(3,0) * sqr(x) + coeff(4,0) * x*y + coeff(5,0) * sqr(y) ); } else if (degreee == 3) { register real8 xx = sqr(x); register real8 yy = sqr(y); sum += ( coeff(1,0) * x + coeff(2,0) * y + coeff(3,0) * xx + coeff(4,0) * x*y + coeff(5,0) * yy + coeff(6,0) * xx*x + coeff(7,0) * xx*y + coeff(8,0) * x*yy + coeff(9,0) * yy*y ); } else if (degreee == 4) { register real8 xx = sqr(x); register real8 xxx = xx*x; register real8 yy = sqr(y); register real8 yyy = yy*y; sum += ( coeff(1,0) * x + coeff(2,0) * y + coeff(3,0) * xx + coeff(4,0) * x*y + coeff(5,0) * yy + coeff(6,0) * xxx + coeff(7,0) * xx*y + coeff(8,0) * x*yy + coeff(9,0) * yyy + coeff(10,0)* xx*xx + coeff(11,0)* xxx*y + coeff(12,0)* xx*yy + coeff(13,0)* x*yyy + coeff(14,0)* yy*yy ); } else if (degreee == 5) { register real8 xx = sqr(x); register real8 xxx = xx*x; register real8 xxxx = xxx*x; register real8 yy = sqr(y); register real8 yyy = yy*y; register real8 yyyy = yyy*y; sum += ( coeff(1,0) * x + coeff(2,0) * y + coeff(3,0) * xx + coeff(4,0) * x*y + coeff(5,0) * yy + coeff(6,0) * xxx + coeff(7,0) * xx*y + coeff(8,0) * x*yy + coeff(9,0) * yyy + coeff(10,0)* xxxx + coeff(11,0)* xxx*y + coeff(12,0)* xx*yy + coeff(13,0)* x*yyy + coeff(14,0)* yyyy + coeff(15,0)* xxxx*x + coeff(16,0)* xxxx*y + coeff(17,0)* xxx*yy + coeff(18,0)* xx*yyy + coeff(19,0)* x*yyyy + coeff(20,0)* yyyy*y ); } else if (degreee != 0) // degreee > 5 { sum = 0.0; register int32 coeffindex = 0; for (register int32 l=0; l<=degreee; l++) { for (register int32 k=0; k<=l ;k++) { sum += coeff(coeffindex,0) * pow(x,real8(l-k)) * pow(y,real8(k)); coeffindex++; } } } return sum; } // END polyval // MA explicit instantiation: w/o these two linesr, whole function needs to go to utilities.hh template matrix polyval( const matrix&, const matrix&, const matrix&, int32 ); template matrix polyval( const matrix&, const matrix&, const matrix&, int32 ); /**************************************************************** * polyval * * * * Evaluate 2d polynomial at regular grid. * * input: * * - x,y: (standing) data axis * * - polynomial coefficients * * (a00 | 01 10 | 20 11 02 | 30 21 12 03 | ...) * * * * output: * * ( - file ascii "TEST" with grid.) * * - matrix with evaluated polynomial * * * * note optimixed for more y than x * * Bert Kampes, 12-Mar-1999 * * Mahmut Arikan, 04-06-2009 use template <> * ****************************************************************/ template // Type real8 or real4 matrix polyval( const matrix &x, const matrix &y, const matrix &coeff, int32 degreee) // optional { TRACE_FUNCTION("polyval (BK 12-Mar-1999)") #ifdef __DEBUG if (x.size() != x.lines()) { PRINT_ERROR("polyval: require standing x vector.") throw(input_error); } if (y.size() != y.lines()) { PRINT_ERROR("polyval: require standing y vector.") throw(input_error); } if (coeff.size() != coeff.lines()) { PRINT_ERROR("polyval: require standing coeff. vector.") throw(input_error); } if (degreee<-1) { PRINT_ERROR("polyval: degreee < -1") throw(input_error); } if (x.size()>y.size()) DEBUG.print("x larger than y, while optimized for y larger x"); #endif // ______Check default arguments______ if (degreee==-1) // default applies degreee = degree(coeff.size()); // ______Evaluate polynomial______ matrix Result(x.size(),y.size()); register int32 i,j; register Type c00; register Type c10; register Type c01; register Type c20; register Type c11; register Type c02; register Type c30; register Type c21; register Type c12; register Type c03; register Type c40; register Type c31; register Type c22; register Type c13; register Type c04; register Type c50; register Type c41; register Type c32; register Type c23; register Type c14; register Type c05; switch (degreee) { case 0: // constant Result.setdata(Type(coeff(0,0))); break; case 1: c00 = coeff(0,0); c10 = coeff(1,0); c01 = coeff(2,0); for (j=0; j5) in loop ______ WARNING.print("polyval on grid for > degree 5 : this seems to be wrong ?? BK 9 feb.00 : Is it? just check results"); WARNING.print("polyval on grid for > degree 5 : this seems to be wrong ?? BK 9 feb.00 : Is it? just check results"); const int32 STARTDEGREE = 6; const int32 STARTCOEFF = Ncoeffs(STARTDEGREE-1); // 5-> 21 6->28 7->36 etc. for (j=0; j &) * * * * evaluates polynomial at (x) * * input: * * - x: point * * - polynomial coefficients in standing vector (a0,a1,a2,..). * * - degree of polynomial. * * * * output: * * - real8 functional value y = f(x). * * * * Bert Kampes, 03-Jun-1999 * ****************************************************************/ real8 polyval1d( real8 x, const matrix &coeff) { #ifdef __DEBUG TRACE_FUNCTION("polyval1d (BK 03-Jun-1999)") if (coeff.size() != coeff.lines()) { PRINT_ERROR("polyval: require standing data vector.") throw(input_error); } #endif real8 sum = 0.0; for (register int32 d=coeff.size()-1;d>=0;--d) { sum *= x; sum += coeff(d,0); } return sum; } // END polyval1d (real8, const matrix &) /**************************************************************** * polyval1d (real8, const matrix &, uint) * * * * evaluates derivative of polynomial at (x) * * input: * * - x: point * * - polynomial coefficients in standing vector (a0,a1,a2,..). * * - derivative of polynomial * * * * output: * * - real8 functional value y = f(x). * * * * Hermann Baehr, 17-Mar-2011 * ****************************************************************/ real8 polyval1d( real8 x, const matrix &coeff, uint deriv) { #ifdef __DEBUG TRACE_FUNCTION("polyval1d (HB 17-Mar-2011)") if (coeff.size() != coeff.lines()) { PRINT_ERROR("polyval: require standing data vector.") throw(input_error); } #endif real8 sum = 0.0; for (register int32 d=coeff.size()-1; d>=deriv ; d--) { int16 a = 1; for (register int32 p=d+1-deriv; p<=d; p++) a *= p; sum *= x; sum += a * coeff(d,0); } return sum; } // END polyval1d (real8, const matrix &, uint) /**************************************************************** * normalize * * * * rescale data[min,max] to interval [-2,2] * * * * input: * * - data * * - min, max * * output: * * - data matrix by reference * * * * Bert Kampes, 21-Jun-1999 * ****************************************************************/ void normalize( matrix &data, real8 min, real8 max ) { TRACE_FUNCTION("normalize (BK 21-Jun-1999)") // ______ zero mean, rescale ______ data -= real4(.5*(min+max)); // [.5a-.5b, -.5a+.5b] data /= real4(.25*(max-min)); // [-2 2] } // END normalize /**************************************************************** * normalize * * * * rescale data to interval [-1,1] * * data -> X(data-min)/(max-min) ; data+SS * * X=1--1==EE-SS; SS=-1, EE=1 * * * * input: * * - data * * - min, max * * output: * * - by reference * * * * Bert Kampes, 21-Jun-1999 * ****************************************************************/ void normalize( matrix &data, // real8 real8 min, real8 max ) { TRACE_FUNCTION("ROUTINE: normalize (BK 21-Jun-1999)") // ______ zero mean, rescale ______ data -= .5*(min+max); // [.5a-.5b, -.5a+.5b] data /= .25*(max-min); // [-2 2] } // END normalize /**************************************************************** * BBparBperp * * get Baseline, Bpar and Bperp based on 3 positions, * * not efficient! See documentation for definitions * * * #%// BK 22-Sep-2000 * ****************************************************************/ void BBparBperp(real8 &B, real8 &Bpar, real8 &Bperp, const cn Master, const cn Point, const cn Slave) { #ifdef __DEBUG TRACE_FUNCTION("BBparBperp (BK 22-Sep-2000)") #endif B = Master.dist(Slave); // baseline. abs. value const real8 range1 = Master.dist(Point); const real8 range2 = Slave.dist(Point); Bpar = range1-range2; // parallel baseline, sign ok const cn r1 = Master.min(Point); const cn r2 = Slave.min(Point); const real8 theta = Master.angle(r1); Bperp = sqr(B)-sqr(Bpar); if (Bperp < 0.0) Bperp=0.0; else Bperp = (theta > Master.angle(r2)) ? // perpendicular baseline, sign ok sqrt(Bperp) : -sqrt(Bperp); } // END BBparBperp /**************************************************************** * BBhBv * * get Baseline, Bh and Bv based on 3 positions, * * not efficient! See documentation for definitions * * cannot get sign of Bh w/o Point P (?) * * * #%// BK 19-Oct-2000 * ****************************************************************/ void BBhBv( real8 &B, real8 &Bh, real8 &Bv, const cn Master, const cn Slave) { TRACE_FUNCTION("BBhBv (BK 19-Oct-2000)") WARNING.print("sign Bh not computed..."); B = Master.dist(Slave);// baseline. abs. value const real8 rho1 = Master.norm(); const real8 rho2 = Slave.norm(); Bv = rho2-rho1; // Bv, sign ok Bh = sqr(B)-sqr(Bv); Bh = (Bh<0.0) ? 0.0 : sqrt(Bh); } // END BBhBv /**************************************************************** * Btemp * * returns temporal baseline (days) based on 2 strings with UTC * * utc as: "30-AUG-1995 09:49:20.453" * * "%d-%b-%Y %T" * * (Btemp>0) if (Tslave later than Tmaster) * #%// BK 19-Oct-2000 * ****************************************************************/ int32 Btemp( const char *utc_master, const char *utc_slave) { TRACE_FUNCTION("Btemp (BK 19-Oct-2000)") struct tm tm_ref; // reference time struct tm tm_master; struct tm tm_slave; char utc_ref[ONE27] = "01-JAN-1985 00:00:01.000"; strptime(utc_ref,"%d-%b-%Y %T",&tm_ref); strptime(utc_master,"%d-%b-%Y %T",&tm_master); strptime(utc_slave, "%d-%b-%Y %T",&tm_slave); time_t time_ref = mktime(&tm_ref); time_t time_master = mktime(&tm_master); time_t time_slave = mktime(&tm_slave); real8 master_since85 = difftime(time_master,time_ref); // 1>2 real8 slave_since85 = difftime(time_slave,time_ref); // 1>2 int32 Btemp = int32(floor( ((slave_since85-master_since85)/(60.0*60.0*24.0))+0.5)); return Btemp; } // END Btemp /**************************************************************** * BalphaBhBvBparBperpTheta * * get Baseline, Bh and Bv based on 3 positions, * * not efficient? See documentation for definitions * * better use velocity vector, not P? * * input: * * - coordinates x,y,z of Master, Slave en Point on ground * * output: * * - abs(B), alpha[-pi,pi], theta[approx23deg], Bh, Bv, Bpar * * Bperp * * * * theta is the looking angle to point P. * * theta2 is the looking angle to point P for slave satellite. * * cos theta = (rho1^2+r1^2-p^2) / (2*rho1*r1) * * approx. * * cos theta2 = (rho2^2+r2^2-p^2) / (2*rho2*r2) * * if (theta1>theta2) then (Bperp>0) * * if (costheta1>costheta2) then (Bperp<0) * * * #%// BK 19-Oct-2000 * ****************************************************************/ void BalphaBhBvBparBperpTheta( real8 &B, real8 &alpha, real8 &Bh, real8 &Bv, real8 &Bpar, real8 &Bperp, real8 &theta, const cn M, const cn P, const cn S) { TRACE_FUNCTION("BalphaBhBvBparBperpTheta (BK 19-Oct-2000)") const cn r1 = P.min(M); const real8 P_2 = P.norm2(); const real8 M_2 = M.norm2(); const real8 r1_2 = r1.norm2(); const real8 costheta1 = (M_2+r1_2-P_2)/(2*sqrt(M_2*r1_2)); const real8 S_2 = S.norm2(); const cn r2 = P.min(S); const real8 r2_2 = r2.norm2(); const real8 costheta2 = (S_2+r2_2-P_2)/(2*sqrt(S_2*r2_2)); const cn vecB = S.min(M); // (vector B points to S) const real8 B_2 = vecB.norm2(); Bpar = sqrt(r1_2)-sqrt(r2_2); // parallel baseline, sign ok Bperp = (costheta1>costheta2) ? // perpendicular bln, sign ok -sqrt(B_2-sqr(Bpar)) : sqrt(B_2-sqr(Bpar)); theta = acos(costheta1); // <0,pi/2>, ok alpha = theta-atan2(Bpar,Bperp); // <-pi,pi> B = sqrt(B_2); // abs. value Bv = B * sin(alpha); // Bv, sign ok Bh = B * cos(alpha); // Bh, sign ok } // END BalphaBhBvBparBperpTheta /**************************************************************** * shiftazispectrum * * Shift spectrum of input matrix data either from fDC to zero, * * or from zero to fDC (Doppler centroid frequency). * * Slcimage gives required polynomial fDC(column). * * Abs(shift) gives the first range column for this polynomial. * * First column is 1, so use this, not 0! * * (shift<0) indicates to shift towards zero, and * * (shift>0) indicates to shift spectrum to fDC (back) * * Spectrum is shifted by multiplication by a trend e^{iphase} * * in the space domain. * * * * If fDC is more or less equal for all columns, then an * * approximation is used. If fDC is smaller then 2 percent of * * PRF then no shifting is performed. * * memory intensive cause matrix is used. * * * #%// BK 09-Nov-2000 * * this is not ok for ovs data * #%// BK 12-Aug-2005 * ****************************************************************/ void shiftazispectrum( matrix &data, // slcdata in space domain const slcimage &slcinfo, // polynomial fDC const real4 shift) // abs(shift)==firstpix in slave system) // if (shift>0) then shift from zero to fDC { // ______ Really debug this by defining: ______ //#define REALLYDEBUG TRACE_FUNCTION("shiftazispectrum (BK 09-Nov-2000)") // ______ Evaluate fdc for all columns ______ if (slcinfo.f_DC_a0==0 && slcinfo.f_DC_a1==0 && slcinfo.f_DC_a2==0) // no shift at all return; // ______ Some constants ______ const int32 NLINES = data.lines(); // compute e^ix const int32 NCOLS = data.pixels(); // width const int32 SIGN = (shift<0) ? -1:1; // e^{SIGN*i*x} // -1 const real4 PIXLO = abs(shift)-1; // first column for fDC polynomial // ______ Compute fDC for all columns ______ // ______ Create axis to evaluate fDC polynomial ______ // ______ fDC(column) = fdc_a0 + fDC_a1*(col/RSR) + fDC_a2*(col/RSR)^2 ______ // ______ offset slave,master defined as: cols=colm+offsetP ______ matrix FDC(1,NCOLS); FDC = slcinfo.f_DC_a0; // constant term if (slcinfo.f_DC_a1!=0 || slcinfo.f_DC_a2!=0) // check to save time { matrix xaxis(1,NCOLS); // lying for (register int32 ii=0; ii trend(NLINES,1); for (register int32 ii=0; ii P = trend * FDC; matrix TREND = // forward or backward (SIGN==-1) ? mat2cr4(cos(P),-sin(P)) : mat2cr4(cos(P), sin(P)); // ______ check if this goes ok with matlab ______ #ifdef REALLYDEBUG static int32 si_buffernum = 0; si_buffernum++; char OFILE[2*ONE27]; ostrstream tmpomem(OFILE,2*ONE27); tmpomem.seekp(0); tmpomem << "datain." << si_buffernum << ends; cerr << "REALLYDEBUG: matrix data dumped to file " << OFILE << " (cr4).\n"; cerr << "#lines, #pixs: " << data.lines() << ", " << data.pixels() << endl; ofstream of; of.open(OFILE); of << data; of.close(); tmpomem.seekp(0); tmpomem << "TREND." << si_buffernum << ends; cerr << "REALLYDEBUG: trend matrix dumped to file " << OFILE << " (cr4).\n"; of.open(OFILE); of << TREND; of.close(); #endif data *= TREND; // return by reference #ifdef REALLYDEBUG tmpomem.seekp(0); tmpomem << "dataout." << si_buffernum << ends; cerr << "REALLYDEBUG: matrix data dumped to file " << OFILE << " (cr4).\n"; of.open(OFILE); of << data; of.close(); #endif } // END shiftazispectrum /**************************************************************** * tiepoint * * * * For a given tiepoint, compute the pixel coordinates and * * timing etc. This can then be used in matlab to correct the * * unwrapped phase by hand. * * This routine is called only if tiepoint is given. * * * * Input: * * lat/lon/hei of a tiepoint * * Output: * * INFO the details * * * #%// BK 14-May-2004 * ****************************************************************/ void tiepoint( const input_gen &generalinput, const slcimage &master, const slcimage &slave, orbit &masterorbit, orbit &slaveorbit, const input_ell &ellips) { TRACE_FUNCTION("tiepoint (Bert Kampes 14-May-2004)") if (abs(generalinput.tiepoint.x) < 0.001 && abs(generalinput.tiepoint.y) < 0.001 && abs(generalinput.tiepoint.z) < 0.001) { INFO.print("No tiepoint given."); return; } if (masterorbit.npoints()==0) { INFO.print("Exiting tiepoint, no orbit data master available."); return; } DEBUG.precision(30); // permanent; INFO << setp(13)<x,y,z //ell2xyz(ellips,tiepointpos,tiepointphi,tiepointlambda,tiepointheight); cn tiepointpos = ellips.ell2xyz(tiepointphi,tiepointlambda,tiepointheight); INFO << "TIEPOINT: x,y,z (WGS84): " << tiepointpos.x << " " << tiepointpos.y << " " << tiepointpos.z; INFO.print(); // ______ Convert to line/pix in master ______ real8 tiepointline;// returned real8 tiepointpix;// returned int32 n_iter = xyz2lp(tiepointline, tiepointpix, master, masterorbit, tiepointpos, MAXITER, CRITERTIM); INFO << "TIEPOINT line/pix in master: " << tiepointline << " " << tiepointpix; INFO.print(); // ______ Compute master azimuth/range time of this pixel______ const real8 m_aztime = master.line2ta(tiepointline); const real8 m_trange = master.pix2tr(tiepointpix); DEBUG << "TIEPOINT master azimuth time: " << m_aztime; DEBUG.print(); DEBUG << "TIEPOINT master range time: " << m_trange; DEBUG.print(); // ______ Ellipsoid reference phase for this point master(l,p) ______ // ______ Compute xyz for slave satellite from P ______ cn P_ref;// point at H=0 (ellips) lp2xyz(tiepointline,tiepointpix, ellips,master,masterorbit,P_ref, MAXITER,CRITERPOS); INFO << "TIEPOINT: same range, but on ellipsoid: x,y,z (WGS84): " << P_ref.x << " " << P_ref.y << " " << P_ref.z; INFO.print(); // ______ Check if slave is there ______ if (slaveorbit.npoints()==0) { INFO.print("tiepoint: no orbit data slave available cannot compute more."); DEBUG.reset(); INFO.reset(); } else { // ______ Compute xyz for slave satellite from P ______ real8 s_aztime; // returned real8 s_trange; // returned xyz2t(s_aztime, s_trange, slave, slaveorbit, tiepointpos, MAXITER, CRITERTIM); DEBUG << "TIEPOINT slave azimuth time: " << s_aztime; DEBUG.print(); DEBUG << "TIEPOINT slave range time: " << s_trange; DEBUG.print(); INFO << "TIEPOINT line/pix in slave: " << slave.ta2line(s_aztime) << " " << slave.tr2pix (s_trange); INFO.print(); // ___ Phase of this point ___ real8 phase = m_minpi4cdivlam*m_trange - s_minpi4cdivlam*s_trange;// [rad] INFO << "TIEPOINT unwrapped phase (incl. reference phase): " << phase << " [rad]"; INFO.print(); // _____ Times for slave image ______ real8 s_tazi_ref; // returned real8 s_trange_ref; // returned xyz2t(s_tazi_ref, s_trange_ref, slave, slaveorbit, P_ref, MAXITER,CRITERTIM); // ___ report reference phase corrected unwrapped phase of tiepoint ___ // ___ real8 m_trange_ref = m_trange;// by definition // ___ t_corrected = t_m - t_m_ref - (t_s - t_s_ref) = t_s_ref-t_s; DEBUG << "TIEPOINT slave range time to Pref: " << s_trange_ref; DEBUG.print(); real8 phase_ref_corrected = s_minpi4cdivlam*(s_trange_ref-s_trange);// [rad] INFO << "TIEPOINT unwrapped phase (ellipsoid ref.phase corrected) [rad]: " << phase_ref_corrected; INFO.print(); INFO.print("This phase can be used to correct the unwrapped interferogram"); INFO.print("make sure that you compute the correct pixel position"); INFO.print("the line/pix here are in original master coordinates."); INFO.print("And use Matlab to add this phase to the unwrapped interferogram."); INFO.print(); // ______ Check if zero-Doppler iteration is correct by going back ______ // ------ Go from P_ref to M and to S, then back from M to P_refcheckM // ------ and from S to P_refcheckS; Bert Kampes, 06-Apr-2005 real8 t_az, t_rg;// tmp variables // --- from P_ref to orbits --- // ______ master: from P_ref to M ____ n_iter = xyz2t(t_az,t_rg,master,masterorbit,P_ref,MAXITER,CRITERTIM);// return t const cn M = masterorbit.getxyz(t_az); // ______ master: from M to P_ref_checkM ____ cn P_ref_checkM; n_iter = lp2xyz(master.ta2line(t_az), master.tr2pix(t_rg), ellips, master, masterorbit, P_ref_checkM, MAXITER, CRITERPOS); // ______ slave: from P_ref to S ____ n_iter = xyz2t(t_az,t_rg,slave, slaveorbit, P_ref,MAXITER,CRITERTIM);// return t const cn S = slaveorbit.getxyz(t_az); // ______ slave: from S to P_ref_checkS ____ cn P_ref_checkS; n_iter = lp2xyz(slave.ta2line(t_az), slave.tr2pix(t_rg), ellips, slave, slaveorbit, P_ref_checkS, MAXITER, CRITERPOS); // ______ finally back again from P_ref to slave and master ______ cn M_check; n_iter = xyz2orb(M_check,master,masterorbit,P_ref,MAXITER,CRITERTIM); cn S_check; n_iter = xyz2orb(S_check,slave, slaveorbit, P_ref,MAXITER,CRITERTIM); // ______ Report: ______ INFO.print("Checking zero-Doppler iteration by doing forward and inverse transform:"); DEBUG << "M(x,y,z) = " << M.x << "; " << M.y << "; "<< M.z; DEBUG.print(); DEBUG << "M'(x,y,z)= " << M_check.x << "; " << M_check.y << "; "<< M_check.z; DEBUG.print(); DEBUG << "P(x,y,z) = " << P_ref.x << "; " << P_ref.y << "; "<< P_ref.z; DEBUG.print(); DEBUG << "P'(x,y,z)= " << P_ref_checkM.x << "; " << P_ref_checkM.y << "; "<< P_ref_checkM.z; DEBUG.print(); DEBUG << "P''(x,y,z)=" << P_ref_checkS.x << "; " << P_ref_checkS.y << "; "<< P_ref_checkS.z; DEBUG.print(); DEBUG << "S(x,y,z) = " << S.x << "; " << S.y << "; "<< S.z; DEBUG.print(); DEBUG << "S'(x,y,z)= " << S_check.x << "; " << S_check.y << "; "<< S_check.z; DEBUG.print(); if (abs(M.dist(M_check))>0.001)// assume 1 mm or so? WARNING.print("check failed for M_check"); if (abs(S.dist(S_check))>0.001)// assume 1 mm or so? WARNING.print("check failed for S_check"); if (abs(P_ref.dist(P_ref_checkM))>0.001)// assume 1 mm or so? WARNING.print("check failed for P_ref_checkM"); if (abs(P_ref.dist(P_ref_checkS))>0.001)// assume 1 mm or so? WARNING.print("check failed for P_ref_checkS"); INFO.print("If no warnings seen then zero-Doppler is within 1 mm accurate."); }// slave orbit present // ______ Tidy up ______ PROGRESS.print("Finished tiepoint."); DEBUG.reset(); INFO.reset(); } // END tiepoint /**************************************************************** * offsets2timing() * * * * * * input: * * - master info * * - simulated amplitude overall offsetL and offsetP * * output: * * - master timing error in the azimuth and range direction * * * * : see also slcimage.hh * * * * Mahmut Arikan, 13-Dec-2008 * ****************************************************************/ void offsets2timing( const slcimage &slcinfo, // normalization factors, ovs_rg/az const int32 &offsetL, const int32 &offsetP, real8 &azTIME, real8 &rgTIME) { TRACE_FUNCTION("offsets2timing (MA 13-DEC-2008)") // switch INFO-->DEBUG when safe. INFO << "The given azimuth timing offset: " << offsetL << " lines."; INFO.print(); INFO << "The given range timing offset: " << offsetP << " pixels."; INFO.print(); // if offsetL is NaN exit // TODO check if line pixel offsets are more than certian threshold ex: > 1000 in // lines > 200 in pixels // this should be a warning // ______ Initialize Variables ______ const real8 &mPRF = slcinfo.prf ; // PRF see slcimage.hh const real8 &mRSRx2 = slcinfo.rsr2x ; // 2xRSR // oversampling updates these values // variables see slcimage.cc DEBUG << "PRF: " << mPRF; DEBUG.print(); DEBUG << "RSR: " << mRSRx2/2.0 ; DEBUG.print(); //slcinfo.showdata(); // debug // ______ Compute Time ______ azTIME = real8( offsetL/mPRF ); // Azimuth timing, in seconds rgTIME = real8( offsetP/mRSRx2 ); // Range timing, in seconds ( two-way) INFO << "Original azimuth timing shift [sec]: " << slcinfo.az_timing_error << " sec."; INFO.print(); INFO << "Original range timing shift [sec]: " << slcinfo.r_timing_error << " sec."; INFO.print(); // following already in mtiming, keep for future implementations // DEBUG << "Estimated master azimuth timing error [sec]: " << azTIME << " sec."; // DEBUG.print(); // DEBUG << "Estimated master range timing error [sec]: " << rgTIME << " sec."; // DEBUG.print(); } // END offsets2timing /**************************************************************** * Write Template KML * * * * Generate a KML file for displaying crop and interferograms * * on Google Earth, based on 4 corner coordinates from orbits. * * * * Batuhan Osmanoglu * * * ****************************************************************/ void write_kml( const input_ell &input_ellips, const window &input_dbow, const slcimage &master, orbit &masterorbit, const char filename[4*ONE27]) { TRACE_FUNCTION("write_kml (MA, FvL, BO 20100123)") real8 cornerPhi, cornerLam, cornerHei, One80overPi; real8 north=0;//initialize values... real8 south=0; real8 east=0; real8 west=0; double rotation=0; double rotationNumerator=0; double rotationDenominator=0; One80overPi=180/PI; char pngFilename[4*ONE27]; strcpy(pngFilename, filename); strcat(pngFilename,".png"); //corner 1 (l0,p0) lp2ell(input_dbow.linelo, input_dbow.pixlo, input_ellips, master, masterorbit, cornerPhi, cornerLam, cornerHei, 10, 1e-3); cornerPhi*=One80overPi; cornerLam*=One80overPi; DEBUG << "philamhei(l0,p0)= " << cornerPhi << ", " << cornerLam << ", " << cornerHei; DEBUG.print(); north+=cornerPhi; //Image should flip or flop automatically. west+= cornerLam; rotationNumerator=cornerPhi; rotationDenominator=cornerLam; //corner 2 (l0,pN) lp2ell(input_dbow.linelo, input_dbow.pixhi, input_ellips, master, masterorbit, cornerPhi, cornerLam, cornerHei, 10, 1e-3); cornerPhi*=One80overPi; cornerLam*=One80overPi; DEBUG << "philamhei(l0,pN)= " << cornerPhi << ", " << cornerLam << ", " << cornerHei; DEBUG.print(); north+=cornerPhi;north/=2; //north=[ phi(l0,p0)+phi(l0,pN) ]/2 east+=cornerLam; //corner 3 (lN,p0) lp2ell(input_dbow.linehi, input_dbow.pixlo, input_ellips, master, masterorbit, cornerPhi, cornerLam, cornerHei, 10, 1e-3); cornerPhi*=One80overPi; cornerLam*=One80overPi; DEBUG << "philamhei(lN,p0)= " << cornerPhi << ", " << cornerLam << ", " << cornerHei; DEBUG.print(); south+=cornerPhi; west+=cornerLam;west/=2; //west= [ lam(l0,pN)+lam(lN,pN) ]/2 rotationNumerator-=cornerPhi; rotationDenominator-=cornerLam; //corner 4 (lN,pN) lp2ell(input_dbow.linehi, input_dbow.pixhi, input_ellips, master, masterorbit, cornerPhi, cornerLam, cornerHei, 10, 1e-3); cornerPhi*=One80overPi; cornerLam*=One80overPi; DEBUG << "philamhei(lN,pN)= " << cornerPhi << ", " << cornerLam << ", " << cornerHei; DEBUG.print(); south+=cornerPhi;south/=2; //south=[ phi(lN,p0)+phi(lN,pN) ]/2 east+=cornerLam;east/=2; //east= [ lam(l0,p0)+lam(lN,p0) ]/2 DEBUG << "GoogleEarth North/South/East/West: " << north << " / " << south << " / " << east << " / " << west; DEBUG.print(); rotation=-(90-atan2(rotationNumerator, rotationDenominator)*One80overPi); DEBUG << "GoogleEarth Rotation: " << rotation; DEBUG.print(); // Write output KML. //open output file ofstream kmlfile; openfstream(kmlfile, filename, true); bk_assert(kmlfile, filename, __FILE__, __LINE__); kmlfile << "" << endl; kmlfile << "" << endl; kmlfile << "" << endl; kmlfile << " 1" << endl; kmlfile << " " << endl; kmlfile << " " << north << "" << endl; kmlfile << " " << south << "" << endl; kmlfile << " " << east << "" << endl; kmlfile << " " << west << "" << endl; kmlfile << " " << rotation << "" << endl; kmlfile << " " << endl; kmlfile << " " << endl; kmlfile << " " << pngFilename << "" << endl; kmlfile << " " << endl; kmlfile << "" << endl; kmlfile << "" << endl; kmlfile << "" << endl; kmlfile.close(); //End of -> Output Crop Corner Coordinates. ////////////////////////////////////////// } //END write_kml Doris-5.0.3Beta/doris_core/utilities.hh000077500000000000000000000673111312547014700200760ustar00rootroot00000000000000/* * Copyright (c) 1999-2009 Delft University of Technology, The Netherlands * * This file is part of Doris, the Delft o-o radar interferometric software. * * Doris 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 2 of the License, or * (at your option) any later version. * * Doris 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ /**************************************************************** * $Source: /users/kampes/DEVELOP/DORIS/doris/src/RCS/utilities.hh,v $ * $Revision: 3.18 $ * * $Date: 2005/10/06 11:09:20 $ * * $Author: kampes $ * * * * - Mathematical utilities. * * - fast trigonometric functions sin/cos/atan2 * ****************************************************************/ #ifndef UTILITIES_H // guard #define UTILITIES_H using namespace std; // BK 29-Mar-2003, new compiler? // Jia defined this for compilation under windows // Bert Kampes, 24-Aug-2005 #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "constants.hh" // typedefs #include "slcimage.hh" // my slc image class #include "orbitbk.hh" // my orbit class #include "ioroutines.hh" // ERROR #include "exceptions.hh" // exceptions class #include // floor, sqr // === prototype requires below, so put first/. // ______ Solve system of 3 equations ______ void solve33( matrix &Result, const matrix &rhs, const matrix &partials); // ______ Solve set of 2 equations ______ matrix solve22( const matrix &rhs, const matrix &partials); // ====== Inline ====== inline real8 deg2rad(const real8 &x){return x * PI / 180.0;} inline real4 deg2rad(const real4 &x){return x * PI / 180.0;} inline real8 rad2deg(const real8 &x){return x * 180.0 / PI;} inline real4 rad2deg(const real4 &x){return x * 180.0 / PI;} // ______ For resampling output ci2 casting ______ // ______ No clipping check? max is 2^15=-32768:32767 inline compli16 cr4toci2(const complr4 &x) {return compli16((x.real() > 0.0) ? short(x.real()+0.5) : short(x.real()-0.5), (x.imag() > 0.0) ? short(x.imag()+0.5) : short(x.imag()-0.5));} // ====== Inline ====== inline bool iseven(const int16 &w) {return (w+1)%2;} inline bool iseven(const int32 &w) {return (w+1)%2;} inline bool iseven(const int64 &w) {return (w+1)%2;} inline bool iseven(const uint &w) {return (w+1)%2;} inline bool iseven(const uint64 &w) {return (w+1)%2;} inline bool isodd (const int16 &w) {return w%2;} inline bool isodd (const int32 &w) {return w%2;} inline bool isodd (const int64 &w) {return w%2;} inline bool isodd (const uint &w) {return w%2;} inline bool isodd (const uint64 &w) {return w%2;} // --- added 1 as power of 2 bk 8/05 inline bool ispower2 (const uint &w) {if (w==1 || w==2 || w==4 || w==8 || w==16 || w==32 || w==64 || w==128 || w==256 || w==512 || w==1024 || w==2048 || w==4096 ) return true; return false;} inline int32 Ncoeffs(const int32 °ree) {return int32(0.5*(sqr(degree+1)+degree+1));} inline int32 degree(const int32 &Ncoeffs) { return int32(0.5*(-1 + int32(sqrt(real4(1+8*Ncoeffs)))))-1;} inline real4 remainder(const real4 &number, const real4 &divisor) {return number-floor(number/divisor)*divisor;} inline real8 remainder(const real8 &number, const real8 &divisor) {return number-floor(number/divisor)*divisor;} inline real4 sinc(const real4 &x) {return ((x==0) ? 1 : sin(PI*x)/(PI*x));} //____ Raffaele Nutricato inline real8 sinc(const real8 &x) {return ((x==0) ? 1 : sin(PI*x)/(PI*x));} inline real4 rect(const real4 &x) {real4 ans = 0.0; if (x<0.5 && x>-0.5) ans = 1; else if (x==0.5 || x==-0.5) ans = 0.5; return ans;} inline real4 tri(const real4 &x) {real4 ans = 0.0; if (x<1.0 && x>-1.0) {(x<0) ? ans=1+x : ans=1-x;} return ans;} // --- positve numbers ? --- // Bert Kampes, 24-Aug-2005 inline real8 onedecimal(const real8 &x) {return real8(int32(x*10+0.5))/10.0;} inline real4 onedecimal(const real4 &x) {return real4(int32(x*10+0.5))/10.0;} /**************************************************************** * myrect * * rect window, lying vector * * r(i) = 1 if abs(i)<=.5 * * used in filtering, see curlander, swabisch, geudtner * * Bert Kampes, 31-Mar-2000 * ****************************************************************/ inline matrix myrect(const matrix &X) { TRACE_FUNCTION("myrect (BK 31-Mar-2000)") #ifdef __DEBUG if (X.lines()!=1) { PRINT_ERROR("myrect: only lying vectors.") throw(argument_error); } #endif matrix Res(1,X.pixels()); // init2zero real4 *pntX = X[0]; real4 *pntR = Res[0]; for (register int32 i=0; i 4.0): if (abs(*pntX)<=0.5) *pntR=1.; pntR++; *pntX++; } // BK 01-Nov-2000: better: ?? //for (real4 *pntX=&X[0][0]; pntX<=&X[X.lines()-1][X.pixels()-1]; ++pntX) // *pntR++ = (abs(*pntX)<=0.5) ? 1 : 0; // rather something like: R(find(abs(X)<.5))=1; return Res; } /**************************************************************** * myhamming * * hamming window, lying vector * * w = (a + (1.-a).*cos((2.*pi/fs).*fr)) .* myrect(fr./Br); * * scale/shift filter by g(x)=f((x-xo)/s) * * alpha==1 yields a myrect window * * Bert Kampes, 31-Mar-2000 * ****************************************************************/ inline matrix myhamming( const matrix &fr, real8 RBW, real8 RSR, real8 alpha) { TRACE_FUNCTION("myhamming (BK 31-Mar-200)") #ifdef __DEBUG if (fr.lines()!=1) { PRINT_ERROR("myhamming: only lying vectors.") throw(argument_error); } if (alpha<0.0 || alpha>1.0) { PRINT_ERROR("myhamming: !alpha e{0..1}.") throw(argument_error); } if (RBW>RSR) { PRINT_ERROR("myhamming: RBW>RSR.") throw(argument_error); } #endif matrix Res(1,fr.pixels()); real4 *pntfr = fr[0]; real4 *pntR = Res[0]; for (register int32 i=0; i * * r P1 P2 * * o .P * * w P3 P4 * * s * * * * input: * * - normalized coordinates of point (row,col). * * - functional values at 4 corners. * * output: * * - interpolated value * * * * Bert Kampes, 19-Jan-2000 * #%// BK 25-Sep-2000 ****************************************************************/ inline real8 interpbilinear( const real8 r, const real8 c, const real8 P1, const real8 P2, const real8 P3, const real8 P4) { #ifdef __DEBUG TRACE_FUNCTION("interpbilinear() (BK 25-Sep-2000)") #endif return P1 + (P2-P1)*c + (P3-P1)*r + (P4-P3-P2+P1)*r*c; } /**************************************************************** * interp_trilinear * * trilinear interpolation using relative coordinates. * * * * ====== Points A,B,C and do trigrid lin. interpolation at "+" * * ====== "+", origin of local coordinate system * * * * A * * * * + * * B * * * * C * * * * ====== Then, cn A.z = f(x,y) = a00+a10*A.x+a01*A.y; * * ====== cn B.z = f(x,y) = a00+a10*B.x+a01*B.y; * * ====== cn C.z = f(x,y) = a00+a10*C.x+a01*C.y; * * ====== solve for a00; the Z value at origin, i.e., it! * * * * input: * * - normalized coordinates of point (row,col). * * - cn A,B,C with relative coordinates and functional values * * output: * * - interpolated value * * * * Bert Kampes, 07-Apr-2005 * ****************************************************************/ inline real8 interp_trilinear( const cn &A, const cn &B, const cn &C) { #ifdef __DEBUG TRACE_FUNCTION("interp_trilinear() (BK 07-Apr-2005)") if (A.x==B.x && A.y==B.y) { WARNING.print("interp_trilinear: A==B"); return (A.z+B.z+C.z)/3.0; } if (A.x==C.x && A.y==C.y) { WARNING.print("interp_trilinear: A==C"); return (A.z+B.z+C.z)/3.0; } if (B.x==C.x && B.y==C.y) { WARNING.print("interp_trilinear: B==C"); return (A.z+B.z+C.z)/3.0; } // --- check if points are on line or are all same... --- // ??? how // --- maybe simply add eps to A.x, A.y and subtract it from B.x, B.y? // --- since how else can we guarantee solve33 won't crash? // we assume the caller routines guarantees this (as referencephase.cc does) // for speed #endif // --- Vandermonde matrix --- // const real8 EPS = 0.00001;// assume points are pixels // matrix DESIGNMAT(3,3); // DESIGNMAT(0,0)=1.0; DESIGNMAT(0,1)=A.x + EPS; DESIGNMAT(0,2) = A.y + EPS; // DESIGNMAT(1,0)=1.0; DESIGNMAT(1,1)=B.x - EPS; DESIGNMAT(1,2) = B.y - EPS; // DESIGNMAT(2,0)=1.0; DESIGNMAT(2,1)=C.x; DESIGNMAT(2,2) = C.y; // // --- Right hand side --- // matrix RHS(3,1); // RHS(0,0)=A.z; // RHS(1,0)=B.z; // RHS(2,0)=C.z; // // --- Solve system using library for all coefficients --- // matrix RESULT(3,1);// returned // solve33(RESULT,RHS,DESIGNMAT);// return result = a00,a10,a01 // const real8 a00 = RESULT(0,0); // return a00; // since first the last element is solved, turn it around and do it locally: //* ====== Then, cn A.z = f(x,y) = [ya,xa,1][a01] //* ====== cn B.z = f(x,y) = [yb,xb,1][a10] //* ====== cn C.z = f(x,y) = [yc,xc,1][a00] <--- solve this on by LU //* ====== solve for a00; the Z value at origin, i.e., it! // ______ LU decomposition ______ const real8 EPS = 0.00000001;// assume points are pixels (zero division if A.y==0.0) const real8 L10 = (B.y-EPS)/(A.y+EPS);// DESIGN(1,0)/DESIGN(0,0); const real8 L20 = C.y/(A.y+EPS);// DESIGN(2,0)/DESIGN(0,0); const real8 U11 = (B.x-EPS)-L10*(A.x+EPS);// DESIGN(1,1)-L10*DESIGN(0,1); // L21 had a bug in placing of brackets before v3.16 // Bert Kampes, 25-Aug-2005 const real8 L21 = (C.x-(A.x+EPS)*L20)/U11;// (DESIGN(2,1)-(DESIGN(0,1)*L20))/U11; const real8 U12 = 1.0-L10;// DESIGN(1,2)-L10*DESIGN(0,2); const real8 U22 = 1.0-L20-L21*U12;// DESIGN(2,2)-L20*DESIGN(0,2)-L21*U12; // ______ Solution: forward substitution ______ const real8 b0 = A.z;// rhs(0,0); const real8 b1 = B.z-b0*L10;// rhs(1,0)-b0*L10; const real8 b2 = C.z-b0*L20-b1*L21;// rhs(2,0)-b0*L20-b1*L21; // ______ Solution: backwards substitution ______ const real8 a00 = b2/U22;//RESULT(2,0) = b2/U22; //RESULT(1,0) = (b1-U12*RESULT(2,0))/U11; //RESULT(0,0) = (b0-DESIGN(0,1)*RESULT(1,0)-DESIGN(0,2)*RESULT(2,0))/DESIGN(0,0); return a00; } /**************************************************************** * ProjectPointOnLine * * Computes Projection of a 3D point M * * on to a vector in 3D. The vector is directed * * from P to S * * this can be useed in baseline computation * #%// KKM 09-March-2005 * ****************************************************************/ inline cn ProjectPointOnLine( cn M, cn P, cn S) { TRACE_FUNCTION("ProjectPointOnLine() (KKM 09-Mar-2005)") cn U = P.min(S);// direction cosines of PS const real8 U_2 = U.in(U); U = U.scale(1.0/sqrt(U_2)); // --- Umat is the matrix representation of U to compute U*U' --- matrix Umat(3,1); Umat(0,0) = U.x; Umat(1,0 ) = U.y; Umat(2,0) = U.z; const matrix UU = matxmatT(Umat,Umat);// [3x3] // --- X is returned, base of perpendicular from M to PS matrix UmatT(1,3); UmatT(0,0) = M.x-S.x; UmatT(0,1) = M.y-S.y; UmatT(0,2) = M.z-S.z; UmatT = UmatT*UU;// [1x3] // --- returned cn, base of perpendicular from M to PS --- return cn(UmatT(0,0)+S.x, UmatT(0,1)+S.y, UmatT(0,2)+S.z); } /**************************************************************** * matrix I = indgen(real4(10)) * * matrix I = indgen(int32(10)), etc. * * create lying matrix [0,1,2,..N-1] * * Bert Kampes, 08-Apr-2005 * ****************************************************************/ template inline matrix indgen( const Type N) // use Type of N to create appropriate matrix { TRACE_FUNCTION("indgen() (BK 08-Apr-2005)") const uint dim = uint(N+0.5);// round positive number matrix e(1,dim); for(uint i=0; i I = linspace(x0,xn,N) * * create lying matrix [x0:xn] equally space N samples * * Bert Kampes, 08-Apr-2005 * ****************************************************************/ template inline matrix linspace( const Type x0, const Type xN, const int32 N) { TRACE_FUNCTION("linspace() (BK 08-Apr-2005)") return x0+((indgen(Type(N)))*((xN-x0)/Type(N-1.0)));// use Type(N) to get ok. } /**************************************************************** * matrix E = ones(10,10) * * create matrix filled with ones. * * Bert Kampes, 08-Apr-2005 * ****************************************************************/ template inline matrix ones( const Type Ny, const Type Nx)// use Type of N to create appropriate matrix { TRACE_FUNCTION("ones() (BK 08-Apr-2005)") const uint dimX = uint(Nx+0.5);// round positive number const uint dimY = uint(Ny+0.5);// round positive number matrix E(dimY,dimX); E.setdata(Type(1)); return E; } /**************************************************************** * matrix I = eye(10) * * create identity matrix with ones on main diagonal. * * Bert Kampes, 08-Apr-2005 * ****************************************************************/ template inline matrix eye( const Type N)// use Type of N to create appropriate matrix { TRACE_FUNCTION("eye() (BK 08-Apr-2005)") const uint dim = uint(N+0.5);// round positive number matrix I(dim,dim); for(uint i=0; i matrix polyval( // MA overloading func. for more precision like real8 const matrix &x, const matrix &y, const matrix &coeff, int32 degree = -1); // ______ Evaluate 2d polynomial ______ real8 polyval( real8 x, real8 y, const matrix &coeff); // ______ Evaluate 2d polynomial ______ real8 polyval( real8 x, real8 y, const matrix &coeff, int32 degree); // ______ Evaluate 1d polynomial ______ real8 polyval1d( real8 x, const matrix &coeff); // int32 degree); // ______ Evaluate derivative of 1d polynomial [HB] ______ real8 polyval1d( real8 x, const matrix &coeff, uint deriv); // ______ Normalize a matrix data -> [-2,2] ______ void normalize( matrix &data, real8 min, real8 max ); // ______ Normalize a matrix data -> [-2,2] ______ void normalize( matrix &data, real8 min, real8 max ); // ______ Normalize data from [min,max] to [-2,2] ______ inline real4 normalize(real4 data, real8 min, real8 max) {return real4((data-(0.5*(min+max)))/(0.25*(max-min)));} // ______ Normalize data from [min,max] to [-2,2] ______ inline real8 normalize(real8 data, real8 min, real8 max) {return (data-(0.5*(min+max)))/(0.25*(max-min));} // ______ Use this to compute Bperp for a few points, slow! ______ void BBparBperp( real8 &B, real8 &Bpar, real8 &Berp, // returned const cn Master, const cn Point, const cn Slave); // ______ Sign not computed, slow! ______ void BBhBv( real8 &B, real8 &Bh, real8 &Bv, // returned const cn Master, const cn Slave); // ______ Temporal baseline in days returned ______ // ______ (positive for master earlier than slave) ______ int32 Btemp( const char *utc_master, const char *utc_slave); // ______ Baseline parametrizations returned ______ void BalphaBhBvBparBperpTheta( real8 &B, real8 &alpha, real8 &Bh, real8 &Bv, real8 &Bpar, real8 &Bperp, real8 &theta, const cn M, const cn P, const cn S); // ______ Shift azimuth spectrum from fDC to zero, and vv. ______ void shiftazispectrum( matrix &data, // slcdata sin space domain const slcimage &slave, // polynomial fDC const real4 shift);// abs(shift==firstpix in slave system) // if shift>0 then shift from zero to fDC // ______ Dump tiepoint INFO ______ void tiepoint( const input_gen &generalinput, const slcimage &master, const slcimage &slave, orbit &masterorbit, orbit &slaveorbit, const input_ell &ellips); // ______ Line,Pixel offsets2timing ______ void offsets2timing( const slcimage &slcinfo, const int32 &offsetL, const int32 &offsetP, real8 &azTIME, real8 &rgTIME); // _________ Write_KML ___________ [BO] void write_kml( const input_ell &ellips, const window &input_dbow, const slcimage &master, orbit &masterorbit, const char filename[4*ONE27]); // ====== Fast trigonometry by LookUpTables ======================== // ______ Standard functions can be switched on using "-D NO_FASTTRIG" // ______ Bert Kampes, 29-Sep-2005 #ifdef NO_FASTTRIG //#warning "NO_FASTTRIG used" // [MA] informative // inline real4 fast_sin(const real4 &x) {return sin(x);} // inline real4 fast_min_sin(const real4 &x) {return -sin(x);} // inline real4 fast_cos(const real4 &x) {return cos(x);} // inline real4 fast_atan(const real4 &x) {return atan(x);} // inline real4 fast_atan2(const real4 &y, const real4 &x) {return atan2(y,x);} // inline real4 fast_arg(const complex &z) {return arg(z);} #define fast_sin sin // [MA] this is better definition #define fast_min_sin -sin #define fast_cos cos #define fast_atan atan #define fast_atan2 atan2 #define fast_arg arg #else // ______ Global variables defined in utilities.cc ______ extern const uint32 LUT_LENGHT; // 65536 extern const uint16 LUT_ATAN_MAX; // 128 extern const real8 LUT_DX_SIN; // idx=int(x*LUT_DX_SIN) extern const real8 LUT_DX_ATAN; // .. extern real8 LUT_SIN[]; // look-up table [0:dx:2pi-dx] extern real8 LUT_ATAN[]; // look-up table [-128:dx:128-dx] // --- Initialize LUTs --- // --- LUT for 0:dx; dx:2dx; Ndx:2pi-dx, etc; eval at start bin --- // --- This function should be called only once at start program --- // Bert Kampes, 04-Oct-2005 inline void init_fasttrig() { for(int32 i=0; iLUT_ATAN_MAX) return PI/2; else return LUT_ATAN[uint64(x*LUT_DX_ATAN)+LUT_LENGHT/2]; } // --- fast_atan2() fast four-quadrant atan2(y,x) by LUT --- // --- Bert Kampes, 04-Oct-2005 inline real8 fast_atan2(const real8 &y, const real8 &x) { if (x==0.0) return (y==0.0) ? 0.0 : (y<0.0) ? -PI/2 : PI/2; if (x<0.0) return (y<0.0) ? fast_atan(y/x)-PI : fast_atan(y/x)+PI; else return fast_atan(y/x); } // --- fast_arg (angle of complex number) --- // --- Bert Kampes, 04-Oct-2005 inline real8 fast_arg(const complex &z) { return fast_atan2(imag(z),real(z)); } #endif // NO_FASTTRIG // /**************************************************************** // * pol2xyz * // * * // * Converts lat,lon,hei(above surface) (sphere) * // * to x,y,z (cartesian) * // * uses constants in constants.h (pi, radius) * // * * // * lat is positive for North, lon is negative for West. * // * * // * Bert Kampes, 21-Dec-1998 * // ****************************************************************/ // void pol2xyz( // cn &xyz, // real8 phi, // real8 lon, // real8 height) //default =0) // { // TRACE_FUNCTION("pol2xyz (BK 21-Dec-1998)"); // real8 Rph = RADIUS + height; // xyz.x = Rph *cos(phi)*cos(lon); // xyz.y = Rph *cos(phi)*sin(lon); // xyz.z = Rph *sin(phi); // } // END pol2xyz // // // /**************************************************************** // * xyz2pol * // * * // * Converts x,y,z (cartesian) * // * to lat,lon,hei(above surface) (sphere) * // * uses constants in constants.h (pi, radius) * // * * // * lat is positive for North, lon is negative for West. * // * * // * Bert Kampes, 21-Dec-1998 * // ****************************************************************/ // void xyz2pol( // const cn &xyz, // real8 &phi, // real8 &lambda, // real8 &height) // { // TRACE_FUNCTION("xyz2pol (BK 21-Dec-1998)"); // real8 r = sqrt(sqr(xyz.x)+sqr(xyz.y)); // phi = atan2(xyz.z,r); // lambda = atan2(xyz.y,xyz.x); // height = (r/cos(phi)) - RADIUS; // } // END xyz2pol // #endif // UTILITIES_H Doris-5.0.3Beta/doris_stack/000077500000000000000000000000001312547014700157045ustar00rootroot00000000000000Doris-5.0.3Beta/doris_stack/functions/000077500000000000000000000000001312547014700177145ustar00rootroot00000000000000Doris-5.0.3Beta/doris_stack/functions/ESD_functions.py000077500000000000000000000321271312547014700230010ustar00rootroot00000000000000import numpy as np from numpy import * from doris.doris_stack.functions.get_ramp import get_ramp, get_parameter import os ######################################################################################################################## # Function to get parameters from files # Parameter = get_parameter(First_param,file_name,format_flag=1,Second_param=None,Third_param=None) def get_parameter(First_param,file_name,format_flag=1,Second_param=None,Third_param=None): Read_contine_flag=0 class set_class(object): pass orbit_info = set_class() time_temp = [] x_temp = [] y_temp = [] z_temp = [] value=None for line in open(file_name): if format_flag==1: if not (line.find(First_param)): index=line.find(':') value=(line[(index+1):].strip(' \n\t')) return value if format_flag==2: if not (line.find(Second_param)): Read_contine_flag=1 if (Read_contine_flag==1) and (not (line.find(First_param))): ##Be careful index=line.find(':') value=(line[(index+1):].strip(' \n\t')) if (not (line.find(Third_param))): ##Be careful Read_contine_flag=0 return value if format_flag==3: if not (line.find(First_param)): index=line.find(':') pixel_time=(line[(index+1):].strip(' \n\t')).split(' ')[1].split(':') return pixel_time if format_flag==4: if not (line.find(First_param)): index=line.find(':') value=int(line[(index+1):].strip(' \n\t')) Read_contine_flag=1 continue if (Read_contine_flag>=1) : new_line = line.strip('\n').split() time_temp.append(float(new_line[0])) x_temp.append(float(new_line[1])) y_temp.append(float(new_line[2])) z_temp.append(float(new_line[3])) Read_contine_flag=Read_contine_flag+1 if (Read_contine_flag==(value+1)): setattr(orbit_info,'x',x_temp) setattr(orbit_info,'y',y_temp) setattr(orbit_info,'z',z_temp) setattr(orbit_info,'time',time_temp) return orbit_info ######################################################################################################################## # Definition to extract data # thisBurstData = freadbk(path_file,line_start=1, pixel_start=1, nofLines=None, nofPixels=None, dt=np.dtype(np.float32), lines=0, pixels=0): def freadbk(path_file, line_start=1, pixel_start=1, nofLines=None, nofPixels=None, dt='float32', lines=0, pixels=0, memmap=True): # First use memmap to get a memory map of the full file, than extract the requested part. if dt == 'cpxint16': dtype = np.dtype([('re', np.int16), ('im', np.int16)]) file_dat = np.memmap(path_file, dtype=dtype, mode='r', shape=(lines, pixels)).view(np.int16).astype(np.float32).view(np.complex64) data = file_dat[line_start - 1:line_start + nofLines - 1, pixel_start - 1:pixel_start + nofPixels - 1].astype( 'complex64', subok=False) elif dt == 'cpxshort': file_dat = np.memmap(path_file, dtype=np.dtype(np.float16), mode='r', shape=(lines, pixels * 2)) data = 1j * file_dat[:, 1::2].astype('float32', subok=False) data += file_dat[:, 0::2].astype('float32', subok=False) data = data[line_start - 1:line_start + nofLines - 1, pixel_start - 1:pixel_start + nofPixels - 1] else: dt = np.dtype(dt) file_dat = np.memmap(path_file, dtype=dt, mode='r', shape=(lines, pixels)) data = file_dat[line_start - 1:line_start + nofLines - 1, pixel_start - 1:pixel_start + nofPixels - 1].astype( dt, subok=False) return data ######################################################################################################################## # Function to calculate normalized Doppler Centroid frequency # Df_DC = get_f_DC_difference(f_DC_1, f_DC_2, BOL_Length, BOL_lines, PRF, normalize) def get_f_DC_difference(nBurst): burst1 = 'burst_' + str(nBurst) + '/' burst2 = 'burst_' + str(nBurst + 1) + '/' this_m_resData = burst1 + 'master.res' next_m_resData = burst2 + 'master.res' os.chdir(os.getcwd() + '/' + burst1) f_DC_1 = get_ramp(os.path.basename(this_m_resData), resampled=0, type='DC') os.chdir(os.path.dirname(os.getcwd())) os.chdir(os.getcwd() + '/' + burst2) f_DC_2 = get_ramp(os.path.basename(next_m_resData), resampled=0, type='DC') os.chdir(os.path.dirname(os.getcwd())) line_start, line_length, first_pixel_this, first_pixel_next, pixel_length, this_nr_oflines, this_nr_ofpixels, next_nr_oflines, next_nr_ofpixels, PRF = get_coordinates(nBurst) Df_DC = f_DC_1[line_start - 1:line_start + line_length - 1, first_pixel_this - 1:first_pixel_this + pixel_length - 1] - \ f_DC_2[0:line_length, first_pixel_next - 1: first_pixel_next + pixel_length - 1] return Df_DC def get_coordinates(nBurst): burst1 = 'burst_' + str(nBurst) + '/' burst2 = 'burst_' + str(nBurst+1) + '/' this_m_resData = burst1 + 'master.res' next_m_resData = burst2 + 'master.res' # Get variables from first burst this_line_first = int(get_parameter('First_line (w.r.t. output_image)',this_m_resData,1)) this_line_last = int(get_parameter('Last_line (w.r.t. output_image)',this_m_resData,1)) this_nr_oflines = int(this_line_last) - int(this_line_first) +1 this_pixel_first = int(get_parameter('First_pixel (w.r.t. output_image)',this_m_resData,1)) this_pixel_last = int(get_parameter('Last_pixel (w.r.t. output_image)',this_m_resData,1)) this_nr_ofpixels = int(this_pixel_last) - int(this_pixel_first) +1 PRF_1 = float(get_parameter('Pulse_Repetition_Frequency (computed, Hz)',this_m_resData,1)) # Get variables from second burst next_line_first = int(get_parameter('First_line (w.r.t. output_image)',next_m_resData,1)) next_line_last = int(get_parameter('Last_line (w.r.t. output_image)',next_m_resData,1)) next_nr_oflines = int(next_line_last) - int(next_line_first) +1 next_pixel_first = int(get_parameter('First_pixel (w.r.t. output_image)',next_m_resData,1)) next_pixel_last = int(get_parameter('Last_pixel (w.r.t. output_image)',next_m_resData,1)) next_nr_ofpixels = int(next_pixel_last) - int(next_pixel_first) +1 PRF = PRF_1 # Read only the Burstoverlap if this_pixel_first < next_pixel_first: first_pixel = next_pixel_first elif this_pixel_first >= next_pixel_first: first_pixel = this_pixel_first if this_pixel_last > next_pixel_last: pixel_length = next_pixel_last - first_pixel + 1 elif this_pixel_last <= next_pixel_last: pixel_length = this_pixel_last - first_pixel + 1 first_pixel_this = first_pixel - this_pixel_first + 1 first_pixel_next = first_pixel - next_pixel_first + 1 line_length = this_line_last - next_line_first + 1 line_start = this_nr_oflines - line_length + 1 return line_start, line_length, first_pixel_this, first_pixel_next, pixel_length, this_nr_oflines, this_nr_ofpixels,\ next_nr_oflines, next_nr_ofpixels, PRF ######################################################################################################################## # Function to calculate the interferograms of both bursts # thisburstdata, nextburstdata, diffBursts, PRF = get_interfero(nBurst, BOL_lines, BOL_Length) def get_offset(nBurst, Df_DC, coh_treshold=0.3): burst1 = 'burst_' + str(nBurst) + '/' burst2 = 'burst_' + str(nBurst+1) + '/' # cpxint16 and cpxfloat32 dataFormat_s = 'complex64' line_start, line_length, first_pixel_this, first_pixel_next, pixel_length, this_nr_oflines, this_nr_ofpixels, next_nr_oflines, next_nr_ofpixels, PRF = get_coordinates(nBurst) ifgs_1 = freadbk(burst1 + 'cint.raw.old', line_start, first_pixel_this, line_length, pixel_length , dataFormat_s, this_nr_oflines, this_nr_ofpixels) ESD_coh_1 = freadbk(burst1 + 'coherence.raw', line_start, first_pixel_this, line_length, pixel_length , 'float32', this_nr_oflines, this_nr_ofpixels) ifgs_2 = freadbk(burst2 + 'cint.raw.old', 1, first_pixel_next, line_length, pixel_length, dataFormat_s, next_nr_oflines, next_nr_ofpixels) ESD_coh_2 = freadbk(burst2 + 'coherence.raw', 1, first_pixel_next, line_length, pixel_length, 'float32', next_nr_oflines, next_nr_ofpixels) ESD_coh = (ESD_coh_1 + ESD_coh_2) / 2 #ifgs_1_total = freadbk(burst1 + 'cint.raw.old', 1, 1, this_nr_oflines, this_nr_ofpixels, dataFormat_s, this_nr_oflines, this_nr_ofpixels) #ifgs_2_total = freadbk(burst2 + 'cint.raw.old', 1, 1, next_nr_oflines, next_nr_ofpixels, dataFormat_s, next_nr_oflines, next_nr_ofpixels) # Remove invalid data both in range and azimuth valid_range = [] valid_azimuth = [] for i in range(0,len(ifgs_1[0,:])): if np.nanmean(abs(ifgs_1[:,i])) != 0 and np.nanmean(abs(ifgs_2[:,i])) != 0: valid_range.append(i) for i in range(0,len(ifgs_1[:,0])): if np.nanmean(abs(ifgs_1[i,:])) != 0 and np.nanmean(abs(ifgs_2[i,:])) != 0: valid_azimuth.append(i) if valid_range and valid_azimuth: ifgs_1 = ifgs_1[:, valid_range[:]] ifgs_2 = ifgs_2[:, valid_range[:]] ESD_coh = ESD_coh[:, valid_range[:]] ifgs_1 = ifgs_1[valid_azimuth[:], :] ifgs_2 = ifgs_2[valid_azimuth[:], :] ESD_coh = ESD_coh[valid_azimuth[:], :] Df_DC = Df_DC[:, valid_range[:]] Df_DC = Df_DC[valid_azimuth[:], :] # First downsample 2 * 10 Nra = 10 Naz = 2 new_ra = ESD_coh.shape[1] / 10 new_az = ESD_coh.shape[0] / 2 ESD_coh = ESD_coh[0:new_az*Naz-1:Naz, 0:new_ra*Nra-1:Nra] ifgs_1_multilook = ifgs_1[:new_az*2, :new_ra*10].reshape([new_az, Naz, new_ra, Nra]).mean(3).mean(1) ifgs_2_multilook = ifgs_2[:new_az*2, :new_ra*10].reshape([new_az, Naz, new_ra, Nra]).mean(3).mean(1) Df_DC_multilook = Df_DC[:new_az * 2, :new_ra * 10].reshape([new_az, Naz, new_ra, Nra]).mean(3).mean(1) # Double difference and calculate weights according to Cramer Rao bound diffBursts = ifgs_1_multilook * ifgs_2_multilook.conj() weights = 2 * ESD_coh*ESD_coh / (1 - ESD_coh*ESD_coh) W = np.sum(weights[ESD_coh > coh_treshold]) angle = (PRF / (2 * np.pi * np.nanmean(Df_DC_multilook[ESD_coh > coh_treshold] * weights[ESD_coh > coh_treshold] / np.mean(weights[ESD_coh > coh_treshold])))) offset = np.angle(np.sum(diffBursts[ESD_coh > coh_treshold] * weights[ESD_coh > coh_treshold]) / W) * angle angle_pixel = angle * (line_start - 1) return offset, W, angle_pixel ######################################################################################################################## # Function to calculate pixel offset for each burst, according to Nida's proposed method. Threshold can be assigned by # user. # offset = apply_ESD_Nida(diffBursts, Df_DC, PRF, threshold) def apply_ESD_Nida(diffBursts, Df_DC, PRF, threshold = 0.0001): # Determine phase of interferogram ph_esd = np.angle(diffBursts) # Do an intitial estimation based on the peak of the histogram N,X = np.histogram(ph_esd[:], 50) idx = np.argmax(N) D_az_init = X[idx]*(PRF/(2*np.pi*np.nanmean(Df_DC[:]))) # Create linspace from -0.1 to 0.1 in 7 steps D_az_span = -0.3*np.pi*(PRF/(2*np.pi*np.nanmean(Df_DC[:]))) D_azs = np.linspace(D_az_init-D_az_span, D_az_init+D_az_span,num=7) del D_az_span c = -1 D_az_min = [] # Keeps refinining until error with earlier estimation is lower than 0.0001 while True: c += 1 ph_test = np.ones(len(D_azs)) # Calculate estimated phase, residual phase and test phase for k in range(0,len(D_azs)): D_az = D_azs[k] ph_est = (2*np.pi*Df_DC*D_az)/PRF ph_res = ph_esd - ph_est ph_test[k] = np.nanmean(np.angle(exp(1j * ph_res[:]))) # should be ph_test(k) = np.nanmean(exp(1i*ph_res[:])) #print ph_test ind = np.argmin(abs(ph_test)) D_az_min.append(D_azs[ind]) # Break iteration when pixel shift is sufficient if c > 2 and abs(D_az_min[c]-D_az_min[c-1]) < threshold and abs(D_az_min[c-1]-D_az_min[c-2]) < threshold: ph_est_opt = np.nanmean(ph_est[:]) offset = -D_az_min[c] break # Use a smaller difference for next iteration D_az_span = D_azs[1] - D_azs[0] D_azs = np.linspace(D_azs[ind]-D_az_span, D_azs[ind]+D_az_span,num=7) del ph_test #print 'amount of loops in iteration ' + str(c) pix_offset = offset / (PRF/(2*np.pi*np.nanmean(Df_DC[:]))) return offset, pix_offset Doris-5.0.3Beta/doris_stack/functions/ESD_ps_ds.py000077500000000000000000000550361312547014700221050ustar00rootroot00000000000000import numpy as np import os, sys from datetime import datetime from datetime import timedelta from doris.doris_stack.functions.ESD_functions import get_f_DC_difference, get_coordinates, freadbk def save_overlapping(stack_folder, master_date, dates, overlap): nBurst, burst, next_burst = get_burst(overlap) esd_folder = os.path.join(stack_folder, 'esd') if not os.path.exists(esd_folder): print('ESD folder does not exist') return overlap_path = os.path.join(stack_folder, 'esd', overlap) if not os.path.exists(overlap_path): os.mkdir(overlap_path) path = swath_path(stack_folder, dates[0], burst) print('reading metadata from ' + path) os.chdir(path) line_start, line_length, first_pixel_this, first_pixel_next, pixel_length, this_nr_oflines, \ this_nr_ofpixels, next_nr_oflines, next_nr_ofpixels, PRF = get_coordinates(nBurst) burst1 = 'burst_' + str(nBurst) + '/' burst2 = 'burst_' + str(nBurst + 1) + '/' # First get the data for the master and df_dc master_path = os.path.join(overlap_path, master_date) df_dc_path = os.path.join(overlap_path, 'df_dc') master_1 = master_file(burst) master_2 = master_file(next_burst) if not os.path.exists(master_path + '_1') or not os.path.exists(master_path + '_2'): master_1 = freadbk(burst1 + master_1, line_start, first_pixel_this, line_length, pixel_length, 'cpxint16', this_nr_oflines, this_nr_ofpixels) master_2 = freadbk(burst2 + master_2, 1, first_pixel_next, line_length, pixel_length, 'cpxint16', next_nr_oflines, next_nr_ofpixels) master_1_file = np.memmap(master_path + '_1', 'complex64', shape=master_1.shape, mode='w+') master_2_file = np.memmap(master_path + '_2', 'complex64', shape=master_2.shape, mode='w+') master_1_file[:] = master_1 master_2_file[:] = master_2 master_1_file.flush() master_2_file.flush() if not os.path.exists(df_dc_path): df_dc = get_f_DC_difference(nBurst) df_dc_file = np.memmap(df_dc_path, 'float32', shape=df_dc.shape, mode='w+') df_dc_file[:,:] = df_dc[:,:] # Then loop over the slaves for date in dates: if date == master_date: continue path = swath_path(stack_folder, date, burst) os.chdir(path) print(path) data_path = os.path.join(overlap_path, date) burst1 = 'burst_' + str(nBurst) + '/' burst2 = 'burst_' + str(nBurst + 1) + '/' if not os.path.exists(data_path + '_1') or not os.path.exists(data_path + '_2'): slave_1 = freadbk(burst1 + 'slave_rsmp_reramped.raw', line_start, first_pixel_this, line_length, pixel_length , 'complex64', this_nr_oflines, this_nr_ofpixels) slave_2 = freadbk(burst2 + 'slave_rsmp_reramped.raw', 1, first_pixel_next, line_length, pixel_length, 'complex64', next_nr_oflines, next_nr_ofpixels) slave_1_file = np.memmap(data_path + '_1', 'complex64', shape=slave_1.shape, mode='w+') slave_2_file = np.memmap(data_path + '_2', 'complex64', shape=slave_2.shape, mode='w+') slave_1_file[:] = slave_1 slave_2_file[:] = slave_2 slave_1_file.flush() slave_2_file.flush() def find_ps_overlapping(stack_folder, overlap): # This is used to find the ps point in overlapping areas nBurst, burst, next_burst = get_burst(overlap) esd_folder = os.path.join(stack_folder, 'esd') overlap_path = os.path.join(esd_folder, overlap) files = os.listdir(os.path.join(overlap_path)) dates = sorted([f[:-2] for f in files if (f.endswith('_1') and len(f) > 10)]) folder = dates[0][0:4] + dates[0][5:7] + dates[0][8:10] os.chdir(os.path.join(stack_folder, folder, overlap[0:7])) line_start, line_length, first_pixel_this, first_pixel_next, pixel_length, this_nr_oflines, \ this_nr_ofpixels, next_nr_oflines, next_nr_ofpixels, PRF = get_coordinates(nBurst) # Remove earlier generated files for ps files = next(os.walk(overlap_path))[2] files = [os.path.join(overlap_path, name) for name in files if (name.endswith('ps') or name.startswith('ps'))] for filename in files: os.remove(filename) # Gather data in one matrix first, second = gather_stack(overlap_path, line_length, pixel_length) # First calculate the ps point for first overlap mean = np.mean(first, axis=2) std = np.std(first, axis=2) with np.errstate(divide='ignore', invalid='ignore'): c = np.true_divide(std, mean) c[~ np.isfinite(c)] = 10000 ps1 = (c < 0.3) ps1_file = os.path.join(overlap_path, 'ps_1') ps1_dat = np.memmap(ps1_file, 'bool', mode= 'w+', shape=(line_length, pixel_length)) ps1_dat[:,:] = ps1[:,:] # Then calculate the ps point for second overlap mean = np.mean(second, axis=2) std = np.std(second, axis=2) with np.errstate(divide='ignore', invalid='ignore'): c = np.true_divide(std, mean) c[~ np.isfinite(c)] = 10000 ps2 = (c < 0.3) ps2_file = os.path.join(overlap_path, 'ps_2') ps2_dat = np.memmap(ps2_file, 'bool', mode= 'w+', shape=(line_length, pixel_length)) ps2_dat[:,:] = ps2[:,:] ps_file = os.path.join(overlap_path, 'ps') ps_dat = np.memmap(ps_file, 'bool', mode='w+', shape=(line_length, pixel_length)) ps_dat[:, :] = ((ps1_dat * ps2_dat) == 1) def select_ps_data(stack_folder, overlap): # This function creates seperate files for the values of the ps points only. esd_folder = os.path.join(stack_folder, 'esd') overlap_path = os.path.join(esd_folder, overlap) files = os.listdir(os.path.join(overlap_path)) dates = sorted([f[:-2] for f in files if (f.endswith('_1') and len(f) > 10)]) folder = dates[0][0:4] + dates[0][5:7] + dates[0][8:10] os.chdir(os.path.join(stack_folder, folder, overlap[0:7])) nBurst = int(overlap.split('_')[3]) line_start, line_length, first_pixel_this, first_pixel_next, pixel_length, this_nr_oflines, \ this_nr_ofpixels, next_nr_oflines, next_nr_ofpixels, PRF = get_coordinates(nBurst) ps_file = os.path.join(overlap_path, 'ps') ps_dat = np.memmap(ps_file, 'bool', mode='r', shape=(line_length, pixel_length)) ps_num = np.sum(ps_dat) # Save only the ps points to file. for date in dates: slave_ps_name = os.path.join(overlap_path, date + '_1_ps') master_ps_name = os.path.join(overlap_path, date + '_2_ps') if not os.path.exists(slave_ps_name) or not os.path.exists(master_ps_name): slave_ps = np.memmap(slave_ps_name, 'complex64', mode='w+', shape=(ps_num)) master_ps = np.memmap(master_ps_name, 'complex64', mode='w+', shape=(ps_num)) slave = np.memmap(os.path.join(overlap_path, date + '_1'), 'complex64', mode='r', shape=(line_length, pixel_length)) master = np.memmap(os.path.join(overlap_path, date + '_2'), 'complex64', mode='r', shape=(line_length, pixel_length)) if ps_num > 0: slave_ps[:] = slave[ps_dat] master_ps[:] = master[ps_dat] # Do the same for the df_dc file if not os.path.exists(os.path.join(overlap_path, 'df_dc_ps')): df_dc_ps = np.memmap(os.path.join(overlap_path, 'df_dc_ps'), 'float32', mode='w+', shape=(ps_num)) df_dc = np.memmap(os.path.join(overlap_path, 'df_dc'), 'float32', mode='r', shape=(line_length, pixel_length)) if ps_num > 0: df_dc_ps[:] = df_dc[ps_dat] def network_esd_ps(stack_folder, overlap, master_date, max_baseline, max_offset=0.02): # Based on ps point esd is calculated using a network approach dates, overlap_path, diff_matrix, var_matrix, to_angle_matrix, weight_matrix, processing = prepare_esd(stack_folder, overlap) folder = dates[0][0:4] + dates[0][5:7] + dates[0][8:10] os.chdir(os.path.join(stack_folder, folder, overlap[0:7])) nBurst = int(overlap.split('_')[3]) line_start, line_length, first_pixel_this, first_pixel_next, pixel_length, this_nr_oflines, \ this_nr_ofpixels, next_nr_oflines, next_nr_ofpixels, PRF = get_coordinates(nBurst) ps_file = os.path.join(overlap_path, 'ps') ps_dat = np.memmap(ps_file, 'bool', mode='r', shape=(line_length, pixel_length)) ps_id = np.where(ps_dat == 1) if not ps_id: # If there are no ps points return diff_matrix, var_matrix, weight_matrix, to_angle_matrix else: ps_num = len(ps_id[0]) df_dc_ps = np.memmap(os.path.join(overlap_path, 'df_dc_ps'), 'float32', mode='r+', shape=ps_num)[:] for date, n in zip(dates, range(len(dates))): for date_2, num in zip(dates, range(len(dates))): # Only calculate the upper triangle, as the others will be the same if processing[n, num] == 1: continue timediff = datetime.strptime(date_2, '%Y-%m-%d') - datetime.strptime(date, '%Y-%m-%d') if timediff > timedelta(minutes=1) and timediff < timedelta(days=max_baseline): first_master = np.memmap(os.path.join(overlap_path, date + '_1_ps'), 'complex64', mode='r', shape=ps_num) first_slave = np.memmap(os.path.join(overlap_path, date_2 + '_1_ps'), 'complex64', mode='r', shape=ps_num) second_master = np.memmap(os.path.join(overlap_path, date + '_2_ps'), 'complex64', mode='r', shape=ps_num) second_slave = np.memmap(os.path.join(overlap_path, date_2 + '_2_ps'), 'complex64', mode='r', shape=ps_num) double_diff = (first_master * first_slave.conj()) * (second_master * second_slave.conj()).conj() # Now select all pixels with an offset of less than x milipixel double_diff[np.isnan(double_diff)] = 0.050 val = (np.abs(np.angle(double_diff)) < max_offset) w = np.sum(val) if w > 0: pixel_diff = np.angle(np.sum(double_diff[val])) * (PRF / (2 * np.pi * np.nanmean(df_dc_ps[val]))) pixel_var = np.var(np.angle(double_diff[val]) * (PRF/(2*np.pi*df_dc_ps[val]))) temp_baseline_w = np.exp(-(float(timediff.days) / 100)) weight_matrix[0, n, num] = temp_baseline_w * w var_matrix[0, n, num] = pixel_var * temp_baseline_w diff_matrix[0, n, num] = pixel_diff # Phase ramp per pixel to_angle_matrix[0, n, num] = (PRF/(2*np.pi*np.nanmean(df_dc_ps[val]))) * (line_start - 1) return diff_matrix, var_matrix, to_angle_matrix, weight_matrix, dates def network_esd_coh(stack_folder, overlap, master_date, max_baseline, ra=10, az=2): dates, overlap_path, diff_matrix, var_matrix, to_angle_matrix, weight_matrix, processed = prepare_esd(stack_folder, overlap) folder = master_date[0:4] + master_date[5:7] + master_date[8:10] + "_" + dates[0][0:4] + dates[0][5:7] + dates[0][8:10] os.chdir(os.path.join(stack_folder, folder, overlap[0:7])) nBurst = int(overlap.split('_')[3]) line_start, line_length, first_pixel_this, first_pixel_next, pixel_length, this_nr_oflines, \ this_nr_ofpixels, next_nr_oflines, next_nr_ofpixels, PRF = get_coordinates(nBurst) # Gather data in one matrix first, second = gather_stack(overlap_path, line_length, pixel_length, abs=False) # Remove the empty rows / columns columns = np.where((np.min(np.abs(np.sum(first, axis=0)), axis=1) != 0) * (np.min(np.abs(np.sum(second, axis=0)), axis=1) != 0) == True)[0] rows = np.where((np.min(np.abs(np.sum(first, axis=1)), axis=1) != 0) * (np.min(np.abs(np.sum(second, axis=1)), axis=1) != 0) == True)[0] first = first[rows[0]:rows[-1]+1, columns[0]:columns[-1]+1, :] second = second[rows[0]:rows[-1]+1, columns[0]:columns[-1]+1, :] # Multilook the df_dc df_dc = np.memmap(os.path.join(overlap_path, 'df_dc'), 'float32', mode='r+', shape=(line_length, pixel_length)) df_dc_ml = multilook(df_dc[rows[0]:rows[-1]+1, columns[0]:columns[-1]+1], az, ra) for date, n in zip(dates, range(len(dates))): # First select the dates we want to compare with c_dates = [] nums = [] for date_2, num in zip(dates, range(len(dates))): # Only calculate the upper triangle, as the others will be the same timediff = datetime.strptime(date_2, '%Y-%m-%d') - datetime.strptime(date, '%Y-%m-%d') if timediff > timedelta(minutes=1) and timediff < timedelta(days=max_baseline) and processed[n, num] != 1: c_dates.append(date_2) nums.append(num) if len(c_dates) != 0: # Then create ifgs of first and second shape_ifg = (first.shape[0], first.shape[1], len(nums)) first_ifg = np.memmap(os.path.join(overlap_path, 'first_ifg'), 'complex64', shape=shape_ifg, mode='w+') first_ifg[:] = first[: ,: ,n][:, :, None] * first[:, :, nums].conj() second_ifg = np.memmap(os.path.join(overlap_path, 'second_ifg'), 'complex64', shape=shape_ifg, mode='w+') second_ifg[:] = second[:, :, n][:, :, None] * second[:, :, nums].conj() # And the double difference double_diff = np.memmap(os.path.join(overlap_path, 'double_diff'), 'complex64', shape=shape_ifg, mode='w+') double_diff[:] = first_ifg * second_ifg.conj() double_diff = multilook(double_diff, az, ra, summation=True) diff_phase = np.angle(double_diff) diff_amp = np.abs(double_diff) # Calculate coherence amp_sq = np.memmap(os.path.join(overlap_path, 'amp_sq'), 'float32', shape=shape_ifg, mode='w+') amp_sq[:] = (np.real(first_ifg) ** 2 + np.imag(first_ifg) ** 2) * (np.real(second_ifg) ** 2 + np.imag(second_ifg) ** 2) coh_amp_sq = multilook(amp_sq, az, ra, summation=True) coh = diff_amp / np.sqrt(coh_amp_sq) # Calculate weights coh[coh == 1] = 0 weight = 2 * az * ra * coh**2 / (1 - coh**2) tot_weight = np.sum(np.sum(weight, axis=0), axis=0) to_angle = PRF / (2 * np.pi * df_dc_ml) shift_pix = diff_phase * to_angle[:, :, None] shift = np.sum(np.sum(shift_pix * weight, axis=0), axis=0) / tot_weight to_angle_weighted = np.sum(np.sum(to_angle[:, :, None] * weight, axis=0), axis=0) / tot_weight var = np.sum(np.sum((shift[None, None, :] - shift_pix)**2 * weight, axis=0), axis=0) / tot_weight var_matrix[0, n, nums] = var diff_matrix[0, n, nums] = shift to_angle_matrix[0, n, nums] = to_angle_weighted weight_matrix[0, n, nums] = tot_weight return diff_matrix, var_matrix, to_angle_matrix, weight_matrix, dates def prepare_esd(stack_folder, overlap, esd_type='ps', load_existing=False): # Get some standard variables for the esd processing, used in both methods. esd_folder = os.path.join(stack_folder, 'esd') overlap_path = os.path.join(esd_folder, overlap) files = os.listdir(os.path.join(overlap_path)) dates = sorted([f[:-2] for f in files if (f.endswith('_1') and len(f) > 10)]) diff_matrix = np.zeros(shape=(1, len(dates), len(dates))) var_matrix = np.zeros(shape=(1, len(dates), len(dates))) to_angle_matrix = np.zeros(shape=(1, len(dates), len(dates))) weight_matrix = np.zeros(shape=(1, len(dates), len(dates))) processed = np.zeros(shape=(len(dates), len(dates))) # Now load the existing results if they are available. if load_existing == True: diff_m = np.load(os.path.join(overlap_path, esd_type + '_diff_matrix.npy')) var_m = np.load(os.path.join(overlap_path, esd_type + '_var_matrix.npy')) to_angle_m = np.load(os.path.join(overlap_path, esd_type + '_to_angle_matrix.npy')) weight_m = np.load(os.path.join(overlap_path, esd_type + '_weight_matrix.npy')) old_dates = np.load(os.path.join(overlap_path, esd_type + '_dates.npy')) dates_overlap = [id for id, date in zip(range(len(dates)), old_dates) if date in dates] diff_matrix[np.ix_(1, dates_overlap, dates_overlap)] = diff_m var_matrix[np.ix_(1, dates_overlap, dates_overlap)] = var_m to_angle_matrix[np.ix_(1, dates_overlap, dates_overlap)] = to_angle_m weight_matrix[np.ix_(1, dates_overlap, dates_overlap)] = weight_m processed[np.ix_(dates_overlap, dates_overlap)] = 1 return dates, overlap_path, diff_matrix, var_matrix, to_angle_matrix, weight_matrix, processed def gather_stack(overlap_path, line_length, pixel_length, abs=True): # This function gathers all data from different date into 2 3D matrices files = os.listdir(overlap_path) first_files = [os.path.join(overlap_path, f) for f in files if f.endswith('_1') and len(f) > 10] first_name = os.path.join(overlap_path, 'first') if os.path.exists(first_name): os.remove(first_name) if abs: first = np.memmap(first_name, 'float32', shape=(line_length, pixel_length, len(first_files)), mode='w+') else: first = np.memmap(first_name, 'complex64', shape=(line_length, pixel_length, len(first_files)), mode='w+') for f, n in zip(first_files, range(len(first_files))): first_dat = np.memmap(f, 'complex64', mode='r', shape=(line_length, pixel_length)) if abs: first[:, :, n] = np.abs(first_dat[:, :]) else: first[:, :, n] = first_dat[:, :] second_files = [os.path.join(overlap_path, f) for f in files if f.endswith('_2') and len(f) > 10] second_name = os.path.join(overlap_path, 'second') if os.path.exists(second_name): os.remove(second_name) if abs: second = np.memmap(second_name, 'float32', shape=(line_length, pixel_length, len(second_files)), mode='w+') else: second = np.memmap(second_name, 'complex64', shape=(line_length, pixel_length, len(second_files)), mode='w+') for f, n in zip(second_files, range(len(second_files))): second_dat = np.memmap(f, 'complex64', mode='r', shape=(line_length, pixel_length)) if abs: second[:, :, n] = np.abs(second_dat[:, :]) else: second[:, :, n] = second_dat[:, :] return first, second def multilook(matrix, az, ra, summation=False): # This function multilooks a matrix, which is either in 2D or 3D. In the case of 3D the third dimension is # considered the time dimension. If summation is True we do not average but sum the values in the multilooking area. # Multilooking always starts at the first range/azimuth pixel. # First downsample 2 * 10 new_ra = matrix.shape[1] / ra new_az = matrix.shape[0] / az size = matrix.shape if len(size) == 3 and summation == False: matrix_multilook = matrix[:new_az * az, :new_ra * ra, :].reshape([new_az, az, new_ra, ra, size[2]]).mean(3).mean(1) elif len(size) == 2 and summation == False: matrix_multilook = matrix[:new_az * az, :new_ra * ra].reshape([new_az, az, new_ra, ra]).mean(3).mean(1) elif len(size) == 3 and summation == True: matrix_multilook = matrix[:new_az * az, :new_ra * ra, :].reshape([new_az, az, new_ra, ra, size[2]]).mean(3).mean(1) elif len(size) == 2 and summation == True: matrix_multilook = matrix[:new_az * az, :new_ra * ra].reshape([new_az, az, new_ra, ra]).mean(3).mean(1) else: print('matrix does not have the right size') return [] matrix_multilook = matrix_multilook.astype(matrix_multilook.dtype, subok=False) return matrix_multilook def get_burst(overlap): s = overlap.split('_') burst = s[0] + '_' + s[1] + '_' + s[2] + '_' + s[3] next_burst = s[4] + '_' + s[5] + '_' + s[6] + '_' + s[7] nBurst = int(s[3]) return nBurst, burst, next_burst def swath_path(stack_folder, date, key): date_folder = date[:4] + date[5:7] + date[8:10] swath_burst = key.split('_') file_path = os.path.join(stack_folder, date_folder, swath_burst[0] + '_' + swath_burst[1]) return file_path def master_file(key): # This function converts combinations of dates and keys to a datafile name string = '_iw_' + key[6] + '_burst_' + key[14:] string = 'master' + string + '.raw' return string # Actually execute the code... if __name__ == "__main__": ps_select = '1' if len(sys.argv) == 7: stack_folder = sys.argv[1] overlap = sys.argv[2] esd_type = sys.argv[3] max_baseline = sys.argv[4] master_date = sys.argv[5] ps_select = sys.argv[6] # Use 1 if needed, use 0 if not elif len(sys.argv) == 6: stack_folder = sys.argv[1] overlap = sys.argv[2] esd_type = sys.argv[3] max_baseline = sys.argv[4] master_date = sys.argv[5] else: sys.exit('usage: stack_folder type burst') print('stack folder is ' + stack_folder) print('burst is ' + overlap) print('ps select is ' + ps_select) print('max baseline is ' + max_baseline) print('master date is ' + master_date) print('type ESD is ' + esd_type) # first get all the dates from the stack: master_key = master_date[:4] + master_date[5:7] + master_date[8:] ifgs = [f for f in os.listdir(stack_folder) if len(f) == 8] dates = [f[:4] + '-' + f[4:6] + '-' + f[6:8] for f in ifgs if f != master_key] # Then run the overlap cutout / ps selection and save_overlapping(stack_folder, master_date, dates, overlap) # If we want to select ps points if ps_select == '1': find_ps_overlapping(stack_folder, overlap) # Get the esd results for the overlapping areas either based on ps or coherence max_baseline = int(max_baseline) if esd_type == 'ps': select_ps_data(stack_folder, overlap) diff_matrix, var_matrix, to_angle_matrix, weight, dates = network_esd_ps(stack_folder, overlap, master_date, max_baseline) elif esd_type == 'coh': diff_matrix, var_matrix, to_angle_matrix, weight, dates = network_esd_coh(stack_folder, overlap, master_date, max_baseline) else: sys.exit('Type should either be coh or ps') # And save them in the corresponding folder: folder = os.path.join(stack_folder, 'esd', overlap) np.save(os.path.join(folder, esd_type + '_diff_matrix'), diff_matrix) np.save(os.path.join(folder, esd_type + '_var_matrix'), var_matrix) np.save(os.path.join(folder, esd_type + '_to_angle_matrix'), to_angle_matrix) np.save(os.path.join(folder, esd_type + '_weight_matrix'), weight) np.save(os.path.join(folder, esd_type + '_dates'), dates) Doris-5.0.3Beta/doris_stack/functions/__init__.py000077500000000000000000000000001312547014700220160ustar00rootroot00000000000000Doris-5.0.3Beta/doris_stack/functions/baselines.py000077500000000000000000000063671312547014700222520ustar00rootroot00000000000000import os import numpy as np import warnings from shutil import copyfile from doris.doris_stack.main_code.resdata import ResData import datetime import subprocess def baselines(dir_in,inputfile,start_date='2014-01-01',end_date='2018-01-01',doris=''): # This function calculates the baselines and plots a baseline plot. # Define doris path if not doris: doris = doris_path if not os.path.exists(dir_in): warnings.warn('The input directory does not exist!') return os.chdir(dir_in) process_folder = os.path.join(dir_in, 'baseline_process') if not os.path.exists(process_folder): os.mkdir(process_folder) os.chdir(process_folder) try: first = np.datetime64(start_date) last = np.datetime64(end_date) except: warnings.warn('Input dates could not be converted, use "yyyy-mm-dd"') return # Search for folders and take only the first burst. folders = next(os.walk(dir_in))[1] folders = sorted(folders) # Initialize... (Search for folders / resfiles / dates) n = 0 res = []; date = [] for fold in folders: # Select only the folders which has a name like yyyymmdd and are within if len(fold) == 8: # define date of folder date_prod = np.datetime64((fold[:4] + '-' + fold[4:6] + '-' + fold[6:])) if date_prod >= first and date_prod <= last: # Select the first swath date_fold = os.path.join(dir_in,fold) swath_fold = os.path.join(date_fold,next(os.walk(date_fold))[1][0]) # Select the first burst prod_files = next(os.walk(swath_fold))[2] for file in prod_files: if file.endswith('1.res'): res.extend([os.path.join(swath_fold,file)]) date.extend([date_prod]) n = n + 1 break # Now create a set of baselines baselines = np.zeros([len(res),len(res)]) resfiles = dict() # First create the ifgs.res files and store the data in a res data class. master = res[0] copyfile(master,os.path.join(process_folder,'master.res')) for resultfile, dat in zip(res, date): copyfile(resultfile,os.path.join(process_folder,'slave.res')) subprocess.call([doris + ' ' + inputfile], shell=True) dat = dat.astype(datetime.datetime).strftime('%Y-%m-%d') resfiles[dat] = ResData(type='interferogram',filename='ifgs.res') resfiles[dat].read() os.remove(os.path.join(process_folder,'ifgs.res')) # Then gather the baselines for dat, j in zip(date, range(len(date))): dat = dat.astype(datetime.datetime).strftime('%Y-%m-%d') baselines[j,0] = resfiles[dat].processes['coarse_orbits']['Bperp'][1] # Create figure of baselines. days = (date[0] - date).astype(float) plt.figure(111) plt.plot(baselines[:,0], days, marker='o') # Annotate for dat, x, y in zip(date, baselines[:,0], days): dat = dat.astype(datetime.datetime).strftime('%Y-%m-%d') plt.annotate( dat, xy = (x, y), xytext = (0, 0), textcoords = 'offset points', size = 8) plt.savefig('baseline_plot.pdf') Doris-5.0.3Beta/doris_stack/functions/burst_metadata.py000077500000000000000000000162461312547014700233010ustar00rootroot00000000000000# Based on the orbit of the swath the orbits of the individual burst is calculated. from orbit_coordinates import lph2xyz, xyz2ell, intrp_orbit import os import numpy as np import collections from datetime import datetime from doris.doris_stack.functions.resdata import ResData from shapely.geometry import Polygon def burst_header(resID): meta = collections.OrderedDict() meta['row_1'] = ['===============================================\n'] meta['MASTER RESULTFILE:'] = resID meta['Created by'] = 'G.Mulder TU Delft' meta['row_2'] = 'Doris (Delft o-o Radar Interferometric Software)' meta['Version'] = 'Version (2015) (For TOPSAR)' meta['FFTW library'] = 'used' meta['VECLIB library'] = 'not used' meta['LAPACK library'] = 'not used' meta['Compiled at'] = 'XXXXXXXX' meta['By GUN gcc'] = 'XXXXXXXX' meta['row_3'] = ['===============================================\n'] return meta def burst_readfiles(meta, burst_num, burst_center, burst_border, swath_data): # First copy swath metadata for burst and create a georef dict which stores information about the geo reference of # the burst. meta['Burst_number_index'] = str(burst_num) aux = meta['aux'] aux['azimuthPRF'] = [meta['Pulse_Repetition_Frequency (computed, Hz)']] meta.pop('aux') # First find coordinates of center and optionally the corners meta['Scene_centre_longitude'] = str(burst_center[0]) meta['Scene_centre_latitude'] = str(burst_center[1]) meta['Scene_ul_corner_latitude'] = str(burst_border[0][1]) meta['Scene_ur_corner_latitude'] = str(burst_border[1][1]) meta['Scene_lr_corner_latitude'] = str(burst_border[2][1]) meta['Scene_ll_corner_latitude'] = str(burst_border[3][1]) meta['Scene_ul_corner_longitude'] = str(burst_border[0][0]) meta['Scene_ur_corner_longitude'] = str(burst_border[1][0]) meta['Scene_lr_corner_longitude'] = str(burst_border[2][0]) meta['Scene_ll_corner_longitude'] = str(burst_border[3][0]) # Find doppler centroid frequency and azimuth reference time doppler_times = [np.datetime64(aux['doppler_azimuth_Time'][i] + '-00') for i in range(len(aux['doppler_azimuth_Time']))] frequency_times = [np.datetime64(aux['doppler_azimuth_Time'][i] + '-00') for i in range(len(aux['doppler_azimuth_Time']))] burst_start_time = np.datetime64(aux['azimuthTimeStart'][burst_num-1] + '-00') meta['First_pixel_azimuth_time (UTC)'] = burst_start_time.astype(datetime).strftime('%Y-%b-%d %H:%M:%S.%f') # First index after start burst for doppler and azimuth doppler_id = np.where(doppler_times > burst_start_time) frequency_id = np.where(frequency_times > burst_start_time) # Assign DC values to metadata if len(doppler_id[0]) > 0: doppler_id = np.min(doppler_id) parameter = aux['dopplerCoeff'][doppler_id].split() meta['DC_reference_azimuth_time'] = np.datetime64(aux['doppler_azimuth_Time'][doppler_id] + '-00').astype(datetime).strftime('%Y-%b-%d %H:%M:%S.%f') meta['DC_reference_range_time'] = aux['doppler_range_Time'][doppler_id] else: parameter = ['0.0','0.0','0.0'] meta['DC_reference_azimuth_time'] = '0.0 0.0' meta['DC_reference_range_time'] = aux['doppler_range_Time'][-1] # Assign parameters meta['Xtrack_f_DC_constant (Hz, early edge)'] = parameter[0] meta['Xtrack_f_DC_linear (Hz/s, early edge)'] = parameter[1] meta['Xtrack_f_DC_quadratic (Hz/s/s, early edge)'] = parameter[2] # Assign FM values to metadata if len(frequency_id[0]) > 0: frequency_id = np.min(frequency_id) if aux['azimuthFmRate_c0']: parameter = [aux['azimuthFmRate_c0'][frequency_id],aux['azimuthFmRate_c1'][frequency_id],aux['azimuthFmRate_c2'][frequency_id]] else: parameter = aux['azimuthFmRatePolynomial'][frequency_id].split() meta['FM_reference_azimuth_time'] = np.datetime64(aux['azimuthFmRate_reference_Azimuth_time'][frequency_id] + '-00').astype(datetime).strftime('%Y-%b-%d %H:%M:%S.%f') meta['FM_reference_range_time'] = aux['azimuthFmRate_reference_Range_time'][frequency_id] else: parameter = ['0.0','0.0','0.0'] meta['doppler_azimuth_Time'] = '0.0 0.0' meta['FM_reference_range_time'] = aux['azimuthFmRate_reference_Range_time'][-1] # Assign parameters meta['FM_polynomial_constant_coeff (Hz, early edge)'] = parameter[0] meta['FM_polynomial_linear_coeff (Hz/s, early edge)'] = parameter[1] meta['FM_polynomial_quadratic_coeff (Hz/s/s, early edge)'] = parameter[2] # Add information about swath meta['row_1'] = ['******************************************************************'] meta['Datafile'] = os.path.basename(swath_data) meta['Dataformat'] = 'tiff' meta['Number_of_lines_original'] = aux['imageLines'][0] meta['Number_of_pixels_original'] = aux['imagePixels'][0] meta['deramp'] = '0' meta['reramp'] = '0' meta['ESD_correct'] = '0' return meta def burst_crop(meta,burst_num,swath_data,new_burst_num): # This function returns a description of the crop files part, which defines how the burst is cropped out of the # swath data. This function is generally called when the .res and raw data is written to the datastack and uses one # of the outputs from the burst_readfiles crop = collections.OrderedDict() last_sample = [int(x) for x in meta['aux']['lastValidSample'][burst_num-1].split()] first_sample = [int(x) for x in meta['aux']['firstValidSample'][burst_num-1].split()] swath_data = os.path.basename(swath_data) crop['Data_output_file'] = 'slave_iw_' + swath_data[6] + '_burst_' + str(new_burst_num) + '.raw' crop['Data_output_format'] = 'complex_short' # Start line of this burst in total swath product lines = meta['aux']['imageLines'][0] extra_lines = int(lines) * (burst_num-1) # All coordinates are one based (e.g. we start at pixel 1) halfway = int(len(last_sample)/2) crop['First_line (w.r.t. tiff_image)'] = str(1 + last_sample[:halfway].count(-1) + extra_lines) crop['Last_line (w.r.t. tiff_image)'] = str(len(last_sample) - last_sample[halfway:].count(-1) + extra_lines) crop['First_line (w.r.t. original_image)'] = str(1 + last_sample[:halfway].count(-1)) crop['Last_line (w.r.t. original_image)'] = str(len(last_sample) - last_sample[halfway:].count(-1)) crop['First_pixel (w.r.t. original_image)'] = str(max(first_sample)) crop['Last_pixel (w.r.t. original_image)'] = str(max(last_sample)) return crop def center_shape_from_res(resfile): # This function reads the shape and center of a burst from a .res file. res = ResData(resfile) res.res_read() meta = res.processes['readfiles'] center = (float(meta['Scene_centre_longitude']), float(meta['Scene_centre_latitude'])) ul = (float(meta['Scene_ul_corner_longitude']), float(meta['Scene_ul_corner_latitude'])) ur = (float(meta['Scene_ur_corner_longitude']), float(meta['Scene_ur_corner_latitude'])) lr = (float(meta['Scene_lr_corner_longitude']), float(meta['Scene_lr_corner_latitude'])) ll = (float(meta['Scene_ll_corner_longitude']), float(meta['Scene_ll_corner_latitude'])) coverage = Polygon([ul, ur, lr, ll]) return center, coverageDoris-5.0.3Beta/doris_stack/functions/cleanup_stack.py000066400000000000000000000135011312547014700231020ustar00rootroot00000000000000# This script can be used to cleanup a datastack # In this script we use the following rational # 1. Data from the master date and ESD are always kept (can change when these scripts evolve) # 2. The last processing step is saved (or if different processing steps are connected and the last one is not finished yet # 3. All .res and .ras files are kept. # 4. Following steps are never deleted > resampled slave / subt_refdem / filtphase (multilooked) / coherence (multilooked) / unwrap import os import sys from doris.doris_stack.main_code.resdata import ResData def res_file_selection(path, dat_type='burst'): # Give an oversight of all files connected to different steps: del_files = [] res_dat = dict() # First check if slave / master / ifgs res files are there for res_type in ['master', 'slave', 'ifgs']: if os.path.exists(os.path.join(path, res_type + '.res')): res_dat[res_type] = ResData(os.path.join(path, res_type + '.res'), type=res_type) else: print('No data found in ' + path) return [] if res_dat['slave'].process_control['readfiles'] == '1' and res_dat['slave'].process_control['crop'] == '1': if res_dat['slave'].processes['readfiles']['deramp'] == '1': # Remove the ramped image data. del_files.append(res_dat['slave'].processes['crop']['Data_output_file'][:-12] + '.raw') if res_dat['ifgs'].process_control['dem_assist'] == '1': # Remove the temporary files for dem_assist del_files.extend(['dac_delta_demline.temp', 'dac_delta_dempixel.temp', 'dac_m_demline.temp', 'dac_m_dempixel.temp']) if res_dat['slave'].process_control['resample'] == '1' and res_dat['ifgs'].process_control['dem_assist'] == '1': del_files.extend(['dac_delta_line.raw', 'dac_delta_pixel.raw']) if res_dat['slave'].process_control['resample'] == '1': # After resampling the deramped file is not needed anymore. Also processing data from resampling is not needed. del_files.append(res_dat['slave'].processes['crop']['Data_output_file']) del_files.extend(['rsmp_orig_slave_line.raw', 'rsmp_orig_slave_pixel.raw']) # Now the resampled slave stays. if res_dat['ifgs'].process_control['subtr_refphase'] == '1': # If the reference phase is subtracted both the reramped slave and interferogram can be removed del_files.extend(['cint.raw', 'slave_rsmp_reramped.raw']) if res_dat['ifgs'].process_control['subtr_refdem'] == '1': # When the dem phase is removed, the interferogram with subtracted reference phase can be removed. del_files.extend(['cint.raw', 'cint_srp.raw', 'demcrop.raw', 'dem_radar.raw', 'master_slave.crd']) if res_dat['ifgs'].process_control['filtphase'] == '1': # When after the the removal of the reference dem the filtphase step is done, the subtrefdem ifgs is removed. del_files.extend(['cint.raw', 'cint_srp.raw', 'cint_srd.raw', 'demcrop.raw', 'dem_radar.raw', 'master_slave.crd']) # Finally if it is about a burst image, we can check whether the filtered and coherence files are already # concatenated, which means they can be removed. image_ifgs = os.path.join(os.path.dirname(os.path.dirname(path)), 'ifgs.res') if dat_type == 'burst' and os.path.exists(image_ifgs): # If there is a ifgs.res file for the full image. image_res = ResData(image_ifgs) if image_res.process_control['coherence'] == '1': del_files.append('coherence.raw') if image_res.process_control['filtphase'] == '1': del_files.append('cint.0.2filtered') if image_res.process_control['filtphase'] == '1': del_files.append('cint.0.2filtered') elif dat_type == 'image': # If we are looking at the full image, is it important to remove the non-multilooked coherence or filtered image if res_dat['ifgs'].process_control['filtphase'] == '1': if res_dat['ifgs'].processes['filtphase']['Data_output_file'].endswith('ml.raw'): del_files.append('cint.0.2filtered') if res_dat['ifgs'].process_control['coherence'] == '1': if res_dat['ifgs'].processes['coherence']['Data_output_file'].endswith('ml.raw'): del_files.append('coherence.raw') del_files = set(del_files) del_files = [os.path.join(path, del_file) for del_file in del_files] del_files = [del_file for del_file in del_files if os.path.exists(del_file)] return del_files def cleanup_stack(path, master_key): # This is the main cleanup function. folders = next(os.walk(path))[1] if not master_key in folders: print('master folder not found in path') return else: folders.remove(master_key) del_files = [] for folder in folders: del_dat = res_file_selection(os.path.join(path, folder), dat_type='image') del_files.extend(del_dat) burst_folders = find_burst_folders(os.path.join(path, folder)) for burst_folder in burst_folders: del_dat = res_file_selection(os.path.join(path, burst_folder), dat_type='burst') del_files.extend(del_dat) for filename in del_files: print('removing: ' + filename) os.remove(filename) print('Succes! path ' + path + ' is cleaned from temporary files.') def find_burst_folders(folder): # This function finds all the burst folders in an image folder folders = [] swaths = next(os.walk(folder))[1] for swath in swaths: bursts = next(os.walk(os.path.join(folder, swath)))[1] for burst in bursts: folders.append(os.path.join(folder, swath, burst)) return folders # Actually execute the code... if __name__ == "__main__": path = sys.argv[1] master_key = sys.argv[2] print('path to be cleaned ' + path) print('master key is ' + master_key) cleanup_stack(path, master_key) Doris-5.0.3Beta/doris_stack/functions/compassbearing.py000077500000000000000000000015261312547014700232720ustar00rootroot00000000000000import math def calculate_initial_compass_bearing(pointA, pointB): if (type(pointA) != tuple) or (type(pointB) != tuple): raise TypeError("Only tuples are supported as arguments") lat1 = math.radians(pointA[0]) lat2 = math.radians(pointB[0]) diffLong = math.radians(pointB[1] - pointA[1]) x = math.sin(diffLong) * math.cos(lat2) y = math.cos(lat1) * math.sin(lat2) - (math.sin(lat1) * math.cos(lat2) * math.cos(diffLong)) initial_bearing = math.atan2(x, y) # Now we have the initial bearing but math.atan2 return values # from -180 to + 180 which is not what we want for a compass bearing # The solution is to normalize the initial bearing as shown below initial_bearing = math.degrees(initial_bearing) compass_bearing = (initial_bearing + 360) % 360 return compass_bearingDoris-5.0.3Beta/doris_stack/functions/concatenate_decatenate.py000077500000000000000000000221741312547014700247400ustar00rootroot00000000000000from doris.doris_stack.main_code.resdata import ResData import numpy as np import os, sys def decatenate(date_folder, image_file, burst_file, datatype, multilooked='none', res_type='master'): # Decatenate data. # Multilooks can be none > not concatenated, only > only multilooked images are concatenated or > # all > both original and multilooked images are concatenated. if len(multilooked) == 7: master = os.path.join(date_folder, image_file[:-4] + '_' + multilooked + '.raw') else: master = os.path.join(date_folder, image_file) # Load .res files image_res, burst_res = read_res(date_folder, type=res_type) # Read image size bursts = burst_res.keys() if multilooked != 'none': try: no_lines = int(burst_res[bursts[0]].processes['readfiles']['Number_of_ml_lines_output_image']) no_pixels = int(burst_res[bursts[0]].processes['readfiles']['Number_of_ml_pixels_output_image']) except: print('Not able to load multilooking parameters for ' + image_file) return else: no_lines = int(burst_res[bursts[0]].processes['readfiles']['Number_of_lines_output_image']) no_pixels = int(burst_res[bursts[0]].processes['readfiles']['Number_of_pixels_output_image']) # First use memmap to get a memory map of the full file. full_image = np.memmap(master, dtype=datatype, mode='r', shape=(no_lines, no_pixels)) for burst in bursts: # Finally write all data from individual bursts to master file. We assume a simple 20 pixel offset from # the side to prevent copying data without information. burst_dat, line_0, line_1, pix_0, pix_1, burst_pix, burst_line, az_offset, ra_offset = \ burst_info(burst, burst_file, burst_res, multilooked) # Cut out data with border of 20 px and write to file. burst_image = np.memmap(burst_dat, dtype=datatype, mode='w+', shape=(burst_line, burst_pix)) burst_image[:, :] = full_image[line_0-1:line_1, pix_0-1:pix_1] burst_image.flush() def concatenate(date_folder, image_file, burst_file, datatype, multilooked='none', res_type='master'): # Concatenate data. if len(multilooked) == 7: master = os.path.join(date_folder, image_file[:-4] + '_' + multilooked + '.raw') else: master = os.path.join(date_folder, image_file) # Load .res files image_res, burst_res = read_res(date_folder, type=res_type) # Read image size bursts = burst_res.keys() if multilooked != 'none': try: no_lines = int(burst_res[bursts[0]].processes['readfiles']['Number_of_ml_lines_output_image']) no_pixels = int(burst_res[bursts[0]].processes['readfiles']['Number_of_ml_pixels_output_image']) except: print('Not able to load multilooking parameters for ' + image_file) return else: no_lines = int(burst_res[bursts[0]].processes['readfiles']['Number_of_lines_output_image']) no_pixels = int(burst_res[bursts[0]].processes['readfiles']['Number_of_pixels_output_image']) # First use memmap to get a memory map of the full file. full_image = np.memmap(master, dtype=datatype, mode='w+', shape=(no_lines, no_pixels)) for burst in bursts: # Finally write all data from individual bursts to master file. We assume a simple 20 pixel offset from # the side to prevent copying data without information. (corrected with multilooking factor) burst_dat, line_0, line_1, pix_0, pix_1, burst_pix, burst_line, daz, dra = \ burst_info(burst, burst_file, burst_res, multilooked) # Cut out data with border of 20 px and write to file. burst_image = np.memmap(burst_dat, dtype=datatype, mode='r', shape=(burst_line,burst_pix)) full_image[(line_0+(daz-1)):(line_1-daz), (pix_0+(dra-1)):(pix_1-dra)] = burst_image[daz:-daz, dra:-dra] def burst_info(burst, burst_file, burst_res, multilooked='none'): # Information about this specific burst if burst_file == 'master.raw': if multilooked: string = '_iw_' + burst[6] + '_burst_' + burst[17:] + '_' + multilooked + '.raw' else: string = '_iw_' + burst[6] + '_burst_' + burst[17:] + '.raw' elif burst_file == 'master_deramped.raw': if multilooked: string = '_iw_' + burst[6] + '_burst_' + burst[17:] + '_deramped' + '_' + multilooked + '.raw' else: string = '_iw_' + burst[6] + '_burst_' + burst[17:] + '_deramped.raw' else: string = burst_file if len(multilooked) == 7: burst_dat = os.path.join(date_folder, burst[0:7], burst[8:], string[:-4] + '_' + multilooked + '.raw') line_0 = int(burst_res[burst].processes['readfiles']['First_line_' + multilooked]) line_1 = int(burst_res[burst].processes['readfiles']['Last_line_ml_' + multilooked]) pix_0 = int(burst_res[burst].processes['readfiles']['First_pixel_ml_' + multilooked]) pix_1 = int(burst_res[burst].processes['readfiles']['Last_pixel_ml_' + multilooked]) ra = int(burst_res[burst].processes['readfiles']['Multilook_range_' + multilooked]) az = int(burst_res[burst].processes['readfiles']['Multilook_azimuth_' + multilooked]) else: burst_dat = os.path.join(date_folder, burst[0:7], burst[8:], string) line_0 = int(burst_res[burst].processes['readfiles']['First_line (w.r.t. output_image)']) line_1 = int(burst_res[burst].processes['readfiles']['Last_line (w.r.t. output_image)']) pix_0 = int(burst_res[burst].processes['readfiles']['First_pixel (w.r.t. output_image)']) pix_1 = int(burst_res[burst].processes['readfiles']['Last_pixel (w.r.t. output_image)']) ra = 1 az = 1 az_offset = int(np.ceil(20 / float(az))) ra_offset = int(np.ceil(100 / float(ra))) burst_pix = pix_1 - pix_0 + 1 burst_line = line_1 - line_0 + 1 return burst_dat, line_0, line_1, pix_0, pix_1, burst_pix, burst_line, az_offset, ra_offset def read_res(date_folder, type='master'): # Read .res data to the burst objects. Generally done after a processing step. swaths = next(os.walk(date_folder))[1] swaths = [fol for fol in swaths if len(fol) == 7] res_burst = dict() for swath in swaths: bursts = next(os.walk(os.path.join(date_folder, swath)))[1] bursts = [burst for burst in bursts if burst.startswith('burst')] for burst in bursts: slave_res = os.path.join(date_folder, swath, burst, 'slave.res') master_res = os.path.join(date_folder, swath, burst, 'master.res') burst_name = swath + '_' + burst if type == 'master' and os.path.exists(master_res): res_burst[burst_name] = ResData(filename=master_res) elif type == 'slave' and os.path.exists(slave_res): res_burst[burst_name]= ResData(filename=slave_res) elif os.path.exists(master_res): res_burst[burst_name] = ResData(filename=master_res) elif os.path.exists(slave_res): res_burst[burst_name]= ResData(filename=slave_res) else: print('No burst master or slave image available') return slave_res = os.path.join(date_folder, 'slave.res') master_res = os.path.join(date_folder, 'master.res') if type == 'master' and os.path.exists(master_res): res_image = ResData(filename=master_res) elif type == 'slave' and os.path.exists(slave_res): res_image = ResData(filename=slave_res) elif os.path.exists(master_res): res_image = ResData(filename=master_res) elif os.path.exists(slave_res): res_image = ResData(filename=slave_res) else: print('No image master or slave image available') return return res_image, res_burst # Actually execute the code... if __name__ == "__main__": date_folder = sys.argv[1] type = sys.argv[2] burst_file = sys.argv[3] datatype = sys.argv[4] if len(sys.argv) > 5: multilooked = sys.argv[5] else: multilooked = 'False' if len(sys.argv) > 6: res_type = sys.argv[6] else: res_type = 'master' print('concatenate folder is ' + date_folder) print('burst_file is ' + burst_file) print('datatype is ' + datatype) print('concatenating multilooked image is ' + multilooked) if len(multilooked) == 7: # Multilooked should be given in a 7 length string azimuth multilook _ range multiloop # example '004_020' # The script detects whether this multilooking is available. Otherwise it will produce an error. multilooked = multilooked else: multilooked = 'none' image_file = burst_file if datatype == 'cpxint16' or datatype == 'complex_short': datatype = np.dtype([('re', np.int16), ('im', np.int16)]) if type == 'decatenate': decatenate(date_folder, image_file, burst_file, datatype, multilooked, res_type) elif type == 'concatenate': concatenate(date_folder, image_file, burst_file, datatype, multilooked, res_type) else: sys.exit('type should either be decatenate or concatenate') Doris-5.0.3Beta/doris_stack/functions/correct_ESD.py000077500000000000000000000034451312547014700224330ustar00rootroot00000000000000# This script is used to remove the residual ramp in the ifgs of individual bursts based on ESD estimates. import numpy as np import os, sys if __name__ == "__main__": # If calling script directly we have to load the package first to our python path folder = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) print(folder) sys.path.extend([folder]) from resdata import ResData def remove_ramp(file, angle_pixel): # Remove ramp from burst res_file = 'master.res' res_dat = ResData(res_file, 'master') crop = res_dat.processes['crop'] lines = int(crop['Last_line (w.r.t. original_image)']) - int(crop['First_line (w.r.t. original_image)']) + 1 pixels = int(crop['Last_pixel (w.r.t. original_image)']) - int(crop['First_pixel (w.r.t. original_image)']) + 1 n = np.arange(lines) phase_diff = n * angle_pixel complex_diff = np.cos(phase_diff).astype('complex64') + 1j * np.sin(phase_diff).astype('complex64') dat_file = np.memmap(file, dtype='complex64', mode='r+', shape=(lines, pixels)) p_before = np.nanmean(np.angle(dat_file)) print('Average phase before is ' + str(p_before)) dat_file[:, :] = dat_file * complex_diff.conj()[:, None] p_after = np.nanmean(np.angle(dat_file)) print('Average phase after is ' + str(p_after)) dat_file.flush() if __name__ == "__main__": # If calling script directly we run the remove_ramp function. if len(sys.argv) == 3: file = sys.argv[1] angle_pixel = sys.argv[2] # Use 1 if needed, use 0 if not else: sys.exit('usage: burst_folder, file, angle_per_pixel') print('file we will deramp is ' + file) print('the angle per pixel is ' + angle_pixel) angle_pixel = float(angle_pixel) remove_ramp(file, angle_pixel) Doris-5.0.3Beta/doris_stack/functions/create_image.py000066400000000000000000000010501312547014700226670ustar00rootroot00000000000000# This function creates images based on complex or real input data. # Input parameters are: # - Input matrix # - datatype # - Image scaling (are pixels for example 1x2 km or 3x1 km?) scaling is azimuth / range. # - Use of logscaling? # - Plot amplitude / phase / both (not relevant for real values...) # If you want to save your data as a geotiff or netcdf file use the read_write_data.py script. This will enable # visualization in for example QGIS or ArcGIS # If you want to do multilooking first apply the multilook.py script. def create_image(): Doris-5.0.3Beta/doris_stack/functions/do_deramp_SLC.py000077500000000000000000000062451312547014700227330ustar00rootroot00000000000000#!/usr/bin/env python import numpy as np from numpy import * from get_ramp import get_ramp from doris.doris_stack.functions.ESD_functions import freadbk from doris.doris_stack.main_code.resdata import ResData import sys def usage(): print '\nUsage: python do_deramp_SLC_nom.py dataFilename resFilename plotFlag' print ' where dataFilename is the name of burst you want to deramp' print ' resFilename is the .res file of burst' print ' plotFlag is a boolean var, to plot only' print ' default of doPlot is false' print ' This function removes the phase ramp (Doppler centroid variations) from single burst of' print ' RS2 or S1 TOPS acquisition. The original binary image at path ' print " DATAFILENAME is saved in 'DATAFILENAME'.orig, whereas the new instance " print ' will be characterized by baseband spectrum. The function also requires ' print ' the .res file RESFILENAME. ' print ' for example ' print ' python do_deramp_SLC.py 20140821_iw_2_burst_1.raw slave.res False ' print ' created by Gert Mulder' print ' Part of code adapted from Lorenzo Iannini and Wu Wenhao' try: dataFilename = sys.argv[1] resFilename = sys.argv[2] except: print 'Unrecognized input' usage() sys.exit(1) #*****************************************************************************# # Calculate chirp for deramping ChirpFilt = get_ramp(resFilename, resampled=0, type='chirp') res = ResData(resFilename) # Image size properties if res.process_control['oversample'] == '1': #oversampled data l0 = int(res.processes['oversample']['First_line (w.r.t. ovs_image)']) lN = int(res.processes['oversample']['Last_line (w.r.t. ovs_image)']) p0 = int(res.processes['oversample']['First_pixel (w.r.t. ovs_image)']) pN = int(res.processes['oversample']['Last_pixel (w.r.t. ovs_image)']) dataFormat = 'cpxfloat32' else: # original data l0 = int(res.processes['crop']['First_line (w.r.t. original_image)']) lN = int(res.processes['crop']['Last_line (w.r.t. original_image)']) p0 = int(res.processes['crop']['First_pixel (w.r.t. original_image)']) pN = int(res.processes['crop']['Last_pixel (w.r.t. original_image)']) dataFormat = 'cpxint16' # Image size Naz_res = lN-l0+1 Nrg_res = pN-p0+1 ################################################################################ # Read data slc = freadbk(dataFilename, 1, 1, int(Naz_res), int(Nrg_res), dataFormat, int(Naz_res), int(Nrg_res)) ####################################################################################### newFilename = dataFilename[:-4] + '_deramped.raw' fid = open(newFilename, 'wb') slc_deramped = conj(ChirpFilt)*slc del ChirpFilt del slc # %% Apply reramping if dataFormat == 'complex64': slc_dat = slc_deramped.astype(np.complex64) else: # cpxint16 slc_dat = np.zeros(shape=(int(Naz_res), int(Nrg_res) * 2)).astype('int16') slc_dat[:, 0::2] = np.real(slc_deramped) slc_dat[:, 1::2] = np.imag(slc_deramped) fid.write(slc_dat) fid.close() print "\nDeramp operation completed\n" Doris-5.0.3Beta/doris_stack/functions/do_reramp_SLC.py000077500000000000000000000070571312547014700227530ustar00rootroot00000000000000#!/usr/bin/env python import numpy as np from numpy import * from doris.doris_stack.functions.get_ramp import get_ramp from doris.doris_stack.functions.ESD_functions import freadbk from doris.doris_stack.main_code.resdata import ResData import sys def usage(): print '\nUsage: python do_reramp_SLC.py dataFilename resFilename resampled' print ' where dataFilename is the name of burst you want to deramp' print ' resFilename is the .res file of burst ' print ' This python applies the inverse phase ramp to the burst pointed by DATAFILENAME (slc)' print ' and RESFILENAME (res) that was deramped by deramp_SLC.m. The phase screen' print ' must account for the new resampled grids PIXRGGRID and PIXAZGRID ' print ' [Nlines_mst x Nsamples_mst] that contain the time coordinates of the' print ' resampled image into the master grid: ' print ' for example ' print ' python do_reramp_SLC.py slave_rsmp.raw slave.res False ' print ' created by Gert Mulder' print ' Part of code adapted from Lorenzo Iannini and Wu Wenhao' try: dataFilename = sys.argv[1] resFilename = sys.argv[2] except: print 'Unrecognized input' usage() sys.exit(1) if len(sys.argv) == 3: resampled = True elif len(sys.argv) == 4: resampled = sys.argv[3] else: print 'Unrecognized input' usage() sys.exit(1) # Read information ################################################################################ res = ResData(resFilename) # Image size properties if res.process_control['resample'] == '1': #oversampled data l0 = int(res.processes['resample']['First_line (w.r.t. original_master)']) lN = int(res.processes['resample']['Last_line (w.r.t. original_master)']) p0 = int(res.processes['resample']['First_pixel (w.r.t. original_master)']) pN = int(res.processes['resample']['Last_pixel (w.r.t. original_master)']) dataFormat = 'complex64' resampled = True else: # original data l0 = int(res.processes['crop']['First_line (w.r.t. original_image)']) lN = int(res.processes['crop']['Last_line (w.r.t. original_image)']) p0 = int(res.processes['crop']['First_pixel (w.r.t. original_image)']) pN = int(res.processes['crop']['Last_pixel (w.r.t. original_image)']) dataFormat = 'cpxint16' resampled = False # Get resampled Slv size Naz_res = lN-l0+1 Nrg_res = pN-p0+1 #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #% Obtain chirp % #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if not resampled: ChirpFilt = get_ramp(resFilename, resampled=0, type='chirp') elif resampled: ChirpFilt = get_ramp(resFilename, resampled=1, type='chirp') else: print('Resampled should be True or False') ################################################################################ # Read data slc = freadbk(dataFilename, 1, 1, int(Naz_res), int(Nrg_res), dataFormat, int(Naz_res), int(Nrg_res)) ####################################################################################### newFilename = dataFilename[:-4] + '_reramped.raw' fid = open(newFilename, 'wb') slc_reramped = slc * ChirpFilt del ChirpFilt del slc #%% Apply reramping if dataFormat == 'complex64': slc_dat = slc_reramped.astype(np.complex64) else: # cpxint16 slc_dat = np.zeros(shape=(int(Naz_res), int(Nrg_res) * 2)).astype('int16') slc_dat[:, 0::2] = np.real(slc_reramped) slc_dat[:, 1::2] = np.imag(slc_reramped) fid.write(slc_dat) fid.close() print "\nReramp operation completed\n" Doris-5.0.3Beta/doris_stack/functions/get_ramp.py000077500000000000000000000264621312547014700221010ustar00rootroot00000000000000import os import numpy as np import gdal from gdalconst import * import sys def get_ramp(res_file, resampled=0, type='chirp'): # Read information ################################################################################ #FM t0_FM = np.float64(get_parameter('FM_reference_range_time', res_file,1)) c0_FM = np.float64(get_parameter('FM_polynomial_constant_coeff (Hz, early edge)', res_file,1)) c1_FM = np.float64(get_parameter('FM_polynomial_linear_coeff (Hz/s, early edge)', res_file,1)) c2_FM = np.float64(get_parameter('FM_polynomial_quadratic_coeff (Hz/s/s, early edge)', res_file,1)) #DC azimuthTime_DC = get_parameter('DC_reference_azimuth_time', res_file,3) azimuthTime_DC = np.float64(azimuthTime_DC[0])*3600+float(azimuthTime_DC[1])*60+float(azimuthTime_DC[2]) t0_DC = np.float64(get_parameter('DC_reference_range_time',res_file,1)) c0_DC = np.float64(get_parameter('Xtrack_f_DC_constant (Hz, early edge)', res_file,1)) c1_DC = np.float64(get_parameter('Xtrack_f_DC_linear (Hz/s, early edge)', res_file,1)) c2_DC = np.float64(get_parameter('Xtrack_f_DC_quadratic (Hz/s/s, early edge)', res_file,1)) Ks = np.float64(get_parameter('Azimuth_steering_rate (deg/s)', res_file,1)) # Image sampling parameters Taz_start = get_parameter('First_pixel_azimuth_time (UTC)', res_file,3) Taz_start = np.float64(Taz_start[0])*3600+float(Taz_start[1])*60+float(Taz_start[2]) Trg_start = np.float64(get_parameter('Range_time_to_first_pixel (2way) (ms)', res_file,1))*1e-3 fsRg = np.float64(get_parameter('Range_sampling_rate (computed, MHz)', res_file,1)) dt_az = np.float64(get_parameter('Azimuth_time_interval (s)', res_file,1)) dt_rg = 1/fsRg/1e6 # Number of lines lNum = int(get_parameter('Number_of_lines_original', res_file,1)) if resampled == 1: l0 = int(get_parameter('First_line (w.r.t. original_master)', res_file,2,'*_Start_resample','* End_resample:_NORMAL')) lN = int(get_parameter('Last_line (w.r.t. original_master)', res_file,2,'*_Start_resample','* End_resample:_NORMAL')) p0 = int(get_parameter('First_pixel (w.r.t. original_master)', res_file,2,'*_Start_resample','* End_resample:_NORMAL')) pN = int(get_parameter('Last_pixel (w.r.t. original_master)', res_file,2,'*_Start_resample','* End_resample:_NORMAL')) else: l0 = int(get_parameter('First_line (w.r.t. original_image)', res_file, 1)) lN = int(get_parameter('Last_line (w.r.t. original_image)', res_file, 1)) p0 = int(get_parameter('First_pixel (w.r.t. original_image)', res_file, 1)) pN = int(get_parameter('Last_pixel (w.r.t. original_image)', res_file, 1)) # Get resampled Slv size Naz_res = lN-l0+1 Nrg_res = pN-p0+1 if resampled == 1: # Read the resampled image and slave coordinates in master geometry ################################################################################# Path_MFF_HDR ='rsmp_orig_slave_pixel'+'.hdr' Link_DATA ='rsmp_orig_slave_pixel'+'.r00' # the default format should be r00 Link_rsmp_orig_slave_pixel ='rsmp_orig_slave_pixel.raw' if (os.path.isfile(Path_MFF_HDR)): os.remove(Path_MFF_HDR) if (os.path.isfile(Link_DATA)): os.remove(Link_DATA) RAW_DATA_ABSOLUTE_PATH=os.path.abspath(Link_rsmp_orig_slave_pixel) print "RAW_DATA_ABSOLUTE_PATH=", RAW_DATA_ABSOLUTE_PATH os.symlink(RAW_DATA_ABSOLUTE_PATH,Link_DATA) outStream = open(Path_MFF_HDR,'w') outStream.write('IMAGE_FILE_FORMAT = MFF\n') outStream.write('FILE_TYPE = IMAGE\n') outStream.write('IMAGE_LINES = %d\n' % int(Naz_res)) outStream.write('LINE_SAMPLES = %d\n'% int(Nrg_res)) outStream.write('BYTE_ORDER = LSB\n') outStream.write('END\n') outStream.close() PixRgGrid = freadbk(Path_MFF_HDR,1, 1,int(Naz_res),int(Nrg_res)) PixRgGrid = PixRgGrid.astype(np.float64) if (os.path.isfile(Path_MFF_HDR)): os.remove(Path_MFF_HDR) if (os.path.isfile(Link_DATA)): os.remove(Link_DATA) ################################################################################# Path_MFF_HDR ='rsmp_orig_slave_line'+'.hdr' Link_DATA ='rsmp_orig_slave_line'+'.r00' Link_rsmp_orig_slave_line ='rsmp_orig_slave_line.raw' if (os.path.isfile(Path_MFF_HDR)): os.remove(Path_MFF_HDR) if (os.path.isfile(Link_DATA)): os.remove(Link_DATA) RAW_DATA_ABSOLUTE_PATH=os.path.abspath(Link_rsmp_orig_slave_line) print "RAW_DATA_ABSOLUTE_PATH=", RAW_DATA_ABSOLUTE_PATH os.symlink(RAW_DATA_ABSOLUTE_PATH,Link_DATA) outStream = open(Path_MFF_HDR,'w') outStream.write('IMAGE_FILE_FORMAT = MFF\n') outStream.write('FILE_TYPE = IMAGE\n') outStream.write('IMAGE_LINES = %d\n' % int(Naz_res)) outStream.write('LINE_SAMPLES = %d\n'% int(Nrg_res)) outStream.write('BYTE_ORDER = LSB\n') outStream.write('END\n') outStream.close() PixAzGrid = freadbk(Path_MFF_HDR,1, 1,int(Naz_res),int(Nrg_res)) PixAzGrid=PixAzGrid.astype(np.float64) if (os.path.isfile(Path_MFF_HDR)): os.remove(Path_MFF_HDR) if (os.path.isfile(Link_DATA)): os.remove(Link_DATA) #%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #% Prepare azimuth and range grids % #%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TrgGrid = Trg_start + (PixRgGrid-1) * dt_rg TazGrid = (PixAzGrid-1) * dt_az - (lNum/2 * dt_az) del PixAzGrid, PixRgGrid elif resampled == 0: Tvect_rg = Trg_start + np.arange(p0-1,pN) * dt_rg Tvect_az = np.arange(l0-1,lN) * dt_az - (lNum/2 * dt_az) Tvect_az = Tvect_az[:, None] TrgGrid = np.tile(Tvect_rg, (Naz_res, 1)) TazGrid = np.tile(Tvect_az, (1, Nrg_res)) else: print 'variable resampled can only be 0 or 1!' return #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #% From S-1 steering rate and orbit information % #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #%%%%%%%%%%%%%%%%%%%%% #% Orbit information % #%%%%%%%%%%%%%%%%%%%%% orbit_number = int(get_parameter('NUMBER_OF_DATAPOINTS',res_file,1)) orbit_time = np.zeros(orbit_number,dtype=np.float64) orbit_velocity_x = np.zeros(orbit_number,dtype=np.float64) orbit_velocity_y = np.zeros(orbit_number,dtype=np.float64) orbit_velocity_z = np.zeros(orbit_number,dtype=np.float64) orbit_info = get_parameter('NUMBER_OF_DATAPOINTS',res_file,4) orbit_info=orbit_info.split('\n') for row in range(orbit_number): orbit_time_position=orbit_info[row] orbit_time[row]=float(orbit_time_position.strip().split()[0]) orbit_velocity_x[row]=float(orbit_time_position.strip().split()[1]) orbit_velocity_y[row]=float(orbit_time_position.strip().split()[2]) orbit_velocity_z[row]=float(orbit_time_position.strip().split()[3]) orbit_velocity = np.sqrt(np.diff(orbit_velocity_x)**2+np.diff(orbit_velocity_y)**2+np.diff(orbit_velocity_z)**2)/np.diff(orbit_time) # Compute Nominal DC for the whole burst # Compute FM rate along range Kfm = c0_FM + c1_FM*(TrgGrid-t0_FM) + c2_FM*(TrgGrid-t0_FM)**2 Kfm_0 = c0_FM + c1_FM*(Trg_start-t0_FM) + c2_FM*(Trg_start-t0_FM)**2 # Compute DC along range at reference azimuth time (azimuthTime) Df_AzCtr = c0_DC + c1_DC*(TrgGrid-t0_DC) + c2_DC*(TrgGrid-t0_DC)**2 f_DC_ref_0 = c0_DC + c1_DC*(Trg_start-t0_DC) + c2_DC*(Trg_start-t0_DC)**2 del TrgGrid # From S-1 steering rate and orbit information % # Computes sensor velocity from orbits C_lambda=np.float64(get_parameter('Radar_wavelength (m)',res_file,1)) # Frequency rate Ks_hz = 2*np.mean(orbit_velocity)/C_lambda*Ks/180*np.pi # Time ratio alpha_nom = 1 - Ks_hz/Kfm # DC Azimuth rate [Hz/s] DR_est = Ks_hz/alpha_nom del Ks_hz, alpha_nom # Reference time az_DC = -(Df_AzCtr / Kfm) + (f_DC_ref_0 / Kfm_0) del Kfm, Kfm_0 Taz_vec = TazGrid - az_DC del az_DC #% Generate inverse chirp % if type == 'chirp': data = np.exp(1j*2*np.pi*(DR_est/2*Taz_vec+Df_AzCtr)*Taz_vec) elif type == 'DC': data = Df_AzCtr + Taz_vec * DR_est else: print 'Choose either chirp or DC for type' return return data def get_parameter(First_param,file_name,format_flag=1,Second_param=None,Third_param=None): Read_contine_flag=0 orbit_info="" value=None for line in open(file_name): if format_flag==1: if not (line.find(First_param)): index=line.find(':') value=(line[(index+1):].strip(' \n\t')) return value if format_flag==2: if not(line.find(Second_param)): Read_contine_flag=1 if (Read_contine_flag==1) and (not (line.find(First_param))): #Be careful index=line.find(':') value=(line[(index+1):].strip(' \n\t')) continue if Read_contine_flag==1 and (not(line.find(Third_param))): #Be careful Read_contine_flag=0 return value if format_flag==3: if not (line.find(First_param)): index=line.find(':') pixel_time=(line[(index+1):].strip(' \n\t')).split(' ')[1].split(':') return pixel_time if format_flag==4: if not (line.find(First_param)): index=line.find(':') value=int(line[(index+1):].strip(' \n\t')) Read_contine_flag=1 continue if (Read_contine_flag>=1): orbit_info=orbit_info+line Read_contine_flag=Read_contine_flag+1 if (Read_contine_flag==(value+1)): return orbit_info ################################################################################ ############################################################################### def freadbk(path_file,line_start=1, pixels_start=1,nofLines1=None,nofPixels1=None): #Driver driver=gdal.GetDriverByName('MFF') driver.Register() gdal.AllRegister() thisBurstData_file=gdal.Open(path_file,GA_ReadOnly) if thisBurstData_file is None: print 'Could not open'+Path_MFF_HDR sys.exit(1) #print 'Driver: ', thisBurstData_file.GetDriver().ShortName,'/', \ # thisBurstData_file.GetDriver().LongName #print 'Size is ',thisBurstData_file.RasterXSize,'x',thisBurstData_file.RasterYSize, \ # 'x',thisBurstData_file.RasterCount #print 'Projection is ',thisBurstData_file.GetProjection() geotransform = thisBurstData_file.GetGeoTransform() if not geotransform is None: print 'Origin = (',geotransform[0], ',',geotransform[3],')' print 'Pixel Size = (',geotransform[1], ',',geotransform[5],')' cint_srd=thisBurstData_file.GetRasterBand(1) #print 'Band Type=',gdal.GetDataTypeName(cint_srd.DataType) if cint_srd.GetOverviewCount() > 0: print 'Band has ', cint_srd.GetOverviewCount(), ' overviews.' thisBurstData= cint_srd.ReadAsArray(int(pixels_start-1),int(line_start-1),nofPixels1,nofLines1) return thisBurstData ################################################################################## Doris-5.0.3Beta/doris_stack/functions/get_winpos.py000077500000000000000000000177621312547014700224640ustar00rootroot00000000000000#!/usr/bin/env python import numpy as np from numpy import * import gdal from gdalconst import * from scipy import ndimage def usage(): print '\nUsage: python get_winpos.py dataFile resFile Nwin outFile ' print 'where dataFile is the name of burst you want to deramp ' print ' resFile is the .res file of burst ' print ' Nwin number of windows to be distributed over the total image' print ' outFile output file name ' print ' for example ' print ' python get_winpos.py 20141003_iw_1_burst_1.raw 20141003_iw_1_burst_1.res 2001 winpos_fine.asc' print ' matlab: TU Delft ' print ' Python: Wu Wenhao Wuhan QQ:460249274 ' try: dataFile = sys.argv[1] resFile = sys.argv[2] Nwin = sys.argv[3] outFile = sys.argv[4] except: print 'Unrecognized input' usage() sys.exit(1) ################################################################################ def get_parameter(First_param,file_name,format_flag=1,Second_param=None,Third_param=None): Read_contine_flag=0 orbit_info="" value=None for line in open(file_name): if format_flag==1: if not (line.find(First_param)): index=line.find(':') value=(line[(index+1):].strip(' \n\t')) return value if format_flag==2: if not(line.find(Second_param)): Read_contine_flag=1 if (Read_contine_flag==1) and (not (line.find(First_param))): #Be careful index=line.find(':') value=(line[(index+1):].strip(' \n\t')) continue if Read_contine_flag==1 and (not(line.find(Third_param))): #Be careful Read_contine_flag=0 return value if format_flag==3: if not (line.find(First_param)): index=line.find(':') pixel_time=(line[(index+1):].strip(' \n\t')).split(' ')[1].split(':') return pixel_time if format_flag==4: if not (line.find(First_param)): index=line.find(':') value=int(line[(index+1):].strip(' \n\t')) Read_contine_flag=1 continue if (Read_contine_flag>=1): orbit_info=orbit_info+line Read_contine_flag=Read_contine_flag+1 if (Read_contine_flag==(value+1)): return orbit_info ############################################################################### #thisBurstData = freadbk(['burst' num2str(nBurst) '/cint_srd.raw'],nofLines1,formatData1, line1, nofLines1,1,nofPixels1); def freadbk(path_file,line_start=1, Pixels_start=1,nofLines1=None,nofPixels1=None): #Driver driver=gdal.GetDriverByName('MFF') driver.Register() gdal.AllRegister() thisBurstData_file=gdal.Open(path_file,GA_ReadOnly) if thisBurstData_file is None: print 'Could not open'+Path_MFF_HDR sys.exit(1) #print 'Driver: ', thisBurstData_file.GetDriver().ShortName,'/', \ # thisBurstData_file.GetDriver().LongName #print 'Size is ',thisBurstData_file.RasterXSize,'x',thisBurstData_file.RasterYSize, \ # 'x',thisBurstData_file.RasterCount #print 'Projection is ',thisBurstData_file.GetProjection() geotransform = thisBurstData_file.GetGeoTransform() #if not geotransform is None: # print 'Origin = (',geotransform[0], ',',geotransform[3],')' # print 'Pixel Size = (',geotransform[1], ',',geotransform[5],')' cint_srd=thisBurstData_file.GetRasterBand(1) #print 'Band Type=',gdal.GetDataTypeName(cint_srd.DataType) if cint_srd.GetOverviewCount() > 0: print 'Band has ', cint_srd.GetOverviewCount(), ' overviews.' thisBurstData= cint_srd.ReadAsArray(int(Pixels_start-1),int(line_start-1),nofPixels1,nofLines1) return thisBurstData ############################################################################### NwinGrid = 5 azSpacing = 20 rSpacing = 5 resData = resFile if get_parameter('First_line (w.r.t. ovs_image)',resData,1): #%oversampled data #% First_line (w.r.t. ovs_image): l0 = int(get_parameter('First_line (w.r.t. ovs_image)',resData,1)); #% Last_line (w.r.t. ovs_image): lN = int(get_parameter('Last_line (w.r.t. ovs_image)',resData,1)); #% First_pixel (w.r.t. ovs_image): p0 = int(get_parameter('First_pixel (w.r.t. ovs_image)',resData,1)); #% Last_pixel (w.r.t. ovs_image): pN = int(get_parameter('Last_pixel (w.r.t. ovs_image)',resData,1)); dataFormat = 'cpxfloat32' else:#original data l0 = int(get_parameter('First_line (w.r.t. original_image)',resData,1)); #% Last_line (w.r.t. original_image): lN = int(get_parameter('Last_line (w.r.t. original_image)',resData,1)) #% First_pixel (w.r.t. original_image): p0 = int(get_parameter('First_pixel (w.r.t. original_image)',resData,1)) #% Last_pixel (w.r.t. original_image): pN = int(get_parameter('Last_pixel (w.r.t. original_image)',resData,1)) dataFormat = 'cpxint16' # Image size Nlines = lN-l0+1; Npixels = pN-p0+1; print "Nlines =",Nlines print "Npixels =",Npixels Ngrid = float(Nwin)/NwinGrid; daz = Nlines*azSpacing; dr = Npixels*rSpacing; ratio = float(dr)/daz Ngrid_az = sqrt(Ngrid/ratio); Ngrid_r = round(Ngrid_az*ratio); Ngrid_az = round(Ngrid_az) Nlines_grid = ceil(Nlines/Ngrid_az) Nlines_grid_orig = Nlines_grid Npixels_grid = ceil(Npixels/Ngrid_r) Npixels_grid_orig = Npixels_grid RAW_CINT_SRD = dataFile Path_MFF_HDR = dataFile.split('.')[0]+'.hdr'; if dataFormat == 'cpxint16': Link_CINT_SRD=dataFile.split('.')[0]+'.j00' else: Link_CINT_SRD=dataFile.split('.')[0]+'.x00' outStream = open(Path_MFF_HDR,'w') outStream.write('IMAGE_FILE_FORMAT = MFF\n') outStream.write('FILE_TYPE = IMAGE\n') outStream.write('IMAGE_LINES = %d\n' % int(Nlines)) outStream.write('LINE_SAMPLES = %d\n'% int(Npixels)) outStream.write('BYTE_ORDER = LSB\n') outStream.write('END\n') outStream.close() if (os.path.exists(Link_CINT_SRD)): os.remove(Link_CINT_SRD) RAW_CINT_SRD_ABSOLUTE_PATH=os.path.abspath(RAW_CINT_SRD) print "RAW_CINT_SRD_ABSOLUTE_PATH=", RAW_CINT_SRD_ABSOLUTE_PATH os.symlink(RAW_CINT_SRD_ABSOLUTE_PATH,Link_CINT_SRD) winpos=np.array([],dtype='int32').reshape(0,2) for v in range(1,int(Ngrid_az)+1): if v==Ngrid_az: Nlines_grid = (Nlines-1)%Nlines_grid_orig+1 else: Nlines_grid = Nlines_grid_orig ampArray = abs(freadbk(Path_MFF_HDR,int((v-1)*Nlines_grid_orig+1),1,int(Nlines_grid),Npixels )) for w in range(1,int(Ngrid_r)+1): if w==Ngrid_r: Npixels_grid = (Npixels-1)%Npixels_grid_orig+1 else: Npixels_grid = Npixels_grid_orig amp = ampArray[:,(w-1)*Npixels_grid_orig:(w-1)*Npixels_grid_orig+Npixels_grid] locMaxsInd = amp == ndimage.grey_dilation(amp, size=(5*rSpacing, 5*azSpacing)) locMaxs = amp[locMaxsInd] [az,r] = where(locMaxsInd) sortIdx =np.argsort(-locMaxs) sortIdx = sortIdx[0:NwinGrid] add_winpos=np.array([az[sortIdx]+l0-1+(v-1)*Nlines_grid_orig,r[sortIdx]+p0-1+(w-1)*Npixels_grid_orig]).transpose() winpos=np.vstack([winpos,add_winpos]) fidRes = open(outFile,'w') cols = winpos.shape[1] rows = winpos.shape[0] #print "cols = ",cols print "rows = ", rows for i_temp in range(0,rows): fidRes.write( '%d %d\n' % (winpos[i_temp,0]+1,winpos[i_temp,1]+1)) fidRes.close() if (os.path.exists(Link_CINT_SRD)): os.remove(Link_CINT_SRD) if (os.path.exists(Path_MFF_HDR)): os.remove(Path_MFF_HDR) Doris-5.0.3Beta/doris_stack/functions/job.started000066400000000000000000000000001312547014700220440ustar00rootroot00000000000000Doris-5.0.3Beta/doris_stack/functions/load_shape_unzip.py000077500000000000000000000174511312547014700236250ustar00rootroot00000000000000import os, sys import zipfile import shutil import warnings import xml.etree.cElementTree as etree from shapely.geometry import Polygon, shape import fiona import numpy as np def unzip_folder(zipped_folder, dest_folder, shapefile='', pol='', data=True, swath='all', overwrite=False, check_valid=False): # This function unzips a data folder. The total amount of data to unpack can be reduced by selecting which data # files are unpacked. In first instance all files except the data files are extracted. Then the other files are # extracted based on the given input: # - pol > only this polarisation is unpacked ('vv', 'hh', 'hv', 'vh') # - shape > only the swaths which overlap with this shape are unpacked shape is a shapefile file # - swath > you can choose either 1/2/3 # If you do not want to extract any data file use data=False. Finally, the script will skip files which are already # unpacked unless you set overwrite to True zipdat = zipfile.ZipFile(zipped_folder) # First check zipfile quality if check_valid == True: test = zipdat.testzip() if test: print('Some files in ' + zipped_folder + ' are corrupted.') return # First check wether the shape overlaps... kml_file, png_file = extract_kml_preview(zipped_folder, dir=dest_folder, overwrite=overwrite) if shapefile: shp = load_shape(shapefile, buffer=0.02) overlap = shape_im_kml(shp, kml_file) if not overlap: print('The image and kml_file do not overlap') return swaths = [] for filename in zipdat.namelist(): absname = os.path.join(dest_folder, filename) if not os.path.exists(absname) or overwrite == True: if not filename.endswith('.tiff'): zipdat.extract(filename, dest_folder) else: swaths.append(filename) if swath in ['1', '2', '3']: # If only one of the swaths is extracted. swaths = [s for s in swaths if os.path.basename(s)[6] == str(swath)] if pol in ['vv','vh','hh','hv']: swaths = [s for s in swaths if os.path.basename(s)[12:14] == pol] if not swaths or data == False: # If there is nothing left, stop unpacking. return if shapefile: d_swath = [] for s in swaths: xml_file = os.path.join(dest_folder, os.path.dirname(os.path.dirname(s)), 'annotation', os.path.basename(s)[:-4] + 'xml') if shape_swath_xml(shp, xml_file): d_swath.append(s) swaths = d_swath # Finally unpack the needed swaths for s in swaths: zipdat.extract(s, dest_folder) def extract_kml_preview(zipped_folder, dir='', kml=True, png=True, overwrite=False): # Extracts quicklook and/or .kml files. zipdat = zipfile.ZipFile(zipped_folder) if not dir: dir = os.path.dirname(zipped_folder) png_name = '' kml_name = '' for filename in zipdat.namelist(): # Unzip and save .kml file if filename.endswith('map-overlay.kml') and kml == True: kml_name = os.path.join(dir, os.path.basename(zipped_folder)[:-4] + '.kml') zipped_kml = zipdat.open(filename) if not os.path.exists(kml_name) or overwrite == True: kml_file = file(kml_name, "wb") with zipped_kml, kml_file: shutil.copyfileobj(zipped_kml, kml_file) for filename in zipdat.namelist(): # Unzip and save quicklook if filename.endswith('quick-look.png') and png == True: png_name = os.path.join(dir, os.path.basename(zipped_folder)[:-4] + '.png') zipped_png = zipdat.open(filename) if not os.path.exists(png_name) or overwrite == True: png_file = file(png_name, "wb") with zipped_png, png_file: shutil.copyfileobj(zipped_png, png_file) return kml_name, png_name def shape_im_kml(shp, kml_file): # This script extracts a Fiona/polygon shape of the footprint given in the .xml file of the image and checks whether # it overlaps # First check is .kml file exist if not os.path.exists(kml_file): warnings.warn('.kml file does not exist.') return False try: in_kml = etree.parse(kml_file) in_kml = in_kml.getroot() coor = in_kml[0][1][1][2][0].text coor = [i.split(',') for i in coor.split(' ')] coverage = Polygon([[float(i[0]),float(i[1])] for i in coor]) except: warnings.warn('.kml file is corrupt') return False if coverage.intersects(shp): return True else: return False def shape_swath_xml(shp, xml_file): # This script extracts a Fiona/polygon shape of the footprint given in the .xml file of the image and checks whether # it overlaps # First check is .xml file exist if not os.path.exists(xml_file): warnings.warn('.xml file does not exist.') return False try: in_xml = etree.parse(xml_file) in_xml = in_xml.getroot() coor = in_xml.find('.geolocationGrid').find('.geolocationGridPointList').findall('.geolocationGridPoint') lats = [] lons = [] line = [] pixel = [] for c in coor: lats.append(float(c.find('.latitude').text)) lons.append(float(c.find('.longitude').text)) pixel.append(int(c.find('.pixel').text)) line.append(int(c.find('.line').text)) maxpixel = np.max(pixel) coor = [[lat, lon] for lon, lat, p in zip(lats, lons, pixel) if p == 0] coor.extend([[lat, lon] for lon, lat, p in zip(lats[::-1], lons[::-1], pixel[::-1]) if p == maxpixel]) coverage = Polygon(coor) except: warnings.warn('.xml file is corrupt') return False if coverage.intersects(shp): return True else: return False def load_shape(shapefile, buffer=0.02): # This function creates a shape to make a selection of usable bursts later on. Buffer around shape is in # degrees. if not shapefile: warnings.warn('Please provide a shapefile or coordinates.') try: if isinstance(shapefile, list): # If the coordinates are already loaded. (for example bounding box) shp = Polygon(shapefile) else: # It should be a shape file. We always select the first shape. sh = fiona.open(shapefile).next() shp = shape(sh['geometry']) # Now we have the shape we add a buffer and simplify first to save computation time. shp = shp.simplify(buffer / 2) shp = shp.buffer(buffer) except: warnings.warn('Unrecognized shape') return return shp # Testing --------------------------------------------- # zipped_folder = '/media/gert/Data/radar_database/sentinel-1/s1_asc_t88/IW_SLC__1SDV_VVVH/20141116/S1A_IW_SLC__1SDV_20141116T172443_20141116T172510_003310_003D5C_E92F.SAFE.zip' # dest_folder = '/media/gert/Data/radar_database/sentinel-1/s1_asc_t88/IW_SLC__1SDV_VVVH/20141116/test' # shapefile = '/media/gert/Data/shapes/netherlands/netherland.shp' # pol = '' # data = True # swath = 'all' # overwrite = False # check_valid = True # ------------------------------------------------------ # Actually execute the code to unzip one data file. if __name__ == "__main__": data = True check_valid = False swath = 'all' zipped_folder = sys.argv[1] dest_folder = sys.argv[2] shapefile = sys.argv[3] pol = sys.argv[4] overwrite = sys.argv[5] if overwrite == 'False': overwrite = False else: overwrite = True print('zipfile is ' + zipped_folder) print('shapefile is ' + shapefile) print('destination folder is ' + dest_folder) unzip_folder(zipped_folder, shapefile=shapefile, pol=pol, dest_folder=dest_folder, overwrite=overwrite, swath=swath, check_valid=check_valid, data=data) Doris-5.0.3Beta/doris_stack/functions/orbit_coordinates.py000077500000000000000000000205041312547014700240030ustar00rootroot00000000000000# The three functions here are used to transform coordinates and times in the original xml files to a usefull format for doris. # Therefore these functions are generally used to read metadata of sentinel files. import math import numpy as np def lph2xyz(line,pixel,container,norm_orbit_line,centroid_lon,centroid_lat,height): # initialization MAXITER=500 CRITERPOS=1.0e-16 # WGS84 Elliposid: ellipsoid=[6378137.0 , 6356752.3141] num_points = np.array([line]).shape[0] xyz = np.zeros((num_points,3)) #$$$ parameter of the image tr1 = float(container['rangeTimePix'][0])/2 # one way range time [sec] RSR = float(container['rangeRSR'][0])*2 # one way in [HZ] centerphi = float(centroid_lat) centerlambda= float(centroid_lon) SOL=299792458 # $$$ reference surace: WGS84 ell_a = ellipsoid[0] # semimajor of the ellipsoid ell_b = ellipsoid[1] # semiminor of the ellipsoid ell_e2 = (ell_a**2-ell_b**2)/ell_a**2 # squared first eccentricity(derived) # $$$ ell_e2b=(ell_a^2-ell_b^2)/ell_b^2; % squared second eccentricity(derived) # $$$ [lat,long,h] of scene center to [x,y,z] h = height # this is only for initial values centerphi = centerphi*np.pi/180 centerlambda = centerlambda*np.pi/180 Ncenter = ell_a/np.sqrt(1-ell_e2*(np.sin(centerphi)**2)) # eccentricity scenecenterx = (Ncenter+h)*np.cos(centerphi)*np.cos(centerlambda) scenecentery = (Ncenter+h)*np.cos(centerphi)*np.sin(centerlambda) scenecenterz = (Ncenter+h-ell_e2*Ncenter)*np.sin(centerphi) for n in range(0,num_points): # loop through points posonellx = scenecenterx posonelly = scenecentery posonellz = scenecenterz ratime = tr1 + (pixel-1.0)/RSR #get position and velocity of the satellite possatx = norm_orbit_line[n,1] possaty = norm_orbit_line[n,2] possatz = norm_orbit_line[n,3] velsatx = norm_orbit_line[n,4] velsaty = norm_orbit_line[n,5] velsatz = norm_orbit_line[n,6] equationset=np.zeros((3,1)) partialsxyz=np.zeros((3,3)) for iter in range(1, MAXITER+1): #update equations and slove system dsat_Px = posonellx - possatx #vector of 'satellite to P on ellipsoid' dsat_Py = posonelly - possaty dsat_Pz = posonellz - possatz equationset[0,0] = -(velsatx*dsat_Px+velsaty*dsat_Py+velsatz* dsat_Pz) equationset[1,0] = -(dsat_Px*dsat_Px+dsat_Py*dsat_Py+dsat_Pz*dsat_Pz-(SOL*ratime)**2) equationset[2,0] = -((posonellx*posonellx+posonelly*posonelly)/((ell_a+height)**2)+(posonellz/(ell_b+height))**2-1.0) partialsxyz[0,0] = velsatx partialsxyz[0,1] = velsaty partialsxyz[0,2] = velsatz partialsxyz[1,0] = 2*dsat_Px partialsxyz[1,1] = 2*dsat_Py partialsxyz[1,2] = 2*dsat_Pz partialsxyz[2,0] = (2*posonellx)/((ell_a+height)**2) partialsxyz[2,1] = (2*posonelly)/((ell_a+height)**2) partialsxyz[2,2] = (2*posonellz)/((ell_b+height)**2) # solve system [NOTE] orbit_normalized, otherwise close to # singular solpos = np.linalg.solve(partialsxyz,equationset) solx = solpos[0,0] soly = solpos[1,0] solz = solpos[2,0] # update solution posonellx = posonellx + solx posonelly = posonelly + soly posonellz = posonellz + solz # check convergence if (abs(solx)=MAXITER): MAXITER=MAXITER+1 # final solution: array of XYZ coordinates xyz[n,:]=np.array([posonellx, posonelly, posonellz]).copy() return xyz def xyz2ell(position): ellipsoid=[6378137.0 , 6356752.3141] ell_a = ellipsoid[0] ell_b = ellipsoid[1] ell_e2 = (ell_a**2-ell_b**2)/ell_a**2 #squared first eccentricity(derived) ell_e2b = (ell_a**2-ell_b**2)/ell_b**2 # squared second eccentricity(derived) posx = position[:,0] posy = position[:,1] posz = position[:,2] r = math.sqrt(posx**2 + posy**2) mu = math.atan2(posz*ell_a, r*ell_b) sin3 = (math.sin(mu))**3 cos3 = (math.cos(mu))**3 phi = math.atan2((posz + ell_e2b * ell_b * sin3),(r - ell_e2 * ell_a* cos3)) Radar_lambda = math.atan2(posy,posx) N = ell_a / math.sqrt(1 - ell_e2 * (math.sin(phi))**2) #for every point no # approx with scene.center height = (r/math.cos(phi)) - N phi_lam_height = np.zeros(3) phi_lam_height[0] = phi*180/math.pi phi_lam_height[1] = Radar_lambda*180/math.pi phi_lam_height[2] = height return phi_lam_height def intrp_orbit(line,container,burst_number): intrpOrder = 'spline' orbit_time = np.zeros(len(container['orbitTime']),dtype=np.float64) orbit_x = np.zeros(len(container['orbitTime']),dtype=np.float64) orbit_y = np.zeros(len(container['orbitTime']),dtype=np.float64) orbit_z = np.zeros(len(container['orbitTime']),dtype=np.float64) for row in range(len(container['orbitTime'])): #orbit_time_position=precorb[row] orbit_time[row] =hms2sec(container['orbitTime'][row].split('T')[1]) orbit_x[row] =float( container['orbitX'][row]) orbit_y[row] =float( container['orbitY'][row]) orbit_z[row] =float( container['orbitZ'][row]) # compute normalization factors px = orbit_time # time f = min(px) g = (max(px)-min(px)) px = (px-f)/g # polyDegree polyDegree = 2 coef_x1 = (np.polyfit(px,orbit_x,polyDegree)); a = coef_x1[2] b = coef_x1[1] c = coef_x1[0] coef_x = [c/(g**2), b/g-(2*c*f)/(g**2), a-b*f/g+c*(f/g)**2] coef_y1 = (np.polyfit(px,orbit_y,polyDegree)) a = coef_y1[2] b = coef_y1[1] c = coef_y1[0] coef_y = [c/(g**2), b/g-(2*c*f)/(g**2), a-b*f/g+c*(f/g)**2] coef_z1 = (np.polyfit(px,orbit_z,polyDegree)); a = coef_z1[2] b = coef_z1[1] c = coef_z1[0] coef_z = [c/(g**2), b/g-(2*c*f)/(g**2), a-b*f/g+c*(f/g)**2] vel_x = np.polyval(np.polyder(coef_x),orbit_time) vel_y = np.polyval(np.polyder(coef_y),orbit_time) vel_z = np.polyval(np.polyder(coef_z),orbit_time) acc_x = np.kron(np.ones(len(container['orbitTime'])),np.polyder(np.polyder(coef_x))) acc_y = np.kron(np.ones(len(container['orbitTime'])),np.polyder(np.polyder(coef_y))) acc_z = np.kron(np.ones(len(container['orbitTime'])),np.polyder(np.polyder(coef_z))) #print 'acc_x.shape=',acc_x.shape # interpolated orbit norm_orbit = np.array([orbit_time, orbit_x,orbit_y,orbit_z,vel_x, vel_y, vel_z,acc_x, acc_y, acc_z]); # interpolated orbit for l_aztime PRF = float(container['azimuthPRF'][0]) #[Hz] # Pulse repeition frequency Taz_start = hms2sec(container['azimuthTimeStart'][burst_number].split('T')[1]) ta1 = Taz_start # start time in UTC [sec] l_aztime = (line-1)/PRF + ta1 pos_orbit_x = np.interp(l_aztime,orbit_time,orbit_x) pos_orbit_y = np.interp(l_aztime,orbit_time,orbit_y) pos_orbit_z = np.interp(l_aztime,orbit_time,orbit_z) vel_orbit_x = np.interp(l_aztime,orbit_time,vel_x) vel_orbit_y = np.interp(l_aztime,orbit_time,vel_y) vel_orbit_z = np.interp(l_aztime,orbit_time,vel_z) #acc = np.interp(orbit_time,[acc_x, acc_y, acc_z], l_aztime,intrpOrder) acc_orbit_x = np.interp(l_aztime,orbit_time,acc_x) acc_orbit_y = np.interp(l_aztime,orbit_time,acc_y) acc_orbit_z = np.interp(l_aztime,orbit_time,acc_z) norm_orbit_line = np.array([l_aztime, pos_orbit_x,pos_orbit_y,pos_orbit_z,vel_orbit_x,vel_orbit_y,vel_orbit_z,acc_orbit_x,acc_orbit_y,acc_orbit_z]) return norm_orbit.transpose(),norm_orbit_line.reshape(1,-1,order='F') #################################################################################################### def hms2sec(hmsString,convertFlag='float'): # input hmsString syntax: XX:XX:XX.xxxxxx secString = int(hmsString[0:2])*3600 + \ int(hmsString[3:5])*60 + \ float(hmsString[6:]) if convertFlag == 'int' : return int(secString) elif convertFlag == 'float' : return float(secString) else: return int(secString)Doris-5.0.3Beta/doris_stack/functions/precise_read.py000077500000000000000000000131631312547014700227220ustar00rootroot00000000000000# This file contains several functions to read data from precise orbit files of sentinel-1 data. # Scripts were created by Wu Wenhao, Wuhan university and adapted by Gert Mulder, TU Delft import time import calendar import numpy as np import os, sys from scipy.interpolate import interp1d import scipy.interpolate as inter import calendar def orbit_read(input_EOF_FileName): try: import xml.etree.cElementTree as etree except: try: from lxml import etree except: #import xml.etree.ElementTree as etree print 'Failed to load lxml.etree or xml.etree.cElementTree' sys.exit(1) inTree = etree.parse(input_EOF_FileName) queryList = { # orbit inf 'Mission' : './/Earth_Explorer_Header/Fixed_Header/Mission',\ 'Validity_Start': './/Earth_Explorer_Header/Fixed_Header/Validity_Period/Validity_Start',\ 'Validity_Stop': './/Earth_Explorer_Header/Fixed_Header/Validity_Period/Validity_Stop',\ 'orbitABS' : './/Data_Block/List_of_OSVs/OSV/Absolute_Orbit',\ 'orbitTime': './/Data_Block/List_of_OSVs/OSV/UTC',\ 'orbitX' : './/Data_Block/List_of_OSVs/OSV/X',\ 'orbitY' : './/Data_Block/List_of_OSVs/OSV/Y',\ 'orbitZ' : './/Data_Block/List_of_OSVs/OSV/Z',\ } # temp variables and parameters container = {} # containerTemp = {} events = ('end',) for key in queryList.keys(): try: vars()[key] except KeyError or NameError: vars()[key] = [] for nodes in inTree.findall(queryList[key]): vars()[key].append(nodes.text) container[key] = vars()[key] return container #-------------------------------------------------------- def interpolate_orbit(input_orbit_dir, date, input_orbit_type, input_interpolation_method, satellite='S1A'): orbit_time = calendar.timegm(time.strptime(date,'%Y-%m-%dT%H:%M:%S.%f')) date_start = calendar.timegm(time.strptime(date[:10],'%Y-%m-%d')) if input_orbit_type == 'POE': input_orbit_dir = os.path.join(input_orbit_dir, 'precise') elif input_orbit_type == 'RES': input_orbit_dir = os.path.join(input_orbit_dir, 'restituted') L = os.listdir(input_orbit_dir) Orbit_info = [] if input_orbit_type == 'POE' and satellite == 'S1A': orbit_type = 'S1A_OPER_AUX_POEORB_OPOD_' elif input_orbit_type == 'RES' and satellite == 'S1A': orbit_type = 'S1A_OPER_AUX_RESORB_OPOD_' elif input_orbit_type == 'POE' and satellite == 'S1B': orbit_type = 'S1B_OPER_AUX_POEORB_OPOD_' elif input_orbit_type == 'RES' and satellite == 'S1B': orbit_type = 'S1B_OPER_AUX_RESORB_OPOD_' for d in L: if d.startswith(orbit_type): start_time = calendar.timegm(time.strptime(d[42:57], '%Y%m%dT%H%M%S')) end_time = calendar.timegm(time.strptime(d[58:73], '%Y%m%dT%H%M%S')) if (start_time < orbit_time) and (end_time > orbit_time): meta = orbit_read(os.path.join(input_orbit_dir, d)) print(d) for i in range(len(meta['orbitTime'])): point_time = calendar.timegm(time.strptime(meta['orbitTime'][i][4:-7], '%Y-%m-%dT%H:%M:%S')) if (point_time > orbit_time-290) and (point_time < orbit_time+290): Tuple_orbit=(float(hms2sec(meta['orbitTime'][i][4:].split('T')[1])),\ float(meta['orbitX'][i]), float(meta['orbitY'][i]),\ float(meta['orbitZ'][i])) Orbit_info.append(Tuple_orbit) set_list=[] Orbit_info=sorted(Orbit_info) for element in range(len(Orbit_info)-1): temp_element =Orbit_info[element][0] temp_element_add =Orbit_info[element+1][0] if int(temp_element) != int(temp_element_add): set_list.append(Orbit_info[element]) Orbit_info=set_list orbit_Time=[] orbit_X =[] orbit_Y =[] orbit_Z =[] for element in Orbit_info: orbit_Time.append(element[0]) orbit_X.append(element[1]) orbit_Y.append(element[2]) orbit_Z.append(element[3]) if len(orbit_X) == 0: return [], orbit_X, orbit_Y, orbit_Z del Orbit_info orbit_Time=np.array(orbit_Time) orbit_X =np.array(orbit_X) orbit_Y =np.array(orbit_Y) orbit_Z =np.array(orbit_Z) if input_interpolation_method=='cubic': spl_x=interp1d(orbit_Time,orbit_X,kind='cubic') spl_y=interp1d(orbit_Time,orbit_Y,kind='cubic') spl_z=interp1d(orbit_Time,orbit_Z,kind='cubic') elif input_interpolation_method=='spline': spl_x = inter.InterpolatedUnivariateSpline (orbit_Time,orbit_X) spl_y = inter.InterpolatedUnivariateSpline (orbit_Time,orbit_Y) spl_z = inter.InterpolatedUnivariateSpline (orbit_Time,orbit_Z) input_time = np.arange((orbit_time - date_start) - 100, (orbit_time - date_start) + 100).astype(dtype='int32') out_orbit_X=spl_x(input_time) out_orbit_Y=spl_y(input_time) out_orbit_Z=spl_z(input_time) return input_time, out_orbit_X, out_orbit_Y, out_orbit_Z #---------------------------------------------------------------- def hms2sec(hmsString,convertFlag='float'): # input hmsString syntax: XX:XX:XX.xxxxxx secString = int(hmsString[0:2])*3600 + \ int(hmsString[3:5])*60 + \ float(hmsString[6:]) if convertFlag == 'int' : return int(secString) elif convertFlag == 'float' : return float(secString) else: return int(secString)Doris-5.0.3Beta/doris_stack/functions/read_write_data.py000077500000000000000000000050751312547014700234160ustar00rootroot00000000000000import numpy as np import os def freadbk(path_file, line_start=1, pixel_start=1, nofLines=None, nofPixels=None, dt='float32', lines=0, pixels=0): # First use memmap to get a memory map of the full file, than extract the requested part. if dt == 'cpxint16': dtype = np.dtype([('re', np.int16), ('im', np.int16)]) file_dat = np.memmap(path_file, dtype=dtype, mode='r', shape=(lines, pixels)).view(np.int16).astype(np.float32).view(np.complex64) data = file_dat[line_start - 1:line_start + nofLines - 1, pixel_start - 1:pixel_start + nofPixels - 1].astype( 'complex64', subok=False) elif dt == 'cpxshort': dtype = np.dtype([('re', np.float16), ('im', np.float16)]) file_dat = np.memmap(path_file, dtype=dtype, mode='r', shape=(lines, pixels)).view(np.float16).astype(np.float32).view(np.complex64) data = file_dat[line_start - 1:line_start + nofLines - 1, pixel_start - 1:pixel_start + nofPixels - 1].astype( 'complex64', subok=False) else: dt = np.dtype(dt) file_dat = np.memmap(path_file, dtype=dt, mode='r', shape=(lines, pixels)) data = file_dat[line_start - 1:line_start + nofLines - 1, pixel_start - 1:pixel_start + nofPixels - 1].astype( dt, subok=False) return data, file_dat def fwritebk(path_file, data, dt): # First define dtype and write to file using memmap. if dt == 'cpxint16': dtype = np.dtype([('re', np.int16), ('im', np.int16)]) data = np.memmap(path_file, dtype=dtype, mode='w', shape=data.shape) data[:, :] = data.view(np.float32).astype(np.int16).view(dtype) elif dt == 'cpxshort': dtype = np.dtype([('re', np.float16), ('im', np.float16)]) data = np.memmap(path_file, dtype=dtype, mode='w', shape=data.shape) data[:, :] = data.view(np.float32).astype(np.float16).view(dtype) else: data = np.memmap(path_file, dtype=dt, mode='w', shape=data.shape) data[:, :] = data return data, file_dat def read_tiff(path_file, line_start=1, pixel_start=1, nofLines=None, nofPixels=None, dt='float32'): print('under construction') def write_tiff(path_file, line_start=1, pixel_start=1, nofLines=None, nofPixels=None, dt='float32'): print('under construction') def read_nc(path_file, line_start=1, pixel_start=1, nofLines=None, nofPixels=None, dt='float32'): print('under construction') def write_nc(path_file, line_start=1, pixel_start=1, nofLines=None, nofPixels=None, dt='float32'): print('under construction') def python_gdal_convert(): print('under construction')Doris-5.0.3Beta/doris_stack/functions/resdata.py000077500000000000000000000442151312547014700217220ustar00rootroot00000000000000import warnings import os import collections class ResData(object): # This class hold metadata of a doris datafile and processing chain and is capable of reading from and writing to a # .res file used by the doris software. def __init__(self,filename='',type=''): # Initialize variables # Filename of resfile and type (single, interferogram) self.res_path = [] self.res_type = '' # Processes, process_control and header of resfile self.processes = collections.OrderedDict() self.process_control = {} self.process_timestamp = {} self.process_time = {} self.header = {} ##################################################### # Create a ResData object (single/interferogram) if type not in ['single','interferogram'] and not filename: warnings.warn('Define if results data is slave, master or interferogram') return else: self.res_type = type if filename: if not os.path.exists(filename): warnings.warn('This filename does not exist: ' + filename) else: self.res_path = filename self.res_read() else: if type == 'single': self.process_control = collections.OrderedDict([('readfiles', '0'),('leader_datapoints', '0'), ('precise_orbits', '0'), ('crop', '0'), ('sim_amplitude', '0'), ('master_timing' , '0'), ('oversample', '0'), ('resample', '0') , ('filt_azi', '0'), ('filt_range', '0'), ('NOT_USED' , '0')]) elif type == 'interferogram': self.process_control = collections.OrderedDict([('coarse_orbits','0'),('coarse_correl','0'),('fine_coreg','0'),('timing_error','0'),('dem_assist','0'), ('comp_coregpm','0'),('interfero','0'),('coherence','0'),('comp_refphase','0'),('subtr_refphase','0'), ('comp_refdem','0'),('subtr_refdem','0'),('filtphase','0'),('unwrap','0'),('est_orbits','0'),('slant2h','0'), ('geocoding','0'),('dinsar','0'),('NOT_USED2','0')]) def res_read(self): self.meta_reader() self.process_reader() def meta_reader(self): # This function with open(self.res_path) as resfile: splitter = ':' temp = collections.OrderedDict() row = 0 for line in resfile: try: ## Filter out rubbish if line == '\n': continue elif 'Start_process_control' in line: self.header = temp temp = collections.OrderedDict() elif 'End_process_control' in line: self.process_control = temp break elif splitter in line and line[0] is not '|' and line[0] is not '\t' : # Split line if possible and add to dictionary l_split = line.split(splitter) temp[l_split[0].strip()] = l_split[1].strip() else: name = 'row_' + str(row) row += 1 temp[name] = [line] except: print 'Error occurred at line: ' + line def process_reader(self,processes = ''): # This function reads random processes based on standard buildup of processes in res files. # leader_datapoints can be one of the processes, although it will not appear in the process_control in a .res file # If loc is true, it will only return the locations where different processes start. if not processes: processes = self.process_control.keys() processes.append('leader_datapoints') process = '' with open(self.res_path) as resfile: # Start at row zero and with empty list temp = collections.OrderedDict() row = 0 line_no = -1 timestamp = False timestamp_line = 0 for line in resfile: try: line_no += 1 # Filter out rubbish if '|'in line[0]: continue elif '**' in line: continue elif line == '\n': continue # Check if timestamp if ' *===========' in line: # First line of time stamp temp = collections.OrderedDict() timestamp = True row = 0 continue elif ' *-----------' in line: timestamp = False timestamp_data = temp timestamp_line = line_no + 5 continue # Check if process if '*' in line[0]: if line.replace('*_Start_', '').split(':')[0].strip() in processes: process = line.replace('*_Start_', '').split(':')[0].strip() temp = collections.OrderedDict() row = 0; space = [0]; space_r = [0,0,0,0,0,0,0,0] # Finally save the timestamp if it exists if line_no == timestamp_line: self.process_timestamp[process] = timestamp_data else: self.process_timestamp[process] = '' elif line.replace('* End_', '').split(':')[0] == process: self.processes[process] = temp temp = collections.OrderedDict() process = '' continue # Save line if timestamp is True: # Save rows in timestamp row_name = 'row_' + str(row) temp[row_name] = line if row == 1: self.process_time[process] = line.split(':', 1)[1].strip() row += 1 elif process: # If we are in a process output line # Split line using ':' , '=' or spaces (tables) # variable space and space row define the future spacing in every processing step in a res file. if process == 'coarse_orbits': # Add some code for a strange exception in coarse_orbits if '//' in line: temp[line.split()[0]] = line.split()[1:] else: l_split = line.replace('=',':').split(':') temp[l_split[0].strip()] = l_split[1].strip() elif ':' in line: l_split = line.split(':',1) temp[l_split[0].strip()] = l_split[1].strip() else: # If the line does not contain a : it is likely a table. l_split = line.replace('\t',' ').split() row_name = 'row_' + str(row) temp[row_name] = [l_split[i].strip() for i in range(len(l_split))] row += 1 except: print 'Error occurred at line: ' + line def process_spacing(self,process=''): spacing = 0 table_spacing = [0,0,0,0,0,0,0] dat = self.processes[process] for key in dat.keys(): spacing = max(len(key) + 8, spacing) if key.startswith('row'): n=0 for val in self.processes[process][key]: table_spacing[n] = max(len(val) + 3, table_spacing[n]) n += 1 spacing = [spacing] return spacing, table_spacing def del_process(self,process=''): # function deletes one or multiple processes from the corresponding res file if isinstance(process, basestring): # one process if not process in self.process_control.keys(): warnings.warn('The requested process does not exist! (or processes are not read jet, use self.process_reader): ' + str(process)) return elif isinstance(process, list): # If we use a list for proc in process: if not proc in self.process_control.keys(): warnings.warn('The requested process does not exist! (or processes are not read jet, use self.process_reader): ' + str(proc)) return else: warnings.warn('process should contain either a string of one process or a list of multiple processes: ' + str(process)) # Now remove the process and write the file again. if isinstance(process, basestring): # Only one process should be removed self.process_control[process] = '0' del self.processes[process] else: for proc in process: self.process_control[proc] = '0' del self.processes[proc] def write(self,new_filename=''): # Here all the available information acquired is written to a new resfile. Generally if information is manually # added or removed and the file should be created or created again. (For example the readfiles for Sentinel 1 # which are not added yet..) if not new_filename and not self.res_path: warnings.warn('Please specify filename: ' + str(new_filename)) return elif not new_filename: new_filename = self.res_path if not self.process_control or not self.processes: warnings.warn('Every result file needs at least a process control and one process to make any sense: ' + str(new_filename)) # Open file and write header, process control and processes self.res_path = new_filename f = open(new_filename, "w") # Write the header: if self.header: spacing = [40] for key in self.header.keys(): if 'row' in key: # If it is just a string f.write(self.header[key][0]) else: # If the key should included f.write((key + ':').ljust(spacing[0]) + self.header[key] + '\n') # Write the process control for i in range(3): f.write('\n') f.write('Start_process_control\n') for process in self.process_control.keys(): if process != 'leader_datapoints': # leader_datapoints is left out in process control f.write((process + ':\t\t') + str(self.process_control[process]) + '\n') f.write('End_process_control\n') # Then loop through all the processes for process in [p for p in self.processes.keys()]: # First check for a timestamp and add it if needed. if self.process_timestamp[process]: for i in range(2): f.write('\n') f.write(' *====================================================================* \n') for key in self.process_timestamp[process].keys(): f.write(self.process_timestamp[process][key]) f.write(' *--------------------------------------------------------------------* \n') # Then write the process itself if process == 'coarse_orbits': spacing = [45] spacing_row = [15,10,15] else: spacing, spacing_row = self.process_spacing(process) data = self.processes[process] for i in range(3): f.write('\n') f.write('******************************************************************* \n') f.write('*_Start_' + process + ':\n') f.write('******************************************************************* \n') for line_key in self.processes[process].keys(): if 'row' in line_key: # If it is a table of consists of several different parts line = ''.join([(' ' + data[line_key][i]).replace(' -','-').ljust(spacing_row[i]) for i in range(len(data[line_key]))]) f.write(line + '\n') elif process == 'coarse_orbits': # the coarse orbits output is different from the others. if 'Control point' in line_key: # Special case coarse orbits... f.write((line_key + ' =').ljust(spacing[0]) + str(self.processes[process][line_key]) + '\n') elif not isinstance(data[line_key], basestring): # Another special case f.write(line_key.ljust(spacing_row[0]) + (data[line_key][0]).ljust(spacing_row[1]) + data[line_key][1].ljust(spacing_row[2]) + ' '.join(data[line_key][2:]) + '\n') elif isinstance(data[line_key], basestring): # Handle as in normal cases f.write((line_key + ':').ljust(spacing[0]) + str(self.processes[process][line_key]) + '\n') else: # If it consists out of two parts f.write((line_key + ':').ljust(spacing[0]) + str(self.processes[process][line_key]) + '\n') f.write('******************************************************************* \n') f.write('* End_' + process + ':_NORMAL\n') f.write('******************************************************************* \n') f.close() # Read the locations in the new file self.process_reader() def insert(self,data,process,variable=''): # This function inserts a variable or a process which does not exist at the moment processes = self.process_control.keys() processes.extend(['header','leader_datapoints']) if process not in processes: warnings.warn('This process does not exist for this datatype: ' + str(process)) return # If a full process is added if not variable: if self.process_control[process] == '1': warnings.warn('This process already exists! Use the update function: ' + str(process)) return elif self.process_control[process] == '0': self.process_control[process] = '1' self.processes[process] = data self.process_timestamp[process] = '' # A variable is added if variable: if variable in self.processes[process].keys(): warnings.warn('This variable already exists! Use the update function: ' + str(variable)) return elif not self.processes[process][variable]: self.processes[process][variable] = data def delete(self,process,variable=''): # This function deletes a variable or a process which does exist at the moment processes = self.process_control.keys() processes.extend(['header','leader_datapoints']) if process not in processes: warnings.warn('This process does not exist for this datatype: ' + str(process)) return # If a full process is deleted if not variable: if self.process_control[process] == '0': warnings.warn('This process does not exist: ' + str(process)) return elif self.process_control[process] == '1': self.process_control[process] = '0' del self.processes[process] del self.process_timestamp[process] # A variable is deleted if variable: if not variable in self.processes[process].keys(): warnings.warn('This variable does not exist: ' + str(variable)) return else: del self.processes[process][variable] def update(self,data,process,variable=''): # This function updates a variable or a process which does exist at the moment processes = self.process_control.keys() processes.extend(['header','leader_datapoints']) if not process in processes: warnings.warn('This process does not exist for this datatype: ' + str(process)) return # If a full process is added if not variable: if self.process_control[process] == '1': self.processes[process] = data elif self.process_control[process] == '0': warnings.warn('This process does not exist. Use the insert function: ' + str(process)) return # A variable is added if variable: if variable in self.processes[process].keys(): self.processes[process][variable] = data elif not self.processes[process][variable]: warnings.warn('This variable does not exist. Use the insert function: ' + str(variable)) return def request(self,process,variable=''): # This function updates a variable or a process which does exist at the moment processes = self.process_control.keys() processes.extend(['header','leader_datapoints']) if not process in processes: warnings.warn('This process does not exist for this datatype: ' + str(process)) return # If a full process is added if not variable: if self.process_control[process] == '1': data = self.processes[process] elif self.process_control[process] == '0': warnings.warn('This process does not exist: ' + str(process)) return # A variable is added if variable: if variable in self.processes[process].keys(): data = self.processes[process][variable] elif not self.processes[process][variable]: warnings.warn('This variable does not exist: ' + str(variable)) return return dataDoris-5.0.3Beta/doris_stack/functions/sentinel_dump_data_function.py000077500000000000000000000056751312547014700260520ustar00rootroot00000000000000#!/usr/bin/env python import os,sys,time if __name__ == "__main__": # If calling script directly we have to load the package first to our python path folder = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) print(folder) sys.path.extend([folder]) import resdata as resdata def dump_data(input_file,res_file, output_file='', coordinates=[]): # This function dumps a .raw file from the original .tif sentinel data. The input_file is the .tif file and the # res_file is the .res file that corresponds with the output file. Coordinates is an optional variable which can be # called if the lines and pixels are not yet defined in the .res file. res_vars = resdata.ResData(filename=res_file) res_vars.res_read() # Check if information about crop is available if not coordinates: if res_vars.process_control['crop'] == '0': print 'There is no information available about how to crop this file!' return else: outputWinFirstPix = int(res_vars.processes['crop']['First_pixel (w.r.t. original_image)']) outputWinLastPix = int(res_vars.processes['crop']['Last_pixel (w.r.t. original_image)']) outputWinFirstLine = int(res_vars.processes['crop']['First_line (w.r.t. tiff_image)']) outputWinLastLine = int(res_vars.processes['crop']['Last_line (w.r.t. tiff_image)']) else: outputWinFirstPix = coordinates[0] outputWinLastPix = coordinates[1] outputWinFirstLine = coordinates[2] outputWinLastLine = coordinates[3] if not output_file: if res_vars.process_control['crop'] == '1': if 'Data_output_file' in res_vars.processes['crop'].keys(): output_file = os.path.join(os.path.dirname(res_file), res_vars.processes['crop']['Data_output_file']) if not output_file: output_file = res_file.split(".")[0] + '.raw' # system parameters :: check whether its there gdalCall = 'gdal_translate' # Output data parameters outputDataFormat = 'MFF' outputDataType = 'CInt16' cmd = '%s %s -ot %s -of %s %s' % (gdalCall,input_file,outputDataType,outputDataFormat,output_file) if outputWinFirstPix is not None: cmd = cmd + (' -srcwin %s %s %s %s' % (outputWinFirstPix,outputWinFirstLine,outputWinLastPix-outputWinFirstPix+1,outputWinLastLine-outputWinFirstLine+1)) failure = os.system(cmd) if failure: print '%s: running %s failed' % (sys.argv[0],cmd) sys.exit(1) else: os.rename(os.path.splitext(output_file)[0]+'.j00',output_file) os.remove(os.path.splitext(output_file)[0]+'.hdr') os.remove(os.path.splitext(output_file)[0]+'.hdr.aux.xml') # Actually execute the code to unzip one data file. if __name__ == "__main__": input_file = sys.argv[1] res_file = sys.argv[2] output_file = sys.argv[3] dump_data(input_file, res_file, output_file, coordinates=[]) Doris-5.0.3Beta/doris_stack/functions/stack_cleanup.py000077500000000000000000000200551312547014700231070ustar00rootroot00000000000000""" This script is meant to cleanup datastacks and remove unnecessary intermediate results. The most general options are the settings for a PS approach and a distributed scatterers approach, which is also used for atmospheric observations. """ import os import shutil # Test: stack_folder = '/media/gert/Data/datastacks/netherlands/asc_t88/stack' cleanup_ps = False cleanup_ds = True full_swath_rm = [] full_swath_keep = [] burst_rm = [] burst_keep = [] remove = False files = cleanup(stack_folder, cleanup_ps, cleanup_ds, full_swath_rm, full_swath_keep, burst_rm, burst_keep, remove) def cleanup(stack_folder, cleanup_ps=True, cleanup_ds=False, full_swath_rm=[], full_swath_keep=[], burst_rm=[], burst_keep=[], remove=True): """ This is the main script to decide what should be removed and what not for an individual full swath. Basically a list is made of the files that should be removed from the full swath and burst folders based on the ending of the file name. The function returns a dictionary where are deleted files are listed. If you only want to list all the files that will be deleted use the remove=False option. Default options are: remove abbreviation PS DS interferogram ifg yes yes ifg earth phase corrected ifg_srp yes yes ifg dem phase corrected ifg_srd no yes ifg phase filtered ifg_filt NA (yes) no ifg coherence ifg_coh yes no ifg unwrapped ifg_unw NA (yes) no dem pixel shift (pixel) dac_delta_p yes yes dem pixel shift (line) dac_delta_l yes yes slave image s_ramp yes yes slave image deramped s_deramp no yes master image m_ramp yes yes master image deramped m_deramp no (*) yes dem phase dem no no latitude phi no (*) no longitude lam no (*) no burst folder b_folder yes yes burst raw files b_raw yes yes burst ras files b_ras yes yes burst res files b_res yes yes * Only one needed in a single master stack. Is not implemented yet. """ # First check what should be removed. if cleanup_ps: swath_clean = {'ifg': True, 'ifg_srp': True, 'ifg_srd': False, 'ifg_filt': True, 'ifg_coh': True, 'ifg_unw': True, 's_ramp': True, 's_deramp': False, 'm_ramp': True, 'm_deramp': False, 'dem': False, 'phi': False, 'lam': False, 'dac_delta_p': True, 'dac_delta_l': True} burst_clean = {'b_folder': True, 'b_raw': True, 'b_ras': True, 'b_res': True} elif cleanup_ds: swath_clean = {'ifg': True, 'ifg_srp': True, 'ifg_srd': True, 'ifg_filt': False, 'ifg_coh': False, 'ifg_unw': False, 's_ramp': True, 's_deramp': True, 'm_ramp': True, 'm_deramp': True, 'dem': False, 'phi': False, 'lam': False, 'dac_delta_p': True, 'dac_delta_l': True} burst_clean = {'b_folder': True, 'b_raw': True, 'b_ras': True, 'b_res': True} else: # Otherwise nothing is removed unless indicated swath_clean = {'ifg': False, 'ifg_srp': False, 'ifg_srd': False, 'ifg_filt': False, 'ifg_coh': False, 'ifg_unw': False, 's_ramp': False, 's_deramp': False, 'm_ramp': False, 'm_deramp': False, 'dem': False, 'phi': False, 'lam': False, 'dac_delta_p': False, 'dac_delta_l': False} burst_clean = {'b_folder': False, 'b_raw': False, 'b_ras': False, 'b_res': False} # Add additional options. for dat in full_swath_rm: swath_clean[dat] = True for dat in full_swath_keep: swath_clean[dat] = False for dat in burst_rm: burst_clean[dat] = True for dat in burst_keep: burst_clean[dat] = False # Then create the strings with which these parts end swath_endings = {'ifg': 'int.raw', 'ifg_srp': 'srp.raw', 'ifg_srd': 'srd.raw', 'ifg_filt': 'filt.raw', 'ifg_coh': 'rence.raw', 'ifg_unw': 'unwrapped.raw', 's_ramp': 'rsmp.raw', 's_deramp': 'rsmp_deramped.raw', 'm_ramp': 'ster.raw', 'm_deramp': 'ster_deramped.raw', 'dem': 'dem_radar.raw', 'phi': 'phi.raw', 'lam': 'lam.raw', 'dac_delta_p': 'delta_pixel.raw', 'dac_delta_l': 'delta_line.raw'} burst_endings = {'b_folder': '', 'b_raw': '.raw', 'b_ras': '.ras', 'b_res': '.res'} # Finally, make a list of which endings should be deleted swath_remove = [dat for key, dat in swath_endings.iteritems() if swath_clean[key]] burst_remove = [dat for key, dat in burst_endings.iteritems() if burst_clean[key]] # Check the total ifgs in the stack swath_folders = scan_stack(stack_folder) # Go over these ifgs and remove intermediate steps in full swath and bursts. deleted = dict() for swath_folder in swath_folders: deleted[swath_folder] = dict() if burst_clean['b_folder']: folders = remove_burst_folders(swath_folder, remove) deleted[swath_folder]['folders'] = folders else: filenames = remove_burst_files(swath_folder, burst_remove, remove) deleted[swath_folder]['burst_files'] = filenames filenames = remove_file(swath_folder, swath_remove, remove) deleted[swath_folder]['swath_files'] = filenames return deleted def scan_stack(stack_folder): # This function enters the children directories and checks whether a master.res, ifgs.res, swath folder and ifg # exist. swath_folders = [] root, dirs, files = os.walk(stack_folder).next() for folder in dirs: r, folders, files = os.walk(os.path.join(root, folder)).next() if 'swath_1' in folders and 'master.res' in files and 'ifgs.res' in files and 'cint.raw' in files: swath_folders.append(os.path.join(root, folder)) return swath_folders def remove_burst_folders(swath_folder, remove): # Remove all burst folders from swath folder folder_names = [] root, dirs, files = os.walk(swath_folder).next() for folder in dirs: if folder.startswith('swath'): if remove: shutil.rmtree(os.path.join(root, folder)) folder_names.append(os.path.join(root, folder)) return folder_names def remove_file(swath_folder, file_endings, remove): # Remove the files in the main folder. file_names = [] root, dirs, files = os.walk(swath_folder).next() for filename in files: for end in file_endings: if filename.endswith(end): if remove: os.remove(os.path.join(root, filename)) file_names.append(os.path.join(root, filename)) return file_names def remove_burst_files(swath_folder, file_endings, remove): # Remove the files in the burst folders. file_names = [] root1, swaths, files = os.walk(swath_folder).next() if len(swaths) == 0: 'Files seems to be deleted already!' return file_names for swath in swaths: root2, bursts, files = os.walk(os.path.join(root1, swath)).next() for burst in bursts: root3, burst_fold, files = os.walk(os.path.join(root2, burst)).next() for filename in files: for end in file_endings: if filename.endswith(end) and remove: if remove: os.remove(os.path.join(root3, filename)) file_names.append(os.path.join(root3, filename)) return file_names Doris-5.0.3Beta/doris_stack/functions/swath_metadata.py000077500000000000000000000144701312547014700232650ustar00rootroot00000000000000from datetime import datetime import collections from doris.doris_stack.functions.precise_read import interpolate_orbit from shapely.geometry import Polygon import numpy as np from scipy.interpolate import RectBivariateSpline import time def swath_datapoints(meta): # First check which datapoints should be included. datapoints = collections.OrderedDict() datapoints['row_1'] = ['t(s)','X(m)','Y(m)','Z(m)'] t = meta['aux']['orbitTime'] x = meta['aux']['orbitX'] y = meta['aux']['orbitY'] z = meta['aux']['orbitZ'] datapoints['NUMBER_OF_DATAPOINTS'] = str(len(t)) i = 0 for n in range(len(t)): t_s = datetime.strptime(t[n],'%Y-%m-%dT%H:%M:%S.%f') t_s = float(t_s.hour * 3600 + t_s.minute * 60 + t_s.second) + float(t_s.microsecond) / 1000000 t_s = "{:.6f}".format(t_s) datapoints['row_' + str(i + 2)] = [t_s, "{:.7f}".format(float(x[n])), "{:.7f}".format(float(y[n])), "{:.7f}".format(float(z[n]))] i += 1 datapoints['NUMBER_OF_DATAPOINTS'] = str(i) return datapoints def swath_precise(meta, precise_folder, dat_type='POE'): # This function utilizes the orbit_read script to read precise orbit files and export them to the resfile format. # Additionally it removes the burst_datapoints part, as it is not needed anymore. # First check whether the precise orbit file exists and load data if that is the case. date = meta['aux']['azimuthTimeStart'][0] X = [] if dat_type not in ['POE', 'RES', 'XML']: print('Choose either POE, RES or XML as data type') return if dat_type == 'POE' or dat_type == 'RES': input_time, X, Y, Z = interpolate_orbit(precise_folder, date, dat_type, 'spline', satellite=meta['Product type specifier']) if len(X) == 0 and dat_type == 'POE': dat_type = 'RES' input_time, X, Y, Z = interpolate_orbit(precise_folder, date, 'RES', 'spline', satellite=meta['Product type specifier']) print('There is no precise orbit file available, we try the restituted files') if len(X) == 0 or dat_type == 'XML': print('There is no precise or restituted orbit file available we use the datapoints from the .xml file') datapoints = swath_datapoints(meta) datatype = 'leader_datapoints' return datapoints, datatype datapoints = collections.OrderedDict() datapoints['row_1'] = ['t(s)','X(m)','Y(m)','Z(m)'] datapoints['NUMBER_OF_DATAPOINTS'] = str(200) for n in range(len(input_time)): datapoints['row_' + str(n + 2)] = [str(input_time[n]), str(X[n]), str(Y[n]), str(Z[n])] return datapoints, 'precise_orbits' def swath_pixel_line_coordinate(meta): # This function converts the given datapoints from xml to line/pixel coordinates with respect to the upper left # pixel of the swath. This information can be used to make a first guess of the corners and center locations of # different burst. aux = meta['aux'] lats = np.array([float(l) for l in aux['sceneCenLat']]) lons = np.array([float(l) for l in aux['sceneCenLon']]) lines = [int(l) for l in aux['sceneCenLine_number']] pixels = [int(l) for l in aux['sceneCenPixel_number']] az_time = [np.datetime64(t) - np.datetime64(aux['azimuthTime'][0]) for t in aux['azimuthTime']] az_step = np.timedelta64(int(float(meta['Azimuth_time_interval (s)']) * 1000000000000), 'ps') new_lines = [int(round(t/az_step)) for t in az_time] lines, count_l = np.unique(new_lines, return_counts=True) pixels, count_p = np.unique(pixels, return_counts=True) lats = lats.reshape((count_p[0], count_l[0])) lons = lons.reshape((count_p[0], count_l[0])) lat_interp = RectBivariateSpline(lines, pixels, lats) lon_interp = RectBivariateSpline(lines, pixels, lons) # These functions can be called using: lat_interp.ev(li, pi). Where li and pi are lists of pixels and lines. return lat_interp, lon_interp def burst_coverage(meta, corners=True, shape=True): # This function returns the lat, lon of the corners of all bursts in this swath. If polygon is True also the poly # gons are generated. # First get the interpolation from pix/line to lat/lon lat_interp, lon_interp = swath_pixel_line_coordinate(meta) # Now calculate the centre pixels of individual bursts. l_b = int(meta['aux']['imageLines'][0]) p_b = int(meta['aux']['imagePixels'][0]) # Calculate first lines start_times = meta['aux']['azimuthTimeStart'] az_time = [np.datetime64(t) - np.datetime64(start_times[0]) for t in start_times] az_step = np.timedelta64(int(float(meta['Azimuth_time_interval (s)']) * 1000000000000), 'ps') start_lines = [int(round(t/az_step)) for t in az_time] burst_center = [] burst_corners = [] burst_shapes = [] # Now loop over all the bursts and calc the center pixel / corners / polygon for l in start_lines: center = [(lon_interp(l+np.floor(l_b/2), np.floor(p_b/2))[0][0], lat_interp(l+np.floor(l_b/2), np.floor(p_b/2))[0][0])] burst_center.append(center) if corners == True or shape == True: ul = (lon_interp(l , 0)[0][0], lat_interp(l, 0)[0][0]) ur = (lon_interp(l , p_b-1)[0][0], lat_interp(l, p_b-1)[0][0]) lr = (lon_interp(l+l_b-1, p_b-1)[0][0], lat_interp(l+l_b-1, p_b-1)[0][0]) ll = (lon_interp(l+l_b-1, 0)[0][0], lat_interp(l+l_b-1, 0)[0][0]) burst_corners.append([ul, ur, lr, ll]) if shape == True: burst_shapes.append(Polygon([ul, ur, lr, ll])) return burst_center, burst_corners, burst_shapes def swath_coverage(meta): # This function calculates the total coverage of the swath. aux = meta['aux'] lats = np.array([float(l) for l in aux['sceneCenLat']]) lons = np.array([float(l) for l in aux['sceneCenLon']]) lines = [int(l) for l in aux['sceneCenLine_number']] pixels = [int(l) for l in aux['sceneCenPixel_number']] lines, count_l = np.unique(lines, return_counts=True) pixels, count_p = np.unique(pixels, return_counts=True) lats = lats.reshape((count_p[0], count_l[0])) lons = lons.reshape((count_p[0], count_l[0])) # ul, ur, lr, ll swath_corners = [(lons[0,0],lats[0,0]), (lons[0,-1],lats[0,-1]), (lons[-1,-1],lats[-1,-1]), (lons[-1,0],lats[-1,0])] swath_shapes = Polygon(swath_corners) return swath_corners, swath_shapes Doris-5.0.3Beta/doris_stack/functions/xml_query.py000077500000000000000000000253451312547014700223270ustar00rootroot00000000000000# This function performs an xml query on a provided xml file. import sys import collections def xml_query(input_xml): try: import xml.etree.cElementTree as etree except: try: from lxml import etree except: #import xml.etree.ElementTree as etree print 'Failed to load lxml.etree or xml.etree.cElementTree' sys.exit(1) inTree = etree.parse(input_xml) queryList = collections.OrderedDict([ ('Volume_file' , 'dummy'), ('Volume_ID' , './/adsHeader/missionDataTakeId'), ('Volume_identifier' , 'dummy'), ('Volume_set_identifier' , 'dummy'), ('Number of records in ref. file' , 'dummy'), ('SAR_PROCESSOR' , 'update_1'), ('SWATH' , './/adsHeader/swath'), ('PASS' , './/generalAnnotation/productInformation/pass'), ('IMAGE_MODE' , './/adsHeader/mode'), ('polarisation' , './/adsHeader/polarisation'), ('Product type specifier' , './/adsHeader/missionId'), ('Logical volume generating facility' , 'dummy'), ('Location and date/time of product creation' , 'dummy'), ('Number_of_lines_Swath' , './/imageAnnotation/imageInformation/numberOfLines'), ('number_of_pixels_Swath' , './/imageAnnotation/imageInformation/numberOfSamples'), ('rangePixelSpacing' , './/imageAnnotation/imageInformation/rangePixelSpacing'), ('azimuthPixelSpacing' , './/imageAnnotation/imageInformation/azimuthPixelSpacing'), ('total_Burst' , 'update_1'), ('Burst_number_index' , 'update_2'), ('RADAR_FREQUENCY (HZ)' , './/generalAnnotation/productInformation/radarFrequency'), ('Scene identification' , 'update_1'), ('Scene location' , 'update_1'), ('Sensor platform mission identifer' , './/adsHeader/missionId'), ('Scene_center_heading' , './/generalAnnotation/productInformation/platformHeading'), ('Scene_centre_latitude' , 'update_2'), ('Scene_centre_longitude' , 'update_2'), ('Radar_wavelength (m)' , 'update_1'), ('Azimuth_steering_rate (deg/s)' , './/generalAnnotation/productInformation/azimuthSteeringRate'), ('Pulse_Repetition_Frequency_raw_data(TOPSAR)' , './/generalAnnotation/downlinkInformationList/downlinkInformation/prf'), ('First_pixel_azimuth_time (UTC)' , 'update_2'), ('Pulse_Repetition_Frequency (computed, Hz)' , './/imageAnnotation/imageInformation/azimuthFrequency'), ('Azimuth_time_interval (s)' , './/imageAnnotation/imageInformation/azimuthTimeInterval'), ('Total_azimuth_band_width (Hz)' , './/imageAnnotation/processingInformation/swathProcParamsList/swathProcParams/azimuthProcessing/totalBandwidth'), ('Weighting_azimuth' , './/imageAnnotation/processingInformation/swathProcParamsList/swathProcParams/azimuthProcessing/windowType'), ('Range_time_to_first_pixel (2way) (ms)' , 'update_1'), ('Range_sampling_rate (computed, MHz)' , 'update_1'), ('Total_range_band_width (MHz)' , 'update_1'), ('Weighting_range' , './/imageAnnotation/processingInformation/swathProcParamsList/swathProcParams/rangeProcessing/windowType'), ('DC_reference_azimuth_time' , 'update_2'), ('DC_reference_range_time' , 'update_2'), ('Xtrack_f_DC_constant (Hz, early edge)' , 'update_2'), ('Xtrack_f_DC_linear (Hz/s, early edge)' , 'update_2'), ('Xtrack_f_DC_quadratic (Hz/s/s, early edge)' , 'update_2'), ('FM_reference_azimuth_time' , 'update_2'), ('FM_reference_range_time' , 'update_2'), ('FM_polynomial_constant_coeff (Hz, early edge)', 'update_2'), ('FM_polynomial_linear_coeff (Hz/s, early edge)', 'update_2'), ('FM_polynomial_quadratic_coeff (Hz/s/s, early edge)', 'update_2'), ('Datafile' , 'update_2'), ('Dataformat' , 'update_2'), ('Number_of_lines_original' , 'update_2'), ('Number_of_pixels_original' , 'update_2') ]) queryList_aux = collections.OrderedDict([ ('Swath_startTime' , './/adsHeader/startTime'), ('Swath_stopTime' , './/adsHeader/stopTime'), ('imageLines' , './/swathTiming/linesPerBurst'), ('imagePixels' , './/swathTiming/samplesPerBurst'), ('firstValidSample' , './/swathTiming/burstList/burst/firstValidSample'), ('lastValidSample' , './/swathTiming/burstList/burst/lastValidSample'), ('productSpec' , './/generalHeader/referenceDocument'), ('productVolDate' , './/setup//IOCSAuxProductGenerationTimeUTC'), ('productDate' , './/generalHeader/generationTime'), ('productFacility' , './/productInfo/generationInfo/level1ProcessingFacility'), ('scenePol' , './/adsHeader/polarisation'), ('sceneMode' , './/adsHeader/mode'), ('sceneCenLine_number' , './/geolocationGrid/geolocationGridPointList/geolocationGridPoint/line'), ('sceneCenPixel_number' , './/geolocationGrid/geolocationGridPointList/geolocationGridPoint/pixel'), ('sceneCenLat' , './/geolocationGrid/geolocationGridPointList/geolocationGridPoint/latitude'), ('sceneCenLon' , './/geolocationGrid/geolocationGridPointList/geolocationGridPoint/longitude'), ('height' , './/geolocationGrid/geolocationGridPointList/geolocationGridPoint/height'), ('azimuthTime' , './/geolocationGrid/geolocationGridPointList/geolocationGridPoint/azimuthTime'), ('sceneRecords' , './/imageDataInfo/imageRaster/numberOfRows'), ('orbitABS' , './/adsHeader/absoluteOrbitNumber'), ('orbitTime' , './/generalAnnotation/orbitList/orbit/time'), ('orbitX' , './/generalAnnotation/orbitList/orbit/position/x'), ('orbitY' , './/generalAnnotation/orbitList/orbit/position/y'), ('orbitZ' , './/generalAnnotation/orbitList/orbit/position/z'), ('rangeRSR' , './/generalAnnotation/productInformation/rangeSamplingRate'), ('rangeBW' , './/imageAnnotation/processingInformation/swathProcParamsList/swathProcParams/rangeProcessing/processingBandwidth'), ('rangeTimePix' , './/imageAnnotation/imageInformation/slantRangeTime'), ('azimuthTimeStart' , './/swathTiming/burstList/burst/azimuthTime'), ('heading' , './/generalAnnotation/productInformation/platformHeading'), ('doppler_azimuth_Time' , './/dopplerCentroid/dcEstimateList/dcEstimate/azimuthTime'), ('doppler_range_Time' , './/dopplerCentroid/dcEstimateList/dcEstimate/t0'), ('dopplerCoeff' , './/dopplerCentroid/dcEstimateList/dcEstimate/dataDcPolynomial'), ('azimuthFmRate_reference_Azimuth_time' , './/generalAnnotation/azimuthFmRateList/azimuthFmRate/azimuthTime'), ('azimuthFmRate_reference_Range_time' , './/generalAnnotation/azimuthFmRateList/azimuthFmRate/t0'), ('azimuthFmRate_c0' , './/generalAnnotation/azimuthFmRateList/azimuthFmRate/c0'), ('azimuthFmRate_c1' , './/generalAnnotation/azimuthFmRateList/azimuthFmRate/c1'), ('azimuthFmRate_c2' , './/generalAnnotation/azimuthFmRateList/azimuthFmRate/c2'), ('azimuthFmRatePolynomial' , './/generalAnnotation/azimuthFmRateList/azimuthFmRate/azimuthFmRatePolynomial') ]) # Now find the variables of queryList and queryList_aux in the xml data. for key in queryList.keys(): try: vars()[key] except KeyError or NameError: vars()[key] = [] if queryList[key][0:3] == './/': for nodes in inTree.findall(queryList[key]): vars()[key].append(nodes.text) dat = vars()[key] if isinstance(dat,list): dat = dat[0] if isinstance(dat,(int,float)): dat = str(dat) queryList[key] = dat for key in queryList_aux.keys(): try: vars()[key] except KeyError or NameError: vars()[key] = [] for nodes in inTree.findall(queryList_aux[key]): vars()[key].append(nodes.text) queryList_aux[key] = vars()[key] # Finally do the first update queryList['SAR_PROCESSOR'] = 'Sentinel-' + queryList['Sensor platform mission identifer'][-2:] queryList['total_Burst'] = str(len(queryList_aux['azimuthTimeStart'])) queryList['Scene identification'] = 'Orbit: '+ queryList_aux['orbitABS'][0] queryList['Scene location'] = 'lat: ' + queryList_aux['sceneCenLat'][0] + ' lon:' + queryList_aux['sceneCenLon'][0] queryList['Radar_wavelength (m)'] = "{:.9f}".format(299792458.0/float(queryList['RADAR_FREQUENCY (HZ)'])) queryList['Range_time_to_first_pixel (2way) (ms)'] = "{:.15f}".format(float(queryList_aux['rangeTimePix'][0])*1000) queryList['Range_sampling_rate (computed, MHz)'] = "{:.9f}".format(float(queryList_aux['rangeRSR'][0])/1000000) queryList['Total_range_band_width (MHz)'] = "{:.9f}".format(float(queryList_aux['rangeBW'][0])/1000000) deldict = ['orbitABS','rangeBW'] for d in deldict: queryList_aux.pop(d) queryList['aux'] = queryList_aux return queryList Doris-5.0.3Beta/doris_stack/main_code/000077500000000000000000000000001312547014700176225ustar00rootroot00000000000000Doris-5.0.3Beta/doris_stack/main_code/__init__.py000066400000000000000000000000001312547014700217210ustar00rootroot00000000000000Doris-5.0.3Beta/doris_stack/main_code/burst.py000066400000000000000000000076461312547014700213500ustar00rootroot00000000000000# This files defines a class for metadata objects of sentinel images. Large part of the work depends on python readers # from the tops toolbox. from doris.doris_stack.functions.burst_metadata import burst_header, burst_readfiles, burst_crop from doris.doris_stack.main_code.resdata import ResData import warnings import os import copy class BurstMeta(ResData): # Class which holds and gathers information of a specific burst for sentinel 1 data. def __init__(self, path='', swath_no='1', pol='vv', burst_num=1, xml='', data=''): # Initialize variables # This indicates the burst number in the swath, acquisition date, centre location and the coverage of the burst (if available). self.burst_num = [] self.new_burst_num = [] self.swath_num = [] self.burst_date = [] self.burst_center = [] self.burst_coverage = [] self.burst_corners = [] self.swath_meta = [] # The following contain the path of xml and data file for swath and burst. self.swath_xml = '' self.swath_data = '' self.burst_res = '' self.burst_data = '' # orbits self.datapoints = [] self.orbit_type = '' ############################################################# # This function creates an swath object and searches for available data and xml files. It gives an error when # either the path does not exist, no data or xml files can be found or the data and xml files do not match.' # Create resdata for this object super(BurstMeta, self).__init__(type='single') if not xml or not data: xml_dir = os.path.join(path, 'annotation') xml = [f for f in os.listdir(xml_dir) if os.path.isfile(os.path.join(xml_dir, f))] data_dir = os.path.join(path, 'measurement') data = [f for f in os.listdir(data_dir) if os.path.isfile(os.path.join(data_dir, f))] # Select polarisation if not any(s in pol for s in ('hh','vv','hv','vh')): warnings.warn('Polarisation not recognized, using default (vv)') pol = 'vv' if not swath_no in ('1','2','3'): warnings.warn('Swath number not recognized, using default (1)') xml = [os.path.join(path,'annotation',x) for x in xml if x[12:14] in pol and x[6] == swath_no] data = [os.path.join(path,'measurement',x) for x in data if x[12:14] in pol and x[6] == swath_no] if type(xml) is str: xml = [xml] if type(data) is str: data = [data] if (len(xml) != 1 and type(xml) is list) or len(data) != 1: warnings.warn('Total number of files should be one!') if not os.path.exists(xml[0]) or not os.path.exists(data[0]): warnings.warn('Either xml or data path does not exist') if xml[0:-3] != data[0:-4]: warnings.warn('xml and data file do not correspond.') if not burst_num: warnings.warn('No burst number given') self.swath_xml = xml[0] self.swath_data = data[0] self.burst_num = burst_num self.swath_num = int(os.path.basename(xml[0])[6]) def meta_burst(self, swath_meta=[], corners=True): # This function reads and stores metadata of the burst based on the swath xml file. If self.swath_meta = swath_meta readfiles = burst_readfiles(copy.deepcopy(self.swath_meta), self.burst_num, self.burst_center, self.burst_corners, self.swath_data) crop = burst_crop(self.swath_meta, self.burst_num, self.swath_data, self.new_burst_num) # Read metadata from xml and inserts in resdata of burst # Insert the different steps (readfiles, orbits and crop) self.header = burst_header('master.res') self.insert(readfiles, process='readfiles') self.insert(self.datapoints, process=self.orbit_type) self.insert(crop, process='crop') Doris-5.0.3Beta/doris_stack/main_code/doris_config.py000066400000000000000000000017511312547014700226450ustar00rootroot00000000000000''' GrsConfig defines paths that are local to the source tree. They are copied into DorisParameters for use in Doris python scripts ''' import xml.etree.ElementTree as ET import sys, os class DorisConfig(object): def __init__(self): xml_file = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'install/doris_config.xml') tree = ET.parse(xml_file) settings = tree.getroot() self.source_path = settings.find('.source_path').text self.doris_path = settings.find('.doris_path').text self.cpxfiddle_path = settings.find('.cpxfiddle_path').text self.job_handler_script = self.source_path + "/doris_stack/main_code/jobHandlerScript" self.function_path = self.source_path + "/doris_stack/functions/" self.main_code_path = self.source_path + "/doris_stack/main_code/" # Extend path sys.path.extend([self.function_path]) sys.path.extend([self.main_code_path]) Doris-5.0.3Beta/doris_stack/main_code/doris_main.py000066400000000000000000000016401312547014700223210ustar00rootroot00000000000000import argparse import os import xml.etree.ElementTree as ET from doris.doris_stack.main_code.doris_sentinel_1 import DorisSentinel1 """Doris processing argument: --parameterfilepath, -p """ # parse arguments here parser = argparse.ArgumentParser(description='Doris processing.') parser.add_argument('--parameterfilepath', '-p', default='./', help='Path to dorisParameter.py file, this file contains case specific parameters') args = parser.parse_args() xml_file = os.path.join(os.path.join(args.parameterfilepath, 'doris_input.xml')) print('Reading ' + xml_file) tree = ET.parse(xml_file) settings = tree.getroot()[0] start_date = settings.find('.start_date').text end_date = settings.find('.end_date').text master_date = settings.find('.master_date').text #start doris sentinel1 run doris_sentinel_1 = DorisSentinel1() doris_sentinel_1.run(args.parameterfilepath, start_date, end_date, master_date) Doris-5.0.3Beta/doris_stack/main_code/doris_parameters.py000066400000000000000000000120211312547014700235330ustar00rootroot00000000000000from datetime import datetime import os from doris_config import DorisConfig import xml.etree.ElementTree as ET class DorisParameters(): """This class contains all parameters that are used in the execution of test_dat_EDS_5.py. path parameters are checked for existance, all parameters are printed to stdout """ def __init__(self, stack_path): grs_config = DorisConfig() self.doris_path = grs_config.doris_path self.cpxfiddle_path = grs_config.cpxfiddle_path self.job_handler_script = grs_config.job_handler_script self.function_path = grs_config.function_path self.source_path = grs_config.source_path self.verbose = True tree = ET.parse(os.path.join(stack_path, 'doris_input.xml')) self.settings = tree.getroot() project_path = self._settings_get('.datastack_folder') self.project_path = project_path data_path = self._settings_get('.sar_data_folder') self.data_path = data_path # # used in single_master.py # # # used in test_dat_ESD # # TODO DLE FIX shape path self.shape_dat = self._settings_get('.shape_file_path') self.track_dir = data_path self.stack_path = project_path + '/stack/' self.precise_orbits = self._settings_get('.orbits_folder') # Start data of datastack. If end date not given it searches till current. self.input_files = project_path + '/input_files/' self.parallel = self._settings_compare('.parallel', 'yes') self.nr_of_jobs = int(self._settings_get('.cores')) self.initialize_flag = self._settings_compare('.initialize_flag', 'yes') self.profile_log = project_path + '/profile_log' self.doris_parallel_flag_dir = project_path + '/.Doris_parallel' self.between_sleep_time = 1 self.end_sleep_time = 1 self.do_coarse_orbits = self._settings_compare('.do_coarse_orbits', 'yes') self.do_deramp = self._settings_compare('.do_deramp', 'yes') self.do_fake_fine_coreg_bursts = self._settings_compare('.do_fake_fine_coreg_bursts', 'yes') self.do_dac_bursts = self._settings_compare('.do_dac_bursts', 'yes') self.do_fake_coreg_bursts = self._settings_compare('.do_fake_coreg_bursts', 'yes') self.do_resample = self._settings_compare('.do_resample', 'yes') self.do_reramp = self._settings_compare('.do_reramp', 'yes') self.do_interferogram = self._settings_compare('.do_interferogram', 'yes') self.do_compref_phase = self._settings_compare('.do_compref_phase', 'yes') self.do_compref_dem = self._settings_compare('.do_compref_dem', 'yes') self.do_coherence = self._settings_compare('.do_coherence', 'yes') self.do_esd = self._settings_compare('.do_esd', 'yes') self.do_network_esd = self._settings_compare('.do_network_esd', 'yes') self.do_ESD_correct = self._settings_compare('.do_ESD_correct', 'yes') self.do_ref_phase = self._settings_compare('.do_ref_phase', 'yes') self.do_ref_dem = self._settings_compare('.do_ref_dem', 'yes') self.do_phasefilt = self._settings_compare('.do_phasefilt', 'yes') self.do_calc_coordinates = self._settings_compare('.do_calc_coordinates', 'yes') self.do_multilooking = self._settings_compare('.do_multilooking', 'yes') self.do_unwrap = self._settings_compare('.do_unwrap', 'yes') # # used in Jobs # # self.job_handler_script = source_path + "/sentinel1/main_code/jobHandlerScript" # # Print parameters, check if paths exist # print 'self.shape_dat: ' + self.shape_dat # self._check_path_exists(self.shape_dat) print 'self.track_dir: ' + self.track_dir self._check_path_exists(self.track_dir) print 'self.stack_path: ' + self.stack_path # self._check_path_exists(self.stack_path) print 'self.precise_orbits: ' + self.precise_orbits self._check_path_exists(self.precise_orbits) print 'self.input_files: ' + self.input_files # self._check_path_exists(self.input_files) # print 'self.main_code_folder: ' + self.main_code_folder # self._check_path_exists(self.main_code_folder) # print 'self.script_folder: ' + self.script_folder # self._check_path_exists(self.script_folder) print 'self.nr_of_jobs: ' + str(self.nr_of_jobs) print 'self.initialize_flag: ' + str(self.initialize_flag) print 'self.jobHandlerScript: ' + self.job_handler_script self._check_path_exists(self.job_handler_script) def _check_path_exists(self, path): if not(os.path.exists(path)): print 'Error Doris_Parameters: path ' + path + ' does not exist' def _settings_get(self, string): return self.settings.find('*/' + string).text def _settings_compare(self, string, comp_string): if (self.settings.find('*/' + string).text.lower()==comp_string.lower()): return True return False Doris-5.0.3Beta/doris_stack/main_code/doris_parameters_path.py000066400000000000000000000006321312547014700245540ustar00rootroot00000000000000import os import sys class DorisParameters_Path(object): def set(self, doris_parameters_path): if(os.path.exists(doris_parameters_path)): sys.path.append(os.path.split(doris_parameters_path)[0]) print 'dorisparameter path: ' + doris_parameters_path else: print 'dorisparameter path: ' + doris_parameters_path + ' not a valid path' Doris-5.0.3Beta/doris_stack/main_code/doris_profile.py000066400000000000000000000011751312547014700230400ustar00rootroot00000000000000import sys import time class Doris_Profile(): def __init__(self, logfile, verbose): self.verbose = verbose if(verbose): self.start_time = time.localtime() self.logfile = logfile + "." + time.strftime("%a, %d %b %Y %H:%M:%S +0000",self.start_time).replace(" ", "_").replace(",", "").replace("+", "") def log_time_stamp(self, logtxt): if(self.verbose): fileHandle = open(self.logfile, 'a') message = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime()) + ' : ' + logtxt + '\n' fileHandle.write(message) fileHandle.close() Doris-5.0.3Beta/doris_stack/main_code/doris_sentinel_1.py000066400000000000000000000201411312547014700234330ustar00rootroot00000000000000# This file is created by: # Gert Mulder # TU Delft # 04-07-2016 ############################## import sys from doris.doris_stack.main_code.stack import StackData from doris.doris_stack.main_code.dorisparameters import DorisParameters from doris.doris_stack.main_code.grs_profile import GRS_Profile from doris.doris_stack.main_code.single_master_stack import SingleMaster class DorisSentinel1(object): def run(self, doris_parameters_path, start_date, end_date, master_date): print 'start sentinel 1 processing' #Set your input variables here. You should use absolute paths. dorisParameters = DorisParameters(doris_parameters_path) # fix DLE sys.path.extend([dorisParameters.function_path]) profile = GRS_Profile(dorisParameters.profile_log + '_' + str(dorisParameters.nr_of_jobs), dorisParameters.verbose) # The shapefile to select the area of interest. You can easily find a shapefile countries or regions on the internet. # For example via diva-gis.org. Shapefile for the Netherlands can be found in the same folder under shapes. shape_dat = dorisParameters.shape_dat # '/...../test.shp' # The folder where SLC images from a specific track are stored. This data will be used as input for the script track_dir = dorisParameters.track_dir # '/......' # This is the output folder. stack_path = dorisParameters.stack_path #'/.....' # Folder where the precise or restituted orbits are stored. Precise orbits can be found via the following link: # 'https://qc.sentinel1.eo.esa.int/aux_poeorb/'. The script will assume that there are precise orbits if this folder is # defined, but falls back to other algorithms if needed. precise_orbits = dorisParameters.precise_orbits #'/......' polarisation = dorisParameters.polarisation # Here the doris inputfiles are stored. (Comes with the python scripts) input_files = dorisParameters.input_files #'/......' profile.log_time_stamp('start') # Create a datastack using the stack function stack = StackData(track_dir=track_dir, shape_dat=shape_dat, start_date=start_date, end_date=end_date, polarisation=polarisation, path=stack_path, db_type=2, precise_dir=precise_orbits) #profile.log_time_stamp('StackData') # Select the images which are new in this datastack. stack.select_image() # Then these images are unzipped stack.check_new_images(master=master_date) # All images which correspond with the start and end date are selected stack.unpack_image() # Based on the shape file bursts are selected for one date print('master date is ' + master_date) stack.select_burst(date=master_date) # And also for the other dates the needed bursts are selected stack.extend_burst() # Remove the images which are not fully present stack.remove_incomplete_images() # Now the exact coordinates of the different burst in the concatenated image is calculated stack.define_burst_coordinates(slaves=True) # Write the datastack to the stack_path folder stack.write_stack(write_path=stack_path,no_data=False) # A few auxiliary functions which are not strictly necessary. # Calculate the coverage of the different sub-swaths stack.swath_coverage() # Write the shapes from the bursts and swaths to a shapefile to check in a GIS program like Qgis. stack.write_shapes() profile.log_time_stamp('stack preparation finished') # Finally delete unzipped images stack.del_unpacked_image() import single_master_stack # Now we import the script to create a single master interferogram processing = SingleMaster(master_date=master_date, start_date=start_date, end_date=end_date, stack_folder=stack_path, input_files=input_files, processing_folder=stack_path) processing.remove_finished(step='dinsar') # Copy the necessary files to start processing profile.log_time_stamp('initialize') processing.initialize() # Calculate the coarse orbits of individual bursts if(dorisParameters.do_coarse_orbits): profile.log_time_stamp('coarse_orbits') processing.coarse_orbits() # Deramp the data of both slave and master if(dorisParameters.do_deramp): profile.log_time_stamp('deramp') processing.deramp(master=True) # Still needed for coherence... # Fake the use of fine window coregistration, which is officially not needed if(dorisParameters.do_fake_fine_coreg_bursts): profile.log_time_stamp('fake_fine_coreg_bursts') processing.fake_fine_coreg() # Perform DEM coregistration for individual bursts if(dorisParameters.do_dac_bursts): profile.log_time_stamp('dac_bursts') processing.dac_bursts() # Fake the use of coregmp, as the orbits are good enough for coregistration if(dorisParameters.do_fake_coreg_bursts): profile.log_time_stamp('fake_coreg_bursts') processing.fake_coregmp() # Resample individual bursts if(dorisParameters.do_resample): profile.log_time_stamp('resample') processing.resample() # Reramp burst if(dorisParameters.do_reramp): profile.log_time_stamp('reramp') processing.reramp() # Perform enhanced spectral diversity for full swath if(dorisParameters.do_esd): profile.log_time_stamp('esd') processing.esd() if (dorisParameters.do_network_esd): profile.log_time_stamp('network esd') processing.network_esd() # Make interferograms for individual bursts if(dorisParameters.do_interferogram): profile.log_time_stamp('interferogram') processing.interferogram() # Calculate earth reference phase from interferograms and combine for full swath if(dorisParameters.do_compref_phase): profile.log_time_stamp('compref_phase') processing.compref_phase() # Calculate height effects from interferograms and combine for full swath if(dorisParameters.do_compref_dem): profile.log_time_stamp('compref_dem') processing.compref_dem() # Remove earth reference phase from interferograms and combine for full swath if(dorisParameters.do_ref_phase): profile.log_time_stamp('ref_phase') processing.ref_phase(concatenate=False) # Remove height effects from interferograms and combine for full swath if(dorisParameters.do_ref_dem): profile.log_time_stamp('ref_dem') processing.ref_dem(concatenate=True, ras=True) # Geocode data if(dorisParameters.do_calc_coordinates): profile.log_time_stamp('calc_coordinates') processing.calc_coordinates() # Correct using ramp ifgs based on ESD if(dorisParameters.do_ESD_correct): profile.log_time_stamp('ESD_correct') processing.ESD_correct_ramp(filename='cint_srd.raw') # Compute coherence if(dorisParameters.do_coherence): profile.log_time_stamp('coherence') processing.coherence(ras=True) if(dorisParameters.do_phasefilt): profile.log_time_stamp('phasefilt') processing.phasefilt(ras=True) # Multilook filtered image and coherence image if(dorisParameters.do_multilooking): profile.log_time_stamp('multilooking') processing.multilook(step='coherence') processing.multilook(step='filtphase') # Unwrap image # processing.del_process('unwrap', type='ifgs', images=True) if(dorisParameters.do_unwrap): profile.log_time_stamp('unwrap') processing.unwrap() profile.log_time_stamp('end') print 'end sentinel 1 processing' Doris-5.0.3Beta/doris_stack/main_code/dorisparameters.py000066400000000000000000000124241312547014700234030ustar00rootroot00000000000000from datetime import datetime import os from doris.doris_stack.main_code.grs_config import GrsConfig import xml.etree.ElementTree as ET class DorisParameters(): """This class contains all parameters that are used in the execution of test_dat_EDS_5.py. path parameters are checked for existance, all parameters are printed to stdout """ def __init__(self, stack_path): grs_config = GrsConfig() self.doris_path = grs_config.doris_path self.cpxfiddle_path = grs_config.cpxfiddle_path self.job_handler_script = grs_config.job_handler_script self.function_path = grs_config.function_path self.source_path = grs_config.source_path self.verbose = True tree = ET.parse(os.path.join(stack_path, 'doris_input.xml')) self.settings = tree.getroot() archive_path = self._settings_get('.sar_data_folder') self.archive_path = archive_path project_path = self._settings_get('.datastack_folder') self.project_path = project_path data_path = self._settings_get('.sar_data_folder') self.data_path = data_path polarisation = self._settings_get('.polarisation') self.polarisation = polarisation track = self._settings_get('.track') self.track = track direction = self._settings_get('.direction') self.direction = direction # # used in single_master.py # # # used in test_dat_ESD # # TODO DLE FIX shape path self.shape_dat = self._settings_get('.shape_file_path') self.track_dir = data_path self.stack_path = os.path.join(project_path, 'stack') self.precise_orbits = self._settings_get('.orbits_folder') # Start data of datastack. If end date not given it searches till current. self.input_files = os.path.join(project_path, 'input_files') self.parallel = self._settings_compare('.parallel', 'yes') self.nr_of_jobs = int(self._settings_get('.cores')) self.profile_log = project_path + '/profile_log' self.doris_parallel_flag_dir = project_path + '/.Doris_parallel' self.between_sleep_time = 1 self.end_sleep_time = 1 self.do_coarse_orbits = self._settings_compare('.do_coarse_orbits', 'yes') self.do_deramp = self._settings_compare('.do_deramp', 'yes') self.do_fake_fine_coreg_bursts = self._settings_compare('.do_fake_fine_coreg_bursts', 'yes') self.do_dac_bursts = self._settings_compare('.do_dac_bursts', 'yes') self.do_fake_coreg_bursts = self._settings_compare('.do_fake_coreg_bursts', 'yes') self.do_resample = self._settings_compare('.do_resample', 'yes') self.do_reramp = self._settings_compare('.do_reramp', 'yes') self.do_interferogram = self._settings_compare('.do_interferogram', 'yes') self.do_compref_phase = self._settings_compare('.do_compref_phase', 'yes') self.do_compref_dem = self._settings_compare('.do_compref_dem', 'yes') self.do_coherence = self._settings_compare('.do_coherence', 'yes') self.do_esd = self._settings_compare('.do_esd', 'yes') self.do_network_esd = self._settings_compare('.do_network_esd', 'yes') self.do_ESD_correct = self._settings_compare('.do_ESD_correct', 'yes') self.do_ref_phase = self._settings_compare('.do_ref_phase', 'yes') self.do_ref_dem = self._settings_compare('.do_ref_dem', 'yes') self.do_phasefilt = self._settings_compare('.do_phasefilt', 'yes') self.do_calc_coordinates = self._settings_compare('.do_calc_coordinates', 'yes') self.do_multilooking = self._settings_compare('.do_multilooking', 'yes') self.do_unwrap = self._settings_compare('.do_unwrap', 'yes') # # used in Jobs # # self.job_handler_script = source_path + "/sentinel1/main_code/jobHandlerScript" # # Print parameters, check if paths exist # print 'self.shape_dat: ' + self.shape_dat # self._check_path_exists(self.shape_dat) print 'self.track_dir: ' + self.track_dir self._check_path_exists(self.track_dir) print 'self.stack_path: ' + self.stack_path # self._check_path_exists(self.stack_path) print 'self.precise_orbits: ' + self.precise_orbits self._check_path_exists(self.precise_orbits) print 'self.input_files: ' + self.input_files # self._check_path_exists(self.input_files) # print 'self.main_code_folder: ' + self.main_code_folder # self._check_path_exists(self.main_code_folder) # print 'self.script_folder: ' + self.script_folder # self._check_path_exists(self.script_folder) print 'self.nr_of_jobs: ' + str(self.nr_of_jobs) print 'self.jobHandlerScript: ' + self.job_handler_script self._check_path_exists(self.job_handler_script) def _check_path_exists(self, path): if not(os.path.exists(path)): print 'Error Doris_Parameters: path ' + path + ' does not exist' def _settings_get(self, string): return self.settings.find('*/' + string).text def _settings_compare(self, string, comp_string): if (self.settings.find('*/' + string).text.lower()==comp_string.lower()): return True return False Doris-5.0.3Beta/doris_stack/main_code/grs_config.py000066400000000000000000000017471312547014700223250ustar00rootroot00000000000000''' GrsConfig defines paths that are local to the source tree. They are copied into DorisParameters for use in Doris python scripts ''' import xml.etree.ElementTree as ET import sys, os class GrsConfig(object): def __init__(self): xml_file = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'install/doris_config.xml') tree = ET.parse(xml_file) settings = tree.getroot() self.source_path = settings.find('.source_path').text self.doris_path = settings.find('.doris_path').text self.cpxfiddle_path = settings.find('.cpxfiddle_path').text self.job_handler_script = self.source_path + "/doris_stack/main_code/jobHandlerScript" self.function_path = self.source_path + "/doris_stack/functions/" self.main_code_path = self.source_path + "/doris_stack/main_code/" # Extend path sys.path.extend([self.function_path]) sys.path.extend([self.main_code_path]) Doris-5.0.3Beta/doris_stack/main_code/grs_profile.py000066400000000000000000000011731312547014700225110ustar00rootroot00000000000000import sys import time class GRS_Profile(): def __init__(self, logfile, verbose): self.verbose = verbose if(verbose): self.start_time = time.localtime() self.logfile = logfile + "." + time.strftime("%a, %d %b %Y %H:%M:%S +0000",self.start_time).replace(" ", "_").replace(",", "").replace("+", "") def log_time_stamp(self, logtxt): if(self.verbose): fileHandle = open(self.logfile, 'a') message = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime()) + ' : ' + logtxt + '\n' fileHandle.write(message) fileHandle.close() Doris-5.0.3Beta/doris_stack/main_code/image.py000066400000000000000000000116651312547014700212670ustar00rootroot00000000000000# This files defines a class for metadata objects of sentinel images. Large part of the work depends on python readers # from the tops toolbox. import os import warnings import zipfile import copy from doris.doris_stack.main_code.swath import SwathMeta class ImageMeta(object): # Object for image files for sentinel data def __init__(self, path='' , pol='all' ,swath_no=['1','2','3']): # Initialize function variables # This will contain a list of swath objects self.swaths = [] self.pol = pol self.swath_no = swath_no # The following contain the path of xml and data files self.swaths_xml = [] self.swaths_data = [] self.image_kml = '' # This variable contains the convex hull of all swaths together self.metadata = [] self.coverage = [] # The following variables store data on which processing steps are performed and the results of these steps. self.steps = [] self.steps_res = [] # The following variable is to check the total number of bursts for this image. This is used to remove time # slots with less bursts. self.burst_no = 0 # Check if the data is unzipped or not. If unzipped run the further initialization. self.zip_path = '' self.unzip_path = '' if path.endswith('.zip'): self.zip_path = path else: self.unzip_path = path # orbit information for this image self.orbit = '' ###################################################### def init_unzipped(self, unzip_path=''): # This function creates an image object and searches for available data and xml files. It gives an error when # either the path does not exist, no data or xml files can be found or the data and xml files do not match. # It is possible to choose one of the available polarisations or swaths using the pol and swath variables. xml_dir = os.path.join(self.unzip_path, 'annotation') xml = [f for f in os.listdir(xml_dir) if os.path.isfile(os.path.join(xml_dir, f))] data_dir = os.path.join(self.unzip_path, 'measurement') data = [f for f in os.listdir(data_dir) if os.path.isfile(os.path.join(data_dir, f))] # Select polarisation if any(s in self.pol for s in ('hh','vv','hv','vh')): xml = [x for x in xml if x[12:14] in self.pol] data = [x for x in data if x[12:14] in self.pol] elif self.pol != 'all': warnings.warn('Polarisation not recognized, using default (all)') # Select swaths xml = sorted([os.path.join(self.unzip_path,'annotation',x) for x in xml if x[6] in self.swath_no]) data = sorted([os.path.join(self.unzip_path,'measurement',x) for x in data if x[6] in self.swath_no]) # Initialize function values dat = [os.path.basename(d) for d in data] self.swaths_xml = [x for x in xml if os.path.basename(x)[:-4] + '.tiff' in dat] self.swaths_data = data # Check if the data is there and if the filenames coincide. if len(self.swaths_xml) == 0: warnings.warn('There are no xml files') def unzip(self, unzip_path=''): # This function unzips the corresponding image, based on some requirements. # Note that this is a backup function, while most unpacking is done by load_shape_unzip.py if not os.path.exists(self.path): try: zip = zipfile.ZipFile(self.path + '.zip') path = os.path.abspath(os.path.join(self.path, os.pardir)) zip.extractall(path) return True except: print('Failed to unpack!') return False else: return True def meta_swath(self, precise_folder=''): # This function reads and stores metadata of different swaths in the swath objects. orbits = [] orb_type = '' if not self.swaths_data: self.init_unzipped() if not self.swaths: for i in range(len(self.swaths_data)): data = self.swaths_data[i] xml = os.path.join(os.path.dirname(os.path.dirname(data)), 'annotation', os.path.basename(data)[:-5] + '.xml') # Initialize swath and load data from xml file swath = SwathMeta(xml=xml, data=data) swath.meta_swath() # Calculate the orbits for this swath and reuse it for other swaths if it is already calculated if not orbits or not orb_type: orbits, orb_type = swath.orbits_swath(precise_folder=precise_folder) else: swath.orbits = copy.deepcopy(orbits) swath.orbit_type = orb_type # Define the resdata for the individual burst. And append the swath to the image object. swath.meta_burst() self.swaths.append(swath) Doris-5.0.3Beta/doris_stack/main_code/jobHandlerScript000077500000000000000000000024601312547014700230070ustar00rootroot00000000000000#!/bin/bash echo ${3} >> ${1}/${2}".started" if [[ "${4}" == "True" ]]; then echo "DORIS PARALLEL:" export PYTHONPATH="${5}:$PYTHONPATH" echo "PYTHONPATH:" echo $PYTHONPATH echo "PATH:" echo $PATH echo ${3}" "${6}" "${7}" "${8}" "${9}" "${10}" "${11}" "${12}" "${13}" "${14}" "${15}" "${16}" "${17}" "${18}" started" date +%T pwd echo >> "./job.started" fi return_value=1 index=0 while [[ $return_value -ne 0 && index -le 5 ]]; do echo "INDEX = "$index if [[ $index -gt 0 ]]; then echo "DORIS PARALLEL Execution FAILED, retry nr "$index echo "DORIS PARALLEL "${3}" "${6}" "${7}" "${8}" "${9}" "${10}" "${11}" "${12}" "${13}" "${14}" "${15}" "${16}" "${17}" "${18}" RESTARTED" fi ${6} ${7} ${8} ${9} ${10} ${11} ${12} ${13} ${14} ${15} ${16} ${17} ${18} 2>&1 | tee job_$index_${2}.log # start job return_value=$? if [ "${3}" == "True" ]; then echo "DORIS PARALLEL return value is:" echo $return_value fi ((index++)) done echo ${3} >> ${1}/${2}".finished" if [ "${4}" == "True" ]; then echo "DORIS PARALLEL:" echo ${3}" "${6}" "${7}" "${8}" "${9}" "${10}" "${11}" "${12}" "${13}" "${14}" "${15}" "${16}" "${17}" "${18}" finished" date +%T pwd echo >> "./job.finished" fi Doris-5.0.3Beta/doris_stack/main_code/jobs.py000066400000000000000000000112141312547014700211300ustar00rootroot00000000000000import os import time class Jobs(object): """The Jobs class runs a list of jobs in parallel. It starts the maximum number of jobs from the list in parallel and monitors for job completion. When jobs are finished, new jobs are started until the maximum is reached again. This is repeated until all jobs from the list are processed. This class executes a jobHandlerScript to execute a job. The job handler script sets job start and job finished flags in a flag directory on the system. In verbose mode the job handler script prints status info to stdout This class generates directories on the system that contain start and finish flags for each job that is run Old flag directories are moved to timestamped directories Methods: Run: executes list of jobs """ def __init__(self, max_jobs, dorisParameters): """max_jobs: maximum number of jobs to run simultaniously verbose: print status to stdout during execution of job list""" self.max_jobs = max_jobs self.pid = str(os.getpid()) self.doris_parameters = dorisParameters self.verbose = self.doris_parameters.verbose self.flag_dir_root = self.doris_parameters.doris_parallel_flag_dir self.between_sleep_time = self.doris_parameters.between_sleep_time self.end_sleep_time = self.doris_parameters.end_sleep_time self.python_path = os.path.dirname(self.doris_parameters.source_path) self.jobs_todo = [] self.jobs_active = [] self.jobs_finished = [] self.flag_dir = '' def _new_id(self): # static class variable Jobs.id = Jobs.id + 1 return Jobs.id def _set_id(self, job_list): for job_dict in job_list: job_dict['id'] = self._new_id() def _create_flag_dir(self): self.flag_dir = self.flag_dir_root + "." + time.asctime(time.localtime(time.time())).replace(" ", "_") os.mkdir(self.flag_dir) def _cleanup_flag_dir(self): # # cleans stuff from current run, if not verbose # if(not (self.verbose)): os.system("rm -rf " + self.flag_dir) def _get_job_id(self, job): # # returns machine level unique job Id return job['path'].replace("/","_") + "." + job['command'].replace("/","_").replace(" ","-") + self.pid def _start_jobs(self): # # starts a number of jobs # returns list of unstarted and list of started jobs # jobs_to_start_count = min((self.max_jobs - len(self.jobs_active)), len(self.jobs_todo)) for index in range(0, jobs_to_start_count): job = self.jobs_todo.pop(0) os.chdir(job['path']) os.system(self.doris_parameters.job_handler_script + " " + self.flag_dir + " " + str(job['id']) + " " + self._get_job_id(job) + " " + str(self.verbose) + " " + self.python_path + " " + job['command'] + " &") self.jobs_active.append(job) return def _check_active_jobs(self): # # returns from the list of jobs, the jobs that are started, but not finished # jobs_active = [] for job in self.jobs_active: # find active jobs this_job_started = False this_job_ready = False for file in os.listdir(self.flag_dir): if str(job['id']) + ".finished" == file: this_job_ready = True # if str(job['id']) + ".started" == file: # this_job_started = True # this_job_active = this_job_started & (not (this_job_ready)) # if (this_job_active): if (not (this_job_ready)): jobs_active.append(job) self.jobs_active = jobs_active return def run(self, job_list): """executes joblist in parallel jobList: list of jobs, containing execution path and command to be executed """ self._create_flag_dir() self.jobs_todo = job_list self._set_id(self.jobs_todo) self._start_jobs() while len(self.jobs_active): if(self.verbose): print time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()) + "jobs busy" time.sleep(self.between_sleep_time) self._check_active_jobs() self._start_jobs() if (self.verbose): print time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()) + "jobs finished" time.sleep(self.end_sleep_time) self._cleanup_flag_dir() Doris-5.0.3Beta/doris_stack/main_code/resdata.py000066400000000000000000000442141312547014700216240ustar00rootroot00000000000000import warnings import os import collections class ResData(object): # This class hold metadata of a doris datafile and processing chain and is capable of reading from and writing to a # .res file used by the doris software. def __init__(self,filename='',type=''): # Initialize variables # Filename of resfile and type (single, interferogram) self.res_path = [] self.res_type = '' # Processes, process_control and header of resfile self.processes = collections.OrderedDict() self.process_control = {} self.process_timestamp = {} self.process_time = {} self.header = {} ##################################################### # Create a ResData object (single/interferogram) if type not in ['single','interferogram'] and not filename: warnings.warn('Define if results data is slave, master or interferogram') return else: self.res_type = type if filename: if not os.path.exists(filename): warnings.warn('This filename does not exist: ' + filename) else: self.res_path = filename self.res_read() else: if type == 'single': self.process_control = collections.OrderedDict([('readfiles', '0'),('leader_datapoints', '0'), ('precise_orbits', '0'), ('crop', '0'), ('sim_amplitude', '0'), ('master_timing' , '0'), ('oversample', '0'), ('resample', '0') , ('filt_azi', '0'), ('filt_range', '0'), ('NOT_USED' , '0')]) elif type == 'interferogram': self.process_control = collections.OrderedDict([('coarse_orbits','0'),('coarse_correl','0'),('fine_coreg','0'),('timing_error','0'),('dem_assist','0'), ('comp_coregpm','0'),('interfero','0'),('coherence','0'),('comp_refphase','0'),('subtr_refphase','0'), ('comp_refdem','0'),('subtr_refdem','0'),('filtphase','0'),('unwrap','0'),('est_orbits','0'),('slant2h','0'), ('geocoding','0'),('dinsar','0'),('NOT_USED2','0')]) def res_read(self): self.meta_reader() self.process_reader() def meta_reader(self): # This function with open(self.res_path) as resfile: splitter = ':' temp = collections.OrderedDict() row = 0 for line in resfile: try: ## Filter out rubbish if line == '\n': continue elif 'Start_process_control' in line: self.header = temp temp = collections.OrderedDict() elif 'End_process_control' in line: self.process_control = temp break elif splitter in line and line[0] is not '|' and line[0] is not '\t' : # Split line if possible and add to dictionary l_split = line.split(splitter) temp[l_split[0].strip()] = l_split[1].strip() else: name = 'row_' + str(row) row += 1 temp[name] = [line] except: print 'Error occurred at line: ' + line def process_reader(self,processes = ''): # This function reads random processes based on standard buildup of processes in res files. # leader_datapoints can be one of the processes, although it will not appear in the process_control in a .res file # If loc is true, it will only return the locations where different processes start. if not processes: processes = self.process_control.keys() processes.append('leader_datapoints') process = '' with open(self.res_path) as resfile: # Start at row zero and with empty list temp = collections.OrderedDict() row = 0 line_no = -1 timestamp = False timestamp_line = 0 for line in resfile: try: line_no += 1 # Filter out rubbish if '|'in line[0]: continue elif '**' in line: continue elif line == '\n': continue # Check if timestamp if ' *===========' in line: # First line of time stamp temp = collections.OrderedDict() timestamp = True row = 0 continue elif ' *-----------' in line: timestamp = False timestamp_data = temp timestamp_line = line_no + 5 continue # Check if process if '*' in line[0]: if line.replace('*_Start_', '').split(':')[0].strip() in processes: process = line.replace('*_Start_', '').split(':')[0].strip() temp = collections.OrderedDict() row = 0; space = [0]; space_r = [0,0,0,0,0,0,0,0] # Finally save the timestamp if it exists if line_no == timestamp_line: self.process_timestamp[process] = timestamp_data else: self.process_timestamp[process] = '' elif line.replace('* End_', '').split(':')[0] == process: self.processes[process] = temp temp = collections.OrderedDict() process = '' continue # Save line if timestamp is True: # Save rows in timestamp row_name = 'row_' + str(row) temp[row_name] = line if row == 1: self.process_time[process] = line.split(':', 1)[1].strip() row += 1 elif process: # If we are in a process output line # Split line using ':' , '=' or spaces (tables) # variable space and space row define the future spacing in every processing step in a res file. if process == 'coarse_orbits': # Add some code for a strange exception in coarse_orbits if '//' in line: temp[line.split()[0]] = line.split()[1:] else: l_split = line.replace('=',':').split(':') temp[l_split[0].strip()] = l_split[1].strip() elif ':' in line: l_split = line.split(':',1) temp[l_split[0].strip()] = l_split[1].strip() else: # If the line does not contain a : it is likely a table. l_split = line.replace('\t',' ').split() row_name = 'row_' + str(row) temp[row_name] = [l_split[i].strip() for i in range(len(l_split))] row += 1 except: print 'Error occurred at line: ' + line def process_spacing(self,process=''): spacing = 0 table_spacing = [0,0,0,0,0,0,0] dat = self.processes[process] for key in dat.keys(): spacing = max(len(key) + 8, spacing) if key.startswith('row'): n=0 for val in self.processes[process][key]: table_spacing[n] = max(len(val) + 3, table_spacing[n]) n += 1 spacing = [spacing] return spacing, table_spacing def del_process(self,process=''): # function deletes one or multiple processes from the corresponding res file if isinstance(process, basestring): # one process if not process in self.process_control.keys(): warnings.warn('The requested process does not exist! (or processes are not read jet, use self.process_reader): ' + str(process)) return elif isinstance(process, list): # If we use a list for proc in process: if not proc in self.process_control.keys(): warnings.warn('The requested process does not exist! (or processes are not read jet, use self.process_reader): ' + str(proc)) return else: warnings.warn('process should contain either a string of one process or a list of multiple processes: ' + str(process)) # Now remove the process and write the file again. if isinstance(process, basestring): # Only one process should be removed self.process_control[process] = '0' del self.processes[process] else: for proc in process: self.process_control[proc] = '0' del self.processes[proc] def write(self,new_filename=''): # Here all the available information acquired is written to a new resfile. Generally if information is manually # added or removed and the file should be created or created again. (For example the readfiles for Sentinel 1 # which are not added yet..) if not new_filename and not self.res_path: warnings.warn('Please specify filename: ' + str(new_filename)) return elif not new_filename: new_filename = self.res_path if not self.process_control or not self.processes: warnings.warn('Every result file needs at least a process control and one process to make any sense: ' + str(new_filename)) # Open file and write header, process control and processes self.res_path = new_filename f = open(new_filename,"w") # Write the header: if self.header: spacing = [40] for key in self.header.keys(): if 'row' in key: # If it is just a string f.write(self.header[key][0]) else: # If the key should included f.write((key + ':').ljust(spacing[0]) + self.header[key] + '\n') # Write the process control for i in range(3): f.write('\n') f.write('Start_process_control\n') for process in self.process_control.keys(): if process != 'leader_datapoints': # leader_datapoints is left out in process control f.write((process + ':\t\t') + str(self.process_control[process]) + '\n') f.write('End_process_control\n') # Then loop through all the processes for process in [p for p in self.processes.keys()]: # First check for a timestamp and add it if needed. if self.process_timestamp[process]: for i in range(2): f.write('\n') f.write(' *====================================================================* \n') for key in self.process_timestamp[process].keys(): f.write(self.process_timestamp[process][key]) f.write(' *--------------------------------------------------------------------* \n') # Then write the process itself if process == 'coarse_orbits': spacing = [45] spacing_row = [15,10,15] else: spacing, spacing_row = self.process_spacing(process) data = self.processes[process] for i in range(3): f.write('\n') f.write('******************************************************************* \n') f.write('*_Start_' + process + ':\n') f.write('******************************************************************* \n') for line_key in self.processes[process].keys(): if 'row' in line_key: # If it is a table of consists of several different parts line = ''.join([(' ' + data[line_key][i]).replace(' -','-').ljust(spacing_row[i]) for i in range(len(data[line_key]))]) f.write(line + '\n') elif process == 'coarse_orbits': # the coarse orbits output is different from the others. if 'Control point' in line_key: # Special case coarse orbits... f.write((line_key + ' =').ljust(spacing[0]) + str(self.processes[process][line_key]) + '\n') elif not isinstance(data[line_key], basestring): # Another special case f.write(line_key.ljust(spacing_row[0]) + (data[line_key][0]).ljust(spacing_row[1]) + data[line_key][1].ljust(spacing_row[2]) + ' '.join(data[line_key][2:]) + '\n') elif isinstance(data[line_key], basestring): # Handle as in normal cases f.write((line_key + ':').ljust(spacing[0]) + str(self.processes[process][line_key]) + '\n') else: # If it consists out of two parts f.write((line_key + ':').ljust(spacing[0]) + str(self.processes[process][line_key]) + '\n') f.write('******************************************************************* \n') f.write('* End_' + process + ':_NORMAL\n') f.write('******************************************************************* \n') f.close() # Read the locations in the new file self.process_reader() def insert(self,data,process,variable=''): # This function inserts a variable or a process which does not exist at the moment processes = self.process_control.keys() processes.extend(['header','leader_datapoints']) if process not in processes: warnings.warn('This process does not exist for this datatype: ' + str(process)) return # If a full process is added if not variable: if self.process_control[process] == '1': warnings.warn('This process already exists! Use the update function: ' + str(process)) return elif self.process_control[process] == '0': self.process_control[process] = '1' self.processes[process] = data self.process_timestamp[process] = '' # A variable is added if variable: if variable in self.processes[process].keys(): warnings.warn('This variable already exists! Use the update function: ' + str(variable)) return elif not self.processes[process][variable]: self.processes[process][variable] = data def delete(self,process,variable=''): # This function deletes a variable or a process which does exist at the moment processes = self.process_control.keys() processes.extend(['header','leader_datapoints']) if process not in processes: warnings.warn('This process does not exist for this datatype: ' + str(process)) return # If a full process is deleted if not variable: if self.process_control[process] == '0': warnings.warn('This process does not exist: ' + str(process)) return elif self.process_control[process] == '1': self.process_control[process] = '0' del self.processes[process] del self.process_timestamp[process] # A variable is deleted if variable: if not variable in self.processes[process].keys(): warnings.warn('This variable does not exist: ' + str(variable)) return else: del self.processes[process][variable] def update(self,data,process,variable=''): # This function updates a variable or a process which does exist at the moment processes = self.process_control.keys() processes.extend(['header','leader_datapoints']) if not process in processes: warnings.warn('This process does not exist for this datatype: ' + str(process)) return # If a full process is added if not variable: if self.process_control[process] == '1': self.processes[process] = data elif self.process_control[process] == '0': warnings.warn('This process does not exist. Use the insert function: ' + str(process)) return # A variable is added if variable: if variable in self.processes[process].keys(): self.processes[process][variable] = data elif not self.processes[process][variable]: warnings.warn('This variable does not exist. Use the insert function: ' + str(variable)) return def request(self,process,variable=''): # This function updates a variable or a process which does exist at the moment processes = self.process_control.keys() processes.extend(['header','leader_datapoints']) if not process in processes: warnings.warn('This process does not exist for this datatype: ' + str(process)) return # If a full process is added if not variable: if self.process_control[process] == '1': data = self.processes[process] elif self.process_control[process] == '0': warnings.warn('This process does not exist: ' + str(process)) return # A variable is added if variable: if variable in self.processes[process].keys(): data = self.processes[process][variable] elif not self.processes[process][variable]: warnings.warn('This variable does not exist: ' + str(variable)) return return dataDoris-5.0.3Beta/doris_stack/main_code/single_master_stack.py000066400000000000000000003637061312547014700242340ustar00rootroot00000000000000import os import numpy as np from datetime import datetime from collections import OrderedDict import copy from copy import deepcopy from doris.doris_stack.main_code.resdata import ResData from doris.doris_stack.main_code.dorisparameters import DorisParameters import collections from jobs import Jobs from doris.doris_stack.functions.baselines import baselines class SingleMaster(object): def __init__(self, start_date='', end_date='', master_date='', stack_folder='', processing_folder='', input_files=''): # This function loads in a datastack to create a single master stack. Optional are the start date, end date and # master date. If they are not defined all dates will be loaded. The master date can be loaded later using the # master function. If you want a random master value, choose master_date='random' # Dates should be given as 'yyyy-mm-dd'. If stack_read is True information is read from the stack_folder. Otherwise # the datastack from an StackData object should be given as input. Jobs.id = 0 doris_parameters = DorisParameters(os.path.dirname(processing_folder)) # (assuming it is stored in the stackfolder self.doris_parameters = doris_parameters if not start_date: self.start_date = doris_parameters.start_date_default else: self.start_date = start_date if not end_date: self.end_date = doris_parameters.end_date_default else: self.end_date = end_date self.start_date = datetime.strptime(self.start_date,'%Y-%m-%d') self.end_date = datetime.strptime(self.end_date, '%Y-%m-%d') self.nr_of_jobs = doris_parameters.nr_of_jobs self.parallel = doris_parameters.parallel self.stack = dict() self.full_swath = dict() self.master_date = '' self.master_key = '' self.folder = processing_folder self.stack_folder = stack_folder self.doris_path = doris_parameters.doris_path self.cpxfiddle = doris_parameters.cpxfiddle_path # '/...../cpxfiddle' self.function_path = doris_parameters.function_path self.input_files = input_files self.ESD_shift = dict() self.ESD_angle_pixel = dict() self.swath = dict() self.overlapping = [] # Initialize ESD variables self.diff_matrix = dict() self.var_matrix = dict() self.to_angle_matrix = dict() self.weight_matrix = dict() if master_date: master_date = datetime.strptime(master_date, '%Y-%m-%d') self.master(master_date) if self.folder: self.processing_read() self.coreg_dates = [d for d in self.stack.keys() if d != self.master_date] def processing_read(self): # This function reads a processing datastack based on the processing folder folders = next(os.walk(self.folder))[1] folders = [fold for fold in folders if len(fold) == 8] self.stack = dict() for fold in folders: s_date = fold[:4] + '-' + fold[4:6] + '-' + fold[6:8] s_datetime = datetime.strptime(s_date,'%Y-%m-%d') if self.start_date <= s_datetime <= self.end_date: self.stack[s_date] = dict() self.full_swath[s_date] = dict() swaths = next(os.walk(os.path.join(self.folder, fold)))[1] swaths = [fol for fol in swaths if len(fol) == 7] for swath in swaths: bursts = next(os.walk(os.path.join(self.folder, fold, swath)))[1] for burst in bursts: burst_name = swath + '_' + burst self.stack[s_date][burst_name] = dict() self.read_res() def remove_finished(self, step='unwrap'): # Checks which processing folders are already finished based on the final step. # possible steps are ('dem_assist', 'comp_coregpm', 'interfero', 'coherence', 'subtr_refphase', 'subtr_refdem', # 'filtphase', 'unwrap', 'geocoding' self.read_res() for date in self.stack.keys(): if 'ifgs' in self.full_swath[date].keys(): if self.full_swath[date]['ifgs'].process_control[step] == '1': self.coreg_dates.remove(date) print('Dates that will be processed are:') for date in self.coreg_dates: print(date) print('End list') def master(self,master_date): # Load master date self.master_date = master_date.strftime('%Y-%m-%d') self.master_key = self.master_date[:4] + self.master_date[5:7] + self.master_date[8:10] if not master_date in self.stack.keys(): print 'Master date is not part of the datastack. If you do not need to initialize anymore this is not a problem.' def baseline(self): # Create baseline plot of datastack. Usefull to select the right master baselines(self.stack_folder,self.start_date,self.end_date) def initialize(self, path='',cascade=False): # If path is not defined the stack will be initialized in the same folder as the datastack. This function does: # - copy .res and .raw files os.chdir(self.folder) for date in self.stack.keys(): date_folder = self.image_path(date) if not os.path.exists(date_folder): os.mkdir(date_folder) for burst in self.stack[date].keys(): swath_folder = self.swath_path(date, burst) if not os.path.exists(swath_folder): os.mkdir(swath_folder) burst_folder = self.burst_path(date, burst, full_path=True) if not os.path.exists(burst_folder): os.mkdir(burst_folder) os.chdir(burst_folder) # Copy data files m_source = self.burst_path(key=burst, date=self.master_date, dat_type='slave', full_path=True) m_dest = self.burst_path(key=burst, date=date, dat_type='master', full_path=True) if not os.path.exists(m_dest): os.symlink(m_source, m_dest) # Write res files new_filename = os.path.join(burst_folder, 'master.res') if not os.path.exists(new_filename): res = deepcopy(self.stack[self.master_date][burst]['slave']) res.processes['crop']['Data_output_file'] = 'master' + res.processes['crop']['Data_output_file'][5:] res.write(new_filename=new_filename) self.read_res() self.create_full_swath() self.coarse_orbits(dates=[self.master_date]) # Create ifgs.res files for master. del self.stack[self.master_date] del self.full_swath[self.master_date] def create_full_swath(self): # Create folders with full swath for individual interferogram. dates = self.stack.keys() # Change the res files. for date in dates: print(date) bursts = self.stack[date].keys() if 'slave' in self.full_swath[date].keys() and 'master' in self.full_swath[date].keys(): continue for dat_type in ['master', 'slave']: self.full_swath[date][dat_type] = copy.deepcopy(self.stack[date][bursts[0]][dat_type]) # Information slave images az_time = self.full_swath[date][dat_type].processes['readfiles']['First_pixel_azimuth_time (UTC)'] az_time = datetime.strptime(az_time,'%Y-%b-%d %H:%M:%S.%f') range_time = float(self.full_swath[date][dat_type].processes['readfiles']['Range_time_to_first_pixel (2way) (ms)']) # First adjust pixel and range times for pixel (1,1) for burst in bursts: az_burst = self.stack[date][burst][dat_type].processes['readfiles']['First_pixel_azimuth_time (UTC)'] az_burst = datetime.strptime(az_burst,'%Y-%b-%d %H:%M:%S.%f') range_burst = float(self.stack[date][burst][dat_type].processes['readfiles']['Range_time_to_first_pixel (2way) (ms)']) if az_burst < az_time: az_time = az_burst if range_burst < range_time: range_time = range_burst az_time = az_time.strftime('%Y-%b-%d %H:%M:%S.%f') range_time = "{0:.15f}".format(range_time) self.full_swath[date][dat_type].processes['readfiles']['First_pixel_azimuth_time (UTC)'] = az_time self.full_swath[date][dat_type].processes['readfiles']['Range_time_to_first_pixel (2way) (ms)'] = range_time # Then change information on image size and crop. no_lines = self.full_swath[date][dat_type].processes['readfiles']['Number_of_lines_output_image'] no_pixels = self.full_swath[date][dat_type].processes['readfiles']['Number_of_pixels_output_image'] self.full_swath[date][dat_type].processes['readfiles']['Number_of_lines_original'] = no_lines self.full_swath[date][dat_type].processes['readfiles']['Number_of_pixels_original'] = no_pixels # Change readfiles self.full_swath[date][dat_type].processes['readfiles']['First_line (w.r.t. output_image)'] = '1' self.full_swath[date][dat_type].processes['readfiles']['Last_line (w.r.t. output_image)'] = no_lines self.full_swath[date][dat_type].processes['readfiles']['First_pixel (w.r.t. output_image)'] = '1' self.full_swath[date][dat_type].processes['readfiles']['Last_pixel (w.r.t. output_image)'] = no_pixels # Change in crop self.full_swath[date][dat_type].processes['crop']['First_line (w.r.t. original_image)'] = '1' self.full_swath[date][dat_type].processes['crop']['Last_line (w.r.t. original_image)'] = no_lines self.full_swath[date][dat_type].processes['crop']['First_pixel (w.r.t. original_image)'] = '1' self.full_swath[date][dat_type].processes['crop']['Last_pixel (w.r.t. original_image)'] = no_pixels if dat_type == 'master': self.full_swath[date][dat_type].processes['crop']['Data_output_file'] = self.master_date + '.raw' else: self.full_swath[date][dat_type].processes['crop']['Data_output_file'] = date + '.raw' self.full_swath[date][dat_type].processes['crop'].pop('First_line (w.r.t. tiff_image)') self.full_swath[date][dat_type].processes['crop'].pop('Last_line (w.r.t. tiff_image)') # Write data to folder folder = self.image_path(date) os.chdir(folder) # Create res_file master_path = self.image_path(date, dat_type + '.res') self.full_swath[date][dat_type].write(new_filename=master_path) self.read_res() def coarse_orbits(self, dates=[]): # Run coarse orbits for all bursts. if not dates: if len(self.coreg_dates) == 0: return dates = self.coreg_dates self.read_res(dates=self.coreg_dates) stack = self.stack full_swath = self.full_swath else: # In the case we process for another date. stack = dict() full_swath = dict() self.read_res(dates=dates, image_stack=full_swath, burst_stack=stack) job_list1 = [] job_list2 = [] bursts = self.stack[dates[0]].keys() for date in dates: for burst in bursts: if 'ifgs' not in self.stack[date][burst].keys(): # If there is an ifgs file, coarse orbits are done... path = self.burst_path(date, burst, full_path=True) command2 = self.doris_path + ' ' + os.path.join(self.input_files, 'input.coarseorb') job_list2.append({"path": path, "command": command2}) if not self.parallel: os.chdir(path) os.system(command2) if self.parallel: jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(job_list2) # Run coarse orbits for full swath if 'ifgs' not in self.full_swath[date].keys(): # If there is an ifgs file, coarse orbits are done... path = self.image_path(date) command1 = self.doris_path + ' ' + os.path.join(self.input_files, 'input.coarseorb') job_list1.append({"path": path, "command": command1}) if not self.parallel: os.chdir(path) os.system(command1) if self.parallel: jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(job_list1) def coarse_correlation(self, ps=False): # Run coarse correlation. if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) for date in self.coreg_dates: job_list1 = [] job_list2 = [] for burst in self.stack[date].keys(): if self.stack[date][burst]['ifgs'].process_control['coarse_correl'] != '1': path = self.burst_path(date, burst, full_path=True) os.chdir(path) if ps is True: master_file = self.burst_path(key=burst,dat_type='master',full_path=False) command1 = 'python -m ' + 'get_winpos' + ' ' + master_file + ' master.res 21 winpos_cc.asc' job_list1.append({"path": path, "command": command1}) command2 = self.doris_path + ' ' + os.path.join(self.input_files, 'input.coarsecorr') job_list2.append({"path": path, "command": command2}) if not self.parallel: os.system('python -m ' + 'get_winpos' + ' ' + master_file + ' master.res 21 winpos_cc.asc') os.system(command2) if ps is False: command = self.doris_path + ' ' + os.path.join(self.input_files, 'input.coarsecorr') job_list1.append({"path": path, "command": command}) if not self.parallel: os.system(command) if (self.parallel): jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(job_list1) jobs.run(job_list2) self.fake_master_steps(step='coarse_correl', full_swath=False) def correct_coarse_correlation(self): # Correct coarse orbits to same reference system for whole image. if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) for date in self.coreg_dates: bursts = self.stack[date].keys() real_trans_p = [] real_trans_l = [] crop_shift_p = [] crop_shift_l = [] for burst in bursts: s_first_pix = self.stack[date][burst]['slave'].processes['readfiles']['First_pixel (w.r.t. output_image)'] s_first_line = self.stack[date][burst]['slave'].processes['readfiles']['First_line (w.r.t. output_image)'] m_first_pix = self.stack[date][burst]['master'].processes['readfiles']['First_pixel (w.r.t. output_image)'] m_first_line = self.stack[date][burst]['master'].processes['readfiles']['First_line (w.r.t. output_image)'] s_first_pix_c = self.stack[date][burst]['slave'].processes['crop']['First_pixel (w.r.t. original_image)'] s_first_line_c = self.stack[date][burst]['slave'].processes['crop']['First_line (w.r.t. original_image)'] m_first_pix_c = self.stack[date][burst]['master'].processes['crop']['First_pixel (w.r.t. original_image)'] m_first_line_c = self.stack[date][burst]['master'].processes['crop']['First_line (w.r.t. original_image)'] coarse_p = self.stack[date][burst]['ifgs'].processes['coarse_correl']['Coarse_correlation_translation_pixels'] coarse_l = self.stack[date][burst]['ifgs'].processes['coarse_correl']['Coarse_correlation_translation_lines'] crop_p = int(s_first_pix) - int(m_first_pix) - int(s_first_pix_c) + int(m_first_pix_c) crop_l = int(s_first_line) - int(m_first_line) - int(s_first_line_c) + int(m_first_line_c) crop_shift_p.append(crop_p) crop_shift_l.append(crop_l) real_trans_p.append(int(coarse_p) + crop_p) real_trans_l.append(int(coarse_l) + crop_l) im_trans_p = int(round(np.median(real_trans_p))) im_trans_l = int(round(np.median(real_trans_l))) for burst, p_shift, l_shift in zip(bursts, crop_shift_p, crop_shift_l): trans_l = str(im_trans_l - l_shift) trans_p = str(im_trans_p - p_shift) self.stack[date][burst]['ifgs'].processes['coarse_correl']['Coarse_correlation_translation_pixels'] = trans_p self.stack[date][burst]['ifgs'].processes['coarse_correl']['Coarse_correlation_translation_lines'] = trans_l self.stack[date][burst]['ifgs'].processes['coarse_correl']['Initial_Offset_CoarseCorr_pixels'] = trans_p self.stack[date][burst]['ifgs'].processes['coarse_correl']['Initial_Offset_CoarseCorr_lines'] = trans_l self.stack[date][burst]['ifgs'].processes['coarse_correl']['Slope_CoarseCorr_pixels'] = '0' self.stack[date][burst]['ifgs'].processes['coarse_correl']['Slope_CoarseCorr_lines'] = '0' self.full_swath[date]['ifgs'].processes['coarse_orbits']['Coarse_orbits_translation_pixels'] = str(im_trans_p) self.full_swath[date]['ifgs'].processes['coarse_orbits']['Coarse_orbits_translation_lines'] = str(im_trans_l) self.update_res(dates=self.coreg_dates) self.fake_master_steps(step='coarse_correl', burst_proc=False) def deramp(self, master=True): # Deramp slave and masters and slaves of bursts. if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) job_list1 = [] job_list2 = [] # Deramp slaves bursts = self.stack[self.coreg_dates[0]].keys() for date in self.coreg_dates: for burst in bursts: path = self.burst_path(date, burst, full_path=True) slave_file = self.burst_path(key=burst, dat_type='slave', full_path=False) slave_deramped = self.burst_path(key=burst, dat_type='slave_deramped', full_path=False) if not os.path.exists(os.path.join(path, slave_deramped)): command2 = 'python ' + os.path.join(self.function_path, 'do_deramp_SLC.py') + ' ' + slave_file + ' slave.res' job_list2.append({"path": path, "command": command2}) if not self.parallel: os.chdir(path) os.system(command2) if self.stack[date][burst]['slave'].processes['crop']['Data_output_file'] != os.path.basename(slave_deramped): self.stack[date][burst]['slave'].processes['crop']['Data_output_file'] = os.path.basename(slave_deramped) if self.stack[date][burst]['slave'].processes['readfiles']['deramp'] != '1': self.stack[date][burst]['slave'].processes['readfiles']['deramp'] = '1' if self.stack[date][burst]['master'].processes['readfiles']['reramp'] != '0': self.stack[date][burst]['master'].processes['readfiles']['reramp'] = '0' # Deramp master date = self.master_date for burst in bursts: path = self.burst_path(date, burst, full_path=True) master_file = self.burst_path(key=burst, dat_type='slave', full_path=False) master_deramped = self.burst_path(key=burst, dat_type='slave_deramped', full_path=False) if not os.path.exists(os.path.join(path, master_deramped)) or not master: command1 = 'python ' + os.path.join(self.function_path, 'do_deramp_SLC.py') + ' ' + master_file + ' slave.res' job_list1.append({"path": path, "command": command1}) if not self.parallel: os.chdir(path) os.system(command1) if self.parallel: jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(job_list1) jobs.run(job_list2) # Create links for master if needed. for burst in bursts: master_file = self.burst_path(key=burst, date=date, dat_type='slave_deramped', full_path=True) for date_slave in self.coreg_dates: slave_file = self.burst_path(key=burst, date=date_slave, dat_type='master_deramped', full_path=True) if not os.path.exists(slave_file): os.symlink(master_file, slave_file) if self.stack[date_slave][burst]['master'].processes['crop']['Data_output_file'] != os.path.basename(slave_file): self.stack[date_slave][burst]['master'].processes['crop']['Data_output_file'] = os.path.basename(slave_file) if self.stack[date_slave][burst]['master'].processes['readfiles']['deramp'] != '1': self.stack[date_slave][burst]['master'].processes['readfiles']['deramp'] = '1' if self.stack[date_slave][burst]['master'].processes['readfiles']['reramp'] != '0': self.stack[date_slave][burst]['master'].processes['readfiles']['reramp'] = '0' self.update_res(dates=self.coreg_dates) def icc_burst(self, ps=False): # Do the icc per burst if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) job_list1 = [] job_list2 = [] for date in self.coreg_dates: for burst in self.stack[date].keys(): if self.stack[date][burst]['ifgs'].process_control['fine_coreg'] != '1': path = self.burst_path(date, burst, full_path=True) master_file = self.burst_path(key=burst,dat_type='master',full_path=False) if not(self.parallel): os.chdir(path) if ps == True: command1 = 'python -m' + 'get_winpos' + ' ' + master_file + ' master.res 101 winpos_fine.asc' job_list1.append({"path": path, "command": command1}) command2 = self.doris_path + ' ' + os.path.join(self.input_files,'input.finecoreg_icc_pointscat') job_list2.append({"path": path, "command": command2}) if (not(self.parallel)): os.system(command1) os.system(command2) elif ps == False: command = self.doris_path + ' ' + os.path.join(self.input_files,'input.finecoreg') job_list1.append({"path": path, "command": command}) if not (self.parallel): os.system(command) if self.parallel: jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(job_list1) jobs.run(job_list2) self.fake_master_steps(step='fine_coreg', full_swath=False) def coreg_full_swath(self): # Do the combined icc and dem coregistration for the full swath # First read all .res files again. if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) for date in self.coreg_dates: # We start by adding the windows of the first burst. no_offset = 0 bursts = self.stack[date].keys() new_icc = copy.deepcopy(self.stack[date][bursts[0]]['ifgs'].processes['fine_coreg']) im_trans_p = self.full_swath[date]['ifgs'].processes['coarse_orbits']['Coarse_orbits_translation_pixels'] im_trans_l = self.full_swath[date]['ifgs'].processes['coarse_orbits']['Coarse_orbits_translation_lines'] for burst in bursts: icc = self.stack[date][burst]['ifgs'].processes['fine_coreg'] position = self.stack[date][burst]['master'].processes['readfiles'] trans_p = self.stack[date][burst]['ifgs'].processes['coarse_correl']['Coarse_correlation_translation_pixels'] trans_l = self.stack[date][burst]['ifgs'].processes['coarse_correl']['Coarse_correlation_translation_lines'] p_shift_offset = int(im_trans_p) - int(trans_p) l_shift_offset = int(im_trans_l) - int(trans_l) p_offset = int(position['First_pixel (w.r.t. output_image)']) - 1 l_offset = int(position['First_line (w.r.t. output_image)']) - 1 window_no = int(icc['Number_of_correlation_windows']) for row in range(1,window_no+1): dat = copy.deepcopy(icc['row_' + str(row)]) dat[0] = str(no_offset) dat[1] = str(int(dat[1]) + l_offset) dat[2] = str(int(dat[2]) + p_offset) dat[3] = str(float(dat[3]) + float(l_shift_offset)) dat[4] = str(float(dat[4]) + float(p_shift_offset)) new_icc['row_' + str(no_offset + 1)] = dat no_offset += 1 new_icc['Number_of_correlation_windows'] = str(no_offset) # Finally save to .res file self.full_swath[date]['ifgs'].insert(new_icc,'fine_coreg') # And write .res file res_path = self.image_path(date,file_path='ifgs.res') self.full_swath[date]['ifgs'].write(new_filename=res_path) self.fake_master_steps(step='fine_coreg', burst_proc=False) def dac_bursts(self): # Do the DEM coregistration and coregpm for the full swath if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) for date in self.coreg_dates: job_list = [] for burst in self.stack[date].keys(): # If this step is not run yet. if self.stack[date][burst]['ifgs'].process_control['dem_assist'] != '1': path = self.burst_path(date, burst, full_path=True) command = self.doris_path + ' ' + os.path.join(self.input_files,'input.dembased') job_list.append({"path": path, "command": command}) if not self.parallel: os.chdir(path) os.system(command) if (self.parallel): jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(job_list) self.fake_master_steps(step='dem_assist', full_swath=False) def coreg_bursts(self,no_poly=True): # Write coregistration results from full swath to individual bursts if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) for date in self.coreg_dates: # First read the polynomials and normalization lines/pixels from full swath path = self.image_path(date) os.chdir(path) os.system(self.doris_path + ' ' + os.path.join(self.input_files,'input.coregpm')) self.read_res(dates=[date]) coreg = copy.deepcopy(self.full_swath[date]['ifgs'].processes['comp_coregpm']) norm_line = [float(coreg['Normalization_Lines'].split()[0]),float(coreg['Normalization_Lines'].split()[1])] norm_pix = [float(coreg['Normalization_Pixels'].split()[0]),float(coreg['Normalization_Pixels'].split()[1])] degree = int(coreg['Degree_cpm']) La = 0; Lb = 0; Lc = 0; Ld = 0; Le = 0; Lf = 0 Pa = 0; Pb = 0; Pc = 0; Pd = 0; Pe = 0; Pf = 0 # Load the polynomial from the full swath if degree == 0 and no_poly == False: Lf = float(coreg['row_0'][0]) Pf = float(coreg['row_1'][0]) if degree == 1 and no_poly == False: Lf = float(coreg['row_0'][0]) Le = float(coreg['row_1'][0]) Ld = float(coreg['row_2'][0]) Pf = float(coreg['row_3'][0]) Pe = float(coreg['row_4'][0]) Pd = float(coreg['row_5'][0]) if degree == 2 and no_poly == False: Lf = float(coreg['row_0'][0]) Le = float(coreg['row_1'][0]) Ld = float(coreg['row_2'][0]) Lc = float(coreg['row_4'][0]) Lb = float(coreg['row_3'][0]) La = float(coreg['row_5'][0]) Pf = float(coreg['row_6'][0]) Pe = float(coreg['row_7'][0]) Pd = float(coreg['row_9'][0]) Pc = float(coreg['row_8'][0]) Pb = float(coreg['row_10'][0]) Pa = float(coreg['row_11'][0]) for burst in self.stack[date].keys(): # Now convert to burst coreg using the pixel and line offset line_burst = int(self.stack[date][burst]['master'].processes['readfiles']['First_line (w.r.t. output_image)']) pixel_burst = int(self.stack[date][burst]['master'].processes['readfiles']['First_pixel (w.r.t. output_image)']) # And convert to an offset in the [-2,2] domain l0 = (line_burst-norm_line[0]) / (norm_line[1]-norm_line[0]) * 4 p0 = (pixel_burst-norm_pix[0]) / (norm_pix[1]-norm_pix[0]) * 4 # Finally convert variables. We assume a 2 degree polynomial. # y = ax'^2+bz'^2+cx'z'+(2ax0+cz0+d)x'+(2bz0+cx0+e)z'+(a0^2+bz0^2+cx0z0+dx0+ez0+f) p_poly = [0,0,0,0,0,0] p_poly[0] = Pa*p0**2 + Pb*l0**2 + Pc*p0*l0 + Pd*p0 + Pe*l0 + Pf p_poly[1] = 2*Pb*l0 + Pc*p0 + Pe p_poly[2] = 2*Pa*l0 + Pc*p0 + Pd p_poly[3] = Pc p_poly[4] = Pb p_poly[5] = Pa l_poly = [0,0,0,0,0,0] l_poly[0] = La*l0**2 + Lb*p0**2 + Lc*p0*l0 + Ld*l0 + Le*p0 + Lf l_poly[1] = 2*Lb*p0 + Lc*l0 + Le l_poly[2] = 2*La*p0 + Lc*l0 + Ld l_poly[3] = Lc l_poly[4] = Lb l_poly[5] = La # lambda function for pixel and line coordinates l_eq = lambda l,p: l_poly[5]*l**2 + l_poly[4]*p**2 + l_poly[3]*l*p + l_poly[2]*l + l_poly[1]*p + l_poly[0] p_eq = lambda l,p: p_poly[5]*p**2 + p_poly[4]*l**2 + p_poly[3]*l*p + p_poly[2]*p + p_poly[1]*l + p_poly[0] # Save new coregistration function to burst coreg['Degree_cpm'] = str(degree) if degree == 0: coreg['row_0'] = ["{0:.8e}".format(l_poly[0]), '0', '0'] coreg['row_1'] = ["{0:.8e}".format(p_poly[0]), '0', '0'] if degree == 1: coreg['row_0'] = ["{0:.8e}".format(l_poly[0]), '0', '0'] coreg['row_1'] = ["{0:.8e}".format(l_poly[1]), '1', '0'] coreg['row_2'] = ["{0:.8e}".format(l_poly[2]), '0', '1'] coreg['row_3'] = ["{0:.8e}".format(p_poly[0]), '0', '0'] coreg['row_4'] = ["{0:.8e}".format(p_poly[1]), '1', '0'] coreg['row_5'] = ["{0:.8e}".format(p_poly[2]), '0', '1'] if degree == 2: coreg['row_0'] = ["{0:.8e}".format(l_poly[0]), '0', '0'] coreg['row_1'] = ["{0:.8e}".format(l_poly[1]), '1', '0'] coreg['row_2'] = ["{0:.8e}".format(l_poly[2]), '0', '1'] coreg['row_3'] = ["{0:.8e}".format(l_poly[4]), '2', '0'] coreg['row_4'] = ["{0:.8e}".format(l_poly[3]), '1', '1'] coreg['row_5'] = ["{0:.8e}".format(l_poly[5]), '0', '2'] coreg['row_6'] = ["{0:.8e}".format(p_poly[0]), '0', '0'] coreg['row_7'] = ["{0:.8e}".format(p_poly[1]), '1', '0'] coreg['row_8'] = ["{0:.8e}".format(p_poly[2]), '0', '1'] coreg['row_9'] = ["{0:.8e}".format(p_poly[4]), '2', '0'] coreg['row_10'] = ["{0:.8e}".format(p_poly[3]), '1', '1'] coreg['row_11'] = ["{0:.8e}".format(p_poly[5]), '0', '2'] coreg['Deltaline_slave00_poly'] = "{0:.8e}".format(-l_eq(-2.0, -2.0)) coreg['Deltapixel_slave00_poly'] = "{0:.8e}".format(-p_eq(-2.0, -2.0)) coreg['Deltaline_slave0N_poly'] = "{0:.8e}".format(-l_eq(-2.0, 2.0)) coreg['Deltapixel_slave0N_poly'] = "{0:.8e}".format(-p_eq(-2, 2.0)) coreg['Deltaline_slaveN0_poly'] = "{0:.8e}".format(-l_eq(2.0, -2.0)) coreg['Deltapixel_slaveN0_poly'] = "{0:.8e}".format(-p_eq(2.0, -2.0)) coreg['Deltaline_slaveNN_poly'] = "{0:.8e}".format(-l_eq(2.0, 2.0)) coreg['Deltapixel_slaveNN_poly'] = "{0:.8e}".format(-p_eq(2.0, 2.0)) # Finally add the Normalization lines / pixels lines = (int(self.stack[date][burst]['master'].processes['crop']['Last_line (w.r.t. original_image)']) - int(self.stack[date][burst]['master'].processes['crop']['First_line (w.r.t. original_image)'])) pixels = (int(self.stack[date][burst]['master'].processes['crop']['Last_pixel (w.r.t. original_image)']) - int(self.stack[date][burst]['master'].processes['crop']['First_pixel (w.r.t. original_image)'])) # Save pixels lines coreg['Normalization_Lines'] = "{0:.8e}".format(1) + ' ' + "{0:.8e}".format(lines) coreg['Normalization_Pixels'] = "{0:.8e}".format(1) + ' ' + "{0:.8e}".format(pixels) # Copy coregistration from full swath to burst try: self.stack[date][burst]['ifgs'].insert(coreg,'comp_coregpm') except: self.stack[date][burst]['ifgs'].update(coreg,'comp_coregpm') self.update_res(dates=[date]) # Save .res files. self.update_res(dates=self.coreg_dates) def fake_fine_coreg(self): # This function is used if only geometrical coregistatration is used. if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) coreg = OrderedDict() coreg['Initial offsets (l,p)'] = '0, 0' coreg['Window_size_L_for_correlation'] = '64' coreg['Window_size_P_for_correlation'] = '64' coreg['Max. offset that can be estimated'] = '32' coreg['Peak search ovs window (l,p)'] = '16 , 16' coreg['Oversampling factor'] = '32' coreg['Number_of_correlation_windows'] = '0' for date in self.coreg_dates: for burst in self.stack[date].keys(): # Insert fake coregistration if not self.stack[date][burst]['ifgs'].process_control['fine_coreg'] == '1': self.stack[date][burst]['ifgs'].insert(coreg,'fine_coreg') self.update_res(dates=self.coreg_dates) self.fake_master_steps(step='fine_coreg', full_swath=False) def fake_coregmp(self): # This function is used if only geometrical coregistatration is used. if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) coreg = OrderedDict() coreg['Degree_cpm'] = '0' coreg['Normalization_Lines'] = '' coreg['Normalization_Pixels'] = '' coreg['Estimated_coefficientsL'] = '' coreg['row_0'] = ["{0:.8e}".format(0), '0', '0'] coreg['Estimated_coefficientsP'] = '' coreg['row_1'] = ["{0:.8e}".format(0), '0', '0'] coreg['Deltaline_slave00_poly'] = "{0:.8e}".format(0) coreg['Deltapixel_slave00_poly'] = "{0:.8e}".format(0) coreg['Deltaline_slave0N_poly'] = "{0:.8e}".format(0) coreg['Deltapixel_slave0N_poly'] = "{0:.8e}".format(0) coreg['Deltaline_slaveN0_poly'] = "{0:.8e}".format(0) coreg['Deltapixel_slaveN0_poly'] = "{0:.8e}".format(0) coreg['Deltaline_slaveNN_poly'] = "{0:.8e}".format(0) coreg['Deltapixel_slaveNN_poly'] = "{0:.8e}".format(0) for date in self.coreg_dates: for burst in self.stack[date].keys(): # Now convert to burst coreg using the pixel and line offset lines = (int(self.stack[date][burst]['master'].processes['crop']['Last_line (w.r.t. original_image)']) - int(self.stack[date][burst]['master'].processes['crop']['First_line (w.r.t. original_image)'])) pixels = (int(self.stack[date][burst]['master'].processes['crop']['Last_pixel (w.r.t. original_image)']) - int(self.stack[date][burst]['master'].processes['crop']['First_pixel (w.r.t. original_image)'])) # Save pixels lines coreg['Normalization_Lines'] = "{0:.8e}".format(1) + ' ' + "{0:.8e}".format(lines) coreg['Normalization_Pixels'] = "{0:.8e}".format(1) + ' ' + "{0:.8e}".format(pixels) # Copy coregistration from full swath to burst if not self.stack[date][burst]['ifgs'].process_control['comp_coregpm'] == '1': self.stack[date][burst]['ifgs'].insert(coreg,'comp_coregpm') self.update_res(dates=self.coreg_dates) self.fake_master_steps(step='comp_coregpm', full_swath=False) def dac_full_swath(self): # This function reads the dem shift result files from the full swath and saves them to both data and result # files of individual bursts. if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) for date in self.coreg_dates: for burst in self.stack[date].keys(): master_dat = self.stack[date][burst]['master'].processes['crop'] lines = int(master_dat['Last_line (w.r.t. original_image)']) - int(master_dat['First_line (w.r.t. original_image)']) pixels = int(master_dat['Last_pixel (w.r.t. original_image)']) - int(master_dat['First_pixel (w.r.t. original_image)']) ref_offset_p = int(self.full_swath[date]['ifgs'].processes['coarse_orbits']['Coarse_orbits_translation_pixels']) ref_offset_l = int(self.full_swath[date]['ifgs'].processes['coarse_orbits']['Coarse_orbits_translation_lines']) offset_p = int(self.stack[date][burst]['ifgs'].processes['coarse_correl']['Coarse_correlation_translation_pixels']) offset_l = int(self.stack[date][burst]['ifgs'].processes['coarse_correl']['Coarse_correlation_translation_lines']) file_path = self.burst_path(date, burst, file_path='dac_delta_pixel.raw', full_path=True) if not os.path.exists(file_path + '.new'): d_pixel = np.memmap(file_path, dtype=np.dtype('float64'), shape=(lines+1,pixels+1)) n_pixel = np.memmap(file_path + '.new', mode='w+', dtype=np.dtype('float64'), shape=(lines+1,pixels+1)) n_pixel[:,:] = d_pixel[:,:] - (offset_p - ref_offset_p) n_pixel.flush() if not os.path.exists(file_path + '.new'): file_path = self.burst_path(date, burst, file_path='dac_delta_line.raw', full_path=True) d_line = np.memmap(file_path, dtype=np.dtype('float64'), shape=(lines+1,pixels+1)) n_line = np.memmap(file_path + '.n', mode='w+', dtype=np.dtype('float64'), shape=(lines+1,pixels+1)) n_line[:,:] = d_line[:,:] - (offset_l - ref_offset_l) n_line.flush() # Write delta line/pixel to burst folder self.concatenate('dac_delta_line.raw.new', 'dac_delta_line.raw.new',dt=np.dtype('float64')) self.concatenate('dac_delta_pixel.raw.new', 'dac_delta_pixel.raw.new',dt=np.dtype('float64')) for date in self.coreg_dates: bursts = self.stack[date].keys() res_dem = deepcopy(self.stack[date][bursts[0]]['ifgs'].processes['dem_assist']) master_crop = deepcopy(self.full_swath[date]['master'].processes['crop']) # Update fields to dimensions of master burst. res_dem['First_line (w.r.t. original_master)'] = master_crop['First_line (w.r.t. original_image)'] res_dem['Last_line (w.r.t. original_master)'] = master_crop['Last_line (w.r.t. original_image)'] res_dem['First_pixel (w.r.t. original_master)'] = master_crop['First_pixel (w.r.t. original_image)'] res_dem['Last_pixel (w.r.t. original_master)'] = master_crop['Last_pixel (w.r.t. original_image)'] lines = int(master_crop['Last_line (w.r.t. original_image)']) - int(master_crop['First_line (w.r.t. original_image)']) res_dem['Number of lines'] = str(lines + 1) pixels = int(master_crop['Last_pixel (w.r.t. original_image)']) - int(master_crop['First_pixel (w.r.t. original_image)']) res_dem['Number of pixels'] = str(pixels + 1) # Load image data file_path = self.image_path(date, file_path='dac_delta_pixel.raw') command = 'mv ' + file_path + '.new ' + file_path os.system(command) d_pixel = np.memmap(file_path, dtype=np.dtype('float64'), shape=(lines+1,pixels+1)) file_path = self.image_path(date, file_path='dac_delta_line.raw') command = 'mv ' + file_path + '.new ' + file_path os.system(command) d_line = np.memmap(file_path, dtype=np.dtype('float64'), shape=(lines+1,pixels+1)) # Correct for corner information. res_dem['Number of pixels'] = str(pixels + 1) res_dem['Deltaline_slave00_dem'] = str(-d_line[0,0]) res_dem['Deltapixel_slave00_dem'] = str(-d_pixel[0,0]) res_dem['Deltaline_slave0N_dem'] = str(-d_line[0,-1]) res_dem['Deltapixel_slave0N_dem'] = str(-d_pixel[0,-1]) res_dem['Deltaline_slaveN0_dem'] = str(-d_line[-1,0]) res_dem['Deltapixel_slaveN0_dem'] = str(-d_pixel[-1,0]) res_dem['Deltaline_slaveNN_dem'] = str(-d_line[-1,-1]) res_dem['Deltapixel_slaveNN_dem'] = str(-d_pixel[-1,-1]) self.full_swath[date]['ifgs'].insert(res_dem,process='dem_assist') self.update_res(dates=self.coreg_dates) self.fake_master_steps(step='dem_assist', burst_proc=False) def resample(self, type=''): # Resample slave bursts if len(self.coreg_dates) == 0: return jobList1 = [] jobList2 = [] for date in self.coreg_dates: for burst in self.stack[date].keys(): if self.stack[date][burst]['slave'].process_control['resample'] != '1': path = self.burst_path(date, burst, full_path=True) command1 = self.doris_path + ' ' + os.path.join(self.input_files, 'input.resample') jobList1.append({"path": path, "command": command1}) if not self.parallel: os.chdir(path) # Resample os.system(command1) if self.parallel: jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(jobList1) jobs.run(jobList2) def reramp(self, type=''): # This function reramps the radar data. If master is True, we assume that there is still an original master file # Which means that it is not needed to reramp that one. If master is false, only the slave is reramped. if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) bursts = self.stack[self.coreg_dates[0]].keys() jobList1 = [] for date in self.coreg_dates: for burst in self.stack[date].keys(): path = self.burst_path(date, burst, full_path=True) if not os.path.exists(os.path.join(path, 'slave_rsmp_reramped.raw')): # If we are before the ESD step and reramp is not jet done. command1 = 'python ' + os.path.join(self.function_path, 'do_reramp_SLC.py') + ' slave_rsmp.raw slave.res' jobList1.append({"path": path, "command": command1}) if not self.parallel: os.chdir(path) os.system(command1) if self.stack[date][burst]['slave'].processes['resample']['Data_output_file'] != 'slave_rsmp_reramped.raw': self.stack[date][burst]['slave'].processes['resample']['Data_output_file'] = 'slave_rsmp_reramped.raw' if self.stack[date][burst]['slave'].processes['readfiles']['reramp'] != '1': self.stack[date][burst]['slave'].processes['readfiles']['reramp'] = '1' # Create links for master if needed. for burst in bursts: for date in self.coreg_dates: # TODO If steps like simamp are added, we have to link back to these files. slave_file = self.burst_path(key=burst, date=date, dat_type='master', full_path=True) if self.stack[date][burst]['master'].processes['crop']['Data_output_file'] != os.path.basename(slave_file): self.stack[date][burst]['master'].processes['crop']['Data_output_file'] = os.path.basename(slave_file) if self.stack[date][burst]['master'].processes['readfiles']['reramp'] != '1': self.stack[date][burst]['master'].processes['readfiles']['reramp'] = '1' if self.parallel: jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(jobList1) self.update_res(dates=self.coreg_dates) self.fake_master_steps(step='resample') def fake_master_resample(self): # This script fakes a resample step for the master file (this is of course not really needed) # This will save us a lot of time in exception handling in steps later on.... # - create a master.res / copy slave.res # - add resampling step (We assume a reramped result) # - add slave_rsmp.raw and slave_rsmp_reramped.raw in complex64 format. # - add the master original and deramp step same as the slave file. date = self.master_date date_1 = self.stack.keys()[0] bursts = self.stack[date_1].keys() burst_res = dict() image_res = dict() self.read_res(dates=[self.master_date], bursts=bursts, burst_stack=burst_res, image_stack=image_res) for burst in self.stack[self.coreg_dates[0]].keys(): # burst_path if not burst_res[date][burst]['slave'].process_control['resample'] == '1': burst_res[date][burst]['slave'].insert(self.stack[date_1][burst]['slave'].processes['resample'], 'resample') # Now create symlink to master data slave_dat = self.burst_path(self.master_date, burst, full_path=True, dat_type='slave') slave_deramped_dat = self.burst_path(self.master_date, burst, full_path=True, dat_type='slave_deramped') master_dat = self.burst_path(self.master_date, burst, full_path=True, dat_type='master') master_deramped_dat = self.burst_path(self.master_date, burst, full_path=True, dat_type='master_deramped') if not os.path.exists(master_dat): os.symlink(slave_dat, master_dat) if not os.path.exists(master_deramped_dat): os.symlink(slave_deramped_dat, master_deramped_dat) # Finally copy the resampled files in complex64 format. resample_dat = self.burst_path(self.master_date, burst, full_path=True, file_path='slave_rsmp.raw') resample_reramped_dat = self.burst_path(self.master_date, burst, full_path=True, file_path='slave_rsmp_reramped.raw') lines = int(burst_res[date][burst]['slave'].processes['readfiles']['Last_line (w.r.t. output_image)']) - \ int(burst_res[date][burst]['slave'].processes['readfiles']['First_line (w.r.t. output_image)']) + 1 pixels = int(burst_res[date][burst]['slave'].processes['readfiles']['Last_pixel (w.r.t. output_image)']) - \ int(burst_res[date][burst]['slave'].processes['readfiles']['First_pixel (w.r.t. output_image)']) + 1 dtype = np.dtype([('re', np.int16), ('im', np.int16)]) if not os.path.exists(resample_dat): resample = np.memmap(resample_dat, dtype='complex64', mode='w+', shape=(lines, pixels)) slc_dat = np.memmap(slave_deramped_dat, dtype=dtype, mode='r', shape=(lines, pixels)).view( np.int16).astype(np.float32).view(np.complex64) resample[:, :] = slc_dat resample.flush() if not os.path.exists(resample_reramped_dat): resample_reramped = np.memmap(resample_reramped_dat, dtype='complex64', mode='w+', shape=(lines, pixels)) slc_ramped_dat = np.memmap(slave_dat, dtype=dtype, mode='r', shape=(lines, pixels)).view( np.int16).astype(np.float32).view(np.complex64) resample_reramped[:, :] = slc_ramped_dat resample_reramped.flush() self.update_res(dates=[date], image_stack=image_res, burst_stack=burst_res) def fake_master_steps(self, step='subtr_refdem', network=True, burst_proc=True, full_swath=True): # This fakes different steps for the ifgs for the master date. These are needed for further processing in a # network setup. Note that we just copy data from one of the other resampled datasets, which means that the actual # information in the .res files is not correct. steps = ['coarse_correl', 'fine_coreg', 'dem_assist', 'comp_coregpm', 'interfero', 'comp_refphase', 'subtr_refphase', 'comp_refdem', 'subtr_refdem', 'filtphase', 'unwrap', 'coherence'] file_steps = {'subtr_refphase': 'cint_srp.raw', 'subtr_refdem': 'cint_srd.raw', 'filtphase': 'cint.0.2filtered', 'unwrapped': 'unwrapped.raw'} if not step in steps: print('Step ' + step + ' does not exist in processing') return elif step == 'resample': self.fake_master_resample() return date = self.master_date date_1 = self.stack.keys()[0] bursts = self.stack[date_1].keys() burst_res = dict() image_res = dict() self.read_res() # Read the information from other steps first. self.read_res(dates=[self.master_date], bursts=bursts, burst_stack=burst_res, image_stack=image_res) if burst_proc: for burst in bursts: if burst_res[date][burst]['ifgs'].process_control[step] != '1': lines = int(burst_res[date][burst]['master'].processes['readfiles']['Last_line (w.r.t. output_image)']) - \ int(burst_res[date][burst]['master'].processes['readfiles']['First_line (w.r.t. output_image)']) + 1 pixels = int(burst_res[date][burst]['master'].processes['readfiles']['Last_line (w.r.t. output_image)']) - \ int(burst_res[date][burst]['master'].processes['readfiles']['First_line (w.r.t. output_image)']) + 1 rsmp_file = self.burst_path(self.master_date, burst, full_path=True, file_path='slave_rsmp_reramped.raw') ifg_file = self.burst_path(self.master_date, burst, full_path=True, file_path='cint.raw') # Cases where we create output files relevant for further processing if not network and step == 'interfero': # If we do not work with a network the interferogram consists of zeros. ifg = np.memmap(ifg_file, dtype='complex64', mode='w+', shape=(lines, pixels)) ifg[:, :] = 0 ifg.flush() elif network and step == 'interfero' and not os.path.exists(ifg_file): os.symlink(rsmp_file, ifg_file) # Check the whether we have to create a file and define which file that should be. elif step in file_steps.keys(): if step == 'coherence': # Coherence of ifg with itself is 1. coh = np.memmap(ifg_file, dtype='float32', mode='w+', shape=(lines, pixels)) coh[:, :] = 1 coh.flush() else: # For other steps we only have to link to the interferogram. This does not make sense for the case # we are using a network for unwrapping and filtphase. But in that case it will not be used... step_file = self.burst_path(self.master_date, burst, full_path=True, file_path=file_steps[step]) if network and not os.path.exists(step_file) and os.path.exists(rsmp_file): os.symlink(rsmp_file, step_file) elif not os.path.exists(ifg_file) and os.path.exists(ifg_file): os.symlink(ifg_file, step_file) # Then copy the information from the other burst files. This hold for all interferogram steps. res_step = copy.deepcopy(self.stack[date_1][burst]['ifgs'].processes[step]) burst_res[date][burst]['ifgs'].insert(res_step, step) # This is generally the same. # And from the main files if needed. Works only if the master resampled slave is also concatenated... if full_swath: if image_res[date]['ifgs'].process_control[step] != '1': # Follow a similar procedure for the full swath lines = int(image_res[date]['master'].processes['readfiles']['Last_line (w.r.t. output_image)']) - \ int(image_res[date]['master'].processes['readfiles']['First_line (w.r.t. output_image)']) + 1 pixels = int(image_res[date]['master'].processes['readfiles']['Last_line (w.r.t. output_image)']) - \ int(image_res[date]['master'].processes['readfiles']['First_line (w.r.t. output_image)']) + 1 rsmp_file = self.image_path(self.master_date, file_path='slave_rsmp_reramped.raw') ifg_file = self.image_path(self.master_date, file_path='cint.raw') if not os.path.exists(rsmp_file) and network: print('Please concatenate the resampled reramped master if you want to do network processing!') # Cases where we create output files relevant for further processing if network == False and step == 'interfero': # If we do not work with a network the interferogram consists of zeros. ifg = np.memmap(ifg_file, dtype='complex64', mode='w+', shape=(lines, pixels)) ifg[:, :] = 0 ifg.flush() elif network and step == 'interfero' and not os.path.exists(ifg_file) and os.path.exists(rsmp_file): os.symlink(rsmp_file, ifg_file) # Check the whether we have to create a file and define which file that should be. elif step in file_steps.keys(): if step == 'coherence': # Coherence of ifg with itself is 1. coh = np.memmap(ifg_file, dtype='float32', mode='w+', shape=(lines, pixels)) coh[:, :] = 1 coh.flush() else: # For other steps we only have to link to the interferogram. This does not make sense for the case # we are using a network for unwrapping and filtphase. But in that case it will not be used... step_file = self.image_path(self.master_date, file_path=file_steps[step]) if network and not os.path.exists(step_file) and os.path.exists(rsmp_file): os.symlink(rsmp_file, step_file) elif not os.path.exists(step_file) and os.path.exists(ifg_file): os.symlink(ifg_file, step_file) # Then copy the information from the other burst files. This hold for all interferogram steps. res_step = copy.deepcopy(self.full_swath[date_1]['ifgs'].processes[step]) image_res[date]['ifgs'].insert(res_step, step) # This is generally the same. self.update_res(dates=[date], image_stack=image_res, burst_stack=burst_res) def fake_interferogram(self): # This step fakes the creation of an interferogram by renaming the resampled slave if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) interfero_dummy = OrderedDict() interfero_dummy['Data_output_file'] = 'slave_rsmp_reramped.raw' interfero_dummy['Data_output_format'] = 'complex_real4' interfero_dummy['First_line (w.r.t. original_master)'] = '' interfero_dummy['First_pixel (w.r.t. original_master)'] = '' interfero_dummy['Last_line (w.r.t. original_master)'] = '' interfero_dummy['Last_pixel (w.r.t. original_master)'] = '' interfero_dummy['Multilookfactor_azimuth_direction'] = '1' interfero_dummy['Multilookfactor_range_direction'] = '1' interfero_dummy['Number of lines (multilooked)'] = '' interfero_dummy['Number of pixels (multilooked)'] = '' # Fake an interferogram for the different bursts. for date in self.coreg_dates: for burst in self.stack[date].keys(): if self.stack[date][burst]['ifgs'].process_control['interfero'] != '1': m_dat = self.stack[date][burst]['master'].processes['crop'] interfero = copy.deepcopy(interfero_dummy) interfero['First_line (w.r.t. original_master)'] = m_dat['First_line (w.r.t. original_image)'] interfero['First_pixel (w.r.t. original_master)'] = m_dat['First_pixel (w.r.t. original_image)'] interfero['Last_line (w.r.t. original_master)'] = m_dat['Last_line (w.r.t. original_image)'] interfero['Last_pixel (w.r.t. original_master)'] = m_dat['Last_pixel (w.r.t. original_image)'] n_lines = int(m_dat['Last_line (w.r.t. original_image)']) - int( m_dat['First_line (w.r.t. original_image)']) + 1 n_pixels = int(m_dat['Last_pixel (w.r.t. original_image)']) - int( m_dat['First_pixel (w.r.t. original_image)']) + 1 interfero['Number of lines (multilooked)'] = str(n_lines) interfero['Number of pixels (multilooked)'] = str(n_pixels) if not self.stack[date][burst]['ifgs'].process_control['interfero'] == '1': self.stack[date][burst]['ifgs'].insert(interfero, 'interfero') # The master and slave results files are switched to get the right correction of the slave file. self.update_res(dates=self.coreg_dates) self.fake_master_steps(step='interfero', network=True, full_swath=False) def interferogram(self, concatenate=True, overwrite=False, ras=False): if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) # Make an interferogram for the different bursts. (Not always necessary) jobList1 = [] for date in self.coreg_dates: for burst in self.stack[date].keys(): if self.stack[date][burst]['ifgs'].process_control['interfero'] != '1': path = self.burst_path(date, burst, full_path=True) os.chdir(path) command1 = self.doris_path + ' ' + os.path.join(self.input_files, 'input.interferogram') jobList1.append({"path": path, "command": command1}) if (not(self.parallel)): os.chdir(path) os.system(command1) if (self.parallel): jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(jobList1) self.read_res(dates=self.coreg_dates) if concatenate == True: cint_name = 'cint.raw' self.concatenate(cint_name, cint_name, dt=np.dtype('complex64'), overwrite=overwrite) for date in self.coreg_dates: if self.full_swath[date]['ifgs'].process_control['interfero'] != '1' or overwrite is True: # Add res file information no_lines = self.full_swath[date]['master'].processes['readfiles']['Number_of_lines_original'] no_pixels = self.full_swath[date]['master'].processes['readfiles']['Number_of_pixels_original'] line_0 = self.full_swath[date]['master'].processes['readfiles']['First_line (w.r.t. output_image)'] line_1 = self.full_swath[date]['master'].processes['readfiles']['Last_line (w.r.t. output_image)'] pix_0 = self.full_swath[date]['master'].processes['readfiles']['First_pixel (w.r.t. output_image)'] pix_1 = self.full_swath[date]['master'].processes['readfiles']['Last_pixel (w.r.t. output_image)'] burst = self.stack[date].keys()[0] res = copy.deepcopy(self.stack[date][burst]['ifgs'].processes['interfero']) res['First_line (w.r.t. original_master)'] = line_0 res['Last_line (w.r.t. original_master)'] = line_1 res['First_pixel (w.r.t. original_master)'] = pix_0 res['Last_pixel (w.r.t. original_master)'] = pix_1 res['Number of lines (multilooked)'] = no_lines res['Number of pixels (multilooked)'] = no_pixels self.full_swath[date]['ifgs'].insert(res, 'interfero') path = self.image_path(date) os.chdir(path) # Finally show preview based on cpxfiddle if ras: pixels = self.full_swath[date]['master'].processes['readfiles']['Number_of_pixels_original'] if not os.path.exists('interferogram_mag.ras') or overwrite: mag = ' -w ' + pixels + ' -e 0.3 -s 1.0 -q mag -o sunraster -b -c gray -M 20/5 -f cr4 -l1 ' \ '-p1 -P' + pixels + ' ' + cint_name + ' > interferogram_mag.ras' os.system(self.cpxfiddle + mag) if not os.path.exists('interferogram_mix.ras') or overwrite: mix = ' -w ' + pixels + ' -e 0.3 -s 1.2 -q mixed -o sunraster -b -c jet -M 20/5 -f cr4 -l1 ' \ '-p1 -P' + pixels + ' ' + cint_name + ' > interferogram_mix.ras' os.system(self.cpxfiddle + mix) if not os.path.exists('interferogram_pha.ras') or overwrite: pha = ' -w ' + pixels + ' -q phase -o sunraster -b -c jet -M 20/5 -f cr4 -l1 ' \ '-p1 -P' + pixels + ' ' + cint_name + ' > interferogram_pha.ras' os.system(self.cpxfiddle + pha) self.update_res(dates=self.coreg_dates) self.fake_master_steps(step='interfero', network=False, full_swath=concatenate) def overlapping(self): # This function calculates the overlapping areas between different bursts. This function will give a list of # overlapping areas between the different bursts. for date in self.stack.keys(): # First make a list of all min max coordinates of all bursts. x0=[]; x1=[]; y0=[]; y1=[] bursts = self.stack[date].keys() for burst in bursts: y0.append(int(self.stack[date][burst][type].processes['readfiles']['First_line (w.r.t. output_image)'])) y1.append(int(self.stack[date][burst][type].processes['readfiles']['Last_line (w.r.t. output_image)'])) x0.append(int(self.stack[date][burst][type].processes['readfiles']['First_pixel (w.r.t. output_image)'])) x1.append(int(self.stack[date][burst][type].processes['readfiles']['Last_pixel (w.r.t. output_image)'])) for b1 in range(len(bursts)): print 'hello' def esd(self, esd_type='ps', max_baseline='200'): esd_folder = os.path.join(self.folder, 'esd') if not os.path.exists(esd_folder): os.mkdir(esd_folder) jobList = [] # First run all the ESD calculations in parallel for date in [self.stack.keys()[0]]: bursts = self.stack[date].keys() sort_id = [int(dat[6]) * 100 + int(dat[14:]) for dat in bursts] bursts = [x for (y, x) in sorted(zip(sort_id, bursts))] for burst, id in zip(bursts, range(len(bursts))): nBurst = int(burst[14:]) next_burst = burst[:14] + str(nBurst + 1) if next_burst in bursts: stack_folder = self.folder overlap = burst + '_' + next_burst ps_select = '1' master_date = self.master_date command = 'python ' + os.path.join(self.function_path, 'ESD_ps_ds.py') + ' ' + stack_folder + ' ' \ + overlap + ' ' + esd_type + ' ' + max_baseline + ' ' + master_date + ' ' + ps_select jobList.append({"path": stack_folder, "command": command}) if not (self.parallel): os.chdir(stack_folder) os.system(command) if self.parallel: jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(jobList) # Now load the different matrices again. # Find all the overlaps and corresponding results: esd_folder = os.path.join(self.stack_folder, 'esd') folders = os.listdir(esd_folder) self.diff_matrix[esd_type] = np.zeros(shape=(len(folders), len(self.stack.keys()) + 1, len(self.stack.keys()) + 1)) self.var_matrix[esd_type] = np.zeros(shape=(len(folders), len(self.stack.keys()) + 1, len(self.stack.keys()) + 1)) self.to_angle_matrix[esd_type] = np.zeros(shape=(len(folders), len(self.stack.keys()) + 1, len(self.stack.keys()) + 1)) self.weight_matrix[esd_type] = np.zeros(shape=(len(folders), len(self.stack.keys()) + 1, len(self.stack.keys()) + 1)) for folder, n in zip(folders, range(len(folders))): f = os.path.join(esd_folder, folder) diff_m = np.load(os.path.join(f, esd_type + '_diff_matrix.npy')) var_m = np.load(os.path.join(f, esd_type + '_var_matrix.npy')) to_angle_m = np.load(os.path.join(f, esd_type + '_to_angle_matrix.npy')) w = np.load(os.path.join(f, esd_type + '_weight_matrix.npy')) self.diff_matrix[esd_type][n, :, :] = diff_m self.var_matrix[esd_type][n, :, :] = var_m self.to_angle_matrix[esd_type][n, :, :] = to_angle_m self.weight_matrix[esd_type][n, :, :] = w def network_esd(self, esd_type='ps', var_calc=False): # This function calculates the ESD values using a network approach dates = (self.stack.keys()) dates.append(self.master_date) dates = sorted(dates) w_matrix = np.sum(self.weight_matrix[esd_type], 0) diff_matrix = np.sum(self.diff_matrix[esd_type] * self.weight_matrix[esd_type], 0) diff_matrix[w_matrix > 0] = diff_matrix[w_matrix > 0] / w_matrix[w_matrix > 0] angle_pixel = np.sum(self.to_angle_matrix[esd_type] * self.weight_matrix[esd_type], 0) angle_pixel[w_matrix > 0] = angle_pixel[w_matrix > 0] / w_matrix[w_matrix > 0] # In case we want to use the variances... if var_calc == True: var_matrix = np.zeros(w_matrix.shape) id = np.where(w_matrix != 0) for n, m in zip(id[0], id[1]): w = self.weight_matrix[esd_type][:, n, m][None, :] v = self.var_matrix[esd_type][:, n, m][None, :] var_matrix[n,m] = np.sum(np.dot(w.transpose(), w) * np.dot(v.transpose(), v)) var_matrix[w_matrix != 0] = var_matrix[w_matrix != 0] / w_matrix[w_matrix != 0] std_calc = np.sqrt(var_matrix) # Finally calculate the network # Find the connections in the difference matrix m_s = np.where(diff_matrix != 0) weight = w_matrix[diff_matrix != 0] # Find the master date master_num = dates.index(self.master_date) slave_nums = range(len(dates)) slave_nums.remove(master_num) # Create the A matrix A = np.zeros(shape=(len(m_s[0]), np.max([np.max(m_s[0]), np.max(m_s[1])]) + 1)) A[range(len(m_s[0])), m_s[0]] = 1 A[range(len(m_s[0])), m_s[1]] = -1 A = np.hstack((A[:, :master_num], A[:, master_num + 1:])) # Create the weight matrix W = np.zeros((len(m_s[0]), len(m_s[0]))) id = range(len(m_s[0])) W[id, id] = 1 / weight W = np.linalg.inv(W) esd_diff = np.dot(np.dot(np.dot(np.linalg.inv(np.dot(np.dot(A.T, W), A)), A.T), W), diff_matrix[diff_matrix != 0]) esd_residue = np.dot(A, esd_diff) - diff_matrix[diff_matrix != 0] print(str(np.nanmean(np.abs(esd_residue)))) sigma = np.std(esd_residue) dates = sorted(self.stack.keys()) for date, shift, n in zip(dates, esd_diff, slave_nums): self.ESD_shift[date] = shift self.ESD_angle_pixel[date] = np.max([angle_pixel[n, master_num], angle_pixel[master_num, n]]) def ESD_correct_ramp(self, filename='cint_srd.raw', network=False): # This function correct for ESD using the expected ramp in the resampled slave image self.read_res() jobList = [] for date in self.stack.keys(): for burst in self.stack[date].keys(): if self.stack[date][burst]['slave'].processes['readfiles']['ESD_correct'] == '0': path = self.burst_path(date, burst, full_path=True) offset = self.ESD_shift[date] angle = self.ESD_angle_pixel[date] if not network and filename.startswith('cint'): # Because after interferogram the slave is subtracted from the master we have to compensate. angle_pixel = str(-offset / angle) else: angle_pixel = str(offset / angle) script = os.path.join(self.function_path, 'correct_ESD.py') command = 'python ' + script + ' ' + filename + ' ' + angle_pixel jobList.append({"path": path, "command": command}) self.stack[date][burst]['slave'].processes['readfiles']['ESD_correct'] = '1' if not (self.parallel): os.chdir(path) os.system(command) if self.parallel: jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(jobList) self.update_res() def combine_slave(self, overwrite=False, ramped=False, deramped=True, ras=False): # This function concatenates the different slave values. Both ramped and deramped. # Add the resample step to the .res file if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) if deramped: self.concatenate('slave_rsmp.raw', 'slave_rsmp.raw', dt= np.dtype('complex64'), overwrite=overwrite) if ramped: self.concatenate('slave_rsmp_reramped.raw', 'slave_rsmp_reramped.raw', dt=np.dtype('complex64'), overwrite=overwrite) for date in self.coreg_dates: if self.full_swath[date]['slave'].process_control != '1': path = self.image_path(date) os.chdir(path) burst = self.stack[date].keys()[0] slave_res = copy.deepcopy(self.stack[date][burst]['slave'].processes['resample']) # Read number of lines lines = int(self.full_swath[date]['master'].processes['readfiles']['Number_of_lines_original']) pixels = int(self.full_swath[date]['master'].processes['readfiles']['Number_of_pixels_original']) # Add information to interfero step about lines and pixels. slave_res['First_line (w.r.t. original_master)'] = str(1) slave_res['Last_line (w.r.t. original_master)'] = str(lines) slave_res['First_pixel (w.r.t. original_master)'] = str(1) slave_res['Last_pixel (w.r.t. original_master)'] = str(pixels) slave_res['Data_output_file'] = 'slave_rsmp_reramped.raw' # Finally add to result file self.full_swath[date]['slave'].insert(slave_res, 'resample') pixels = self.full_swath[date]['master'].processes['readfiles']['Number_of_pixels_original'] if ras: if deramped and (not os.path.exists('slave_rsmp.ras') or overwrite): mag = ' -w ' + pixels + ' -e 0.3 -s 1.0 -q mag -o sunraster -b -c gray -M 20/5 -f cr4 -l1 ' \ '-p1 -P' + pixels + ' slave_rsmp.raw > slave_rsmp.ras' os.system(self.cpxfiddle + mag) if ramped and (not os.path.exists('slaver_rsmp_reramped.ras') or overwrite): mag = ' -w ' + pixels + ' -e 0.3 -s 1.0 -q mag -o sunraster -b -c gray -M 20/5 -f cr4 -l1 ' \ '-p1 -P' + pixels + ' slave_rsmp_reramped.raw > slave_rsmp_reramped.ras' os.system(self.cpxfiddle + mag) self.update_res(dates=self.coreg_dates) def combine_master(self, overwrite=False, ramped=False, deramped=True, ras=False): # This function concatenates the master files to one image. Afterwards the full master files are linked using # symbolic links. date = self.master_date date_1 = self.stack.keys()[0] bursts = self.stack[date_1].keys() burst_res = dict() image_res = dict() self.read_res(dates=[date], bursts=bursts, burst_stack=burst_res, image_stack=image_res) if deramped: self.concatenate('slave_rsmp.raw', 'slave_rsmp.raw', dt=np.dtype('complex64'), overwrite=overwrite, dates=[date]) if ramped: self.concatenate('slave_rsmp_reramped.raw', 'slave_rsmp_reramped.raw', dt=np.dtype('complex64'), overwrite=overwrite, dates=[date]) path = self.image_path(date) os.chdir(path) if image_res[date]['slave'].process_control != '1': burst = burst_res[date].keys()[0] slave_res = copy.deepcopy(burst_res[date][burst]['slave'].processes['resample']) # Read number of lines lines = int(image_res[date]['master'].processes['readfiles']['Number_of_lines_original']) pixels = int(image_res[date]['master'].processes['readfiles']['Number_of_pixels_original']) # Add information to interfero step about lines and pixels. slave_res['First_line (w.r.t. original_master)'] = str(1) slave_res['Last_line (w.r.t. original_master)'] = str(lines) slave_res['First_pixel (w.r.t. original_master)'] = str(1) slave_res['Last_pixel (w.r.t. original_master)'] = str(pixels) slave_res['Data_output_file'] = 'slave_rsmp_reramped.raw' # Finally add to result file image_res[date]['slave'].insert(slave_res, 'resample') pixels = image_res[date]['master'].processes['readfiles']['Number_of_pixels_original'] if ras: if deramped and (not os.path.exists('slave_rsmp.ras') or overwrite): mag = ' -w ' + pixels + ' -e 0.3 -s 1.0 -q mag -o sunraster -b -c gray -M 20/5 -f cr4 -l1 ' \ '-p1 -P' + pixels + ' slave_rsmp.raw > slave_rsmp.ras' os.system(self.cpxfiddle + mag) if ramped and (not os.path.exists('slaver_rsmp_reramped.ras') or overwrite): mag = ' -w ' + pixels + ' -e 0.3 -s 1.0 -q mag -o sunraster -b -c gray -M 20/5 -f cr4 -l1 ' \ '-p1 -P' + pixels + ' slave_rsmp_reramped.raw > slave_rsmp_reramped.ras' os.system(self.cpxfiddle + mag) self.update_res(dates=[date], image_stack=image_res, burst_stack=burst_res) def compref_phase(self, network=False): # This function performs the final steps in making an interferogram for all full images. if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) if network: self.update_res(dates=self.coreg_dates, switch=True) for date in self.coreg_dates: job_list1 = [] for burst in self.stack[date].keys(): if self.stack[date][burst]['ifgs'].process_control['comp_refphase'] != '1': path = self.burst_path(date, burst, full_path=True) command1 = self.doris_path + ' ' + os.path.join(self.input_files, 'input.comprefpha') job_list1.append({"path": path, "command": command1}) if (not(self.parallel)): os.chdir(path) os.system(command1) if (self.parallel): jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(job_list1) if network: self.read_res(dates=self.coreg_dates) self.update_res(dates=self.coreg_dates, switch=True) self.fake_master_steps(step='comp_refphase', full_swath=False) def ref_phase(self,concatenate=True, overwrite=False, network=False, ras=False): # This function performs the final steps in making an interferogram for all full images. if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) job_list2 = [] for date in self.coreg_dates: for burst in self.stack[date].keys(): if self.stack[date][burst]['ifgs'].process_control['subtr_refphase'] != '1': path = self.burst_path(date, burst, full_path=True) command2 = self.doris_path + ' ' + os.path.join(self.input_files, 'input.subtrrefpha') job_list2.append({"path": path, "command": command2}) if (not(self.parallel)): os.chdir(path) os.system(command2) if (self.parallel): jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(job_list2) self.read_res(dates=self.coreg_dates) if concatenate == True: self.concatenate('cint_srp.raw', 'cint_srp.raw', dt=np.dtype('complex64'), overwrite=overwrite) for date in self.coreg_dates: if self.full_swath[date]['ifgs'].process_control['subtr_refphase'] != '1' or overwrite is True: # Add res file information no_lines = self.full_swath[date]['master'].processes['readfiles']['Number_of_lines_original'] no_pixels = self.full_swath[date]['master'].processes['readfiles']['Number_of_pixels_original'] line_0 = self.full_swath[date]['master'].processes['readfiles']['First_line (w.r.t. output_image)'] line_1 = self.full_swath[date]['master'].processes['readfiles']['Last_line (w.r.t. output_image)'] pix_0 = self.full_swath[date]['master'].processes['readfiles']['First_pixel (w.r.t. output_image)'] pix_1 = self.full_swath[date]['master'].processes['readfiles']['Last_pixel (w.r.t. output_image)'] burst = self.stack[date].keys()[0] res_1 = copy.deepcopy(self.stack[date][burst]['ifgs'].processes['comp_refphase']) res_2 = copy.deepcopy(self.stack[date][burst]['ifgs'].processes['subtr_refphase']) res_2['First_line (w.r.t. original_master)'] = line_0 res_2['Last_line (w.r.t. original_master)'] = line_1 res_2['First_pixel (w.r.t. original_master)'] = pix_0 res_2['Last_pixel (w.r.t. original_master)'] = pix_1 res_2['Number of lines (multilooked)'] = no_lines res_2['Number of pixels (multilooked)'] = no_pixels self.full_swath[date]['ifgs'].insert(res_1, 'comp_refphase') self.full_swath[date]['ifgs'].insert(res_2, 'subtr_refphase') path = self.image_path(date) os.chdir(path) # Finally show preview based on cpxfiddle if ras: pixels = self.full_swath[date]['master'].processes['readfiles']['Number_of_pixels_original'] if not os.path.exists('interferogram_srp_mag.ras') or overwrite: mag = ' -w ' + pixels + ' -e 0.3 -s 1.0 -q mag -o sunraster -b -c gray -M 20/5 -f cr4 -l1 ' \ '-p1 -P' + pixels + ' cint_srp.raw > interferogram_srp_mag.ras' os.system(self.cpxfiddle + mag) if not os.path.exists('interferogram_srp_mix.ras') or overwrite: mix = ' -w ' + pixels + ' -e 0.3 -s 1.2 -q mixed -o sunraster -b -c jet -M 20/5 -f cr4 -l1 ' \ '-p1 -P' + pixels + ' cint_srp.raw > interferogram_srp_mix.ras' os.system(self.cpxfiddle + mix) if not os.path.exists('interferogram_srp_pha.ras') or overwrite: pha = ' -w ' + pixels + ' -q phase -o sunraster -b -c jet -M 20/5 -f cr4 -l1 ' \ '-p1 -P' + pixels + ' cint_srp.raw > interferogram_srp_pha.ras' os.system(self.cpxfiddle + pha) self.update_res(dates=self.coreg_dates) self.fake_master_steps(step='subtr_refphase', full_swath=concatenate) def compref_dem(self, network=False): # This function performs the final steps in making an interferogram for all full images. if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) for date in self.coreg_dates: job_list1 = [] for burst in self.stack[date].keys(): if self.stack[date][burst]['ifgs'].process_control['comp_refdem'] != '1': path = self.burst_path(date, burst, full_path=True) command1 = self.doris_path + ' ' + os.path.join(self.input_files, 'input.comprefdem') job_list1.append({"path": path, "command": command1}) if (not(self.parallel)): os.chdir(path) os.system(command1) if (self.parallel): jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(job_list1) self.fake_master_steps(step='comp_refdem', full_swath=False) def ref_dem(self,concatenate=True, overwrite=False, network=False, ras=False): # This function performs the final steps in making an interferogram for all full images. if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) job_list1 = [] job_list2 = [] for date in self.coreg_dates: for burst in self.stack[date].keys(): if self.stack[date][burst]['ifgs'].process_control['subtr_refdem'] != '1': path = self.burst_path(date, burst, full_path=True) command1 = self.doris_path + ' ' + os.path.join(self.input_files, 'input.subtrrefdem') job_list1.append({"path": path, "command": command1}) if network: command2 = 'python ' + os.path.join(self.function_path, 'remove_dem_earth_phase.py') + ' ' + \ self.stack_folder + ' ' + date + ' ' + burst job_list2.append({"path": path, "command": command2}) if not self.parallel: os.chdir(path) os.system(command2) if self.parallel: jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(job_list1) if self.parallel: jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(job_list2) self.read_res(dates=self.coreg_dates) if concatenate == True: self.concatenate('cint_srd.raw', 'cint_srd.raw', dt=np.dtype('complex64'), overwrite=overwrite) for date in self.coreg_dates: if self.full_swath[date]['ifgs'].process_control['subtr_refdem'] != '1' or overwrite is True: # Add res file information no_lines = self.full_swath[date]['master'].processes['readfiles']['Number_of_lines_original'] no_pixels = self.full_swath[date]['master'].processes['readfiles']['Number_of_pixels_original'] line_0 = self.full_swath[date]['master'].processes['readfiles']['First_line (w.r.t. output_image)'] line_1 = self.full_swath[date]['master'].processes['readfiles']['Last_line (w.r.t. output_image)'] pix_0 = self.full_swath[date]['master'].processes['readfiles']['First_pixel (w.r.t. output_image)'] pix_1 = self.full_swath[date]['master'].processes['readfiles']['Last_pixel (w.r.t. output_image)'] burst = self.stack[date].keys()[0] res_1 = copy.deepcopy(self.stack[date][burst]['ifgs'].processes['comp_refdem']) res_2 = copy.deepcopy(self.stack[date][burst]['ifgs'].processes['subtr_refdem']) res_1['First_line (w.r.t. original_master)'] = line_0 res_1['Last_line (w.r.t. original_master)'] = line_1 res_1['First_pixel (w.r.t. original_master)'] = pix_0 res_1['Last_pixel (w.r.t. original_master)'] = pix_1 res_1['Number of lines (multilooked)'] = no_lines res_1['Number of pixels (multilooked)'] = no_pixels res_2['First_line (w.r.t. original_master)'] = line_0 res_2['Last_line (w.r.t. original_master)'] = line_1 res_2['First_pixel (w.r.t. original_master)'] = pix_0 res_2['Last_pixel (w.r.t. original_master)'] = pix_1 res_2['Number of lines (multilooked)'] = no_lines res_2['Number of pixels (multilooked)'] = no_pixels self.full_swath[date]['ifgs'].insert(res_1, 'comp_refdem') self.full_swath[date]['ifgs'].insert(res_2, 'subtr_refdem') path = self.image_path(date) os.chdir(path) # Finally show preview based on cpxfiddle if ras: pixels = self.full_swath[date]['master'].processes['readfiles']['Number_of_pixels_original'] if not os.path.exists('interferogram_srd_mag.ras') or overwrite: mag = ' -w ' + pixels + ' -e 0.3 -s 1.0 -q mag -o sunraster -b -c gray -M 20/5 -f cr4 -l1 ' \ '-p1 -P' + pixels + ' cint_srd.raw > interferogram_srd_mag.ras' os.system(self.cpxfiddle + mag) if not os.path.exists('interferogram_srd_mix.ras') or overwrite: mix = ' -w ' + pixels + ' -e 0.3 -s 1.2 -q mixed -o sunraster -b -c jet -M 20/5 -f cr4 -l1 ' \ '-p1 -P' + pixels + ' cint_srd.raw > interferogram_srd_mix.ras' os.system(self.cpxfiddle + mix) if not os.path.exists('interferogram_srd_pha.ras') or overwrite: pha = ' -w ' + pixels + ' -q phase -o sunraster -b -c jet -M 20/5 -f cr4 -l1 ' \ '-p1 -P' + pixels + ' cint_srd.raw > interferogram_srd_pha.ras' os.system(self.cpxfiddle + pha) self.update_res(dates=self.coreg_dates) self.fake_master_steps(step='comp_refdem', full_swath=concatenate) self.fake_master_steps(step='subtr_refdem', full_swath=concatenate) def coherence(self, concatenate=True, overwrite=False, coh_type='single_master', ras=False): # This function performs the final steps in making an interferogram for all full images. if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) for date in self.coreg_dates: job_list = [] for burst in self.stack[date].keys(): if self.stack[date][burst]['ifgs'].process_control['coherence'] != '1': path = self.burst_path(date, burst, full_path=True) if coh_type == 'single_master': command = self.doris_path + ' ' + os.path.join(self.input_files, 'input.coherence') elif coh_type == 'network': command = self.doris_path + ' ' + os.path.join(self.input_files, 'input.coherence_network') job_list.append({"path": path, "command": command}) if (not(self.parallel)): os.chdir(path) os.system(command) if (self.parallel): jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(job_list) self.read_res(dates=self.coreg_dates) if concatenate == True: self.concatenate('coherence.raw', 'coherence.raw', dt=np.dtype('float32'), overwrite=overwrite) for date in self.coreg_dates: if self.full_swath[date]['ifgs'].process_control['coherence'] != '1' or overwrite is True: # Add res file information no_lines = self.full_swath[date]['master'].processes['readfiles']['Number_of_lines_original'] no_pixels = self.full_swath[date]['master'].processes['readfiles']['Number_of_pixels_original'] line_0 = self.full_swath[date]['master'].processes['readfiles']['First_line (w.r.t. output_image)'] line_1 = self.full_swath[date]['master'].processes['readfiles']['Last_line (w.r.t. output_image)'] pix_0 = self.full_swath[date]['master'].processes['readfiles']['First_pixel (w.r.t. output_image)'] pix_1 = self.full_swath[date]['master'].processes['readfiles']['Last_pixel (w.r.t. output_image)'] burst = self.stack[date].keys()[0] res = copy.deepcopy(self.stack[date][burst]['ifgs'].processes['coherence']) res['First_line (w.r.t. original_master)'] = line_0 res['Last_line (w.r.t. original_master)'] = line_1 res['First_pixel (w.r.t. original_master)'] = pix_0 res['Last_pixel (w.r.t. original_master)'] = pix_1 res['Number of lines (multilooked)'] = no_lines res['Number of pixels (multilooked)'] = no_pixels self.full_swath[date]['ifgs'].insert(res, 'coherence') path = self.image_path(date) os.chdir(path) # Finally show preview based on cpxfiddle if ras: pixels = self.full_swath[date]['master'].processes['readfiles']['Number_of_pixels_original'] if not os.path.exists('coherence.ras') or overwrite: mag = ' -w ' + pixels + ' -q normal -o sunraster -b -c gray -M 20/5 -r 0.0/1.0 -f r4 -l1 ' \ '-p1 -P' + pixels + ' coherence.raw > coherence.ras' os.system(self.cpxfiddle + mag) self.update_res(dates=self.coreg_dates) self.fake_master_steps(step='coherence', full_swath=concatenate) def phasefilt(self,concatenate=True, overwrite=False, ras=False): # This function performs the phase filtering of the individual bursts. if len(self.coreg_dates) == 0: return self.read_res(dates=self.coreg_dates) for date in self.coreg_dates: job_list = [] for burst in self.stack[date].keys(): if self.stack[date][burst]['ifgs'].process_control['filtphase'] != '1': path = self.burst_path(date, burst, full_path=True) command = self.doris_path + ' ' + os.path.join(self.input_files, 'input.phasefilt') job_list.append({"path": path, "command": command}) if (not(self.parallel)): os.chdir(path) os.system(command) if (self.parallel): jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(job_list) self.read_res(dates=self.coreg_dates) if concatenate == True: self.concatenate('cint.0.2filtered', 'cint_filt.raw', dt=np.dtype('complex64'), overwrite=overwrite) for date in self.coreg_dates: if self.full_swath[date]['ifgs'].process_control['filtphase'] != '1' or overwrite is True: # Add res file information no_lines = self.full_swath[date]['master'].processes['readfiles']['Number_of_lines_original'] no_pixels = self.full_swath[date]['master'].processes['readfiles']['Number_of_pixels_original'] line_0 = self.full_swath[date]['master'].processes['readfiles']['First_line (w.r.t. output_image)'] line_1 = self.full_swath[date]['master'].processes['readfiles']['Last_line (w.r.t. output_image)'] pix_0 = self.full_swath[date]['master'].processes['readfiles']['First_pixel (w.r.t. output_image)'] pix_1 = self.full_swath[date]['master'].processes['readfiles']['Last_pixel (w.r.t. output_image)'] burst = self.stack[date].keys()[0] res = copy.deepcopy(self.stack[date][burst]['ifgs'].processes['filtphase']) res['First_line (w.r.t. original_master)'] = line_0 res['Last_line (w.r.t. original_master)'] = line_1 res['First_pixel (w.r.t. original_master)'] = pix_0 res['Last_pixel (w.r.t. original_master)'] = pix_1 res['Number of lines (multilooked)'] = no_lines res['Number of pixels (multilooked)'] = no_pixels self.full_swath[date]['ifgs'].insert(res, 'filtphase') path = self.image_path(date) os.chdir(path) # Finally show preview based on cpxfiddle if ras: pixels = self.full_swath[date]['master'].processes['readfiles']['Number_of_pixels_original'] if not os.path.exists('interferogram_filt_mag.ras') or overwrite: mag = ' -w ' + pixels + ' -e 0.3 -s 1.0 -q mag -o sunraster -b -c gray -M 20/5 -f cr4 -l1 ' \ '-p1 -P' + pixels + ' cint.0.2filtered > interferogram_filt_mag.ras' os.system(self.cpxfiddle + mag) if not os.path.exists('interferogram_filt_mix.ras') or overwrite: mix = ' -w ' + pixels + ' -e 0.3 -s 1.2 -q mixed -o sunraster -b -c jet -M 20/5 -f cr4 -l1 ' \ '-p1 -P' + pixels + ' cint.0.2filtered > interferogram_filt_mix.ras' os.system(self.cpxfiddle + mix) if not os.path.exists('interferogram_filt_pha.ras') or overwrite: pha = ' -w ' + pixels + ' -q phase -o sunraster -b -c jet -M 20/5 -f cr4 -l1 ' \ '-p1 -P' + pixels + ' cint.0.2filtered > interferogram_filt_pha.ras' os.system(self.cpxfiddle + pha) self.update_res(dates=self.coreg_dates) self.fake_master_steps(step='filtphase', full_swath=concatenate) def unwrap(self, ras=True): # This function is used to call the unwrapping program snaphu via doris. for date in self.coreg_dates: path = self.image_path(date) os.chdir(path) # First create an phase input file for unwrapping pixels = self.full_swath[date]['ifgs'].processes['filtphase']['Number of pixels (multilooked)'] print pixels pha = ' -w ' + pixels + ' -q phase -o float -M 1/1 -f cr4 -l1 ' \ '-p1 -P' + pixels + ' cint_filt_ml.raw > unwrap_input.raw' os.system(self.cpxfiddle + pha) command = self.doris_path + ' ' + os.path.join(self.input_files, 'input.unwrap') os.system(command) # And create an image using cpxfiddle if ras: pha = ' -w ' + pixels + ' -q normal -o sunraster -b -c jet -M 1/1 -f r4 -l1 ' \ '-p1 -P' + pixels + ' unwrapped.raw > unwrapped.ras' os.system(self.cpxfiddle + pha) self.fake_master_steps(step='unwrap', burst_proc=False) def calc_coordinates(self, createdem=True): # Calculate the coordinates of grid cells # choose date closest to master as reference date = self.master_date date_1 = self.stack.keys()[0] bursts = self.stack[date_1].keys() burst_res = dict() image_res = dict() self.read_res(dates=[self.master_date], bursts=bursts, burst_stack=burst_res, image_stack=image_res) print('Coordinates are created for master date ' + date) doris_dir = self.doris_path for burst in burst_res[date].keys(): dem_path = self.burst_path(date, burst, 'dem_radar.raw', full_path=True) dem_path_s = self.burst_path(date_1, burst, 'dem_radar.raw', full_path=True) if not os.path.exists(dem_path) and createdem: if os.path.exists(dem_path_s): os.symlink(dem_path_s, dem_path) # path = self.burst_path(date, burst, full_path=True) # Create grid coordinates and heights # dem_inputfile = os.path.join(self.input_files, 'input.createdem') # Run if one of the files does not exist... # geocode_master(folder, geocode_inputfile, dem_inputfile, doris_dir) # this function geocode the bursts of a master file, based on a DEM # Run the create DEM command # command1 = self.doris_path + ' ' + dem_inputfile # job_list1.append({"path": path, "command": command1}) #if not self.parallel: # os.chdir(path) # os.system(command1) #if self.parallel: # jobs = Jobs(self.nr_of_jobs, self.doris_parameters) # jobs.run(job_list1) self.read_res(dates=[self.master_date], bursts=bursts, burst_stack=burst_res, image_stack=image_res) for burst in burst_res[date].keys(): if not burst_res[date][burst]['ifgs'].process_control['slant2h'] == 1: resultfile = copy.deepcopy(self.stack[date_1][burst]['ifgs']) # Add the slant2height information. This is meant to fake the doris script sl2h_dat = collections.OrderedDict() sl2h_dat['Method'] = 'schwabisch' sl2h_dat['Data_output_file'] = 'dem_radar.raw' sl2h_dat['Data_output_format'] = 'real4' sl2h_dat['First_line (w.r.t. original_master)'] = resultfile.processes['comp_refdem'][ 'First_line (w.r.t. original_master)'] sl2h_dat['Last_line (w.r.t. original_master)'] = resultfile.processes['comp_refdem'][ 'Last_line (w.r.t. original_master)'] sl2h_dat['First_pixel (w.r.t. original_master)'] = resultfile.processes['comp_refdem'][ 'First_pixel (w.r.t. original_master)'] sl2h_dat['Last_pixel (w.r.t. original_master)'] = resultfile.processes['comp_refdem'][ 'Last_pixel (w.r.t. original_master)'] sl2h_dat['Multilookfactor_azimuth_direction'] = resultfile.processes['comp_refdem'][ 'Multilookfactor_azimuth_direction'] sl2h_dat['Multilookfactor_range_direction'] = resultfile.processes['comp_refdem'][ 'Multilookfactor_range_direction'] sl2h_dat['Ellipsoid (name,a,b)'] = 'WGS84 6.37814e+06 6.35675e+06' # Add this to all date .res files burst_res[date][burst]['ifgs'].insert(sl2h_dat, process='slant2h') self.update_res(dates=[date], image_stack=image_res, burst_stack=burst_res) job_list1 = [] for burst in burst_res[date].keys(): if not burst_res[date][burst]['ifgs'].process_control['geocoding'] == 1: path = self.burst_path(date, burst, full_path=True) geocode_inputfile = os.path.join(self.input_files, 'input.geocode') # Generate lat / lon files command1 = doris_dir + ' ' + geocode_inputfile job_list1.append({"path": path, "command": command1}) if not self.parallel: os.system(command1) if self.parallel: jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(job_list1) self.concatenate('phi.raw', 'phi.raw', dt=np.dtype('float32'), dates=[date]) self.concatenate('lam.raw', 'lam.raw', dt=np.dtype('float32'), dates=[date]) self.concatenate('dem_radar.raw', 'dem_radar.raw', dt=np.dtype('float32'), dates=[date]) dates = self.coreg_dates # create links for burst in burst_res[date].keys(): if burst_res[date][burst]['ifgs'].process_control['slant2h'] == 1 and \ burst_res[date][burst]['ifgs'].process_control['geocoding'] == 1: res_sl2h = copy.deepcopy(burst_res[date][burst]['ifgs'].processes['slant2h']) res_geo = copy.deepcopy(burst_res[date][burst]['ifgs'].processes['geocoding']) for date_s in dates: if not self.stack[date_s][burst]['ifgs'].process_control['slant2h'] == '1': self.stack[date_s][burst]['ifgs'].insert(res_sl2h, process='slant2h') if not self.stack[date_s][burst]['ifgs'].process_control['geocoding'] == '1': self.stack[date_s][burst]['ifgs'].insert(res_geo, process='geocoding') # Create symlinks for bursts for burst in burst_res[date].keys(): dat_lam = self.burst_path(self.master_date, burst, 'lam.raw', full_path=True) dat_phi = self.burst_path(self.master_date, burst, 'phi.raw', full_path=True) dat_dem = self.burst_path(self.master_date, burst, 'dem_radar.raw', full_path=True) for date_s in dates: link_lam = self.burst_path(date_s, burst, 'lam.raw', full_path=True) link_phi = self.burst_path(date_s, burst, 'phi.raw', full_path=True) link_dem = self.burst_path(date_s, burst, 'dem_radar.raw', full_path=True) if not os.path.exists(link_lam): os.symlink(dat_lam, link_lam) if not os.path.exists(link_phi): os.symlink(dat_phi, link_phi) if not os.path.exists(link_dem): os.symlink(dat_dem, link_dem) # Create symlinks for images for date in dates: dat_lam = self.image_path(self.master_date, 'lam.raw') dat_phi = self.image_path(self.master_date, 'phi.raw') dat_dem = self.image_path(self.master_date, 'dem_radar.raw') link_lam = self.image_path(date, 'lam.raw') link_phi = self.image_path(date, 'phi.raw') link_dem = self.image_path(date, 'dem_radar.raw') if not os.path.exists(link_lam): os.symlink(dat_lam, link_lam) if not os.path.exists(link_phi): os.symlink(dat_phi, link_phi) if not os.path.exists(link_dem): os.symlink(dat_dem, link_dem) def concatenate(self, burst_file, master_file, dt=np.dtype(np.float32), overwrite=False, dates=[], multilooked='False', res_type='master'): # Concatenate all burst to a single full swath product. If burst_file = 'master' then the input master files are read... # This function also accepts cpxint16 datatype if not dates: dates = self.stack.keys() job_list1 = [] for date in dates: path = self.image_path(date) final_path = os.path.join(path, master_file) if not os.path.exists(final_path) or overwrite == True: command1 = 'python ' + os.path.join(self.function_path, 'concatenate_decatenate.py') + ' ' + path \ + ' concatenate ' + burst_file + ' ' + dt.name + ' ' + multilooked + ' ' + res_type job_list1.append({"path": path, "command": command1}) if not self.parallel: os.chdir(path) os.system(command1) if self.parallel: jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(job_list1) def multilook(self, ra=40, az=10, step='filtphase'): # This function does the multilooking using cpxfiddle and updates the resolution of the step variable. You # have to careful that if you want to perform this step to follow on with a smaller data file, for e.g. unwrapping # this should be the last mentioned step. if step == 'filtphase': filename = 'cint.0.2filtered' filename2 = 'cint_filt_ml.raw' type = 'cr4' elif step == 'coherence': filename = 'coherence.raw' filename2 = 'coherence_ml.raw' type = 'r4' elif step == 'subtr_refdem': filename = 'cint_srd.raw' filename2 = 'cint_srd_ml.raw' type = 'cr4' elif step == 'subtr_refpha': filename = 'cint_srp.raw' filename2 = 'cint_srp_ml.raw' type = 'cr4' elif step == 'interfero': filename = 'cint.raw' filename2 = 'cint_ml.raw' type = 'cr4' else: print('Choose for step between filtphase, coherence, subtrefdem, subtrefpha and interfero') self.read_res() for date in self.coreg_dates: print(date) lines = int(self.full_swath[date]['master'].processes['readfiles']['Number_of_lines_original']) pixels = int(self.full_swath[date]['master'].processes['readfiles']['Number_of_pixels_original']) date_path = self.image_path(date) os.chdir(date_path) # Create cpxfiddle command command = ' -w ' + str(pixels) + ' -o float -M ' + str(ra) + '/'+ str(az) + ' -f ' + type + ' ' \ '-l1 -p1 -P' + str(pixels) + ' -q normal ' + filename + ' > ' + filename2 os.system(self.cpxfiddle + command) # Update res file new_lines = str(int(np.floor(lines / az))) new_pixels = str(int(np.floor(pixels / ra))) res = self.full_swath[date]['ifgs'].processes[step] res['Data_output_file'] = filename2 res['Multilookfactor_azimuth_direction'] = str(az) res['Multilookfactor_range_direction'] = str(ra) res['Number of lines (multilooked)'] = new_lines res['Number of pixels (multilooked)'] = new_pixels self.full_swath[date]['ifgs'].processes[step] = res # Finally create an image using cpxfiddle (full resolution) if type == 'r4': # Only show the magnitude if step == 'coherence': mag = ' -w ' + new_pixels + ' -q normal -o sunraster -b -c gray -M 20/5 -r 0.0/1.0 -f r4 -l1 ' \ '-p1 -P' + new_pixels + ' ' + filename2 + ' > ' + filename2[:-4] + '.ras' else: mag = ' -w ' + new_pixels + ' -e 0.3 -s 1.0 -q normal -o sunraster -b -c gray -M 1/1 -f r4 -l1 ' \ '-p1 -P' + new_pixels + ' ' + filename2 + ' > ' + filename2[:-4] + '.ras' os.system(self.cpxfiddle + mag) elif type == 'cr4': # Show the 3 images mag = ' -w ' + new_pixels + ' -e 0.3 -s 1.0 -q mag -o sunraster -b -c gray -M 1/1 -f cr4 -l1 ' \ '-p1 -P' + new_pixels + ' ' + filename2 + ' > ' + filename2[:-4] + '_mag.ras' os.system(self.cpxfiddle + mag) mix = ' -w ' + new_pixels + ' -e 0.3 -s 1.2 -q mixed -o sunraster -b -c jet -M 1/1 -f cr4 -l1 ' \ '-p1 -P' + new_pixels + ' ' + filename2 + ' > ' + filename[:-4] + '_mix.ras' os.system(self.cpxfiddle + mix) pha = ' -w ' + new_pixels + ' -q phase -o sunraster -b -c jet -M 1/1 -f cr4 -l1 ' \ '-p1 -P' + new_pixels + ' ' + filename2 + ' > ' + filename2[:-4] + '_pha.ras' os.system(self.cpxfiddle + pha) self.update_res() def decatenate(self, burst_file, master_file, dt=np.dtype(np.float32), dates=[], multilooked=False, res_type='master'): # Split full swath into different burst products. (to be used for DEM result splitting) if not dates: dates = self.stack.keys() job_list1 = [] for date in dates: path = self.image_path(date) command1 = os.path.join(self.function_path, 'concatenate_decatenate.py') + ' ' + path + ' decatenate ' + burst_file + ' ' + dt.str job_list1.append({"path": path, "command": command1}) if not(self.parallel): os.chdir(path) os.system(command1) if (self.parallel): jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(job_list1) # Following functions are helper function which help acces the correct folders and files more easily: def burst_path(self, date='', key='', file_path='', stack_folder=False, dat_type='', full_path=False): if stack_folder == False: stack_folder = self.stack_folder if dat_type: file_path = '_iw_' + key[6] + '_burst_' + key[14:] if dat_type == 'master' or dat_type == 'slave': file_path = dat_type + file_path + '.raw' elif dat_type == 'master_deramped' or dat_type == 'slave_deramped': file_path = dat_type[:-9] + file_path + '_deramped.raw' if full_path is True: if len(date) == 10: date_folder = date[:4] + date[5:7] + date[8:10] else: date_folder = date swath_folder = key[:7] burst_folder = key[8:] if file_path: file_path = os.path.join(stack_folder, date_folder, swath_folder, burst_folder, file_path) else: file_path = os.path.join(stack_folder, date_folder, swath_folder, burst_folder) return file_path def burst_paths(self, stack, dates=[], stack_folder=False, dat_type='', file_path='', full_path=False): # Creates a list of all burst paths for this file, given the dates. if stack_folder == False: stack_folder = self.stack_folder if not dates: dates = stack.keys() paths = [] for date in dates: for key in stack[date].keys(): burst_path = self.burst_path(date, key, stack_folder=stack_folder, dat_type=dat_type, file_path=file_path, full_path=full_path) paths.append(burst_path) return paths def swath_path(self, date, key, stack_folder=False): if stack_folder == False: stack_folder = self.stack_folder if len(date) == 10: date_folder = date[:4] + date[5:7] + date[8:10] else: date_folder = date swath_burst = key.split('_') file_path = os.path.join(stack_folder, date_folder, swath_burst[0] + '_' + swath_burst[1]) return file_path def swath_paths(self, stack, dates=[], stack_folder=False): # Creates a list of all swath paths given the dates. if stack_folder == False: stack_folder = self.stack_folder if not dates: dates = stack.keys() paths = [] for date in dates: keys = set([key[:7] for key in stack[date].keys()]) for key in keys: swath_path = self.swath_path(date, key, stack_folder) paths.append(swath_path) return paths def image_path(self, date, file_path='', stack_folder=False): if stack_folder == False: stack_folder = self.stack_folder if len(date) == 10: date_folder = date[:4] + date[5:7] + date[8:10] else: date_folder = date if file_path: file_path = os.path.join(stack_folder, date_folder, file_path) else: file_path = os.path.join(stack_folder, date_folder) return file_path def image_paths(self, stack, dates=[], file_path='', stack_folder=False): # Creates a list of all image paths if stack_folder == False: stack_folder = self.stack_folder if not dates: dates = stack.keys() paths = [] for date in dates: image_path = self.image_path(date, file_path, stack_folder) paths.append(image_path) return paths @staticmethod def read_image_paths(master_key, stack_folder): # This functions reads all the current folders from a stack. # Select different categories of directories. stack_dirs = next(os.walk(stack_folder))[1] master = os.path.join(stack_folder, master_key) esd = os.path.join(stack_folder, 'esd') slaves = [os.path.join(stack_folder, dir_s) for dir_s in stack_dirs if dir_s != master_key and len(dir_s) == 8] ifg = [os.path.join(stack_folder, dir_s) for dir_s in stack_dirs if len(dir_s) == 21] return master, slaves, ifg, esd def read_burst_paths(self, master_key, stack_folder, dat_type='list'): # The output can be in 2 formats. A list with all # folders, including image and burst folders, or a dict structure. if dat_type == 'list': folders = [[], [], []] elif dat_type == 'dict': folders = [dict(), dict(), dict()] else: print('dat_type should either be a list or dict') return master, slaves, ifg = self.read_image_paths(master_key, stack_folder)[:3] # And find the corresponding folders: for fold, dirs in zip(folders, [[master], slaves, ifg]): for direc in dirs: if dat_type == 'list': fold.append(os.path.basename(direc)) elif dat_type == 'dict': fold[os.path.basename(direc)] = dict() swaths = next(os.walk(direc))[1] for swath in swaths: if dat_type == 'dict': fold[os.path.basename(direc)][swath] = dict() bursts = next(os.walk(os.path.join(direc, swath)))[1] for burst in bursts: if dat_type == 'dict': fold[os.path.basename(direc)][swath][burst] = [] elif dat_type == 'list': fold.append(os.path.join(os.path.basename(direc), swath, burst)) # Now return master, slave and ifg setup return folders[0], folders[1], folders[2] def update_res(self, dates='default', stack_folder='', burst_stack=list(), image_stack=list()): # Save to .res file based on the burst objects. if not burst_stack: burst_stack = self.stack if not image_stack: image_stack = self.full_swath if dates == 'default': dates = self.stack.keys() if not stack_folder: stack_folder = self.stack_folder for date in dates: for burst in burst_stack[date].keys(): files = burst_stack[date][burst].keys() if 'slave' in files: slave_res = self.burst_path(date, burst, 'slave.res', stack_folder=stack_folder, full_path=True) burst_stack[date][burst]['slave'].write(new_filename=slave_res) if 'master' in files: master_res = self.burst_path(date, burst, 'master.res', stack_folder=stack_folder, full_path=True) burst_stack[date][burst]['master'].write(new_filename=master_res) if 'ifgs' in files: ifgs_res = self.burst_path(date,burst,'ifgs.res', stack_folder=stack_folder, full_path=True) burst_stack[date][burst]['ifgs'].write(new_filename=ifgs_res) files = image_stack[date].keys() if 'slave' in files: slave_res = self.image_path(date, 'slave.res', stack_folder=stack_folder) image_stack[date]['slave'].write(new_filename=slave_res) if 'master' in files: master_res = self.image_path(date, 'master.res', stack_folder=stack_folder) image_stack[date]['master'].write(new_filename=master_res) if 'ifgs' in files: ifgs_res = self.image_path(date, 'ifgs.res', stack_folder=stack_folder) image_stack[date]['ifgs'].write(new_filename=ifgs_res) def read_res(self, coreg_dates=False, dates='default', stack_folder='', burst_stack='', image_stack='', bursts=[]): # Read .res data to the burst objects. Generally done after a processing step. if burst_stack == '': burst_stack = self.stack if image_stack == '': image_stack = self.full_swath if dates == 'default': dates = self.stack.keys() if not stack_folder: stack_folder = self.stack_folder if not bursts: if dates[0] in burst_stack.keys(): bursts = burst_stack[dates[0]].keys() else: date_1 = self.stack.keys()[0] bursts = self.stack[date_1].keys() # TODO Maybe add search for folders and bursts if no specific date or burst is specified? for date in dates: if not date in burst_stack.keys(): burst_stack[date] = dict() for burst in bursts: if not burst in burst_stack[date].keys(): burst_stack[date][burst] = dict() slave_res = self.burst_path(date, burst, 'slave.res', stack_folder=stack_folder, full_path=True) master_res = self.burst_path(date, burst, 'master.res', stack_folder=stack_folder, full_path=True) ifgs_res = self.burst_path(date, burst,'ifgs.res', stack_folder=stack_folder, full_path=True) if os.path.exists(slave_res): burst_stack[date][burst]['slave'] = ResData(filename=slave_res) if os.path.exists(master_res): burst_stack[date][burst]['master'] = ResData(filename=master_res) if os.path.exists(ifgs_res): burst_stack[date][burst]['ifgs'] = ResData(filename=ifgs_res) if not date in image_stack.keys(): image_stack[date] = dict() slave_res = self.image_path(date, 'slave.res', stack_folder=stack_folder) master_res = self.image_path(date, 'master.res', stack_folder=stack_folder) ifgs_res = self.image_path(date, 'ifgs.res', stack_folder=stack_folder) if os.path.exists(slave_res): image_stack[date]['slave'] = ResData(filename=slave_res) if os.path.exists(master_res): image_stack[date]['master'] = ResData(filename=master_res) if os.path.exists(ifgs_res): image_stack[date]['ifgs'] = ResData(filename=ifgs_res) def del_res(self, type='ifgs', images=False, bursts=True, dates='default', stack_folder=''): if dates == 'default': dates = self.stack.keys() for date in dates: for burst in self.stack[date].keys(): if bursts: res = self.burst_path(date,burst, type + '.res', stack_folder=stack_folder) if os.path.exists(res): os.remove(res) if images: res = self.image_path(date, type + '.res', stack_folder=stack_folder) if os.path.exists(res): os.remove(res) def del_process(self, process, type='ifgs', images=False, bursts=True, dates='default', burst_stack=list(), image_stack=list()): # Delete a process from the .res files. if not burst_stack: burst_stack = self.stack if not image_stack: image_stack = self.full_swath if dates == 'default': dates = self.stack.keys() self.read_res(dates=dates) # Read data for date in dates: for burst in burst_stack[date].keys(): if bursts and burst_stack[date][burst][type].process_control[process] == '1': burst_stack[date][burst][type].delete(process) if images and image_stack[date][type].process_control[process] == '1': image_stack[date][type].delete(process) self.update_res(dates=dates) Doris-5.0.3Beta/doris_stack/main_code/stack.py000066400000000000000000001055451312547014700213130ustar00rootroot00000000000000# This script gathers available sentinel files from the database and checks the coverage in space and time for this data # stack. import os import warnings from collections import Counter, OrderedDict from datetime import datetime import shutil import fiona import numpy as np from shapely.geometry import shape, mapping, box from shapely.ops import cascaded_union import image as image from doris.doris_stack.functions.load_shape_unzip import extract_kml_preview, shape_im_kml, load_shape from doris.doris_stack.main_code.dorisparameters import DorisParameters from doris.doris_stack.functions.burst_metadata import center_shape_from_res from doris.doris_stack.main_code.jobs import Jobs class StackData(object): # This function holds information for a full datastack of sentinel data and is used to select relevant images and # bursts based on a given area of interest. def __init__(self, track_dir, shape_dat, buffer=0.02, start_date='2014-04-01', end_date='', polarisation='vh', path='', db_type=1, precise_dir=''): # Initialize variables: Jobs.id = 0 # Datastack folder where all data from the datastack is stored (database,shapes,burst data, res files and results) # You should have write acces to this folder! self.path = path self.unzip_path = '' # Search path, shape, buffer and polarisation for this datastack. Currently only one polarisation is implemented. If # needed this can be extended later. self.search_path = [] self.start_date = [] self.end_date = [] self.master_date = [] self.shape = [] self.shape_filename = shape_dat self.buffer = [] self.polarisation = '' self.precise_orbits = '' # All images included in this datastack. Including lists of shapes and acquistion dates self.images = [] self.image_files = [] self.image_shapes = [] self.image_dates = [] # The shapes and names of the swaths self.swath_names = list() self.swath_shapes = list() # The resulting dates, with underlying bursts. This information can be used to create res files and images # of individual bursts. Variable data includes a structure using (dates > swaths > bursts). self.dates = list() self.datastack = dict() self.concatenated = dict() self.coordinates = dict() self.burst_names = list() self.burst_shapes = list() self.burst_centers = list() # Some important characteristics of the dataset of bursts. (matrices with names on y and dates on x axis) self.burst_no = 0 self.burst_availability = [] self.burst_lon = [] self.burst_lat = [] self.burst_baselines = [] # Temporary variable to store images which are not yet checked for shape or dates. self.image_dump = [] # parallel computing: doris_parameters = DorisParameters(os.path.dirname(self.path)) self.doris_parameters = doris_parameters self.nr_of_jobs = doris_parameters.nr_of_jobs self.parallel = doris_parameters.parallel self.function_path = doris_parameters.function_path #################################################################### # This function initializes the datastack using a search path, start/end dates and a buffer shape. The start and # end date should have the format yyyy-mm-dd and the shape should either be a shapefile or a list of coordinate # pairs. [[lat,lon][lat,lon] enz. ]. Minimum input is a folder which contains the .SAFE folders (a track folder) if not track_dir or not os.path.exists(track_dir): warnings.warn('This function needs an existing path as input!') return self.search_files(track_dir) if shape: self.create_shape(shape_dat,buffer) if end_date: self.end_date = np.datetime64(end_date).astype('datetime64[s]') + np.timedelta64(1, 'D').astype('timedelta64[s]') else: self.end_date = np.datetime64('now').astype('datetime64[s]') self.start_date = np.datetime64(start_date).astype('datetime64[s]') if isinstance(polarisation, basestring): polarisation = [polarisation] for i in polarisation: if not i in ['hh','vv','hv','vh']: warnings.warn('This polarisation does not exist for sentinel data.') return self.polarisation = polarisation self.search_path = track_dir if not path: warnings.warn('You did not specify an output path. Please do so later on using the add_path function') else: self.add_path(path) if precise_dir: if os.path.exists(precise_dir): self.precise_orbits = precise_dir else: print 'Precise orbit path does not exist' def add_path(self,path): # This function adds the output path. if os.path.isdir(path): self.path = path elif os.path.isdir(os.path.dirname(path[:-1])): os.mkdir(path) self.path = path else: warnings.warn('Neither the directory itself nor the parents directory exists. Choose another path.') def search_files(self, track_dir): # This function searches for files within a certain folder. This folder should contain images from the same # track. These images are added to the variable image dump. images = list() top_dir = next(os.walk(track_dir)) for data in top_dir[2]: if data.endswith('.zip'): images.append(os.path.join(track_dir, data)) for data in top_dir[1]: if data.endswith('.SAFE'): images.append(os.path.join(track_dir, data)) else: # Likely images are stored in a folder. sec_dir = next(os.walk(os.path.join(track_dir, data))) for dat in sec_dir[1]: if dat.endswith('.SAFE'): images.append(os.path.join(track_dir, data, dat)) for dat in sec_dir[2]: if dat.endswith('.zip'): images.append(os.path.join(track_dir, data, dat)) if images: images = sorted(images) else: print('No images found in track_dir = ' + str(track_dir) + ', switching to archive folder') track_name = self.doris_parameters.direction + '_t' + self.doris_parameters.track.zfill(3) track_dir = os.path.join(track_dir, track_name) print('Searching in folder ' + track_dir) top_dirs = next(os.walk(track_dir))[1] if len(top_dirs) == 1: track_dir = os.path.join(track_dir, top_dirs[0]) elif len(top_dirs) > 1: for top_dir in top_dirs: user_input = raw_input("Do you want to use folder " + top_dir + " as resource folder? (yes/no)").lower() if user_input in ['yes', 'y']: track_dir = os.path.join(track_dir, top_dir) dir_new = next(os.walk(track_dir)) for dat in dir_new[1]: dat_files = next(os.walk(os.path.join(track_dir, dat)))[2] for data in dat_files: if data.endswith('.zip'): images.append(os.path.join(track_dir, dat, data)) if images: images = sorted(images) else: warnings.warn('No images found! Please choose another data folder. Track_dir = ' + str(track_dir)) base = [] # Remove double hits because data is already unzipped. for i in images: # Drop all .zip files which are unpacked already. if i.endswith('.SAFE.zip'): base.append(os.path.basename(i[:-9])) elif i.endswith('.zip'): base.append(os.path.basename(i[:-4])) elif i.endswith('.SAFE'): base.append(os.path.basename(i[:-5])) b, id = np.unique(base, return_index=True) rem = [] for i in range(len(base)): if i in id: self.image_dump.append(images[i]) else: rem.append(images[i]) if rem: print('removed the following zip files from stack:') for r in rem: print(r) print('It is advised to work with zipfiles instead of unpacked data. This saves diskspace and will ') def create_shape(self,shape_dat,buffer=0.02): # This function creates a shape to make a selection of usable bursts later on. Buffer around shape is in # degrees. self.shape = load_shape(shape_dat, buffer) self.buffer = buffer def check_new_images(self, master): # This function checks which images are already processed, and which are not. If certain dates are already # processed they are removed from the list. You have to specify the master date, otherwise the script will not # know how many burst are expected per date. # Which dates are available? image_dates = [im.astype('datetime64[D]') for im in self.image_dates] # What is the master date date = np.datetime64(master).astype('datetime64[D]') date_folders = [d for d in next(os.walk(self.path))[1] if len(d) == 8] rm_id = [] if date_folders: dates = [np.datetime64(d[0:4] + '-' + d[4:6] + '-' + d[6:8]) for d in date_folders] if date in dates: date_folder = date_folders[np.where(dates == date)[0][0]] # Check existing files in master folder swaths = dict() swath_folders = next(os.walk(os.path.join(self.path, date_folder)))[1] if len(swath_folders) == 0: print('No swaths in master folder') return for swath in swath_folders: self.swath_names.append(swath) swaths[swath] = sorted(next(os.walk(os.path.join(self.path, date_folder, swath)))[1]) # Now check if the burst also in slave folders exist.... for folder, d in zip(date_folders, dates): # Check existing files in master folder try: swath_folders = next(os.walk(os.path.join(self.path, folder)))[1] if not set(swath_folders) == set(swaths.keys()): raise LookupError('Amount of swaths is not the same for ' + folder) for swath in swath_folders: bursts = sorted(next(os.walk(os.path.join(self.path, date_folder, swath)))[1]) if not set(bursts) == set(swaths[swath]): raise LookupError('Amount of bursts is not the same for ' + folder) if d == date: # If the master is already processed we have to create the list of center and coverage of # bursts. # TODO make this robust for the case no seperate input data folders are created. res_files = [] for burst in bursts: dat_file = [r for r in next(os.walk(os.path.join(self.path, date_folder, swath, burst)))[2] if (r.startswith('slave_iw') and len(r) < 25)] res_file = os.path.join(self.path, date_folder, swath, burst, 'slave.res') res_files.append(res_file) center, coverage = center_shape_from_res(resfile=res_file) # Assign coverage, center coordinates and burst name. self.burst_shapes.append(coverage) self.burst_centers.append(center) burst_num = os.path.basename(dat_file[0])[17:-4] self.burst_names.append(swath + '_burst_' + burst_num) self.burst_no += 1 # If all bursts are the same these files are not processed. for id in np.where(image_dates == d)[0][::-1]: del self.image_dates[id] del image_dates[id] del self.images[id] del self.image_files[id] except LookupError as error: print(error) def select_image(self,start_date='',end_date='', dest_folder=''): # This function selects usable images based on .kml files and dates if not dest_folder: dest_folder = os.path.join(self.path, 'kml') if not os.path.exists(dest_folder): os.makedirs(dest_folder) if not self.shape: warnings.warn('There is no shape loaded to select images. Please use the create_shape function to do so.') if start_date: self.start_date = np.datetime64(start_date).astype('datetime64[s]') if end_date: self.end_date = np.datetime64(end_date).astype('datetime64[s]') + np.timedelta64(1, 'D').astype('timedelta64[s]') # First select images based on dates and check if polygons intersect. for i in self.image_dump: d = os.path.basename(i)[17:32] acq_time = np.datetime64(d[0:4] + '-' + d[4:6] + '-' + d[6:11] + ':' + d[11:13] + ':' + d[13:] + '-0000') if acq_time >= self.start_date and acq_time <= self.end_date: im = image.ImageMeta(path=i) kml, png = extract_kml_preview(i, dir=dest_folder, png=False, overwrite=True) succes = shape_im_kml(self.shape, kml) if succes: self.images.append(im) self.image_dates.append(acq_time) self.image_files.append(os.path.basename(i)) self.dates = sorted(list(set([d.astype('datetime64[D]') for d in self.image_dates]))) for date in self.dates: print(date) def select_burst(self, date=''): # This function selects the usefull bursts at one epoch (user defined or automatically selected) and searches # usefull burst at other dates. This function uses the extend_burst function, which is intended to search for # bursts at other dates. This function can be run later on to update the datastack. if self.burst_names: print('Master data is already loaded from earlier processed data.') return image_dates = [im.astype('datetime64[D]') for im in self.image_dates] # First select which date will be the master if date: date = np.datetime64(date).astype('datetime64[D]') # date = deepcopy(image_dates[min(abs(self.image_dates-date))]) else: # if no date is specified date = Counter(image_dates).most_common(1)[0][0] # Load the metadata for this date for the bursts and swaths for date in image_dates: print(date) print(date) image_id = np.where(image_dates == date)[0] for i in image_id: print('processing data: ' + self.images[i].unzip_path) self.images[i].meta_swath(precise_folder=self.precise_orbits) # Order the selected images by acquisition time. image_id = [x for (y,x) in sorted(zip([self.image_dates[i] for i in image_id],image_id))] date = date.astype(datetime).strftime('%Y-%m-%d') self.master_date = date self.datastack[date] = dict() swath_nums = ['1', '2', '3'] for p in self.polarisation: for swath in swath_nums: swath_id = 'iw' + swath + '-slc-' + p swath_name = 'swath_' + swath burst_no = 1 data = [] for i in image_id: # Check which swath should be selected. if not self.images[i].swaths_data: continue swath_names = [os.path.basename(data) for data in self.images[i].swaths_data] swath_no = [no for no in range(len(swath_names)) if swath_id in swath_names[no]] if not swath_no: # If there is no data for this swath continue swath_no = swath_no[0] for burst in self.images[i].swaths[swath_no].bursts: if burst.burst_coverage.intersects(self.shape): # Check if we do not have a copy of former bursts... if len(self.burst_centers) != 0: dist_center = [np.sqrt((burst.burst_center[0] - center[0])**2 + (burst.burst_center[1] - center[1])**2) for center in self.burst_centers] if min(dist_center) < 0.02: print('Possible duplicate burst deleted') continue # If there are bursts in this swath, which intersect, add burst to list. if swath_name not in self.datastack[date].keys(): # If there are burst and no burst list exists self.datastack[date][swath_name] = dict() if swath_name not in self.swath_names: self.swath_names.append(swath_name) # Assign burst to data stack burst_name = 'burst_' + str(burst_no) burst.new_burst_num = burst_no self.datastack[date][swath_name][burst_name] = burst # Create .res file data burst.meta_burst(swath_meta=self.images[i].swaths[swath_no].metadata) # Assign coverage, center coordinates and burst name. self.burst_shapes.append(burst.burst_coverage) self.burst_centers.append(burst.burst_center) self.burst_names.append(swath_name + '_' + burst_name) burst_no += 1 # Finally add also to the number of bursts from the image self.images[i].burst_no += 1 self.burst_no += 1 def extend_burst(self): # Searches for burst at dates other than the dates that are already available. This means that if there are # images added for dates which are already indexed, this data will not be used! image_dates = [d.astype('datetime64[D]') for d in self.image_dates] for date in self.dates: # Append data to datastack variable date_str = date.astype(datetime).strftime('%Y-%m-%d') self.datastack[date_str] = dict() data = [] # Load the metadata for this date for the bursts and swaths image_id = np.where(image_dates == date)[0] if len(image_id) == 0: continue for i in image_id: if date_str == self.master_date: continue print('processing data: ' + self.images[i].unzip_path) self.images[i].meta_swath(precise_folder=self.precise_orbits) for swath in self.swath_names: # Add swath to datastack self.datastack[date_str][swath] = OrderedDict() for i in image_id: # Select correct swath in image swath_id = swath[-1] + '-slc-' + self.polarisation[0] swath_names = [os.path.basename(data) for data in self.images[i].swaths_data] swath_no = [no for no in range(len(swath_names)) if swath_id in swath_names[no]] if not swath_no: # If there is no data for this swath continue swath_no = swath_no[0] for burst in self.images[i].swaths[swath_no].bursts: x_dist = np.array([xy[0] - burst.burst_center[0] for xy in self.burst_centers]) y_dist = np.array([xy[1] - burst.burst_center[1] for xy in self.burst_centers]) dist = np.sqrt(x_dist**2 + y_dist**2) burst_id = np.argmin(dist) if dist[burst_id] < 0.1: # Assign burst to data stack burst.new_burst_num = int(self.burst_names[burst_id][14:]) self.datastack[date_str][swath][self.burst_names[burst_id][8:]] = burst # Create .res file data burst.meta_burst(swath_meta=self.images[i].swaths[swath_no].metadata) else: print('No corresponding burst found! Closest is ' + str(dist[burst_id]) + ' ' + date_str + ' ' + swath + ' ' + self.burst_names[burst_id]) # Remove all unnecessary dates from stack for dat_key in self.datastack.keys(): if not self.datastack[dat_key]: del self.datastack[dat_key] def remove_incomplete_images(self): # This function removes all the images with less than maximum bursts. This will make a stack more consistent. for key in self.datastack.keys(): burst_no = 0 for key_swath in self.datastack[key].keys(): burst_no += len(self.datastack[key][key_swath]) if burst_no != self.burst_no: self.datastack.pop(key) print('Number of burst for ' + key + ' is ' + str(burst_no) + ' instead of ' + str(self.burst_no) + ' and is removed from the datastack.') def define_burst_coordinates(self,slaves=False): # This function defines the exact coordinates in pixels of every burst based on the lower left corner of the first # burst image. In this way the total overlap of these bursts can easily be monitored. Results are written to the # coordinates variable if slaves is True: dates = self.datastack.keys() else: dates = [self.master_date] self.coordinates = OrderedDict() for date in dates: self.coordinates[date] = OrderedDict() self.coordinates[date]['shapes'] = [] ref = False min_line = 1; min_pixel = 1 max_line = 1; max_pixel = 1 for swath in self.datastack[date].keys(): self.coordinates[date][swath] = OrderedDict() self.coordinates[date][swath]['corners'] = np.zeros([len(self.datastack[date][swath].keys()), 4, 2],dtype='int') b = 0 for burst in sorted(self.datastack[date][swath].keys(), key = lambda x: int(x[6:])): if ref is False: self.coordinates[date]['ref_az_time'] = self.datastack[date][swath][burst].processes['readfiles']['First_pixel_azimuth_time (UTC)'] self.coordinates[date]['ref_range_time'] = self.datastack[date][swath][burst].processes['readfiles']['Range_time_to_first_pixel (2way) (ms)'] ref = True az_first = self.datastack[date][swath][burst].processes['readfiles']['First_pixel_azimuth_time (UTC)'] az_samp = self.datastack[date][swath][burst].processes['readfiles']['Pulse_Repetition_Frequency (computed, Hz)'] first_line = int(self.datastack[date][swath][burst].processes['crop']['First_line (w.r.t. original_image)']) last_line = int(self.datastack[date][swath][burst].processes['crop']['Last_line (w.r.t. original_image)']) range_first = self.datastack[date][swath][burst].processes['readfiles']['Range_time_to_first_pixel (2way) (ms)'] range_samp = self.datastack[date][swath][burst].processes['readfiles']['Range_sampling_rate (computed, MHz)'] first_pixel = int(self.datastack[date][swath][burst].processes['crop']['First_pixel (w.r.t. original_image)']) last_pixel = int(self.datastack[date][swath][burst].processes['crop']['Last_pixel (w.r.t. original_image)']) no_lines = int(self.datastack[date][swath][burst].processes['readfiles']['Number_of_lines_original']) no_pixels = int(self.datastack[date][swath][burst].processes['readfiles']['Number_of_pixels_original']) # Calculate difference w.r.t. reference point. range_time_diff = (float(range_first) - float(self.coordinates[date]['ref_range_time'])) pixel_diff = int(round((float(range_samp) * 1e3) * range_time_diff)) az_time1 = datetime.strptime(az_first, '%Y-%b-%d %H:%M:%S.%f') az_time2 = datetime.strptime(self.coordinates[date]['ref_az_time'], '%Y-%b-%d %H:%M:%S.%f') az_time_diff = (az_time1 - az_time2).total_seconds() line_diff = int(round(float(az_samp) * az_time_diff)) # Calculate final corner coordinates. ll = np.array([line_diff + first_line, pixel_diff + first_pixel], ndmin=2) ul = np.array([line_diff + last_line, pixel_diff + first_pixel], ndmin=2) ur = np.array([line_diff + last_line, pixel_diff + last_pixel], ndmin=2) lr = np.array([line_diff + first_line, pixel_diff + last_pixel], ndmin=2) self.coordinates[date][swath]['corners'][b,:,:] = np.vstack([ll,ul,ur,lr]) b += 1 # Check for max/min line/pixel to prevent negative pixel numbers. min_line = min(1 + line_diff, min_line) max_line = max(line_diff + no_lines, max_line) min_pixel = min(1 + pixel_diff, min_pixel) max_pixel = max(pixel_diff + no_pixels, max_pixel) if min_line < 1: max_line = max_line + (1 - min_line) if min_pixel < 1: max_pixel = max_pixel + (1 - min_pixel) for swath in self.datastack[date].keys(): # If one of the lines or pixels is lower then 1, correct all coordinates to have positive coordinates for all # bursts. if min_line < 1: self.coordinates[date][swath]['corners'][:,:,0] = self.coordinates[date][swath]['corners'][:,:,0] + (1 - min_line) if min_pixel < 1: self.coordinates[date][swath]['corners'][:,:,1] = self.coordinates[date][swath]['corners'][:,:,1] + (1 - min_pixel) for burst in range(len(self.datastack[date][swath].keys())): shape_c = self.coordinates[date][swath]['corners'][burst,:,:] shape = box(shape_c[0,1],shape_c[0,0],shape_c[2,1],shape_c[2,0]) self.coordinates[date]['shapes'].append(shape) # Finally add information to the .res file if already loaded if self.datastack[date][swath]['burst_' + str(burst+1)].processes['readfiles']: read = self.datastack[date][swath]['burst_' + str(burst+1)].processes['readfiles'] read['First_line (w.r.t. output_image)'] = str(shape_c[0,0]) read['Last_line (w.r.t. output_image)'] = str(shape_c[2,0]) read['First_pixel (w.r.t. output_image)'] = str(shape_c[0,1]) read['Last_pixel (w.r.t. output_image)'] = str(shape_c[2,1]) read['Number_of_pixels_output_image'] = str(max_pixel) read['Number_of_lines_output_image'] = str(max_line) self.datastack[date][swath]['burst_' + str(burst+1)].processes['readfiles'] = read else: print 'No resfile available, so information is not added to resfile' def write_stack(self,write_path='',no_data=False): # This function writes the full datastack to a given folder using the dates / swaths / bursts setup. This # also generates the res readfiles data. if write_path and os.path.exists(write_path): self.path = write_path if (not write_path or not os.path.exists(write_path)) and not self.path: warnings.warn('Please specify a path that exists to write the data') return write_jobs = [] burst_num = [] for date in self.datastack.keys(): date_basic = date.translate(None,'-') date_path = os.path.join(self.path, date_basic) if not os.path.exists(date_path): os.mkdir(date_path) for swath in self.datastack[date].keys(): swath_path = os.path.join(date_path, swath) if not os.path.exists(swath_path): os.mkdir(swath_path) for burst in self.datastack[date][swath].keys(): burst_path = os.path.join(date_path, swath, burst) if not os.path.exists(burst_path): os.mkdir(burst_path) # Finally write the bursts with their res files and precise orbits xml = self.datastack[date][swath][burst].swath_xml data = self.datastack[date][swath][burst].swath_data image_no = str(self.datastack[date][swath][burst].burst_num) stack_no = burst[6:] xml_base = os.path.basename(xml) res_name = os.path.join(burst_path, 'slave.res') outdata = os.path.join(burst_path, 'slave_iw_' + xml_base[6] + '_burst_' + stack_no + '.raw') self.datastack[date][swath][burst].write(res_name) if not os.path.exists(res_name) or not os.path.exists(outdata): write_jobs.append('python ' + self.function_path + 'sentinel_dump_data_function.py ' + data + ' ' + res_name + ' ' + outdata) burst_num.append(stack_no + '_' + xml_base[6] + '_' + xml_base[15:23]) # Burst are sorted in such a way that mainly read from different data files sorted by burst then swath then date. ids = sorted(range(len(burst_num)), key=lambda x: burst_num[x]) jobList1 = [] for id_val in ids: jobList1.append({"path": self.path, "command": write_jobs[id_val]}) if not self.parallel: os.chdir(self.path) # Resample os.system(write_jobs[id_val]) if self.parallel: jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(jobList1) def unpack_image(self, dest_folder=''): if not dest_folder: dest_folder = os.path.join(self.path, 'slc_data_files') self.unzip_path = dest_folder if not os.path.exists(dest_folder): os.mkdir(dest_folder) jobList1 = [] # This program unpacks the images which are needed for processing. If unpacking fails, they are removed.. for imagefile in self.images: zipped_folder = imagefile.zip_path if zipped_folder.endswith('.SAFE.zip'): imagefile.unzip_path = os.path.join(dest_folder, os.path.basename(zipped_folder[:-9] + '.SAFE')) elif zipped_folder.endswith('.zip'): imagefile.unzip_path = os.path.join(dest_folder, os.path.basename(zipped_folder[:-4] + '.SAFE')) shapefile = self.shape_filename pol = self.polarisation[0] overwrite = False command1 = ('python ' + self.function_path + 'load_shape_unzip.py ' + zipped_folder + ' ' + dest_folder + ' ' + shapefile + ' ' + pol + ' ' + str(overwrite)) jobList1.append({"path": self.path, "command": command1}) if not self.parallel: os.chdir(self.path) # Resample os.system(command1) if self.parallel: jobs = Jobs(self.nr_of_jobs, self.doris_parameters) jobs.run(jobList1) def del_unpacked_image(self): # This program unpacks the images which are needed for processing. for image_dat in self.images: shutil.rmtree(image_dat.unzip_path) def swath_coverage(self): # Create a convex hull for the different swaths. for swath in self.swath_names: # Assign coverage of swath using convex hull. burst_id = [i for i in range(len(self.burst_names)) if swath in self.burst_names[i]] swath_shape = cascaded_union([self.burst_shapes[i] for i in burst_id]) self.swath_shapes.append(swath_shape) def write_shapes(self,coverage=True,images=True,swaths=True,bursts=True): # This function writes shapefiles of the area of interest, images and bursts. if not coverage and not images and not bursts: warnings.warn('Select at least one of shape types') return shapes = list(); shape_names = list(); shape_files = list() if coverage and self.shape: shape_files.append(self.path + 'area_of_interest.shp') if self.shape.type == 'MultiPolygon': shapes.append([sh for sh in self.shape]) shape_names.append([('coverage_with_buffer_of_' + str(self.buffer) + '_degrees_' + str(i)) for i in range(len(shapes[0]))]) elif self.shape.type == 'Polygon': shape_names.append(['coverage_with_buffer_of_' + str(self.buffer) + '_degrees']) shapes.append([self.shape]) if images and self.image_shapes: shape_files.append(self.path + 'image_coverage.shp') shape_names.append([date.astype(datetime).strftime('%Y-%m-%dT%H:%M:%S') for date in self.image_dates]) shapes.append(self.image_shapes) if swaths and self.swath_shapes: shape_files.append(self.path + 'swath_coverage.shp') shape_names.append(self.swath_names) shapes.append(self.swath_shapes) if bursts and self.burst_shapes: shape_files.append(self.path + 'burst_coverage.shp') shape_names.append(self.burst_names) shapes.append(self.burst_shapes) shape_setup = { 'geometry': 'Polygon', 'properties': {'name': 'str'}, } for i in range(len(shape_files)): with fiona.open(shape_files[i], 'w', 'ESRI Shapefile', shape_setup) as sh: for n in range(len(shapes[i])): sh.write({ 'geometry': mapping(shapes[i][n]), 'properties': {'name': shape_names[i][n]}, }) Doris-5.0.3Beta/doris_stack/main_code/swath.py000066400000000000000000000117151312547014700213270ustar00rootroot00000000000000# This files defines a class for metadata objects of sentinel images. Large part of the work depends on python readers # from the tops toolbox. from doris.doris_stack.functions.xml_query import xml_query import warnings import os from doris.doris_stack.main_code.burst import BurstMeta from doris.doris_stack.functions.swath_metadata import burst_coverage, swath_coverage, swath_precise class SwathMeta(object): # Class which stores and gathers information of a swath in a sentinel dataset def __init__(self, path='', swath_no='1', pol='vv', xml='', data=''): # Initialize object variables # This will contain a list of burst objects self.bursts = [] # The following contain the path of xml and data file. Also swath_no and polarisation are given. self.swath_xml = '' self.swath_data = '' self.swath_no = '' self.swath_pol = '' # These variables contain the metadata and the convex hull of the bursts self.metadata = [] self.coverage = [] self.burst_centers = [] self.burst_corners = [] self.burst_shapes = [] self.orbits = [] self.orbit_type = '' # This function creates an swath object and searches for available data and xml files. It gives an error when # either the path does not exist, no data or xml files can be found or the data and xml files do not match.' if (not xml or not data) and not path: warnings.warn('Please provide either a product path or xml and data path') return if not xml or not data: warnings.warn('Data path is now used') xml_dir = os.path.join(path, 'annotation') xml = [f for f in os.listdir(xml_dir) if os.path.isfile(os.path.join(xml_dir, f))] data_dir = os.path.join(path, 'measurement') data = [f for f in os.listdir(data_dir) if os.path.isfile(os.path.join(data_dir, f))] # Select polarisation if not any(s in pol for s in ('hh','vv','hv','vh')): warnings.warn('Polarisation not recognized, using default (vv)') pol = 'vv' if not swath_no in ('1','2','3'): warnings.warn('Swath number not recognized, using default (1)') xml = [os.path.join(path,'annotation',x) for x in xml if x[12:14] in pol and x[6] == swath_no] data = [os.path.join(path,'measurement',x) for x in data if x[12:14] in pol and x[6] == swath_no] # Check if the data is there and if the filenames coincide. # print xml + str(len(xml)) # print data + str(len(data)) if type(xml) is str: xml = [xml] if type(data) is str: data = [data] if (len(xml) != 1 and type(xml) is list) or len(data) != 1: warnings.warn('Total number of files should be one!') if not os.path.exists(xml[0]) or not os.path.exists(data[0]): warnings.warn('Either xml or data path does not exist') if xml[0:-3] != data[0:-4]: warnings.warn('xml and data file do not correspond.') self.swath_xml = xml[0] self.swath_data = data[0] def meta_swath(self): # This function reads and stores metadata of different swaths in the swath objects. self.metadata = xml_query(self.swath_xml) corners, self.coverage = swath_coverage(self.metadata) self.burst_centers, self.burst_corners, self.burst_shapes = burst_coverage(self.metadata) def orbits_swath(self, precise_folder=''): # This functions loads the precise orbits for this swath if not precise_folder: print('xml information on orbit is used because no precise folder is specified') orbits, type_orb = swath_precise(self.metadata, precise_folder=precise_folder, dat_type='XML') else: orbits, type_orb = swath_precise(self.metadata, precise_folder=precise_folder, dat_type='POE') self.orbits = orbits self.orbit_type = type_orb return orbits, type_orb def meta_burst(self, precise_folder=''): # This function reads and stores metadata of different bursts in the bursts objects. if not self.metadata: self.meta_swath() if not self.orbits: self.orbits_swath(precise_folder=precise_folder) bursts_num = len(self.metadata['aux']['azimuthTimeStart']) if self.bursts: self.bursts = [] for no in range(bursts_num): self.bursts.append(BurstMeta(path='',swath_no=self.swath_no, pol=self.swath_pol, burst_num=no + 1, xml=self.swath_xml, data=self.swath_data)) self.bursts[no].burst_center = self.burst_centers[no][0] self.bursts[no].burst_coverage = self.burst_shapes[no] self.bursts[no].burst_corners = self.burst_corners[no] self.bursts[no].datapoints = self.orbits self.bursts[no].orbit_type = self.orbit_type Doris-5.0.3Beta/envisat_tools/000077500000000000000000000000001312547014700162705ustar00rootroot00000000000000Doris-5.0.3Beta/envisat_tools/Makefile000077500000000000000000000074141312547014700177410ustar00rootroot00000000000000######################################### ### Makefile to compile envisat tools ### ### based on BEST toolbox of ESA ### ### see source code for info ### ### i did a quick hack, but am not ### ### familar with c (but did not want ### ### to mix it with c++ for such a ### ### simple program). ### ### Bert Kampes, 15-JUN-2003 ### ### ### ### Support for ERS in Envisat Format ### ### Mahmut Arikan, 19-Oct-2010 ### ### ### ######################################### ### Check if you agree with the options below (install_dir OK?) ### then simply type: "make install" SHELL = /bin/sh CC = gcc #CFLAGS = -O3 #CFLAGS = -m32 # for 64-bit systems, it requires compatibility lib32, no need for epr_api v2.2 LFLAGS = -lm INSTALL_DIR = /home/gertmulder/bin/doris/doris_v5_wu_branch ############################################################# ### THERE SHOULD BE NOTHING YOU HAVE TO CHANGE BELOW HERE ### ############################################################# LIB_SRC = epr_api-2.2/src/epr_api.c \ epr_api-2.2/src/epr_band.c \ epr_api-2.2/src/epr_bitmask.c \ epr_api-2.2/src/epr_core.c \ epr_api-2.2/src/epr_dataset.c \ epr_api-2.2/src/epr_dddb.c \ epr_api-2.2/src/epr_dsd.c \ epr_api-2.2/src/epr_dump.c \ epr_api-2.2/src/epr_field.c \ epr_api-2.2/src/epr_msph.c \ epr_api-2.2/src/epr_param.c \ epr_api-2.2/src/epr_product.c \ epr_api-2.2/src/epr_ptrarray.c \ epr_api-2.2/src/epr_record.c \ epr_api-2.2/src/epr_string.c \ epr_api-2.2/src/epr_swap.c \ epr_api-2.2/src/epr_typconv.c ### targets ### default: envisat_dump_header envisat_dump_data envisat_dump_HH envisat_dump_VV ### compile envisat_dump_header program (dumps envisat header info to stdout) ### envisat_dump_header: BEST $(CC) $(CFLAGS) $(LFLAGS) \ -o envisat_dump_header \ epr_api-2.2/src/*.o \ envisat_dump_header.c ### compile envisat_dump_data program (dumps envisat slc short int data to file) ### envisat_dump_data: BEST $(CC) $(CFLAGS) $(LFLAGS) \ -o envisat_dump_data \ epr_api-2.2/src/*.o \ envisat_dump_data.c ### compile envisat_dump_data program (dumps envisat slc short int data to file) ### envisat_dump_HH: BEST $(CC) $(CFLAGS) $(LFLAGS) \ -o envisat_dump_HH \ epr_api-2.2/src/*.o \ envisat_dump_HH.c ### compile envisat_dump_data program (dumps envisat slc short int data to file) ### envisat_dump_VV: BEST $(CC) $(CFLAGS) $(LFLAGS) \ -o envisat_dump_VV \ epr_api-2.2/src/*.o \ envisat_dump_VV.c ### create object code BEST library functions ### BEST: $(LIB_SRC) (cd epr_api-2.2/src/; make) ### installer ### PROGS = envisat_dump_header envisat_dump_data envisat_dump_HH envisat_dump_VV SCRIPTS = envisat_dump_header2doris.csh install: $(PROGS) $(SCRIPTS) @echo "installing envisat tools..." cp -f $(PROGS) $(SCRIPTS) $(INSTALL_DIR)/. #if test -d /cygdrive/c/cygwin; then \ # echo "* cygwin detected"; \ # cp -f envisat_dump_header $(INSTALL_DIR)/.; \ # cp -f envisat_dump_data $(INSTALL_DIR)/.; \ # cp -f envisat_dump_header.exe $(INSTALL_DIR)/.; \ # cp -f envisat_dump_data.exe $(INSTALL_DIR)/.; \ #fi; make cleaner; @echo " " @echo "------------------------------------" @echo "FINISHED INSTALLING ENVISAT TOOLS..." @echo " executables in: $(INSTALL_DIR)" @echo "------------------------------------" ### cleaners ### uninstall: cleaner @echo "un-installing envisat tools in $(INSTALL_DIR)..." (cd $(INSTALL_DIR); rm -f $(PROGS) $(SCRIPTS)) @echo "now you can rm this directory yourself" @echo "for a full uninstall" @echo " " clean: @echo "cleaning envisat tools..." (cd epr_api-2.2/src/; make clean) rm -f *.o cleaner: clean rm -f $(PROGS) ### EOF. Doris-5.0.3Beta/envisat_tools/README000077500000000000000000000033471312547014700171620ustar00rootroot00000000000000Here we have 4 c programs to handle ENVISAT data. ------------------------------------------------- envisat_dump_header simply reads in the header and dumps it. envisat_dump_header2doris.csh is a simple csh program that calls envisat_dump_header and then uses awk command to create a result section for doris. envisat_dump_data creates a "raw" pixel interleaved short complex file, major row order, in the host byte order. possibly a crop. envisat_dump_data_HH Similarly dumps HH polarization band "MDS1" from alternating polarization products. envisat_dump_data_VV Similarly dumps VV polarization band "MDS2" from alternating polarization products. The library function from the epr_api c functions distributed by ESA under the public domain type licence are used to access the data. To compile the programs, perform a "make" and a "make install". Make sure to specify the correct c compiler (gcc by default) and installation directory (/usr/local/bin) TU Delft, 06-Jun-2011 History ------ #%// TU Delft 06-Jan-2011 [MA] Change from epr_api 2.0.1 to 2.2 for full 64-bit support see epr_api 2.2 Change.txt for more information #%// TU Delft 19-Oct-2010 [MA] Tweak epr_api so it handles ERS1/2 in Envisat format #%// BK 16-Apr-2004 It seems on some systems these programs act a bit strangely. We took out -O3 for compilation. Could also have to do with the script envisat2doris.csh, that some awk is wrong there on linux and not on SUN?? #%// BK 24-Nov-2003 There are also 2 simple programs that extract HH and VV from alternating polarization products. These are extreme simple hacks. They actually simply dump the records named "MDS1" and "MDS2". Doris-5.0.3Beta/envisat_tools/envisat_dump_HH.c000077500000000000000000000164151312547014700215230ustar00rootroot00000000000000/* BK: simple program to dump binary data for ENVISAT for alternating pol, HH channel. #%// BK 24-Nov-2003 $Id: envisat_dump_HH.c,v 1.2 2004/05/13 18:13:39 kampes Exp $ THIS program is not really good, but a fast hack for Z.Perksi.. */ #include #include #include #include #include #include #include #include "epr_api-2.2/src/epr_api.h" #if defined(WIN32) && defined(_DEBUG) #include #endif /* if defined(WIN32) && defined(_DEBUG) */ int main(int argc, char** argv) { const char* product_file_path; const char* outfile; const char* record_name; FILE* outstream; EPR_SProductId* product_id; EPR_SDatasetId* MAIN_PROC_PM_ID; EPR_SDatasetId* MDS1; EPR_SRecord* rec1; EPR_SRecord* rec5; //EPR_SField* numlines_field; //EPR_SField* numpixels_field; //EPR_SField* line_field; EPR_SField numlines_field; EPR_SField numpixels_field; EPR_SField line_field; //EPR_SField* line_num_field; // not used int status; ulong line_num; ulong numlines; ulong numberoflines; ulong numberoffields; ulong numpixels; //ulong l0; //ulong lN; //ulong p0; //ulong pN; unsigned int l0; // MA due to difference between 32-bit/64-bit data structure: define typedef like Doris see constant.h unsigned int lN; unsigned int p0; unsigned int pN; //ulong cnt; //ulong x,y; /* loop counter go upto 25.000 or so */ int cnt; int x,y; /* loop counter go upto 25.000 or so */ short realpart_short;/* written to output file */ short imagpart_short;/* written to output file */ /* handle input */ printf("argc: %f\n", (float)argc); if (argc != 3 && argc !=7 && argc !=8) { printf("Usage: envisat_dump_HH envisat-product outputfile [l0 lN p0 pN]\n"); printf(" where envisat-product is the input filename of the alternating pol product\n"); printf(" outputfile is the output filename\n"); printf(" l0 is the first azimuth line (starting at 1)\n"); printf(" lN is the last azimuth line\n"); printf(" p0 is the first range pixel (starting at 1)\n"); printf(" pN is the last range pixel\n"); printf("Example:\n"); printf(" envisat_dump_HH ASA_IMS_1PNDPA20021025_175208_000000162010_00356_03416_0005.N1 crop.out 0 10 0 100\n\n"); exit(1); } product_file_path = argv[1]; outfile = argv[2]; printf("infile: %s\n",product_file_path); printf("outfile: %s\n",outfile); if (argc>=7) { status=sscanf(argv[3],"%u",&l0); status=sscanf(argv[4],"%u",&lN); status=sscanf(argv[5],"%u",&p0); status=sscanf(argv[6],"%u",&pN); printf("sscanf l0: %f\n", (float)l0); printf("sscanf lN: %f\n", (float)lN); printf("sscanf p0: %f\n", (float)p0); printf("sscanf pN: %f\n", (float)pN); } /* record_name = (argc==8) ? argv[8] : "MDS1"; printf("record name: %s\n",record_name); */ /* Initialize the API. Set log-level to DEBUG and use default log-output (stdout) */ epr_init_api(e_log_debug, epr_log_message, NULL); /* Open the product; an argument is a path to product data file */ /* PRODUCT dataset record field element */ product_id = epr_open_product(product_file_path); /* product DATASET record field element */ MAIN_PROC_PM_ID = epr_get_dataset_id(product_id, "MAIN_PROCESSING_PARAMS_ADS"); MDS1 = epr_get_dataset_id(product_id, "MDS1"); /* product dataset RECORD field element */ rec1 = epr_read_record(MAIN_PROC_PM_ID, 0, NULL); /* product dataset record FIELD element */ //numlines_field = epr_get_field(rec1, "num_output_lines"); //numpixels_field = epr_get_field(rec1, "num_samples_per_line"); numlines_field = *(epr_get_field(rec1, "num_output_lines")); numpixels_field = *(epr_get_field(rec1, "num_samples_per_line")); /* epr_free_record(rec1); */ //epr_print_field(numlines_field, stdout); //epr_print_field(numpixels_field, stdout); epr_print_field(&numlines_field, stdout); epr_print_field(&numpixels_field, stdout); //numlines = epr_get_field_elem_as_ulong(numlines_field, 0); //numpixels = epr_get_field_elem_as_ulong(numpixels_field, 0); numlines = epr_get_field_elem_as_uint(&numlines_field, 0); numpixels = epr_get_field_elem_as_uint(&numpixels_field, 0); if (argc == 3) { l0 = 1; lN = numlines; p0 = 1; pN = numpixels; } /* loop over data record to get data and dump it to file */ numberoflines = epr_get_num_records(MDS1); printf("numberoflines: %f\n", (float)numberoflines); printf("numlines: %f\n", (float)numlines); printf("numpixels: %f\n", (float)numpixels); printf("l0: %f\n", (float)l0); printf("lN: %f\n", (float)lN); printf("p0: %f\n", (float)p0); printf("pN: %f\n", (float)pN); /* check if number of records indeed equals the number of lines */ if (numberoflines != numlines) { printf("numlines not equal in check, ASAR format error?."); exit(1); } /* --- Check if input as acceptable ---------------------------- */ if (l0 < 1) { printf("l0<1 not allowed. first line is 1 not 0.\n"); exit(1); } if (p0 < 1) { printf("p0<1 not allowed. first line is 1 not 0.\n"); exit(1); } if (lN > numlines) { printf("lN>numlines not allowed.\n"); exit(1); } if (pN > numpixels) { printf("pN>numpixels not allowed.\n"); exit(1); } /* read in whole line of cpx data */ outstream = fopen(outfile,"wb"); for (y=l0;y<=lN;y++) { rec5 = epr_read_record(MDS1, y-1, NULL); /* numberoffields = epr_get_num_fields(rec5); line_num_field = epr_get_field(rec5, "line_num"); line_num = epr_get_field_elem_as_ulong(line_num_field,0); printf("numberoffields: %i\n", numberoffields); printf("line number: %i\n", line_num); */ //line_field = epr_get_field(rec5, "proc_data"); line_field = *(epr_get_field(rec5, "proc_data")); cnt = 2*(p0-1);/* p0 starts at 1 for first element */ /* write out selected pixels */ for (x=p0;x<=pN;x++) { // realpart_short = epr_get_field_elem_as_short(line_field,cnt); // cnt = cnt + 1; // imagpart_short = epr_get_field_elem_as_short(line_field,cnt); // cnt = cnt + 1; realpart_short = epr_get_field_elem_as_short(&line_field,cnt); cnt++; imagpart_short = epr_get_field_elem_as_short(&line_field,cnt); cnt++; /* printf("%i,%i: realpart: %f %f\n", x,y,(float)realpart_short,(float)imagpart_short); */ status = fwrite(&realpart_short,2,1,outstream); if (status != 1) fprintf(stderr,"fwrite could not write to disk?"); status = fwrite(&imagpart_short,2,1,outstream); if (status != 1) fprintf(stderr,"fwrite could not write to disk?"); } /* this program seemed to fill all memory for some reason? try to free it */ epr_free_record(rec5); } fclose(outstream); epr_close_product(product_id); /* Closes product reader API, release all allocated resources */ epr_close_api(); return 0; } Doris-5.0.3Beta/envisat_tools/envisat_dump_VV.c000077500000000000000000000164771312547014700215670ustar00rootroot00000000000000/* BK: simple program to dump binary data for ENVISAT for alternating pol, VV channel. #%// BK 24-Nov-2003 $Id: envisat_dump_VV.c,v 1.2 2004/05/13 18:13:39 kampes Exp $ THIS program is not really good, but a fast hack for Z.Perksi.. */ #include #include #include #include #include #include #include #include "epr_api-2.2/src/epr_api.h" #if defined(WIN32) && defined(_DEBUG) #include #endif /* if defined(WIN32) && defined(_DEBUG) */ int main(int argc, char** argv) { const char* product_file_path; const char* outfile; const char* record_name; FILE* outstream; EPR_SProductId* product_id; EPR_SDatasetId* MAIN_PROC_PM_ID; EPR_SDatasetId* MDS1; EPR_SRecord* rec1; EPR_SRecord* rec5; //EPR_SField* numlines_field; //EPR_SField* numpixels_field; //EPR_SField* line_field; EPR_SField numlines_field; EPR_SField numpixels_field; EPR_SField line_field; //EPR_SField* line_num_field; // not used int status; ulong line_num; ulong numlines; ulong numberoflines; ulong numberoffields; ulong numpixels; //ulong l0; //ulong lN; //ulong p0; //ulong pN; unsigned int l0; // MA due to difference between 32-bit/64-bit data structure: define typedef like Doris see constant.h unsigned int lN; unsigned int p0; unsigned int pN; //ulong cnt; //ulong x,y; /* loop counter go upto 25.000 or so */ int cnt; int x,y; /* loop counter go upto 25.000 or so */ short realpart_short;/* written to output file */ short imagpart_short;/* written to output file */ /* handle input */ printf("argc: %f\n", (float)argc); if (argc != 3 && argc !=7 && argc !=8) { printf("Usage: envisat_dump_VV envisat-product outputfile [l0 lN p0 pN]\n"); printf(" where envisat-product is the input filename of the alternating pol product\n"); printf(" outputfile is the output filename\n"); printf(" l0 is the first azimuth line (starting at 1)\n"); printf(" lN is the last azimuth line\n"); printf(" p0 is the first range pixel (starting at 1)\n"); printf(" pN is the last range pixel\n"); printf("Example:\n"); printf(" envisat_dump_VV ASA_IMS_1PNDPA20021025_175208_000000162010_00356_03416_0005.N1 crop.out 0 10 0 100\n\n"); exit(1); } product_file_path = argv[1]; outfile = argv[2]; printf("infile: %s\n",product_file_path); printf("outfile: %s\n",outfile); if (argc>=7) { status=sscanf(argv[3],"%u",&l0); status=sscanf(argv[4],"%u",&lN); status=sscanf(argv[5],"%u",&p0); status=sscanf(argv[6],"%u",&pN); printf("sscanf l0: %f\n", (float)l0); printf("sscanf lN: %f\n", (float)lN); printf("sscanf p0: %f\n", (float)p0); printf("sscanf pN: %f\n", (float)pN); } /* record_name = (argc==8) ? argv[8] : "MDS1"; printf("record name: %s\n",record_name); */ /* Initialize the API. Set log-level to DEBUG and use default log-output (stdout) */ epr_init_api(e_log_debug, epr_log_message, NULL); /* Open the product; an argument is a path to product data file */ /* PRODUCT dataset record field element */ product_id = epr_open_product(product_file_path); /* product DATASET record field element */ MAIN_PROC_PM_ID = epr_get_dataset_id(product_id, "MAIN_PROCESSING_PARAMS_ADS"); /* see product specs, record is called MDS2! */ MDS1 = epr_get_dataset_id(product_id, "MDS2"); /* product dataset RECORD field element */ rec1 = epr_read_record(MAIN_PROC_PM_ID, 0, NULL); /* product dataset record FIELD element */ //numlines_field = epr_get_field(rec1, "num_output_lines"); //numpixels_field = epr_get_field(rec1, "num_samples_per_line"); numlines_field = *(epr_get_field(rec1, "num_output_lines")); numpixels_field = *(epr_get_field(rec1, "num_samples_per_line")); /* epr_free_record(rec1); */ //epr_print_field(numlines_field, stdout); //epr_print_field(numpixels_field, stdout); epr_print_field(&numlines_field, stdout); epr_print_field(&numpixels_field, stdout); //numlines = epr_get_field_elem_as_ulong(numlines_field, 0); //numpixels = epr_get_field_elem_as_ulong(numpixels_field, 0); numlines = epr_get_field_elem_as_uint(&numlines_field, 0); numpixels = epr_get_field_elem_as_uint(&numpixels_field, 0); if (argc == 3) { l0 = 1; lN = numlines; p0 = 1; pN = numpixels; } /* loop over data record to get data and dump it to file */ numberoflines = epr_get_num_records(MDS1); printf("numberoflines: %f\n", (float)numberoflines); printf("numlines: %f\n", (float)numlines); printf("numpixels: %f\n", (float)numpixels); printf("l0: %f\n", (float)l0); printf("lN: %f\n", (float)lN); printf("p0: %f\n", (float)p0); printf("pN: %f\n", (float)pN); /* check if number of records indeed equals the number of lines */ if (numberoflines != numlines) { printf("numlines not equal in check, ASAR format error?."); exit(1); } /* --- Check if input as acceptable ---------------------------- */ if (l0 < 1) { printf("l0<1 not allowed. first line is 1 not 0.\n"); exit(1); } if (p0 < 1) { printf("p0<1 not allowed. first line is 1 not 0.\n"); exit(1); } if (lN > numlines) { printf("lN>numlines not allowed.\n"); exit(1); } if (pN > numpixels) { printf("pN>numpixels not allowed.\n"); exit(1); } /* read in whole line of cpx data */ outstream = fopen(outfile,"wb"); for (y=l0;y<=lN;y++) { rec5 = epr_read_record(MDS1, y-1, NULL); /* numberoffields = epr_get_num_fields(rec5); line_num_field = epr_get_field(rec5, "line_num"); line_num = epr_get_field_elem_as_ulong(line_num_field,0); printf("numberoffields: %i\n", numberoffields); printf("line number: %i\n", line_num); */ //line_field = epr_get_field(rec5, "proc_data"); line_field = *(epr_get_field(rec5, "proc_data")); cnt = 2*(p0-1);/* p0 starts at 1 for first element */ /* write out selected pixels */ for (x=p0;x<=pN;x++) { // realpart_short = epr_get_field_elem_as_short(line_field,cnt); // cnt = cnt + 1; // imagpart_short = epr_get_field_elem_as_short(line_field,cnt); // cnt = cnt + 1; realpart_short = epr_get_field_elem_as_short(&line_field,cnt); cnt++; imagpart_short = epr_get_field_elem_as_short(&line_field,cnt); cnt++; /* printf("%i,%i: realpart: %f %f\n", x,y,(float)realpart_short,(float)imagpart_short); */ status = fwrite(&realpart_short,2,1,outstream); if (status != 1) fprintf(stderr,"fwrite could not write to disk?"); status = fwrite(&imagpart_short,2,1,outstream); if (status != 1) fprintf(stderr,"fwrite could not write to disk?"); } /* this program seemed to fill all memory for some reason? try to free it */ epr_free_record(rec5); } fclose(outstream); epr_close_product(product_id); /* Closes product reader API, release all allocated resources */ epr_close_api(); return 0; } Doris-5.0.3Beta/envisat_tools/envisat_dump_data.c000077500000000000000000000136571312547014700221420ustar00rootroot00000000000000/* BK: simple program to dump binary data for ENVISAT 08-July-2004 $Id: envisat_dump_data.c,v 1.5 2004/08/09 09:43:28 kampes Exp $ */ #include #include #include #include #include #include #include #include "epr_api-2.2/src/epr_api.h" #if defined(WIN32) && defined(_DEBUG) #include #endif /* if defined(WIN32) && defined(_DEBUG) */ //#include int main(int argc, char** argv) { const char* product_file_path; const char* outfile; FILE* outstream; EPR_SProductId* product_id; EPR_SDatasetId* MAIN_PROC_PM_ID; EPR_SDatasetId* MDS1; EPR_SRecord* rec1; EPR_SRecord* rec5; EPR_SField numlines_field; EPR_SField numpixels_field; EPR_SField line_field; int status; ulong line_num; ulong numlines; ulong numberoflines; ulong numberoffields; ulong numpixels; //ulong l0; //ulong lN; //ulong p0; //ulong pN; unsigned int l0; // MA due to difference between 32-bit/64-bit data structure: define typedef like Doris see constant.h unsigned int lN; unsigned int p0; unsigned int pN; int cnt; int x,y; /* loop counter go upto 25.000 or so */ short realpart_short;/* written to output file */ short imagpart_short;/* written to output file */ /* handle input */ printf("argc: %f\n", (float)argc); if (argc != 3 && argc !=7) { printf("Usage: envisat_dump_data envisat-product outputfile [l0 lN p0 pN]\n"); printf(" where envisat-product is the input filename\n"); printf(" outputfile is the output filename\n"); printf(" l0 is the first azimuth line (starting at 1)\n"); printf(" lN is the last azimuth line\n"); printf(" p0 is the first range pixel (starting at 1)\n"); printf(" pN is the last range pixel\n"); printf("Example:\n"); printf(" envisat_dump_data ASA_IMS_1PNDPA20021025_175208_000000162010_00356_03416_0005.N1 crop.out 0 10 0 100\n\n"); exit(1); } product_file_path = argv[1]; outfile = argv[2]; printf("infile: %s\n",product_file_path); printf("outfile: %s\n",outfile); if (argc==7) { status=sscanf(argv[3],"%u",&l0); status=sscanf(argv[4],"%u",&lN); status=sscanf(argv[5],"%u",&p0); status=sscanf(argv[6],"%u",&pN); printf("sscanf l0: %f\n", (float)l0); printf("sscanf lN: %f\n", (float)lN); printf("sscanf p0: %f\n", (float)p0); printf("sscanf pN: %f\n", (float)pN); //printf("sscanf lN: %s\n", typeid(lN)); } /* Initialize the API. Set log-level to DEBUG and use default log-output (stdout) */ epr_init_api(e_log_debug, epr_log_message, NULL); /* Open the product; an argument is a path to product data file */ /* PRODUCT dataset record field element */ product_id = epr_open_product(product_file_path); /* product DATASET record field element */ MAIN_PROC_PM_ID = epr_get_dataset_id(product_id, "MAIN_PROCESSING_PARAMS_ADS"); MDS1 = epr_get_dataset_id(product_id, "MDS1"); /* product dataset RECORD field element */ rec1 = epr_read_record(MAIN_PROC_PM_ID, 0, NULL); /* product dataset record FIELD element */ numlines_field = *(epr_get_field(rec1, "num_output_lines")); numpixels_field = *(epr_get_field(rec1, "num_samples_per_line")); /* epr_free_record(rec1); */ epr_print_field(&numlines_field, stdout); epr_print_field(&numpixels_field, stdout); numlines = epr_get_field_elem_as_uint(&numlines_field, 0); numpixels = epr_get_field_elem_as_uint(&numpixels_field, 0); if (argc == 3) { l0 = 1; lN = numlines; p0 = 1; pN = numpixels; } /* loop over data record to get data and dump it to file */ numberoflines = epr_get_num_records(MDS1); printf("numberoflines: %f\n", (float)numberoflines); printf("numlines: %f\n", (float)numlines); printf("numpixels: %f\n", (float)numpixels); printf("l0: %f\n", (float)l0); printf("lN: %f\n", (float)lN); printf("p0: %f\n", (float)p0); printf("pN: %f\n", (float)pN); /* check if number of records indeed equals the number of lines */ if (numberoflines != numlines) { printf("numlines not equal in check, ASAR format error?."); exit(1); } /* --- Check if input as acceptable ---------------------------- */ if (l0 < 1) { printf("l0<1 not allowed. first line is 1 not 0.\n"); exit(1); } if (p0 < 1) { printf("p0<1 not allowed. first line is 1 not 0.\n"); exit(1); } if (lN > numlines) { printf("lN>numlines not allowed.\n"); exit(1); } if (pN > numpixels) { printf("pN>numpixels not allowed.\n"); exit(1); } /* --- read in whole line of cpx data -------------------------- */ outstream = fopen(outfile,"wb"); for (y=l0;y<=lN;y++) { rec5 = epr_read_record(MDS1, y-1, NULL); line_field = *(epr_get_field(rec5, "proc_data")); cnt = 2*(p0-1);/* p0 starts at 1 for first element (BUGFIX!) */ /* write out selected pixels */ for (x=p0;x<=pN;x++) { realpart_short = epr_get_field_elem_as_short(&line_field,cnt); cnt++; imagpart_short = epr_get_field_elem_as_short(&line_field,cnt); cnt++; status = fwrite(&realpart_short,2,1,outstream); if (status != 1) fprintf(stderr,"fwrite could not write to disk?"); status = fwrite(&imagpart_short,2,1,outstream); if (status != 1) fprintf(stderr,"fwrite could not write to disk?"); } /* this program seemed to fill all memory for some reason? try to free it */ epr_free_record(rec5); } fclose(outstream); epr_close_product(product_id); /* Closes product reader API, release all allocated resources */ epr_close_api(); return 0; } Doris-5.0.3Beta/envisat_tools/envisat_dump_header.c000077500000000000000000000220411312547014700224440ustar00rootroot00000000000000/* BK: simple program to get header info for ENVISAT * 13-Jun-2003 * simply dumps all header info. a unix script will be used to * convert this to doris input $Id: envisat_dump_header.c,v 1.4 2004/05/13 18:13:39 kampes Exp $ */ #include #include #include #include #include #include #include #include "epr_api-2.2/src/epr_api.h" #if defined(WIN32) && defined(_DEBUG) #include #endif /* if defined(WIN32) && defined(_DEBUG) */ int main(int argc, char** argv) { EPR_SProductId* product_id; EPR_SDatasetId* MDS1_SQ_ADS; EPR_SDatasetId* MAIN_PROC_PM_ID; EPR_SDatasetId* DOP_CENTROID_COEFFS_ADS; EPR_SDatasetId* CHIRP_PARAMS_ADS; EPR_SDatasetId* GEOLOCATION_GRID_ADS; EPR_SRecord* mph; EPR_SRecord* sph; EPR_SRecord* rec0; EPR_SRecord* rec1; EPR_SRecord* rec2; EPR_SRecord* rec3; EPR_SRecord* rec4; EPR_SField* azitime0_field; EPR_EErrCode err_code=e_err_none; int status; const char* product_file_path; /* const char* datasetname; */ /* --- Handle input ----------------------------------------- */ printf("+-----------------------------------------------+\n"); printf("| This is envisat_dump_header by Bert Kampes |\n"); printf("+-----------------------------------------------+\n"); if (argc <= 1) { printf("Usage: envisat_dump_header envisat-product\n"); printf(" where envisat-product is the input filename\n"); printf("Example:\n"); printf(" envisat_dump_header ASA_IMS_1PNDPA20021025_175208_000000162010_00356_03416_0005.N1\n\n"); exit(1); } product_file_path = argv[1]; printf("\nInitializing api.\n"); printf("-------------------------------------------------\n"); /* Initialize the API. Set log-level to DEBUG and use default log-output (stdout) */ /* How to set error logging without exiting? */ /*status = epr_init_api(e_log_debug, epr_log_message, epr_log_message);*/ status = epr_init_api(e_log_debug, epr_log_message, NULL); if (status != 0) { printf("envisat_dump_header: fatal error in epr_init_api\n"); printf("exiting.\n"); exit(1); }; /* Open the product; an argument is a path to product data file */ /* PRODUCT dataset record field element */ printf("\nOpening product.\n"); printf("-------------------------------------------------\n"); product_id = epr_open_product(product_file_path); err_code = epr_get_last_err_code(); if (err_code != e_err_none) { printf("envisat_dump_header: fatal error in epr_open_product\n"); printf("exiting.\n"); exit(1); } /* Read fields that I want for Doris */ /* product DATASET record field element */ /* --- MAIN PRODUCT HEADER ---------------------------------------- */ printf("\nTrying to read record: MPH\n"); printf("-------------------------------------------------\n"); mph = epr_get_mph(product_id); err_code = epr_get_last_err_code(); if (err_code == e_err_none) { epr_print_record(mph, stdout); } else { printf("envisat_dump_header: likely fatal error in epr_get_mph\n"); printf("continuing.\n"); epr_clear_err(); } /* --- SECOND PRODUCT HEADER -------------------------------------- */ printf("\nTrying to read record: SPH\n"); printf("-------------------------------------------------\n"); sph = epr_get_sph(product_id); err_code = epr_get_last_err_code(); if (err_code == e_err_none) { epr_print_record(sph, stdout); } else { printf("envisat_dump_header: likely fatal error in epr_get_sph\n"); epr_clear_err(); } /* dsd = epr_get_dsd(product_id); */ /* epr_print_record(dsd, stdout);*/ /* --- MDS1_SQ_ADS ------------------------------------------------ */ printf("\nTrying to read record: MDS1_SQ_ADS\n"); printf("-------------------------------------------------\n"); MDS1_SQ_ADS = epr_get_dataset_id(product_id, "MDS1_SQ_ADS"); err_code = epr_get_last_err_code(); if (err_code == e_err_none) { rec0 = epr_read_record(MDS1_SQ_ADS, 0, NULL); err_code = epr_get_last_err_code(); if (err_code == e_err_none) { epr_print_record(rec0, stdout); } else { printf("envisat_dump_header: non-fatal error in epr_read_record MDS1_SQ_ADS\n"); printf("could not read this record. may not be a problem.\n"); epr_clear_err(); } } else { printf("envisat_dump_header: error in epr_get_dataset_id MDS1_SQ_ADS\n"); printf("could not read this record. may not be a problem.\n"); epr_clear_err(); } /* --- MAIN_PROC_PM_ID -------------------------------------------- */ printf("\nTrying to read record: MAIN_PROCESSING_PARAMS_ADS\n"); printf("-------------------------------------------------\n"); MAIN_PROC_PM_ID = epr_get_dataset_id(product_id, "MAIN_PROCESSING_PARAMS_ADS"); err_code = epr_get_last_err_code(); if (err_code == e_err_none) { rec1 = epr_read_record(MAIN_PROC_PM_ID, 0, NULL); err_code = epr_get_last_err_code(); if (err_code == e_err_none) { epr_print_record(rec1, stdout); } else { printf("envisat_dump_header: error in epr_read_record MAIN_PROCESSING_PARAMS_ADS\n"); printf("could not read this record. may not be a problem.\n"); epr_clear_err(); } } else { printf("envisat_dump_header: error in epr_get_dataset_id MAIN_PROCESSING_PARAMS_ADS\n"); printf("could not read this record. may not be a problem.\n"); epr_clear_err(); } /* --- DOP_CENTROID_COEFFS_ADS ------------------------------------ */ printf("\nTrying to read record: DOP_CENTROID_COEFFS_ADS\n"); printf("-------------------------------------------------\n"); DOP_CENTROID_COEFFS_ADS = epr_get_dataset_id(product_id, "DOP_CENTROID_COEFFS_ADS"); err_code = epr_get_last_err_code(); if (err_code == e_err_none) { rec2 = epr_read_record(DOP_CENTROID_COEFFS_ADS, 0, NULL); err_code = epr_get_last_err_code(); if (err_code == e_err_none) { epr_print_record(rec2, stdout); } else { printf("envisat_dump_header: error in epr_read_record DOP_CENTROID_COEFFS_ADS\n"); printf("could not read this record. may not be a problem.\n"); epr_clear_err(); } } else { printf("envisat_dump_header: error in epr_get_dataset_id DOP_CENTROID_COEFFS_ADS\n"); printf("could not read this record. may not be a problem.\n"); epr_clear_err(); } /* --- CHIRP_PARAMS_ADS ------------------------------------------- */ printf("\nTrying to read record: CHIRP_PARAMS_ADS\n"); printf("-------------------------------------------------\n"); /* it seems ESRIN does not include this. For now do not read it at all Problems with BAM data, report Z.Perksi #%// Bert Kampes, 12-May-2004 */ CHIRP_PARAMS_ADS = epr_get_dataset_id(product_id, "CHIRP_PARAMS_ADS"); err_code = epr_get_last_err_code(); if (err_code == e_err_none) { rec3 = epr_read_record(CHIRP_PARAMS_ADS, 0, NULL); err_code = epr_get_last_err_code(); if (err_code == e_err_none) { epr_print_record(rec3, stdout); } else { printf("envisat_dump_header: error in epr_read_record CHIRP_PARAMS_ADS\n"); printf("could not read this record. may not be a problem.\n"); epr_clear_err(); } } else { printf("envisat_dump_header: error in epr_get_dataset_id CHIRP_PARAMS_ADS\n"); printf("could not read this record. may not be a problem.\n"); epr_clear_err(); } /* --- GEOLOCATION_GRID_ADS --------------------------------------- */ printf("\nTrying to read record: GEOLOCATION_GRID_ADS\n"); printf("-------------------------------------------------\n"); GEOLOCATION_GRID_ADS = epr_get_dataset_id(product_id, "GEOLOCATION_GRID_ADS"); err_code = epr_get_last_err_code(); if (err_code == e_err_none) { rec4 = epr_read_record(GEOLOCATION_GRID_ADS, 0, NULL); err_code = epr_get_last_err_code(); if (err_code == e_err_none) { epr_print_record(rec4, stdout); } else { printf("envisat_dump_header: error in epr_read_record GEOLOCATION_GRID_ADS\n"); printf("could not read this record. may not be a problem.\n"); epr_clear_err(); } } else { printf("envisat_dump_header: error in epr_get_dataset_id GEOLOCATION_GRID_ADS\n"); printf("could not read this record. may not be a problem.\n"); epr_clear_err(); } /* product dataset record FIELD element */ /* azitime0_field = epr_get_field(rec1, "first_zero_doppler_time"); epr_print_field(azitime0_field, stdout); */ /* Close product_id and release rest of the allocated memory */ printf("\n"); epr_close_product(product_id); /* Closes product reader API, release all allocated resources */ epr_close_api(); printf("\n+-----------------------------------------------+\n"); printf("| Thank you for using envisat_dump_header |\n"); printf("+-----------------------------------------------+\n\n"); return 0; } Doris-5.0.3Beta/envisat_tools/envisat_dump_header2doris.csh000077500000000000000000000276641312547014700241420ustar00rootroot00000000000000#!/bin/csh -f ################################################################### # envisatdumpheader2doris.csh # 1) Read envisat file, and dump to TMPFILE such as # ASA_IMS_1PNDPA20021025_175208_000000162010_00356_03416_0005.N1 # 2) Convert dumped header of envisat to a doris resultfile # section "readfiles". # this includes the orbit in this section. do not run precise # orbits step. # This script depends on the binary envisat_dump_header that must # be executable on your system. The source code of envisat_dump_header # is included in the Doris distribution. # BK 16-JUN-2003 # LOCALE settings of awk gave a problem # Added more output. Still report is that range_time_to_first pixel # may be wrong. (crop GEO seems to crop wrong for Envisat?) # added tr -d '"' to remove quotes from strings. This may not work everywhere? #%// Bert Kampes, 13-May-2004 # After bug report, made string with Datafile a bit smaller. # I don;t really like this, but OK. #%// Bert Kampes, 03-Jun-2004 # added Platform heading + Polarization info # added Orbit velocities #%// Mahmut Arikan, 29-Jul-2010 # added support for ERS in Envisat Format #%// Mahmut Arikan, 19-Oct-2010 ################################################################### set PRG = `basename "$0"` set VER = "v1.2, Doris software" set AUT = "TUDelft, (c) 2003-2010" echo " " echo "$PRG $VER, $AUT" # Handle wrong input if ( $#argv != 1 ) then cat << __EOFHD USAGE: $PRG inputfile where inputfile is the envisat SLC file. EXAMPLE: $PRG ASA_IMS_1PNDPA20021025_175208_000000162010_00356_03416_0005.N1 __EOFHD exit 1 endif ### Handle input set ASARFILE = $1 set DUMPHEADER = envisat_dump_header set TMPFILE = envisat_dump_header.log ### find out if nawk is available, since awk seems not to know atan2? set AWK = awk; echo 1 | /usr/xpg4/bin/awk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = '/usr/xpg4/bin/awk' echo 1 | gawk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = 'gawk' echo 1 | nawk '{print 1}' >& /dev/null if ( $status == 0 ) set AWK = 'nawk' echo "Using as awk program: $AWK" ### set LOCALE to decimal.point style #kampes@newton[18:22]: setenv LC_NUMERIC pl #kampes@newton[18:22]: echo "5300000000.0" | awk '{print 299792458.0/$1}' #0,0565646 #kampes@newton[18:22]: setenv LC_NUMERIC C #kampes@newton[18:22]: echo "5300000000.0" | awk '{print 299792458.0/$1}' #0.0565646 #we could check first with: locale -ck decimal_point #setenv LC_ALL POSIX setenv LC_ALL C setenv LC_NUMERIC C ### Run dumpheader program $DUMPHEADER $ASARFILE > $TMPFILE if ( $status != 0 ) then echo "exit status of $DUMPHEADER not 0" echo "continuing, but this may go wrong." echo "We experienced this with data processed by ESRIN" endif ### Get parameters from dumped header file. set DUMMY = "dummy" set PRODUCT = `$AWK '/^PRODUCT /{print $3}' $TMPFILE` set PRODUCT_TYPE = `$AWK '/^PRODUCT /{print substr($3,2,3)}' $TMPFILE` # MA ASA --> Envisat ASAR or SAR --> ERS SAR set PROC_FAC = `$AWK '/^PROC_CENTER/{print $3}' $TMPFILE` set PROC_TIME = `$AWK '/^PROC_TIME/{print $3" "$4}' $TMPFILE` set TRACK = `$AWK '/^REL_ORBIT/{print $3}' $TMPFILE` set ORBIT = `$AWK '/^ABS_ORBIT/{print $3}' $TMPFILE` set FRAME = `$AWK '/^CYCLE/{print $3}' $TMPFILE` set FIRST_LINE_TIME = `$AWK '/^FIRST_LINE_TIME/{print $3" "$4}' $TMPFILE | cut -f2 -d'"' | cut -f1 -d'"'` # not used: set LAST_LINE_TIME = `$AWK '/^LAST_LINE_TIME/{print $3" "$4}' $TMPFILE` set FIRST_MID_LAT = `$AWK '/^FIRST_MID_LAT/{print $3}' $TMPFILE` set FIRST_MID_LONG = `$AWK '/^FIRST_MID_LONG/{print $3}' $TMPFILE` set LAST_MID_LAT = `$AWK '/^LAST_MID_LAT/{print $3}' $TMPFILE` set LAST_MID_LONG = `$AWK '/^LAST_MID_LONG/{print $3}' $TMPFILE` ### center coordinates set MIDLAT = `echo "$FIRST_MID_LAT $LAST_MID_LAT" | $AWK '{print ($1+$2)/2e6}'` set MIDLON = `echo "$FIRST_MID_LONG $LAST_MID_LONG" | $AWK '{print ($1+$2)/2e6}'` set MIDHEA = `$AWK '/^sub_sat_track/{print $3}' $TMPFILE` set VOLSETID = `date --date="$FIRST_LINE_TIME" +%Y%m%d%H%M%S` # MA # Decide on satellite if ( $PRODUCT_TYPE == "SAR" ) then set PRODUCT_TYPE = "ERS_SAR" else set PRODUCT_TYPE = "ASAR" endif set numpixels = `$AWK '/^num_samples_per_line/{print $3}' $TMPFILE` set numlines = `$AWK '/^num_output_lines/{print $3}' $TMPFILE` set checknumlines = `$AWK '/^num_output_lines/{print $3+1}' $TMPFILE` set wgt_azimuth = `$AWK '/^filter_az/{print $3}' $TMPFILE` set wgt_range = `$AWK '/^filter_window/{print $3}' $TMPFILE` ### remove double quotes: set wgt_azimuth = `echo $wgt_azimuth | tr -d '"'` set wgt_range = `echo $wgt_range | tr -d '"'` set RSR = `$AWK '/^range_samp_rate/{printf "%f\n", $3/1e6}' $TMPFILE` ### After first awk, RBW="{1550000.000000," thus do a cut and to MHz set RBW = `$AWK '/^bandwidth.tot_bw_range/{print $3}' $TMPFILE | cut -f2 -d'{' | cut -f1 -d',' | $AWK '{print $1/1e6}'` ### not ok, this is time used in doppler est. ### not ok: set SRT = `$AWK '/slant_range_time/{print $3/1e6}' $TMPFILE` set SAMPLE = `$AWK '/^first_line_tie_points.samp_numbers/{print $3}' $TMPFILE | cut -f2 -d'{' | cut -f1 -d','` # 1 ### fast time in [ns], RSR in [MHz], 2-way time. set T_TO_SAMPLE = `$AWK '/^first_line_tie_points.slant_range_times/{print $3}' $TMPFILE | cut -f2 -d'{' | cut -f1 -d','` # 5523270.000000 set SRT = `echo "$T_TO_SAMPLE $SAMPLE $RSR" | $AWK '{printf "%f\n", $1/1e6+($2-1)/($3*1e3)}'` # 5523270.000000 1 19.207680 ### also obtain time to last pixel and compute RSR, same for PRF #RSR = (PIX_N-PIX_1)/DT #kampes@capone[18:43]: reken 5174/(5810316.50-5540945.5) #.01920770981286033017 ### After first awk, PRF="{14.1223121," thus do a cut set PRF = `$AWK '/^image_parameters.prf_value/{print $3}' $TMPFILE | cut -f2 -d'{' | cut -f1 -d','` set ABW = `$AWK '/^to_bw_az/{print $3}' $TMPFILE` ### Doppler parameters set FDC0 = `$AWK '/^dop_coef/{print $3 $4 $5}' $TMPFILE | cut -f2 -d'{' | cut -f1 -d','` set FDC1 = `$AWK '/^dop_coef/{print $3 $4 $5}' $TMPFILE | cut -f2 -d'{' | cut -f2 -d','` set FDC2 = `$AWK '/^dop_coef/{print $3 $4 $5}' $TMPFILE | cut -f2 -d'{' | cut -f3 -d','` set WAVELENGTH = `$AWK '/^radar_freq/{print 299792458.0/$3}' $TMPFILE` ### Assume we have 5 state vectors, but check anyway... set state_x = `$AWK '/^orbit_state_vectors...x_pos/{printf "%f\n", $3/1e2}' $TMPFILE` set state_y = `$AWK '/^orbit_state_vectors...y_pos/{printf "%f\n", $3/1e2}' $TMPFILE` set state_z = `$AWK '/^orbit_state_vectors...z_pos/{printf "%f\n", $3/1e2}' $TMPFILE` set state_xdot = `$AWK '/^orbit_state_vectors...x_vel/{printf "%f\n", $3/1e2}' $TMPFILE` set state_ydot = `$AWK '/^orbit_state_vectors...y_vel/{printf "%f\n", $3/1e2}' $TMPFILE` set state_zdot = `$AWK '/^orbit_state_vectors...z_vel/{printf "%f\n", $3/1e2}' $TMPFILE` ### Time seems to be daynumber seconds milliseconds set state_t_sec = `$AWK '/^orbit_state_vectors...state_vect_time/{print $4}' $TMPFILE | cut -f2 -d'=' | cut -f1 -d','` set state_t_dsec = `$AWK '/^orbit_state_vectors...state_vect_time/{print $5}' $TMPFILE | cut -f2 -d'=' | cut -f1 -d'}'` set NUMSTATEVECTORS = $#state_x ### SARPROCESSOR: is used by Doris set SOFTWARE_VER = `$AWK '/^SOFTWARE_VER/{print $3}' $TMPFILE` set SOFTWARE_VER = "ASAR $SOFTWARE_VER" ### some extra for general information, not used by Doris. set SWATH = `$AWK '/^SWATH/{print $3}' $TMPFILE` set PASS = `$AWK '/^PASS/{print $3}' $TMPFILE` set SPH_DESCRIPTOR = `$AWK '/^SPH_DESCRIPTOR/{print $3, $4, $5, $6, $7, $8}' $TMPFILE` set FREQUENCY = `$AWK '/^radar_freq/{print $3}' $TMPFILE` set POLAR_1 = `$AWK '/^MDS1_TX_RX_POLAR/{print $3}' $TMPFILE` set POLAR_2 = `$AWK '/^MDS2_TX_RX_POLAR/{print $3}' $TMPFILE` set POLAR = "$POLAR_1 $POLAR_2" ### create a result section to a tmp file. cat << __EOFHD ******************************************************************* *_Start_readfiles: ******************************************************************* Volume file: $PRODUCT Volume_ID: $DUMMY Volume_identifier: $DUMMY Volume_set_identifier: $VOLSETID (Check)Number of records in ref. file: $checknumlines Product type specifier: $PRODUCT_TYPE SAR_PROCESSOR: $SOFTWARE_VER SWATH: $SWATH PASS: $PASS SPH_DESCRIPTOR: $SPH_DESCRIPTOR IMAGING_MODE: $POLAR RADAR_FREQUENCY (HZ): $FREQUENCY Logical volume generating facility: $PROC_FAC Logical volume creation date: $DUMMY Location and date/time of product creation: $PROC_TIME Scene identification: ORBIT $ORBIT TRACK $TRACK Scene location: FRAME $FRAME Leader file: $PRODUCT Sensor platform mission identifer: ENVISAT-ASAR-SLC Scene_centre_latitude: $MIDLAT Scene_centre_longitude: $MIDLON Scene_centre_heading: $MIDHEA Radar_wavelength (m): $WAVELENGTH First_pixel_azimuth_time (UTC): $FIRST_LINE_TIME TIME TO LAST LINE: compute prf: $LAST_LINE_TIME Pulse_Repetition_Frequency (computed, Hz): $PRF Total_azimuth_band_width (Hz): $ABW Weighting_azimuth: $wgt_azimuth Xtrack_f_DC_constant (Hz, early edge): $FDC0 Xtrack_f_DC_linear (Hz/s, early edge): $FDC1 Xtrack_f_DC_quadratic (Hz/s/s, early edge): $FDC2 Range_time_to_first_pixel (2way) (ms): $SRT Range_sampling_rate (computed, MHz): $RSR Total_range_band_width (MHz): $RBW Weighting_range: $wgt_range ******************************************************************* *_Start_leader_datapoints ******************************************************************* t(s) X(m) Y(m) Z(m) NUMBER_OF_DATAPOINTS: $NUMSTATEVECTORS __EOFHD ### t_dsec is given in ms. (place 0's before it, do not use "$t.$dt") @ i = 1 while ( $i <= $NUMSTATEVECTORS ) set t = `echo "$state_t_sec[$i] $state_t_dsec[$i]" | awk '{printf "%.8f", $1+$2/1e6}'` #echo "$t $state_x[$i] $state_y[$i] $state_z[$i]" # dump state vectors only echo "$t $state_x[$i] $state_y[$i] $state_z[$i] $state_xdot[$i] $state_ydot[$i] $state_zdot[$i]" # dump velocities too @ i++ end ############################### #%// Bert Kampes, 03-Jun-2004 # report that line is too long: #Datafile: $ASARFILE # therefore, suggested to check with #if ( `echo "$ASARFILE" | awk '{print length($1)}'` > 70 ) then ##or: if ( `echo "$ASARFILE" | wc -c` > 70 ) then # echo "Datafile: $ASARFILE" #else # echo "Datafile: $ASARFILE" #endif ############################### #does not work #set DF = "Datafile: $ASARFILE" #if ( `echo "$ASARFILE" | wc -c` > 70 ) then #set DF = "Datafile: $ASARFILE" #endif #again check length within 127 total, else create a soft link and warn... cat << __EOFHD ******************************************************************* * End_leader_datapoints:_NORMAL ******************************************************************* #Report that else next line could easily be too long: Datafile: $ASARFILE Dataformat: ENVISAT Number_of_lines_original: $numlines Number_of_pixels_original: $numpixels ******************************************************************* * End_readfiles:_NORMAL ******************************************************************* __EOFHD ###EOF Doris-5.0.3Beta/install/000077500000000000000000000000001312547014700150455ustar00rootroot00000000000000Doris-5.0.3Beta/install/INSTALL.txt000077500000000000000000000113611312547014700167210ustar00rootroot00000000000000This "INSTALL" file describes the installation of the "Doris" Delft radar interferometric software package. Doris has been installed on virtually all operating systems world-wide (mainly UNIX like, for MS Windows(c) your best option is using Cygwin.) If the following does not work for you, please first search the FAQ via http://doris.tudelft.nl There are 5 components in this distribution (doris v5.0beta). 1. doris_stack subdirectory: doris stack code for handling processing of stacks. (sentinel 1) 2. prepare_stack subdirectory: code for setting up a doris stack. 3. doris_core and bin subdirectory: doris core software (C++ source code, python and shell scripts); 4. ENVISAT_TOOLS subdir: standalone reader for ENVISAT (C source code); 5. SARtools subdir: standalone utilities (C++ source code). -------------------------------------------- - INSTALLATION OF Doris 5 - -------------------------------------------- -------------------------------------------- - OPTIONAL: installation of FFTW library --- - tested for Cygwin, SUN Solaris, Linux ---- -------------------------------------------- 1. download fftw-3.2.1 from http://www.fftw.org : wget -c http://www.fftw.org/fftw-3.2.1.tar.gz 2. gunzip and tar xvf it in subdirectory of doris root installation. 3. cd fftw-3.2.1 4. ./configure --prefix=`pwd` --enable-float 5. make 6. make install -------------------------------------------- - COMPILATION OF THE DORIS CORE ------------ -------------------------------------------- 7. cd ../doris_core 8. Read the README file 9. ./configure (creates "Makefile") # requires tcsh shell to run, to install type "sudo apt-get install tcsh" at shell prompt on Ubuntu platform. ( +answer the questions about libraries, etc.) 10. make (compiles the software) 11. make install (installs doris and bin scripts) -------------------------------------------- - COMPILATION OF DORIS UTILITIES ----------- -------------------------------------------- 12. cd ../sartools 13. make 14. Review/edit the Makefile if this does not work (for example if you do not want to use GNU gcc/g++ as compiler) 15. make install (installs in /usr/local/bin unless you edit the Makefile) 16. cd ../envisat_tools # on 64-bit system requires libc-dev-i386 library ex: "sudo apt-get install libc-dev-i386" 17. make 18. Review/edit the Makefile if this does not work (for example if you do not want to use gcc as compiler) 19. make install -------------------------------------------- - INSTALLATION OF USEFUL EXTERNAL SOFTWARE - -------------------------------------------- The doris software depends for full functionality on: 21. getorb: precise orbits for ERS/ENVISAT # requires fortran(ff7, g77 or gfortran) ex: "sudo apt-get install gfortran" and edit Makefile and update FC = gfortran (used by Doris step M_PORBITS and S_PORBITS). 22. snaphu: standalone executable used for unwrapping (used by Doris step UNWRAP). These programs should also be installed on your system. Refer to the download area of the doris website http://doris.tudelft.nl where to obtain these programs. -------------------------------------------- - INSTALLATION OF Doris - python part -------------------------------------------- To use the Doris Python scripts you will need to install the following Python packages: - numpy, scipy (for calculations) - matplotlib (visualization) - requests (data download) - gdal, gdal-dev, shapely, fiona, pyproj, fastkml, osr (GIS) This can be done using: 23. pip install [package_name] If you installed Doris via pip, this should be done automatically. Packages can also be installed using anaconda. This package comes with de Spyder IDE, which can be used to do some editing of the code. When you want a better insight in the overall project structure we recommend you install PyCharm as an additional IDE. After installation of the python packages you have to make a link to the doris_core, cpxfiddle and snaphu executables. You can do so by executing the install script, but you will have to create user accounts first to be able to download Sentinel-1 and SRTM DEMs. 25. create an account for the downloading of SRTM DEMs at https://urs.earthdata.nasa.gov/users/new 26. create an account for downloading Sentinel data at https://urs.earthdata.nasa.gov/users/new/ # move to the install directory 26. cd ../install 27. python init_cfg.py and fill in the different paths and user accounts This should be it ... To setup your processing of a certain datastack, see the README file in the DORIS root directory for further instructions on the use of DORIS. Enjoy, TUDELFT RADAR GROUP 2017 doris_users@tudelft.nlDoris-5.0.3Beta/install/__init__.py000066400000000000000000000000001312547014700171440ustar00rootroot00000000000000Doris-5.0.3Beta/install/doris_config_template.xml000066400000000000000000000004541312547014700221320ustar00rootroot00000000000000 Doris-5.0.3Beta/install/init_cfg.py000066400000000000000000000055361312547014700172120ustar00rootroot00000000000000import xml.etree.ElementTree as ET import os def init_cfg(): template_xml_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'doris_config_template.xml') xml_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'doris_config.xml') tree = ET.parse(template_xml_file) settings = tree.getroot() settings.find('.source_path').text = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) input = False while input == False: user_input = raw_input("Enter the path to doris: ") if os.path.exists(user_input) and user_input.endswith('doris'): settings.find('.doris_path').text = user_input input = True else: print('The path is incorrect, use another path') input = False while input == False: user_input = raw_input("Enter the path to cpxfiddle: ") if os.path.exists(user_input) and user_input.endswith('cpxfiddle'): settings.find('.cpxfiddle_path').text = user_input input = True else: print('The path is incorrect, use another path') input = False while input == False: user_input = raw_input("Enter the path to snaphu: ") if os.path.exists(user_input) and user_input.endswith('snaphu'): settings.find('.snaphu_path').text = user_input input = True else: print('The path is incorrect, use another path') # Now create the password file. user_input = raw_input("Enter your username for scihub (https://scihub.copernicus.eu/dhus/#/self-registration)") if len(user_input) > 0: settings.find('.scihub_username').text = user_input else: print('Username field is empty, you can change it later in the doris_config.xml file') user_input = raw_input("Enter your password for scihub ") if len(user_input) > 0: settings.find('.scihub_password').text = user_input else: print('Password field is empty, you can change it later in the doris_config.xml file') user_input = raw_input("Enter your username for srtm download (https://urs.earthdata.nasa.gov/users/new/)") if len(user_input) > 0: settings.find('.usgs_username').text = user_input else: print('Username field is empty, you can change it later in the doris_config.xml file') user_input = raw_input("Enter your password for srtm download ") if len(user_input) > 0: settings.find('.usgs_password').text = user_input else: print('Password field is empty, you can change it later in the doris_config.xml file') print('Doris is initialized. If you want to make changes later, you can change the doris_config.xml file' + ' or run this script again') tree.write(open(xml_file, 'w')) # Actually execute the code... if __name__ == "__main__": # Initialize... init_cfg() Doris-5.0.3Beta/prepare_stack/000077500000000000000000000000001312547014700162225ustar00rootroot00000000000000Doris-5.0.3Beta/prepare_stack/__init__.py000066400000000000000000000000001312547014700203210ustar00rootroot00000000000000Doris-5.0.3Beta/prepare_stack/create_datastack_bash.py000066400000000000000000000054201312547014700230540ustar00rootroot00000000000000# This function creates the bash script in the data folder to run the final datastack. # please note that you still have to define your start and end dates! import os import xml.etree.ElementTree as ET class CreateBash(object): def __init__(self): return def create(self, stack_folder, root_folder, nodes): xml_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'install/doris_config.xml') tree = ET.parse(xml_file) settings = tree.getroot() source_path = settings.find('.source_path').text doris_folder = os.path.dirname(settings.find('.doris_path').text) cpxfiddle_folder = os.path.dirname(settings.find('.cpxfiddle_path').text) snaphu_folder = os.path.dirname(settings.find('.snaphu_path').text) file_path=os.path.join(stack_folder, 'doris_stack.sh') f = open(file_path, 'w') doris_run_script = os.path.join(source_path, 'doris_stack', 'main_code', 'doris_main.py') processing = stack_folder f.write('#!/bin/bash \n') f.write('\n') f.write('#PBS -l nodes=1:ppn=' + nodes + ' \n') f.write('\n') f.write('source_path=' + source_path + '\n') f.write('export PYTHONPATH=$source_path:$PYTHONPATH \n') f.write('export PATH=' + doris_folder + ':' + cpxfiddle_folder + ':' + snaphu_folder + ':' + '$PATH \n') f.write('python ' + doris_run_script + ' -p ' + processing + ' \n') f.close() # make sure the file is executable os.chmod(file_path, 0744) # Also create a download and dem creation bash script. file_path = os.path.join(stack_folder, 'create_dem.sh') f = open(file_path, 'w') doris_run_script = os.path.join(source_path, 'prepare_stack', 'create_dem.py') processing = stack_folder f.write('#!/bin/bash \n') f.write('\n') f.write('source_path=' + source_path + '\n') f.write('export PYTHONPATH=$source_path:$PYTHONPATH \n') f.write('python ' + doris_run_script + ' ' + processing + ' SRTM3 \n') f.close() # make sure the file is executable os.chmod(file_path, 0744) file_path = os.path.join(stack_folder, 'download_sentinel.sh') f = open(file_path, 'w') f.write('source_path=' + source_path + '\n') f.write('export PYTHONPATH=$source_path:$PYTHONPATH \n') doris_run_script = os.path.join(source_path, 'prepare_stack', 'download_sentinel_data_orbits.py') processing = stack_folder f.write('#!/bin/bash \n') f.write('\n') f.write('python ' + doris_run_script + ' ' + processing + ' \n') f.close() # make sure the file is executable os.chmod(file_path, 0744)Doris-5.0.3Beta/prepare_stack/create_dem.py000066400000000000000000001007751312547014700206760ustar00rootroot00000000000000# Function created by Gert Mulder # Institute TU Delft # Date 9-11-2016 # Part of Doris 5.0 # This function creates a dem based on either a shape/kml file or a given bounding box. If a shape/kml file is given a # minimum offset of about 0.1 degrees is used. # All grids are based on the WGS84 projection. # Downloaded data is based on SRTM void filled data: # Documentation: https://lpdaac.usgs.gov/sites/default/files/public/measures/docs/NASA_SRTM_V3.pdf # Description srtm data: https://lpdaac.usgs.gov/dataset_discovery/measures/measures_products_table/SRTMGL1_v003 # Description srtm q data: https://lpdaac.usgs.gov/node/505 import numpy as np import gdal import gdalconst import osr from HTMLParser import HTMLParser import pickle import requests import os import zipfile import fastkml import shutil from fiona import collection import xml.etree.ElementTree as ET import sys # This are some example values... # shape_filename = '/media/gert/Data/shapes/netherlands/netherland.shp' # data_folder = '/media/gert/Data/dem/' # dem_path = '/media/gert/Data/dem/test/' # resample = 'regular_grid' # doris_input = True # quality = 'SRTM1' # out_file = dem_path + 'output.dem' # lats = np.arange(50.1, 53, 0.0005) # lons = np.arange(2, 8, 0.0005) # rounding = 1 # border = 0.1 # create_binary('', out_file, resample, doris_input, lats, lons, rounding, border, data_folder, quality) class CreateDem: def __init__(self): return def create(self, shape_filename='', out_file='' ,var_file='', resample='regular_grid', doris_input=True, lats=[], lons=[], rounding=1, border=0.1, data_folder='', quality='SRTM1', password='', username='', password_file=''): # This function stitches the different files together. If no data is available values will be zero. Which is # generally true because it is above sealevel. # The resampling is either # - none # - regular_grid (based on vectors of lats/lons) # - irregular_grid (based on lats/lons) if not out_file and not resample == 'irregular_grid': print('Please specify an output filename!') if shape_filename: latlim, lonlim = self._kml_shp_2_bb(shape_filename) else: try: latlim = [min(lats), max(lats)] lonlim = [min(lons), max(lons)] except: print('Not possible to create DEM grid.') return # Now add the rounding and borders to add the sides of our image # Please use rounding as a n/60 part of a degree (so 1/15 , 1/10 or 1/20 of a degree for example..) latlim = [np.floor((latlim[0] - border) / rounding) * rounding, np.ceil((latlim[1] + border) / rounding) * rounding] lonlim = [np.floor((lonlim[0] - border) / rounding) * rounding, np.ceil((lonlim[1] + border) / rounding) * rounding] # First download needed .hgt files. Quality is either 1, 3 or 30. If possible the files are downloaded. Otherwise # we fall back to lower quality. This is done using the elevation package tiles, q_tiles, tiles_30 = self._download_dem_files(latlim, lonlim, quality, data_folder, password=password, username=username) # Then create the final grid. This depends on the needed data type and possible resampling... if quality == 'SRTM1': pixel_degree = 3600 elif quality == 'SRTM3': pixel_degree = 1200 elif quality == 'SRTM30': pixel_degree = 120 else: print('quality should be either SRTM1, SRTM3 or SRTM30!') return lat_size = int((latlim[1] - latlim[0]) * pixel_degree) + 1 lon_size = int((lonlim[1] - lonlim[0]) * pixel_degree) + 1 print('Bounding box is:') print('from ' + str(latlim[0]) + ' latitude to ' + str(latlim[1])) print('from ' + str(lonlim[0]) + ' longitude to ' + str(lonlim[1])) # Create final grid and add tiles. if quality == 'SRTM1' or quality == 'SRTM3': # Create file for DEM data bin_data = np.memmap(out_file, dtype=np.int16, shape=(lat_size, lon_size), mode='w+') bin_data = self._add_tiles(bin_data, tiles, quality, latlim, lonlim) # Create file for quality data bin_q_data = np.memmap(out_file + '.q', dtype=np.uint8, shape=(lat_size, lon_size), mode='w+') bin_q_data = self._add_tiles(bin_q_data, q_tiles, quality, latlim, lonlim, quality_file=True) # Save quality file to geotiff temp_q = os.path.join(data_folder, 'temp_q.tiff') n_latlim = [latlim[0] - 0.5 / pixel_degree, latlim[1] + 0.5 / pixel_degree] n_lonlim = [lonlim[0] - 0.5 / pixel_degree, lonlim[1] + 0.5 / pixel_degree] q_tiff = self._create_georeference(n_latlim, n_lonlim, 1.0 / pixel_degree, 1.0 / pixel_degree, 'uint8', temp_q) q_tiff.GetRasterBand(1).WriteArray(bin_q_data) q_tiff = None else: # We are creating a 30 seconds map # Create file for DEM data bin_data = np.memmap(out_file, dtype=np.uint16, shape=(lat_size, lon_size)) bin_data = self._add_tiles(bin_data, quality, tiles_30, latlim, lonlim) n_latlim = latlim n_lonlim = lonlim # Save the binary data as a geotiff print('Save data to geotiff') dem_tiff = os.path.join(data_folder, 'temp_dem.tiff') dem_data = self._create_georeference(n_latlim, n_lonlim, 1.0 / pixel_degree, 1.0 / pixel_degree, 'int16', dem_tiff) dem_data.GetRasterBand(1).WriteArray(bin_data) dem_data = None # First remove the egm96 from this raster. # Pre assign the egm tiff file first. print('Calculate geoid correction for SRTM data') egm_tiff = os.path.join(data_folder, 'egm96_resample.tiff') egm_data = self._create_georeference(n_latlim, n_lonlim, 1.0 / pixel_degree, 1.0 / pixel_degree, 'float32', egm_tiff) egm_data = None print('Correct DEM for geoid') self._add_egm96(dem_tiff, egm_tiff, data_folder) if resample == 'regular_grid': # If regular grid is used, we convert using gdal. # First create a geotiff file, then resample geotiff file. We always use cubic interpolation. print('Resampling to new regular grid') dlat = lats[1] - lats[0] dlon = lons[1] - lons[0] dem_tiff_final = os.path.join(data_folder, 'dem.tiff') dem_data_final = self._create_georeference(latlim, lonlim, dlat, dlon, 'float32', dem_tiff_final) dem_data_final = None dem_data_final = gdal.Open(dem_tiff_final, gdal.GA_Update) dem_data = gdal.Open(dem_tiff, gdal.GA_Update) gdal.ReprojectImage(dem_data, dem_data_final, None, None, gdal.GRA_Cubic) dem_data_final = None dem_tiff = dem_tiff_final elif resample == 'irregular_grid': # Use a simple bilinear approach to find values for specific points. print('Resampling to new irregular grid') heights = self._simple_bilinear(lats, lons, dem_tiff) return heights if doris_input == True: # Create a binary output file command = 'gdal_translate -of MFF ' + dem_tiff + ' ' + dem_tiff[:-5] + '.raw' os.system(command) if not os.path.exists(os.path.dirname(out_file)): os.makedirs(os.path.dirname(out_file)) shutil.move(dem_tiff[:-5] + '.r00', out_file) # And create the scripts that go with them. self._output_doris_inputfiles(dem_tiff, out_file, var_file) # Finally also move .tiff file shutil.move(dem_tiff, out_file[:-4] + '.tiff') return def _add_tiles(self, outputdata, tiles, quality, latlim, lonlim, quality_file=False): # This function adds tiles to np.memmap file if quality == 'SRTM1': shape = (3601, 3601) s_size = 1.0 / 3600.0 step_lat = 1 step_lon = 1 elif quality == 'SRTM3': shape = (1201, 1201) s_size = 1.0 / 1200.0 step_lat = 1 step_lon = 1 elif quality == 'SRTM30': shape = (6000, 4800) s_size = 1.0 / 120.0 step_lat = 50.0 - s_size step_lon = 40.0 - s_size else: print('quality should be either SRTM1, SRTM3 or SRTM30!') return print('total file size is ' + str(outputdata.shape[0]) + ' in latitude and ' + str(outputdata.shape[1]) + ' in longitude') for tile in tiles: if quality_file: image = np.fromfile(tile, dtype='>u1').reshape(shape) else: image = np.fromfile(tile, dtype='>i2').reshape(shape) if os.path.basename(tile)[7] == 'N': lat = float(os.path.basename(tile)[8:10]) else: lat = - float(os.path.basename(tile)[8:10]) if os.path.basename(tile)[10] == 'E': lon = float(os.path.basename(tile)[11:14]) else: lon = - float(os.path.basename(tile)[11:14]) if quality == 'SRTM30': lat = lat - 50 + (s_size / 2) lon += (s_size / 2) print('adding ' + tile) # Find the coordinates of the part of the tile that should be written to the output data. t_latlim = [max(lat, latlim[0]), min(lat + step_lat, latlim[1])] t_lonlim = [max(lon, lonlim[0]), min(lon + step_lon, lonlim[1])] t_latid = [shape[0] - int(round((t_latlim[0] - lat) / s_size)), shape[0] - (int(round((t_latlim[1] - lat) / s_size)) + 1)] t_lonid = [int(round((t_lonlim[0] - lon) / s_size)), int(round((t_lonlim[1] - lon) / s_size)) + 1] latsize = int(round((latlim[1] - latlim[0]) / s_size)) + 1 latid = [latsize - int(round((t_latlim[0] - latlim[0]) / s_size)), latsize - (int(round((t_latlim[1] - latlim[0]) / s_size)) + 1)] lonid = [int(round((t_lonlim[0] - lonlim[0]) / s_size)), int(round((t_lonlim[1] - lonlim[0]) / s_size)) + 1] print('Adding tile lat ' + str(t_latid[1] + 1) + ' to ' + str(t_latid[0]) + ' into dem file ' + str(latid[1] + 1) + ' to ' + str(latid[0])) print('Adding tile lon ' + str(t_lonid[0] + 1) + ' to ' + str(t_lonid[1]) + ' into dem file ' + str(lonid[0] + 1) + ' to ' + str(lonid[1])) # Assign values from tiles to outputdata if quality == 'SRTM30': outputdata[latid[1]: latid[0]-2, lonid[0]: lonid[1]-2] = image[t_latid[1]: t_latid[0]-2, t_lonid[0]: t_lonid[1]-2] else: outputdata[latid[1]: latid[0]-1, lonid[0]: lonid[1]-1] = image[t_latid[1]: t_latid[0]-1, t_lonid[0]: t_lonid[1]-1] return outputdata def _download_dem_files(self, latlim, lonlim, quality, data_folder, username='', password='', password_xml=''): # This function downloads data either in 1,3 or 30 arc seconds. When you choose either 1 or 3 seconds also 30 # seconds is downloaded to fill the voids. # In this operation the needed files are also extracted... # Check the username and password and load from config file if needed. if not username or not password: if os.path.exists(password_xml): tree = ET.parse(password_xml) settings = tree.getroot() username = settings.find('.usgs_username').text password = settings.find('.usgs_password').text else: print('You should specify a username and password to download SRTM data. ') return filelist = self._srtm_listing(data_folder, username=username, password=password) outfiles = [] q_files = [] outfiles_30 = [] lats = np.arange(np.floor(latlim[0]), np.ceil(latlim[1])) lons = np.arange(np.floor(lonlim[0]), np.ceil(lonlim[1])) if quality == 'SRTM1' or quality == 'SRTM3': for lat in lats: for lon in lons: lat = int(lat) lon = int(lon) if lat < 0: latstr = 'S' + str(abs(lat)).zfill(2) else: latstr = 'N' + str(lat).zfill(2) if lon < 0: lonstr = 'W' + str(abs(lon)).zfill(3) else: lonstr = 'E' + str(lon).zfill(3) # Check if file exists in filelist if str(lat) not in filelist[quality]: continue elif str(lon) not in filelist[quality][str(lat)]: continue filename = os.path.join(data_folder, latstr + lonstr + 'SRTMGL3.hgt.zip') q_file = os.path.join(data_folder, latstr + lonstr + 'SRTMGL3.q.zip') extracted_file = os.path.join(data_folder, quality + '__' + latstr + lonstr + '.hgt') q_extracted = os.path.join(data_folder, quality + '__' + latstr + lonstr + '.q') if not os.path.exists(extracted_file) or not os.path.exists(q_extracted): # Download and unzip download_dem = filelist[quality][str(lat)][str(lon)] download_q = download_dem[:-7] + 'num.zip' command = 'wget ' + download_dem + ' --user ' + username + ' --password ' + password + ' -O ' + filename q_command = 'wget ' + download_q + ' --user ' + username + ' --password ' + password + ' -O ' + q_file try: os.system(command) zip_data = zipfile.ZipFile(filename) source = zip_data.open(zip_data.namelist()[0]) target = open(extracted_file, 'wb') shutil.copyfileobj(source, target, length=-1) target.close() outfiles.append(extracted_file) os.remove(filename) os.system(q_command) zip_data = zipfile.ZipFile(q_file) source = zip_data.open(zip_data.namelist()[0]) target = open(q_extracted, 'wb') shutil.copyfileobj(source, target, length=-1) target.close() q_files.append(q_extracted) os.remove(q_file) except: print('Failed to download or process ' + filename) else: outfiles.append(extracted_file) q_files.append(q_extracted) for lat in lats: for lon in lons: # Now check with which 30 seconds file this corresponds lat50 = int(np.floor(float(lat + 10) / 50)) * 50 + 40 lon40 = int(np.floor(float(lon + 20) / 40)) * 40 - 20 if lat50 < 0: latstr = 'S' + str(abs(lat50)).zfill(2) else: latstr = 'N' + str(lat50).zfill(2) if lon40 < 0: lonstr = 'W' + str(abs(lon40)).zfill(3) else: lonstr = 'E' + str(lon40).zfill(3) # Does this file exist.. if str(lat50) not in filelist['SRTM30']: continue elif str(lon40) not in filelist['SRTM30'][str(lat50)]: continue filename = os.path.join(data_folder, latstr + lonstr + 'SRTMGL3.hgt.zip') extracted_file = os.path.join(data_folder, 'SRTM30_' + latstr + lonstr + '.hgt') # Download and unzip file if possible and add to list if not os.path.exists(extracted_file): # Download and unzip user = 'USERNAME' password = 'PASSWORD' command = 'wget ' + filelist['SRTM30'][str(lat50)][str(lon40)] + ' --user ' + user + ' --password ' + password + \ ' -O ' + filename try: os.system(command) zip_data = zipfile.ZipFile(filename) source = zip_data.open(zip_data.namelist()[0]) target = open(extracted_file, 'wb') shutil.copyfileobj(source, target, length=-1) target.close() outfiles_30.append(extracted_file) except: print('Failed to download or process ' + filename) elif extracted_file not in outfiles_30: outfiles_30.append(extracted_file) return outfiles, q_files, outfiles_30 def _simple_bilinear(self, lats, lons, dem_tiff, data_folder): # To resample to datapoints, we convert the tiff file to a binary file bin_file = os.path.join(data_folder, 'dem.raw') command = 'gdal_translate -of MFF ' + dem_tiff + ' ' + bin_file os.system(command) shutil.move(bin_file[:-4] + '.r00', bin_file) # Read it as a memmap function dem_data = gdal.Open(dem_tiff, gdal.GA_Update) size = (dem_data.RasterYSize, dem_data.RasterXSize) data = np.memmap(bin_file, shape=size, dtype=np.dtype('float32')) r = dem_data.GetGeoTransform() # And find the values of corresponding points using bilinear interpolation. x_id = np.floor((lons - r[0]) / r[1]).astype('int32') x_diff = (((lons - r[0]) / r[1]) - x_id) y_id = np.floor((lats - r[3]) / r[5]).astype('int32') y_diff = (((lats - r[3]) / r[5]) - y_id) # Calculate final results ll_cont = data[y_id, x_id] * (1-x_diff) * (1-y_diff) ul_cont = data[y_id + 1, x_id] * (1-x_diff) * y_diff ur_cont = data[y_id + 1, x_id + 1] * x_diff * y_diff lr_cont = data[y_id, x_id + 1] * x_diff * (1-y_diff) heights = ll_cont + ul_cont + ur_cont + lr_cont return heights def _kml_shp_2_bb(self, filename): # from kml and shape file to a bounding box. We will always use a bounding box to create the final product. if filename.endswith('.shp'): with collection(filename, "r") as inputshape: shapes = [shape for shape in inputshape] # only first shape dat = shapes[0]['geometry']['coordinates'] lon = [l[0] for l in dat[0]] lat = [l[1] for l in dat[0]] latlim = [min(lat), max(lat)] lonlim = [min(lon), max(lon)] elif filename.endswith('.kml'): doc = file(filename).read() k = fastkml.KML() k.from_string(doc) dat = list(list(k.features())[0].features())[0].geometry[0].exterior.coords[:] lon = [l[0] for l in dat[0]] lat = [l[1] for l in dat[0]] latlim = [min(lat), max(lat)] lonlim = [min(lon), max(lon)] else: print 'format not recognized! Pleas creat either a .kml or .shp file.' return [] return latlim, lonlim def _add_egm96(self, dem_tiff, egm_tiff, data_folder): # This function adds the geoid from egm96 # Load egm96 grid and resample to input grid using gdal. # (For this purpose the grid is downloaded from: # http://earth-info.nga.mil/GandG/wgs84/gravitymod/egm96/binary/binarygeoid.html # In principle this is converted to geotiff here, filename = os.path.join(data_folder, 'EGM96_15min.dat') egm_source_tiff = os.path.join(data_folder, 'EGM96_15min.tiff') if not os.path.exists(egm_source_tiff): if not os.path.exists(filename): # Download egm96 file command = 'wget http://earth-info.nga.mil/GandG/wgs84/gravitymod/egm96/binary/WW15MGH.DAC -O ' + filename os.system(command) # Get georeference latlim = [-90.125, 90.125] lonlim = [-0.125, 359.875] dlat = 0.25 dlon = 0.25 egm_data = self._create_georeference(latlim, lonlim, dlat, dlon, 'float32', egm_source_tiff) # Load data egm96 = np.fromfile(filename, dtype='>i2').reshape((721, 1440)).astype('float32') # Save as geotiff egm_data.GetRasterBand(1).WriteArray(egm96 / 100) egm_data = None egm_source = gdal.Open(egm_source_tiff, gdal.GA_Update) egm_data = gdal.Open(egm_tiff, gdal.GA_Update) # Now resample to new dataset. (Copy information from gdal_dem) gdal.ReprojectImage(egm_source, egm_data, None, None, gdalconst.GRA_Bilinear) egm_data = None dem_new = dem_tiff + '.new' # Finally open original dataset and subtract command = 'gdal_calc.py -A ' + dem_tiff + ' -B ' + egm_tiff + ' --outfile=' + dem_new + ' --calc="A+B"' os.system(command) shutil.move(dem_new, dem_tiff) def _output_doris_inputfiles(self, dem_tiff, out_file, var_file): # This script outputs doris inputfiles which can be copied for further processing. dem = gdal.Open(dem_tiff) xsize = dem.RasterXSize ysize = dem.RasterYSize georef = dem.GetGeoTransform() dlat = georef[1] dlon = abs(georef[5]) lonmin = georef[0] + (dlon * 0.5) latmax = georef[3] - (dlat * 0.5) output_txt = out_file + '.doris_inputfile' output_var = var_file output_var = open(output_var, 'w') txtfile = open(output_txt, 'w') dem_var = dict() dem_var['in_dem'] = out_file dem_var['in_format'] = 'r4' dem_var['in_size'] = str(ysize) + " " + str(xsize) dem_var['in_delta'] = str(dlat) + " " + str(dlon) dem_var['in_ul'] = str(latmax) + " " + str(lonmin) dem_var['in_nodata'] = '-32768' pickle.dump(dem_var, output_var) output_var.close() txtfile.write("# The processing cards generated by $(basename $0) script. \n") txtfile.write("# Using parameters: $@ \n") txtfile.write('# Copy the section(s) that is/are necessary to your processing setup. \n') txtfile.write("c ___ ___ \n") txtfile.write("comment ___SIM AMPLITUDE___ \n") txtfile.write("c \n") txtfile.write("SAM_IN_DEM " + out_file + " \n") txtfile.write("SAM_IN_FORMAT r4 \t\t\t // default is short integer \n") txtfile.write("SAM_IN_SIZE " + str(ysize) + " " + str(xsize) + " \n") txtfile.write("SAM_IN_DELTA " + str(dlat) + " " + str(dlon) + " \n") txtfile.write("SAM_IN_UL " + str(latmax) + " " + str(lonmin) + " \n") txtfile.write("SAM_IN_NODATA -32768 \n") txtfile.write(" \n") txtfile.write(" \n") txtfile.write("c ___ ___ \n") txtfile.write("comment ___DEM ASSIST___ \n") txtfile.write("c \n") txtfile.write("DAC_IN_DEM $dempath/$outfile5 \n") txtfile.write("DAC_IN_FORMAT r4 \t\t\t // default is short integer \n") txtfile.write("DAC_IN_SIZE " + str(ysize) + " " + str(xsize) + " \n") txtfile.write("DAC_IN_DELTA " + str(dlat) + " " + str(dlon) + " \n") txtfile.write("DAC_IN_UL " + str(latmax) + " " + str(lonmin) + " \n") txtfile.write("DAC_IN_NODATA -32768 \n") txtfile.write(" \n") txtfile.write(" \n") txtfile.write("c ___ ___ \n") txtfile.write("comment ___REFERENCE DEM___ \n") txtfile.write("c \n") txtfile.write("## CRD_METHOD DEMINTRPMETHOD \n") txtfile.write("CRD_IN_DEM $dempath/$outfile5 \n") txtfile.write("CRD_IN_FORMAT r4 \t\t\t // default is short integer \n") txtfile.write("CRD_IN_SIZE " + str(ysize) + " " + str(xsize) + " \n") txtfile.write("CRD_IN_DELTA " + str(dlat) + " " + str(dlon) + " \n") txtfile.write("CRD_IN_UL " + str(latmax) + " " + str(lonmin) + " \n") txtfile.write("CRD_IN_NODATA -32768 \n") txtfile.close() def _srtm_listing(self, data_folder, username, password): # This script makes a list of all the available 1,3 and 30 arc second datafiles. # This makes it easier to detect whether files do or don't exist. data_file = os.path.join(data_folder, 'filelist') if os.path.exists(data_file): dat = open(data_file, 'r') filelist = pickle.load(dat) dat.close() return filelist server = "http://e4ftl01.cr.usgs.gov" folders = 'SRTM/SRTMGL1.003/2000.02.11/', 'SRTM/SRTMGL3.003/2000.02.11/', 'SRTM/SRTMGL30.002/2000.02.11/' keys = ['SRTM1', 'SRTM3', 'SRTM30'] filelist = dict() filelist['SRTM1'] = dict() filelist['SRTM3'] = dict() filelist['SRTM30'] = dict() for folder, key_value in zip(folders, keys): conn = requests.get(server + '/' + folder, auth=(username, password)) if conn.status_code == 200: print "status200 received ok" else: print "an error occurred during connection" data = conn.text parser = parseHTMLDirectoryListing() parser.feed(data) files = parser.getDirListing() if key_value == 'SRTM1' or key_value == 'SRTM3': files = [f for f in files if f.endswith('hgt.zip')] north = [int(filename[1:3]) for filename in files] east = [int(filename[4:7]) for filename in files] for i in [i for i, filename in enumerate(files) if filename[0] == 'S']: north[i] = north[i] * -1 for i in [i for i, filename in enumerate(files) if filename[3] == 'W']: east[i] = east[i] * -1 else: files = [f for f in files if f.endswith('dem.zip')] north = [int(filename[5:7]) for filename in files] east = [int(filename[1:4]) for filename in files] for i in [i for i, filename in enumerate(files) if filename[4] == 's']: north[i] = north[i] * -1 for i in [i for i, filename in enumerate(files) if filename[0] == 'w']: east[i] = east[i] * -1 for filename, n, e in zip(files, north, east): if not str(n) in filelist[key_value]: filelist[key_value][str(n)] = dict() filelist[key_value][str(n)][str(e)] = server + '/' + folder + filename file_list = open(os.path.join(data_folder, 'filelist'), 'w') pickle.dump(filelist, file_list) file_list.close() return filelist def _create_georeference(self, latlim, lonlim, dlat, dlon, dtype='int16', filename=''): # This function also creates a dem file but creates an geotiff file instead. This functionality is used to allow # resampling in later steps using gdal. conversion = { "uint8": 1, "int8": 1, "uint16": 2, "int16": 3, "uint32": 4, "int32": 5, "float32": 6, "float64": 7, "complex64": 10, "complex128": 11, } if filename: driver = gdal.GetDriverByName('Gtiff') dataset = driver.Create(filename, int(np.round((lonlim[1] - lonlim[0]) / dlon)), int(np.round((latlim[1] - latlim[0]) / dlat)), 1, conversion[dtype], ['COMPRESS=LZW', 'BIGTIFF=YES']) else: driver = gdal.GetDriverByName('mem') dataset = driver.Create('', int((lonlim[1] - lonlim[0]) / dlon), int((latlim[1] - latlim[0]) / dlat), 1, conversion[dtype]) dataset.SetGeoTransform(( lonlim[0], # 0 dlat, # 1 0, # 2 latlim[1], # 3 0, # 4 -dlon)) spatial_ref = osr.SpatialReference() spatial_ref.ImportFromEPSG(4326) dataset.SetProjection(spatial_ref.ExportToWkt()) return dataset # This function is not used because data does not contain gaps.... def _fill_voids(self, outputdata, output_30sec, quality): # This function fills the voids in our output data. if quality == 'SRTM1': s_size = 1.0 / 3600.0 elif quality == 'SRTM3': s_size = 1.0 / 1200.0 else: print('quality should be either SRTM1 or SRTM3!') return # This script assumes that the final dem is at least divided in 1 arc minute blocks so the two input fields are # perfectly alligned. id_void = np.argwhere(outputdata == -32767) if id: # If there are any voids... id_30 = np.floor(id_void * 120.0 * s_size) outputdata[id_void] = output_30sec[id_30] return outputdata # Following code is adapted from srtm-1.py > downloaded from # https://svn.openstreetmap.org/applications/utils/import/srtm2wayinfo/python/srtm.py class parseHTMLDirectoryListing(HTMLParser): def __init__(self): # print "parseHTMLDirectoryListing.__init__" HTMLParser.__init__(self) self.title = "Undefined" self.isDirListing = False self.dirList = [] self.inTitle = False self.inHyperLink = False self.currAttrs = "" self.currHref = "" def handle_starttag(self, tag, attrs): # print "Encountered the beginning of a %s tag" % tag if tag == "title": self.inTitle = True if tag == "a": self.inHyperLink = True self.currAttrs = attrs for attr in attrs: if attr[0] == 'href': self.currHref = attr[1] def handle_endtag(self, tag): # print "Encountered the end of a %s tag" % tag if tag == "title": self.inTitle = False if tag == "a": # This is to avoid us adding the parent directory to the list. if self.currHref != "": self.dirList.append(self.currHref) self.currAttrs = "" self.currHref = "" self.inHyperLink = False def handle_data(self, data): if self.inTitle: self.title = data print "title=%s" % data if "Index of" in self.title: # print "it is an index!!!!" self.isDirListing = True if self.inHyperLink: # We do not include parent directory in listing. if "Parent Directory" in data: self.currHref = "" def getDirListing(self): return self.dirList # Actually execute the code... if __name__ == "__main__": stack_folder = sys.argv[1] if len(sys.argv) > 2: quality = sys.argv[2] if quality not in ['SRTM1', 'SRTM3']: quality = 'SRTM3' else: quality = 'SRTM3' xml_file = os.path.join(os.path.join(stack_folder, 'doris_input.xml')) print('reading xml file stack ' + xml_file) tree_stack = ET.parse(xml_file) settings_stack = tree_stack.getroot()[0] xml_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'install', 'doris_config.xml') print('reading xml file settings doris ' + xml_file) tree_doris = ET.parse(xml_file) settings_doris = tree_doris.getroot() # Then create the dem file shapefile = settings_stack.find('.shape_file_path').text dem_calc_folder = settings_stack.find('.dem_processing_folder').text dem_out_folder = settings_stack.find('.dem_folder').text dem_out = os.path.join(dem_out_folder, 'dem.raw') dem_var = os.path.join(dem_out_folder, 'var.raw') srtm_username = settings_doris.find('.usgs_username').text srtm_password = settings_doris.find('.usgs_password').text dem = CreateDem() dem.create(shapefile, dem_out, dem_var, resample=None, doris_input=True, rounding=1, border=1, data_folder=dem_calc_folder, quality=quality, password=srtm_password, username=srtm_username) Doris-5.0.3Beta/prepare_stack/create_doris_input_xml.py000066400000000000000000000151311312547014700233370ustar00rootroot00000000000000import xml.etree.ElementTree as ET import os from datetime import datetime class CreateDorisInputXml(object): def __init__(self, input_file): self.input_file_dict={} self.dem_folder='' if(len(input_file)==0): self._create_xml() else: self._read_xml(input_file) def _create_xml(self): # This will first create the framework with data folders the stackfolder should contain # a dorisparameters file. input = False while input == False: user_input = raw_input("Enter the path to the archive data folder: ") if os.path.exists(user_input): self.input_file_dict['sar_data_folder'] = user_input input = True else: print('The path is incorrect, use another path') input = False while input == False: user_input = raw_input("Which polarisation do you want to use (vv,hh,vh,hv): ") if user_input in ['vv', 'hh', 'vh', 'hv']: self.input_file_dict['polarisation'] = user_input input = True else: print('This polarisation does not exist') input = False while input == False: user_input = raw_input("Which track do you want to work with? (explore on https://scihub.copernicus.eu/dhus/) : ") try: input = str(int(user_input)).zfill(3) self.input_file_dict['track'] = user_input input = True except: print('This track does not exist') input = False while input == False: user_input = raw_input("Is this track ascending or descending? (asc/dsc) : ") if user_input in ['asc', 'dsc']: self.input_file_dict['direction'] = user_input input = True else: print('Input should either be asc or dsc') input = False while input == False: self.input_file_dict['datastack_folder'] = raw_input("Enter the path to the folder of new datastack: ") if os.path.exists(self.input_file_dict['datastack_folder']): input = True else: print('The path is incorrect, use another path') input = False while input == False: self.input_file_dict['shape_file_path'] = raw_input("Enter full path to the shapefile: ") if os.path.exists(self.input_file_dict['shape_file_path']) and self.input_file_dict['shape_file_path'].endswith('.shp'): input = True else: print('The path is incorrect, use another path') input = False while input == False: user_input = raw_input("Enter the path to the folder of the orbit files: ") if os.path.exists(user_input): self.input_file_dict['orbits_folder'] = user_input input = True else: print('The path is incorrect, use another path') input = False while input == False: user_input = raw_input("Do you want to generate the DEM file automaticly (Yes/No): ").lower() if user_input == 'yes' or user_input == 'no': self.input_file_dict['generate_dem'] = user_input input = True else: print('You should use either yes or no') input = False while input == False: self.input_file_dict['dem_processing_folder'] = raw_input("Enter path to the dem folder: ") self.input_file_dict['dem_folder'] = os.path.join(self.input_file_dict['datastack_folder'], 'dem') if os.path.exists(self.input_file_dict['dem_processing_folder']): input = True else: print('The path is incorrect, use another path') input = False while input == False: user_input = raw_input("Do you want to use parallel computing (Yes/No): ").lower() if user_input == 'yes' or user_input == 'no': self.input_file_dict['parallel'] = user_input input = True else: print('You should use either yes of no') if user_input == 'yes': nodes = raw_input("How many cores do you want to use: ") self.input_file_dict['cores'] = nodes input = False while input == False: user_input = raw_input("What is the start date of your stack in yyyy-mm-dd (can be changed later): ").lower() try: date = datetime.strptime(user_input, '%Y-%m-%d') self.input_file_dict['start_date'] = user_input input = True except: print('Format not recognized, 01-01-2014 chosen') self.input_file_dict['start_date'] = user_input input = False while input == False: user_input = raw_input("What is the end date of your stack in yyyy-mm-dd (can be changed later): ").lower() try: date = datetime.strptime(user_input, '%Y-%m-%d') self.input_file_dict['end_date'] = user_input input = True except: print('Format not recognized, 01-01-2050 chosen') self.input_file_dict['end_date'] = user_input input = False while input == False: user_input = raw_input("What is the master date of your stack in yyyy-mm-dd (can be changed later): ").lower() try: date = datetime.strptime(user_input, '%Y-%m-%d') self.input_file_dict['master_date'] = user_input input = True except: print('Format not recognized, 01-01-2016 chosen. Check https://scihub.copernicus.eu/dhus/#/home for valid date') self.input_file_dict['master_date'] = user_input xml_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'doris_input_template.xml') tree = ET.parse(xml_file) self.settings = tree.getroot() for key in self.input_file_dict.keys(): self.settings.find('*/' + key).text = self.input_file_dict.get(key) tree.write(os.path.join(self.input_file_dict['datastack_folder'], 'doris_input.xml')) return self.input_file_dict def _read_xml(self, input_file): xml_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), input_file) tree = ET.parse(xml_file) self.settings = tree.getroot() def get_value(self, key): return self.settings.find('*/' + key).text Doris-5.0.3Beta/prepare_stack/create_inputfiles.py000066400000000000000000000112331312547014700223010ustar00rootroot00000000000000# Function created by Gert Mulder # Institute TU Delft # Date 9-11-2016 # Part of Doris 5.0 # This function will create the needed files for a datastack based on input information from the datastack. import xml.etree.ElementTree as ET import os import pickle # Test data # settings_table = '/home/gert/software/doris/Doris_s1/sentinel_1/functions/inputfile_template.xml' # inputfile_folder = '/media/gert/Data/dem/test/' # sensor = 'sentinel-1' # dem_info = inputfile_folder + 'output.dem.var' class CreateInputFiles: # Input for the class to create inputfiles are: # - dem_info > variable or file with variable with information on the dem. # - settings_table > this table includes the general settings for different sensors. You can either choose one of # the predefined sensors or create a custom one. # - sensor > select the predefined sensor of your choice # - Other settings are mainly related to how much output information you want from the program. Also you can define # the amount of memory used by the program. def __init__(self, dem_info ,settings_table, sensor): tree = ET.parse(settings_table) settings = tree.getroot() self.xml_data = settings.find('.' + sensor) self.header_data = self.xml_data.find('.header_settings') dem_info = open(dem_info, 'r') self.dem_var = pickle.load(dem_info) self.inputfilenames = ['coarsecorr', 'coarseorb', 'coherence', 'coherence_network', 'comprefdem', 'comprefpha', 'coregpm', 'dembased', 'finecoreg', 'geocode', 'interferogram', 'resample', 'subtrrefdem', 'subtrrefpha', 'unwrap', 'phasefilt'] self.processes = ['coarsecorr', 'coarseorb', 'coherence', 'coherence', 'comprefdem', 'comprefpha', 'coregpm', 'dembased', 'finecoreg', 'geocode', 'interferogram', 'resample', 'subtrrefdem', 'subtrrefpha', 'unwrap', 'phasefilt'] def create(self, inputfile_folder): for process_name, filename in zip(self.processes, self.inputfilenames): # Create file inputfilename = os.path.join(inputfile_folder, 'input.' + filename) txtfile = open(inputfilename, 'w') # Load xml data for processing step process = self.xml_data.find('./' + process_name + '/PROCESS') process_data = self.xml_data.find('.' + process_name) # Write to file txtfile = self._header(txtfile, self.header_data, process) txtfile = self._create_inputfiles(txtfile, process_data, self.dem_var) # Close file txtfile.close() def _create_inputfiles(self, txtfile, process_data, dem_var): # This functions calls the different inputfile creation scripts. for node in process_data: if not node.tag == 'PROCESS': if node.attrib['c'] == 'on': c = 'c ' else: c = '' if 'var' in node.attrib and node.attrib['comment']: txtfile.write(c + node.tag.ljust(20) + '\t' + dem_var[node.attrib['var']].ljust(20) + '\t // ' + node.attrib['comment'] + '\n') elif not 'var' in node.attrib and node.attrib['comment']: txtfile.write(c + node.tag.ljust(20) + '\t' + node.text.ljust(20) + '\t // ' + node.attrib['comment'] + '\n') elif 'var' in node.attrib and not node.attrib['comment']: txtfile.write(c + node.tag.ljust(20) + '\t' + dem_var[node.attrib['var']].ljust(20) + '\n') elif not 'var' in node.attrib and not node.attrib['comment']: txtfile.write(c + node.tag.ljust(20) + '\t' + node.text.ljust(20) + '\n') txtfile.write("STOP \n") return txtfile def _header(self, txtfile, header_data, process): # Function to write header txtfile.write("c Inputfile created by Doris 5.0" + '\n') txtfile.write("c " + "___".ljust(len(process.text) + 3) + "___ \n") txtfile.write("comment ___" + process.text + "___ \n") txtfile.write("c \n") for node in header_data: if node.tag == 'PROCESS': txtfile.write("c \n") txtfile.write("PROCESS ".ljust(15) + process.text + " \n") txtfile.write("c \n") else: if node.attrib['comment']: txtfile.write(node.tag.ljust(20) + '\t' + node.text.ljust(20) + '\t // ' + node.attrib['comment'] + '\n') txtfile.write("c \n") return txtfile Doris-5.0.3Beta/prepare_stack/doris_input_template.xml000066400000000000000000000030241312547014700231750ustar00rootroot00000000000000 Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Doris-5.0.3Beta/prepare_stack/download_sentinel_data_orbits.py000066400000000000000000000456701312547014700246730ustar00rootroot00000000000000# This file contains a function to check which files for sentinel are available, which ones are downloaded and a quality # check for the files which are downloaded. import urllib import urllib2 import ssl import re import os, sys import datetime import base64 import subprocess from fiona import collection from fastkml import kml from lxml import etree import xml.etree.ElementTree as ET def sentinel_available(start_day='', end_day='', sensor_mode='', product='', level='', track='', polarisation='', orbit_direction='', ROI='', user='', password=''): # All available sentinel 1 images are detected and printed on screen. # Following variables can be used to make a selection. # shape > defining shape file or .kml # start_day > first day for downloads (default one month before now) [yyyymmdd] # end_day > last day for downloads (default today) # track > the tracks we want to check (default all) # polarisation > which polarisation will be used. (default all) # string is the field we enter as url string = '' if sensor_mode: string = string + ' AND ' + 'sensoroperationalmode:' + sensor_mode if product: string = string + ' AND ' + 'producttype:' + product if level: string = string + ' AND ' + level if orbit_direction: string = string + ' AND ' + 'orbitdirection:' + orbit_direction if track: string = string + ' AND ' + 'relativeorbitnumber:' + track if start_day: start = datetime.datetime.strptime(start_day, '%Y-%m-%d').strftime('%Y-%m-%d') else: start = (datetime.datetime.now() - datetime.timedelta(days=350)).strftime('%Y-%m-%d') if end_day: end = datetime.datetime.strptime(end_day, '%Y-%m-%d').strftime('%Y-%m-%d') else: end = datetime.datetime.now().strftime('%Y-%m-%d') if polarisation: string = string + ' AND ' + 'polarisationmode:' + polarisation if ROI: shape_str = load_shape_info(ROI) string = string + ' AND footprint:"Intersects(POLYGON(' + shape_str + '))"' date_string = 'beginPosition:[' + start + 'T00:00:00.000Z TO ' + end + 'T23:59:59.999Z] AND endPosition:[' + start + 'T00:00:00.000Z TO ' + end + 'T23:59:59.999Z]' string = string + ' AND ' + date_string # Finally we do the query to get the search result. string = string[5:] + '&rows=1000' url = 'https://scihub.copernicus.eu/dhus/search?q=' + urllib.quote_plus(string) print(url) print('Requesting available products: ' + url) request = urllib2.Request(url) base64string = base64.b64encode('%s:%s' % (user, password)) request.add_header("Authorization", "Basic %s" % base64string) # connect to server. Hopefully this works at once try: dat = urllib2.urlopen(request) except: print 'not possible to connect this time' return [], [], [] html_dat = '' for line in dat: html_dat = html_dat + line parser = etree.HTMLParser() tree = etree.fromstring(html_dat, parser) products = [data for data in tree.iter(tag='entry')] links = [data.find('link').attrib for data in tree.iter(tag='entry')] dates = [data.findall('date')[1].text for data in tree.iter(tag='entry')] print('Following products will be downloaded') for link in links: print(link) return products, links, dates def load_shape_info(shapefile): # This script converts .kml, .shp and .txt files to the right format. If multiple shapes are available the script # will select the first one. if shapefile.endswith('.shp'): with collection(shapefile, "r") as inputshape: for shape in inputshape: # only first shape dat = shape['geometry']['coordinates'] st='(' for p in dat[0]: st = st + str(p[0]) + ' ' + str(p[1]) + ',' st = st[:-1] + ')' break elif shapefile.endswith('.kml'): doc = file(shapefile).read() k = kml.KML() k.from_string(doc) shape = list(list(k.features())[0].features())[0].geometry.exterior.coords[:] st='(' for p in shape: st = st + str(p[0]) + ' ' + str(p[1]) + ',' st = st[:-1] + ')' else: print 'format not recognized! Pleas creat either a .kml or .shp file.' return [] return st def sentinel_check_validity(products=[], destination_folder='', user='', password='', remove=True): # Check if the downloaded files are valid and remove if not valid_files = [] invalid_files = [] if not products: print 'Nothing to check' return for product in products: date = str(product.findall('date')[1].text) date = datetime.datetime.strptime(date[:19], '%Y-%m-%dT%H:%M:%S') name = str(product.find('title').text) track = str(product.find('int[@name="relativeorbitnumber"]').text) data_type = str(product.find(".//str[@name='filename']").text)[4:16] pol = str(product.find(".//str[@name='polarisationmode']").text).replace(' ', '') direction = str(product.find(".//str[@name='orbitdirection']").text) if direction == 'ASCENDING': direction = 'asc' elif direction == 'DESCENDING': direction = 'dsc' trackfolder = os.path.join(destination_folder, 's1_' + direction + '_t' + track) typefolder = os.path.join(trackfolder, data_type + '_' + pol) datefolder = os.path.join(typefolder, date.strftime('%Y%m%d')) xml_dir = os.path.join(datefolder, name + '.xml') file_dir = os.path.join(datefolder, name + '.SAFE.zip') kml_dir = os.path.join(datefolder, name + '.kml') preview_dir = os.path.join(datefolder, name + '.jpg') # First check the file if os.path.exists(file_dir): uuid = product.find('id').text valid_dat = sentinel_quality_check(file_dir, uuid, user, password) else: valid_dat = False if not valid_dat: if os.path.exists(file_dir) and remove == True: os.system('rm ' + file_dir) if os.path.exists(xml_dir) and remove == True: os.system('rm ' + xml_dir) if os.path.exists(kml_dir) and remove == True: os.system('rm ' + kml_dir) if os.path.exists(preview_dir) and remove == True: os.system('rm ' + preview_dir) invalid_files.append(file_dir) else: valid_files.append(file_dir) return invalid_files, valid_files def sentinel_download(products=[], xml_only=False, destination_folder='', project_folder='', user='', password=''): # Download the files which are found by the sentinel_available script. if not products: print 'No files to download' return wget_base = 'wget --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 --continue --tries=20 --no-check-certificate --user=' + user + ' --password=' + password + ' ' for product in products: date = str(product.findall('date')[1].text) date = datetime.datetime.strptime(date[:19], '%Y-%m-%dT%H:%M:%S') url = str('"'+product.findall('link')[0].attrib['href'][:-6]+ urllib.quote_plus('$value') +'"') name = str(product.find('title').text) track = str(product.find('int[@name="relativeorbitnumber"]').text) data_type = str(product.find(".//str[@name='filename']").text)[4:16] pol = str(product.find(".//str[@name='polarisationmode']").text).replace(' ', '') direction = str(product.find(".//str[@name='orbitdirection']").text) if direction == 'ASCENDING': direction = 'asc' elif direction == 'DESCENDING': direction = 'dsc' trackfolder = os.path.join(destination_folder, direction + '_t' + track.zfill(3)) if not os.path.exists(trackfolder): os.mkdir(trackfolder) typefolder = os.path.join(trackfolder, data_type + '_' + pol) if not os.path.exists(typefolder): os.mkdir(typefolder) datefolder = os.path.join(typefolder, date.strftime('%Y%m%d')) if not os.path.exists(datefolder): os.mkdir(datefolder) xml_dir = os.path.join(datefolder, name + '.xml') file_dir = os.path.join(datefolder, name + '.SAFE.zip') kml_dir = os.path.join(datefolder, name + '.kml') preview_dir = os.path.join(datefolder, name + '.jpg') if project_folder: datefolder = os.path.join(project_folder, 's1', date.strftime('%Y%m%d') + '_t' + track) if not os.path.exists(datefolder): os.mkdir(datefolder) sentinel_folder = os.path.join(datefolder, 'sentinel_1') if not os.path.exists(sentinel_folder): os.mkdir(sentinel_folder) xml_project = os.path.join(datefolder, 'sentinel_1', name + '.xml') link_project = os.path.join(datefolder, 'sentinel_1', name + '.SAFE.zip') kml_project = os.path.join(datefolder, 'sentinel_1', name + '.kml') preview_project = os.path.join(datefolder, 'sentinel_1', name + '.jpg') # Save .xml files prod = etree.ElementTree(product) if not os.path.exists(xml_dir): prod.write(xml_dir, pretty_print = True) if project_folder: if not os.path.exists(xml_project): prod.write(xml_project, pretty_print = True) prev = "'preview'" png = "'quick-look.png'" kml = "'map-overlay.kml'" dat = "'" + name + ".SAFE'" preview_url = url[:-10] + '/Nodes(' + dat + ')/Nodes(' + prev + ')/Nodes(' + png + ')/' + urllib.quote_plus('$value') + '"' kml_url = url[:-10] + '/Nodes(' + dat + ')/Nodes(' + prev + ')/Nodes(' + kml + ')/' + urllib.quote_plus('$value') + '"' # Download data files and create symbolic link if xml_only == False: # So we also download the file if not os.path.exists(file_dir): wget_data = wget_base + url + ' -O ' + file_dir print('download url is:' + wget_data) os.system(wget_data) # Finally check whether the file is downloaded correctly. Otherwise delete file and wait for next round of # downloads. uuid = product.find('id').text valid = sentinel_quality_check(file_dir, uuid, user, password) else: # If the file already exists we assume it is valid. valid = True if valid == True: # First download additional files if not os.path.exists(preview_dir): wget_preview = wget_base + preview_url + ' -O ' + preview_dir os.system(wget_preview) if not os.path.exists(kml_dir): wget_kml = wget_base + kml_url + ' -O ' + kml_dir os.system(wget_kml) # Then copy to user folder and create links if project folder is used if project_folder: if not os.path.exists(preview_project): os.system('cp ' + preview_dir + ' ' + preview_project) if not os.path.exists(kml_project): os.system('cp ' + kml_dir + ' ' + kml_project) if not os.path.exists(link_project): os.system('ln -s ' + file_dir + ' ' + link_project) else: os.system('rm ' + file_dir) os.system('rm ' + xml_dir) os.system('rm ' + xml_project) def sentinel_quality_check(filename, uuid, user, password): # Check whether the zip files can be unpacked or not. This is part of the download procedure. checksum_url = "https://scihub.copernicus.eu/dhus/odata/v1/Products('" + uuid + "')/Checksum/Value/" + urllib.quote_plus('$value') request = urllib2.Request(checksum_url) base64string = base64.b64encode('%s:%s' % (user, password)) request.add_header("Authorization", "Basic %s" % base64string) # connect to server. Hopefully this works at once try: dat = urllib2.urlopen(request) except: print 'not possible to connect this time' return False html_dat = '' for line in dat: html_dat = html_dat + line # Check file on disk if sys.platform == 'darwin': md5 = subprocess.check_output('md5 ' + filename, shell=True)[-33:-1] elif sys.platform == 'linux2': md5 = subprocess.check_output('md5sum ' + filename, shell=True)[:32] else: 'This function only works on mac or linux systems!' return False if md5 == html_dat.lower(): return True else: return False def download_orbits(start_date, end_date, pages=30, precise_folder='', restituted_folder =''): # This script downloads all orbits files from the precise orbits website, when pages is set to a very high number. # By default only the first page for the last two days (restituted) is checked. pages_res = min(pages, 60) pages_poe = pages # every day there are 8 restituted orbit files last_precise = '' # Last precise orbit file. Used to remove unused restituted orbit files. start_num = int(start_date[0:4] + start_date[5:7] + start_date[8:10]) end_num = int(end_date[0:4] + end_date[5:7] + end_date[8:10]) if precise_folder: for i in range(pages_poe): # First extract the orbitfiles from the page. url = 'https://qc.sentinel1.eo.esa.int/aux_poeorb/?page=' + str(i + 1) gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1) try: page = urllib2.urlopen(url, context=gcontext) except TypeError: page = urllib2.urlopen(url) html = page.read().split('\n') orb_files = [] for line in html: if re.search('', line): if re.search('EOF', line): dat = re.search('(.*)', line) orb_files.append(dat.group(1)) if not last_precise: last_precise = orb_files[0] for orb in orb_files: # Download the orbit files filename = os.path.join(precise_folder, orb) if int(orb[42:50]) + 1 <= end_num and int(orb[42:50]) + 1 >= start_num: url = 'https://qc.sentinel1.eo.esa.int/aux_poeorb/' + orb if not os.path.exists(filename): try: urllib.urlretrieve(url, filename, context=gcontext) except TypeError: urllib.urlretrieve(url, filename) print(orb + ' downloaded') else: print(orb + ' already downloaded') else: print(orb + ' is out of date range') if len(orb_files) > 0: if int(orb[42:50]) < start_num: break if restituted_folder: now = datetime.datetime.now() last_date = datetime.datetime.strptime(end_date, '%Y-%m-%d') diff = datetime.timedelta(days=25) print('Time difference to last date is ' + str((now - last_date).days)) if now - last_date < diff: # only run when precise orbits will not be available for i in range(pages_res): # First extract the orbitfiles from the page. url = 'https://qc.sentinel1.eo.esa.int/aux_resorb/?page=' + str(i + 1) gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1) try: page = urllib2.urlopen(url, context=gcontext) except TypeError: page = urllib2.urlopen(url) html = page.read().split('\n') orb_files = [] for line in html: if re.search('', line): if re.search('EOF', line): dat = re.search('(.*)', line) orb_files.append(dat.group(1)) for orb in orb_files: # Download the orbit files filename = os.path.join(precise_folder, orb) if int(orb[42:50]) + 1 <= end_num and int(orb[42:50]) + 1 >= start_num: url = 'https://qc.sentinel1.eo.esa.int/aux_poeorb/' + orb if not os.path.exists(filename): try: urllib.urlretrieve(url, filename, context=gcontext) except TypeError: urllib.urlretrieve(url, filename) print(orb + ' downloaded') else: print(orb + ' already downloaded') else: print(orb + ' is out of date range') if len(orb_files) > 0: if int(orb[42:50]) < start_num: break # Actually execute the code... if __name__ == "__main__": stack_folder = sys.argv[1] xml_file = os.path.join(os.path.join(stack_folder, 'doris_input.xml')) tree = ET.parse(xml_file) settings = tree.getroot()[0] print('reading xml file stack ' + xml_file) ROI = settings.find('.shape_file_path').text polarisation = settings.find('.polarisation').text archive_folder = settings.find('.sar_data_folder').text track = settings.find('.track').text orbit_folder = settings.find('.orbits_folder').text start_date = settings.find('.start_date').text end_date = settings.find('.end_date').text # Standard settings level = 'L1' sensor_mode = 'IW' product = 'SLC' # user settings xml_name = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) config_xml_file = os.path.join(os.path.join(xml_name, 'install', 'doris_config.xml')) print('reading xml file settings doris ' + config_xml_file) tree = ET.parse(config_xml_file) settings = tree.getroot() user = settings.find('.scihub_username').text password = settings.find('.scihub_password').text products, links, dates = sentinel_available(start_day=start_date, end_day=end_date, ROI=ROI, polarisation=polarisation, sensor_mode=sensor_mode, track=track, orbit_direction='', level=level, product=product,user=user, password=password) sentinel_download(products, destination_folder=archive_folder, user=user, password=password) precise_folder = os.path.join(orbit_folder, 'precise') if not os.path.exists(precise_folder): os.makedirs(precise_folder) restituted_folder = os.path.join(orbit_folder, 'restituted') if not os.path.exists(restituted_folder): os.makedirs(restituted_folder) download_orbits(start_date, end_date, pages=100, precise_folder=precise_folder, restituted_folder=restituted_folder) Doris-5.0.3Beta/prepare_stack/inputfile_template.xml000066400000000000000000000165241312547014700226460ustar00rootroot00000000000000 sentinel-1 Settings for the headers 2000 error on on on on info log.out ifgs.res master.res slave.res 0.0 POLYFIT WGS84 coarse correlation COARSECORR magfft 30 30 10 1024 256 orbit coarse orbits COARSEORB coherence between master and slave COHERENCE INCLUDE_REFDEM coherence.raw 1 1 2 10 coherence between master and slave COHERENCE refphase_only coherence.raw 1 1 2 10 compute the reference phase due to DEM COMPREFDEM OFF refdem.raw dem_radar.raw h2ph_srd.raw master_slave.crd compute reference phase due to earth curvature COMPREFPHA porbits 3 101 combine DEM and windows coregistration COREGPM 0.001 1 bamler 1 NOBG dem assisted coregistration DEMASSIST fine coregistration (windows) FINE coherence 3 fc_pos.in 64 64 8 8 coarsecorr 32 0.65 BG calculate lat/lon of radar pixels GEOCODE lam.raw phi.raw calculate lat/lon of radar pixels INTERFERO cint.raw 1 1 resample image RESAMPLE rc12p off slave_rsmp.raw cr4 52.13 4.38 5000 1000 remove DEM induced reference phase SUBTRREFDEM cint_srd.raw 1 1 remove DEM induced reference phase SUBTRREFPHA exact cint_srp.raw 1 1 OFF refphase.raw h2ph_srp.raw remove DEM induced reference phase unwrap SNAPHU unwrapped.raw REAL4 snaphu.log unwrap_input.raw SMOOTH MST ON phase filter FILTPHASE 32 3 1 2 3 2 1 goldstein 0.2 5 1 1 1 1 1 Doris-5.0.3Beta/prepare_stack/prepare_datastack.py000066400000000000000000000052361312547014700222570ustar00rootroot00000000000000# Function created by Gert Mulder # Institute TU Delft # Date 9-11-2016 # Part of Doris 5.0 # This function makes a setup of the processing folder, based on a single shapefile. # Inputs are # - the satellite sensor used # - the shapefile # - the processing folder we want to create # - the dem source folder where the intermediate DEM data is stored import os from create_dem import CreateDem from create_inputfiles import CreateInputFiles from create_doris_input_xml import CreateDorisInputXml from create_datastack_bash import CreateBash import xml.etree.ElementTree as ET class PrepareDatastack(object): def __init__(self): return def prepare(self, inputfile): # This will first create the framework with data folders the stackfolder should contain # a dorisparameters file. doris_input_xml = CreateDorisInputXml(inputfile) folders = ['input_files', 'stack', 'dem'] for foldername in folders: if not os.path.exists(os.path.join(doris_input_xml.get_value('datastack_folder'), foldername)): os.mkdir(os.path.join(doris_input_xml.get_value('datastack_folder'), foldername)) # Then create the dem file password_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),'install', 'doris_config.xml') tree_doris = ET.parse(password_file) settings_doris = tree_doris.getroot() srtm_username = settings_doris.find('.usgs_username').text srtm_password = settings_doris.find('.usgs_password').text dem_out = os.path.join(doris_input_xml.get_value('dem_folder'), 'dem.raw') dem_var = dem_out + '.var' dem = CreateDem() if doris_input_xml.get_value('generate_dem'.lower())=='yes': dem.create(doris_input_xml.get_value('shape_file_path'), dem_out, dem_var, resample=None, doris_input=True, rounding=0.1, border=1.5, data_folder=doris_input_xml.get_value('dem_processing_folder'), quality='SRTM3', password=srtm_password, username=srtm_username) ## Then create the inputfiles inputfiles_folder = os.path.join(doris_input_xml.get_value('datastack_folder'), 'input_files') xml_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'inputfile_template.xml') satellite = 'sentinel-1' CreateInputFiles(dem_var, xml_file, satellite).create(inputfiles_folder) root_folder = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) CreateBash().create(doris_input_xml.get_value('datastack_folder'), root_folder, doris_input_xml.get_value('cores')) Doris-5.0.3Beta/prepare_stack/prepare_datastack_main.py000066400000000000000000000010261312547014700232540ustar00rootroot00000000000000import argparse from prepare_datastack import PrepareDatastack """Doris prepare datastack arguments: --doris_input_file, -i """ # parse arguments here parser = argparse.ArgumentParser(description='Doris prepare datastack.') parser.add_argument('--doris_input_file', '-i', default='', help='Path to doris input file, this file contains case specific parameters') args = parser.parse_args() #start doris sentinel1 run prepare_data_stack = PrepareDatastack() prepare_data_stack.prepare(args.doris_input_file) Doris-5.0.3Beta/sar_tools/000077500000000000000000000000001312547014700154045ustar00rootroot00000000000000Doris-5.0.3Beta/sar_tools/Makefile000066400000000000000000000112631312547014700170470ustar00rootroot00000000000000################################################################# # Makefile for HP aCC c++ programs SAR tools # # should work with other compilers as well # # "make [all]" all exe's # # "make prog.o" compile only prog.o # # "make prog" compile only prog # # "make clean" remove junk caused by makes # # "make cleaner" remove all caused by makes # # "make uninstall" remove all caused by makes (incl. inst) # # "make install" installs executables in INSTALL_DIR # # (or if it's me, in CB_INSTALL # # also installs gmt scripts. # # # #%// Bert Kampes 27-Dec-2000 # ### RCS # # $Header: /users/kampes/DEVELOP/DORIS/SARtools/RCS/Makefile, # # v 3.8 2004/08/06 15:41:24 kampes Exp $ # #%// TUDelft 16-Apr-2009 # ################################################################# ### The shell we're using ### SHELL = /bin/sh ### Installdirdef should exist! #INSTALL_DIR = /usr/local/bin INSTALL_DIR = /home/dlevelt/src/Doris_s1_git/bin ### GCC compiler CC = g++ CFLAGS = -O3 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE #-m32 to force 32bit on 64bit platform ### Intel compiler #CC = icpc #CFLAGS = -Wp64 # -fast -O3 -parallel -auto-ilp32 -pc32 ################################################################## ### THERE SHOULD BE NOTHING YOU WANT TO CHANGE BELOW THIS LINE ### ################################################################## ### Only for me, this will be ignored... CB_INSTALL = ../../executables/64bit ### The programs we want PROGS = wrap \ bkconvert \ cpxmult \ cpxdiv \ cpxconj \ flapjack \ cpxfiddle \ floatmult \ floatmask \ readrasterheader \ rasterheader \ dateconv # usedin install: SCRIPTS = #SCRIPTS = cpx2ps \ # philamh2ps ### Compilation default: all all: $(PROGS) dummy # dummy, since else makefile want to recompile the last util. dummy: # the utilities. bkconvert: bkconvert.o $(CC) $(CFLAGS) $@.o -o $@ wrap: wrap.o $(CC) $(CFLAGS) $@.o -o $@ cpxmult: cpxmult.o $(CC) $(CFLAGS) $@.o -o $@ cpxdiv: cpxdiv.o $(CC) $(CFLAGS) $@.o -o $@ cpxconj: cpxconj.o $(CC) $(CFLAGS) $@.o -o $@ cpxfiddle: cpxfiddle.o $(CC) $(CFLAGS) $@.o -o $@ flapjack: flapjack.o $(CC) $(CFLAGS) $@.o -o $@ floatmask: floatmask.o $(CC) $(CFLAGS) $@.o -o $@ floatmult: floatmult.o $(CC) $(CFLAGS) $@.o -o $@ readrasterheader: readrasterheader.o $(CC) $(CFLAGS) $@.o -o $@ rasterheader: rasterheader.o $(CC) $(CFLAGS) $@.o -o $@ dateconv: dateconv.o $(CC) $(CFLAGS) $@.o -o $@ ### Install in CB_INSTALL by linking/copying executables ### install: $(PROGS) dir=$(CB_INSTALL); \ if test -d $$dir; then \ $(MAKE) cbinstall; else $(MAKE) definstall; fi; # or use ln instead of cp # ln -sf `pwd`/$$p $(CB_INSTALL)/$$p; \ ### Use symbolic links at our system, copy to /usr/local/bin on other. definstall: $(PROGS) dir=$(INSTALL_DIR); \ if test ! -d $$dir; then \ echo "Sorry, dir $(INSTALL_DIR) does not exist, exiting..."; exit; fi; \ echo Installing in directory: $$dir; \ list='$(PROGS) $(SCRIPTS)'; for p in $$list; do \ echo "Installing (copy): $$p"; \ cp -f $$p $(INSTALL_DIR)/$$p; \ done $(MAKE) cleaner ### Use symbolic links at our system, copy to /usr/local/bin on other. cbinstall: dir=$(CB_INSTALL); \ if test ! -d $$dir; then \ echo "Sorry, dir $(CB_INSTALL) does not exist, exiting..."; exit; fi; \ echo Installing in directory: $$dir; \ list='$(PROGS) $(SCRIPTS)'; for p in $$list; do \ echo "Installing (copy): $$p"; \ cp -f $$p $(CB_INSTALL)/$$p; \ done $(MAKE) cleaner lninstall: dir=$(CB_INSTALL); \ if test ! -d $$dir; then \ echo "Sorry, you are not me, exiting..."; exit; fi; \ echo Installing in directory: $$dir; \ list='$(PROGS) $(SCRIPTS)'; for p in $$list; do \ echo "Installing (link): $$p"; \ cp -f `pwd`/$$p $(CB_INSTALL)/$$p; \ done #ln -sf `pwd`/$$p $(CB_INSTALL)/$$p; \ $(MAKE) cleaner ### Helpers ### clean: @rm -f *.o *dummy* *.bak @echo "* Removed junk." ### some reason under cygwin progs are not removed without ".exe"??? CYGWIN_EXE = $(PROGS:=.exe) cleaner: clean @rm -f $(PROGS) $(CYGWIN_EXE) a.out @echo "* Removed executables in source dir: `pwd`." uninstall: cleaner dir=$(CB_INSTALL); \ if test -d $$dir; then \ cd $(CB_INSTALL); rm -f $(PROGS); \ echo "* Removed executables in install dir: $(CB_INSTALL)."; fi; dir=$(INSTALL_DIR); \ if test -d $$dir; then \ cd $(INSTALL_DIR); rm -f $(PROGS) $(CYGWIN_EXE); \ echo "* Removed executables in install dir: $(INSTALL_DIR)."; fi; ### How to make object files ### .cc.o: $(CC) $(CFLAGS) -c -o $(@) $< ### EOF. Doris-5.0.3Beta/sar_tools/README000066400000000000000000000027071312547014700162720ustar00rootroot00000000000000### file: README ### SARtools utility programs. ### Tested on HP-UX and Linux machines with g++ compiler (GNU) ### These programs should be portable. ### ### Bert Kampes 11-Dec-2000 ### TUDelft 19-Dec-2008 ### doris_users@tudelft.nl ### *** For Doris, only the program cpxfiddle is important to install *** *** For Doris, only the program cpxfiddle is important to install *** *** For Doris, only the program cpxfiddle is important to install *** ### Contents: bkconvert.c Convert binary files. cpxfiddle.c Great program to play around with binary complex files. cpxmult.c Complex multiplication of raw binary files. cpxdiv.c Complex division of raw binary files. (ignores NaN values) cpxconj.c Complex conjugate of raw binary files. flapjack.c Complex multiplication of binary files. floatmult.c Real dot mult. rasterheader.c Create a SUN raster file. readrasterheader.c Read a SUN raster file. wrap.c Wrap real file. dateconv.c utility to format date strings ### Compilation: Compile with the Makefile. 1. Typing: make install should compile all .c files and install them in the INSTALLDIRDEF (/usr/local/bin) 2. Add the install dir to your path. ### Known problems: sometimes an include file may be different on systems. Simply add the required file, e.g., add: #include if compilation breaks down due to missing declaration of strcmp. ### EOF Doris-5.0.3Beta/sar_tools/bkconvert.cc000066400000000000000000000306061312547014700177150ustar00rootroot00000000000000// convert.c // prog converts binary file formats in to format out. // formats: short, int, float, double (complex) // BK 28-Jan-00 // MA 19-Dec-08 : support > 4GB using namespace std; #include #include #include #include // ====== Typedefs for portability ====== typedef long long int64; typedef unsigned long long uint64; const int ONE27=127*2; // [MA] now 255 struct sizeofel { int ifile; int ofile; }; struct input { char ifilename[ONE27]; char ofilename[ONE27]; int iformat; int oformat; sizeofel bytesperelement; }; /* ***** */ void usage(char *programname) { cerr << "\n Program: " << programname << "\n\tconvert binary data to other format.\n\n" << " SYNOPSIS:\n\t" << programname << " inputfile outputfile informat oformat\n\n" << "\tinputfile: \tname of binary input file [INFILE]\n" << "\toutputfile: \tname of binary output file [OUTFILE]\n" << "\tifmt: \tinput format [2]\n" << "\tofmt: \toutput format [4]\n" << "\n FORMATS:\n" << "\t1 \tsigned (complex) char\n" << "\t101 \tunsigned (complex) char\n" << "\t2 \tsigned (complex) short\n" << "\t102 \tunsigned (complex) short\n" << "\t3 \tsigned (complex) int\n" << "\t103 \tunsigned (complex) int\n" << "\t4 \tsigned (complex) float\n" // << "\t104 \tunsigned (complex) float\n" << "\t5 \tsigned (complex) double\n" // << "\t105 \tunsigned (complex) double\n" << "\nNote: no rounding is performed when converting from e.g. float to int.\n" << endl; exit(-1); } /* ***** */ void handleinput(int argc, char* argv[], input &options) { // default short to float options.iformat = 2; options.oformat = 4; strcpy(options.ifilename,"INFILE"); strcpy(options.ofilename,"OUTFILE"); // Handle command line arguments switch (argc) { case 5: // ofmt options.oformat = atoi(argv[4]); //--- fall through --- // case 4: // ifmt options.iformat = atoi(argv[3]); //--- fall through --- // case 3: // of strcpy(options.ofilename,argv[2]); //--- fall through --- // case 2: // if strcpy(options.ifilename,argv[1]); break; default: usage(argv[0]); } // switch handle arguments cerr << "TEST: " << options.ifilename << "; " << options.ofilename << "; " << options.iformat << "; " << options.oformat << "; " << endl; if (options.iformat==1 || options.iformat==101) options.bytesperelement.ifile = sizeof(char); else if (options.iformat==2 || options.iformat==102) options.bytesperelement.ifile = sizeof(short); else if (options.iformat==3 || options.iformat==103) options.bytesperelement.ifile = sizeof(int); else if (options.iformat==4 || options.iformat==104) options.bytesperelement.ifile = sizeof(float); else if (options.iformat==5 || options.iformat==105) options.bytesperelement.ifile = sizeof(double); else usage(argv[0]); if (options.oformat==1 || options.oformat==101) options.bytesperelement.ofile = sizeof(char); else if (options.oformat==2 || options.oformat==102) options.bytesperelement.ofile = sizeof(short); else if (options.oformat==3 || options.oformat==103) options.bytesperelement.ofile = sizeof(int); else if (options.oformat==4 || options.oformat==104) options.bytesperelement.ofile = sizeof(float); else if (options.oformat==5 || options.oformat==105) options.bytesperelement.ofile = sizeof(double); else usage(argv[0]); if (options.iformat == options.oformat) usage(argv[0]); if (options.bytesperelement.ofile < options.bytesperelement.ifile) cerr << "WARNING: writing to less bytes, no rounding of numbers.\n"; } // handleinput // /* ***** // * rcw: read, convert, write // * template to read numelements of TypeA from opened ifile // * and to write them to opened ofile as TypeB // * A and B are dummy function arguments, used to identificate correct template function. // */ // template // void rcw(TypeA in, TypeB out, ifstream &ifile, ofstream &ofile, int numelements) // { // const int sizeofin = sizeof(TypeA); // const int sizeofout = sizeof(TypeB); // for (int i=0; i void writedata(TypeA *in, ofstream &ofile, int numelements, int oformat, int sizeofout) { int i; switch (oformat) { case 1: { char out; for (i=0; i> dummychar; if (dummychar=='y' || dummychar=='Y') ofstream ofile(options.ofilename, ios::out | ios::binary | ios::trunc); else return 2; } int buffersize = 512; // number of elements in data buffer const uint64 NUMBUFFERS = numelements/buffersize; const uint64 restelements = numelements%buffersize; const int EXTRABUF = (restelements!=0) ? 1 : 0; // // input buffer arrays // // should be done dynamically to save memory. // char data_schar[buffersize]; // unsigned char data_uchar[buffersize]; // short data_sshort[buffersize]; // unsigned short data_ushort[buffersize]; // int data_sint[buffersize]; // unsigned int data_uint[buffersize]; // float data_sfloat[buffersize]; // unsigned float data_ufloat[buffersize]; // double data_sdouble[buffersize]; // unsigned double data_udouble[buffersize]; // input buffer arrays // should be done dynamically to save memory. char data_schar[512]; unsigned char data_uchar[512]; short data_sshort[512]; unsigned short data_ushort[512]; int data_sint[512]; unsigned int data_uint[512]; float data_sfloat[512]; double data_sdouble[512]; for (int i=1; i<=NUMBUFFERS+EXTRABUF; i++) { if (i==NUMBUFFERS+1) // last smaller buffer buffersize=restelements; // read data in array switch (options.iformat) { case 1: ifile.read((char*)&data_schar[0],buffersize*options.bytesperelement.ifile); writedata(data_schar, ofile, buffersize, options.oformat, options.bytesperelement.ofile); break; case 101: ifile.read((char*)&data_uchar[0],buffersize*options.bytesperelement.ifile); writedata(data_uchar, ofile, buffersize, options.oformat, options.bytesperelement.ofile); break; case 2: ifile.read((char*)&data_sshort[0],buffersize*options.bytesperelement.ifile); writedata(data_sshort, ofile, buffersize, options.oformat, options.bytesperelement.ofile); break; case 102: ifile.read((char*)&data_ushort[0],buffersize*options.bytesperelement.ifile); writedata(data_ushort, ofile, buffersize, options.oformat, options.bytesperelement.ofile); break; case 3: ifile.read((char*)&data_sint[0],buffersize*options.bytesperelement.ifile); writedata(data_sint, ofile, buffersize, options.oformat, options.bytesperelement.ofile); break; case 103: ifile.read((char*)&data_uint[0],buffersize*options.bytesperelement.ifile); writedata(data_uint, ofile, buffersize, options.oformat, options.bytesperelement.ofile); break; case 4: ifile.read((char*)&data_sfloat[0],buffersize*options.bytesperelement.ifile); writedata(data_sfloat, ofile, buffersize, options.oformat, options.bytesperelement.ofile); break; // case 104: // ifile.read((char*)&data_ufloat[0],buffersize*options.bytesperelement.ifile); // writedata(data_ufloat, // ofile, buffersize, options.oformat, options.bytesperelement.ofile); // break; case 5: ifile.read((char*)&data_sdouble[0],buffersize*options.bytesperelement.ifile); writedata(data_sdouble, ofile, buffersize, options.oformat, options.bytesperelement.ofile); break; // case 105: // ifile.read((char*)&data_udouble[0],buffersize*options.bytesperelement.ifile); // writedata(data_udouble, // ofile, buffersize, options.oformat, options.bytesperelement.ofile); // break; default: cerr << "impossible error with checked input.\n"; return 5; } } ifile.close(); ofile.close(); //rcw(gettypea(options.iformat), gettypeb(options.oformat), // ifile, ofile, numelements); cout << "Normal termination.\n"; cerr << "Output file: \"" << options.ofilename << "\"\n"; return 0; } Doris-5.0.3Beta/sar_tools/cpxconj.cc000066400000000000000000000076661312547014700173760ustar00rootroot00000000000000// cpxconj.c // baarda::g++ -O cpxconj.c -o cpxconj // usage: cpxdiv infile outfile // cpxconj: pixelwise complex subtraction of 2 files (if add=1 then adds). // files: major row order binary (complex) float pixel interleaved // // exit levels: // 0: successful exit; // -1: wrong input; // 1: input file cannot be opened; // 2: output file cannot be opened; // // $Revision: 1.0 $ $Date: 2008/06/16 14:25:52 $ // BK 19-Apr-2000 (cpxmult) // MA 16-Jun-2008 update from cpxmult to cpxconj using namespace std; #include // cout #include // file #include // exit #include // atan etc. #include // conj etc. #include // strcat // ====== Typedefs for portability ====== typedef long long int64; typedef unsigned long long uint64; void usage(char *programname) { cerr << "\nProgram: " << programname << " take conjugate of a given complex float file\n" << "\n USAGE:\n\t" << programname << " infile1 [ outfile ]\n\n" << " infile[12] contain complex values a+ib\n" << " outfile contains conj(a+ib)\n\n" << " EXAMPLE:\n\t" << programname << " cint.raw cint.raw.conj" << "\n\ndefault output file == infile1.conj\n\n" << "exit levels: 0:ok; -1: wrong input; 1:ifile;\n\n\n"; exit(-1); } int main(int argc, char* argv[]) { char ident[] = "@(#)Doris software, TUDELFT.lr.nl"; const int ONE27 = 127; char ifile1[ONE27]; // input file name char ofile[ONE27] = " "; // output filename == "ifile.ml" const int sizeofelement = sizeof(complex); // data in file // ====== Handle input ====== switch (argc) { case 3: strcpy(ofile,argv[2]); // output filename arg3 //--- fall through ---// case 2: strcpy(ifile1,argv[1]); // input filename arg1 break; // --- ---// default: usage(argv[0]); } // switch input // ______ Set defaults if required _____ if (!strcmp(ofile," ")) // nothing specified { strcpy(ofile,ifile1); strcat(ofile,".conj"); } // ______ Check / echo input ______ cerr << "Program parameters:\n\t" << argv[0] << " " << ifile1 << " " << ofile << " " << endl; if (!strcmp(ofile,ifile1) ) { cerr << "input file name same as other one: " << ifile1 << " =? " << ofile << endl; usage(argv[0]); } // ====== Start complex multiply ====== //ifstream infile1(ifile1, ios::in | ios::nocreate | ios::binary); ifstream infile1(ifile1, ios::in | ios::binary); if (!infile1) cerr << "Problem opening file: " << ifile1 << endl, exit(1); infile1.seekg(0,ios::end); // filepointer at end //const int totalbytes1 = infile1.tellg(); const streamoff totalbytes1 = infile1.tellg(); // MA cerr << "# fsize: " << totalbytes1 << "\n"; // MA infile1.seekg(0,ios::beg); // start of file1 //ifstream infile2(ifile2, ios::in | ios::nocreate | ios::binary); //const int numberofpixels = totalbytes1/sizeofelement; const uint64 numberofpixels = totalbytes1/sizeofelement; ofstream outfile(ofile, ios::out | ios::binary | ios::trunc); if (!outfile) cerr << "Problem opening file: " << ofile << endl, exit(2); int tenpercent = int(floor(numberofpixels/10.)); int percent = 0; register complex value1; register complex value2; // ______ Good compiler would get rid of 'if' in for loop, but 2b sure. for (register int i=0; i // cout #include // file #include // exit #include // atan etc. #include // conj etc. #include // strcat // ====== Typedefs for portability ====== typedef long long int64; typedef unsigned long long uint64; void usage(char *programname) { cerr << "\nProgram: " << programname << " divides two given complex float files\n" << "\n USAGE:\n\t" << programname << " infile1 infile2 [outfile [cnj==0]]\n\n" << " infile[12] contain complex values a+ib\n" << " outfile contains (a1+ib1)/(a2+ib2)\n\n" << " If cnj=1 then phases are added.\n\n" << " outfile contains (a1+ib1)/conj(a2+ib2)\n\n" << " EXAMPLE:\n\t" << programname << " cint.raw cint2.raw division.raw" << "\ndefault output file == infile1.div.infile2\n\n" << "exit levels: 0:ok; -1: wrong input; 1:ifile; 2:ofile.\n\n\n"; exit(-1); } int main(int argc, char* argv[]) { char ident[] = "@(#)Doris software, TUDELFT.lr.nl"; const int ONE27 = 127; char ifile1[ONE27]; // input file name char ifile2[ONE27]; // input file name char ofile[ONE27] = " "; // output filename == "ifile.ml" bool cnj = false; // take no conj by default const int sizeofelement = sizeof(complex); // data in file // ====== Handle input ====== switch (argc) { case 5: cnj=true; // should be checked... //--- fall through ---// case 4: strcpy(ofile,argv[3]); // output filename arg3 //--- fall through ---// case 3: strcpy(ifile2,argv[2]); // input filename arg1 //--- fall through ---// case 2: strcpy(ifile1,argv[1]); // input filename arg1 break; // --- ---// default: usage(argv[0]); } // switch input // ______ Set defaults if required _____ if (!strcmp(ofile," ")) // nothing specified { strcpy(ofile,ifile1); strcat(ofile,".div."); strcpy(ofile,ifile2); } // ______ Check / echo input ______ cerr << "Program parameters:\n\t" << argv[0] << " " << ifile1 << " " << ifile2 << " " << ofile << " " << cnj << endl; if (!strcmp(ofile,ifile1) || !strcmp(ofile,ifile2)) { cerr << "input file name same as other one: " << ifile1 << " =? " << ofile << " =? " << ifile2 << endl; usage(argv[0]); } // ====== Start complex multiply ====== //ifstream infile1(ifile1, ios::in | ios::nocreate | ios::binary); ifstream infile1(ifile1, ios::in | ios::binary); if (!infile1) cerr << "Problem opening file: " << ifile1 << endl, exit(1); infile1.seekg(0,ios::end); // filepointer at end //const int totalbytes1 = infile1.tellg(); const streamoff totalbytes1 = infile1.tellg(); // MA cerr << "# fsize1: " << totalbytes1 << "\n"; // MA infile1.seekg(0,ios::beg); // start of file1 //ifstream infile2(ifile2, ios::in | ios::nocreate | ios::binary); ifstream infile2(ifile2, ios::in | ios::binary); if (!infile2) cerr << "Problem opening file: " << ifile2 << endl, exit(1); infile2.seekg(0,ios::end); // filepointer at end //const int totalbytes2 = infile2.tellg(); const streamoff totalbytes2 = infile2.tellg(); // MA cerr << "# fsize2: " << totalbytes2 << "\n"; // MA infile2.seekg(0,ios::beg); // start of file2 if (totalbytes1!=totalbytes2) { cerr << "size of file1 != size of file2: " << totalbytes1 << "!=" << totalbytes2 << endl; exit(2); } const uint64 numberofpixels = totalbytes1/sizeofelement; ofstream outfile(ofile, ios::out | ios::binary | ios::trunc); if (!outfile) cerr << "Problem opening file: " << ofile << endl, exit(2); int tenpercent = int(floor(numberofpixels/10.)); int percent = 0; register complex value1; register complex value2; // ______ Good compiler would get rid of 'if' in for loop, but 2b sure. if (cnj) // MA conjugate = 1 { for (register int i=0; i(1,0); value1= complex(0,0); // assign 0 instead // cerr << "# value: " << value1 << "\n"; // MA } outfile.write((char*)&value1,sizeofelement); if (!(i%tenpercent)) { cerr << "\rprocessed: " << percent << "%"; percent += 10; } } // loop over all pixels } // ====== Tidy up ====== infile1.close(); infile2.close(); outfile.close(); cout << "\n\nThank you for using " << argv[0] << "!\n"; return 0; } // END Doris-5.0.3Beta/sar_tools/cpxfiddle.cc000066400000000000000000003072071312547014700176660ustar00rootroot00000000000000/**************************************************************** * cpxfiddle -- fiddle around with complex files. * * make -n cpxfiddle * * g++ -O -c -ocpxfiddle.o cpxfiddle.c * * g++ -O cpxfiddle.o -o cpxfiddle * * * * TUDelft 10-May-2000 * * $Revision: 4.06 $ $Date: 2011/10/25 17:34:19 $ * * * * TODO: * * - output binary -ofloat add -oshort to crop slc's * #%// BK 01-Feb-2001 done. * * - -B (swap bytes) * #%// BK 12-Mar-2001 * * - band interleaved input formats * * - -q(uiet) * * - -o sunraster -q mag: rescale etc. * * - handle input defaults better, no lot of options. * #%// BK 20-Apr-2001 * * - -S scalebar for sunraster. * * - -version info. * * BK 02 APRIL 2003 ******************************************** * - removed nocreate ios bit since g++ v3.2 does not know it * * (not standard C++?) * * - removed cout.setf(ios::binary) for same reason, though * * this means cpxfiddle does not work properly. How can we * * write binary to stdout?? * * cout.write((char*)&x, sizeof(x));// seems to work... * * it actually seems fine, i already did it like this... * * -bugfix when byteswapping and multilooking * * -changed multilooking to normalize by number of looks * * -for HGT input, or R4 disguished as cpx, added some things. * #%// BK 05-Jan-2001 * * added skip header bytes * #%// BK 17-Oct-2003 * #%// PM 2007 * * Various fixes * #%// MA 19-Jun-2008 * * added > 4GB filesize support * #%// MA 14-Oct-2008 * * added -r min/max for scalling magnitude,normal,mixed outputs * #%// MA 24-Oct-2008 * * changed handling of float data for scaling computation * * added --ignorenan only for scaling, see help * * added --fullstat for scaling, see help * * [TODO] proper scalling during high multilooking * #%// MA 29-Aug-2009 * * fixed last column value when multilooked to float data * #%// MA 23-MAR-2011 * * fixed long path name issue affecting other paramters * #%// MA 25-NOV-2011 * * added missing input comments for -f * * ignore isinf values in --ignorenan option * ****************************************************************/ using namespace std; #include // cerr etc #include // binary to stdout #include // files #include // atan2 #include // strcmp #include // getopt #include // getopt long options [MA] #include // exit #include // ntohl htonl htons #include // with gcc 4.3.1 CHAR_MAX or #include // NAN // #include // short type run time id, does not exist?? // test... // #include //#include // ====== version id -h ====== //#define SWVERSION "v2.1 02-April-2003" //#define SWVERSION "v2.2 16-Jun-2003" //#define SWVERSION "v2.3 20-Jan-2004" //#define SWVERSION "v2.4 19-Jun-2008" //#define SWVERSION "v2.5 14-Oct-2008" #define SWVERSION "v2.6 29-Aug-2009" // ====== consts ====== typedef unsigned char uchar; // ====== Typedefs for portability ====== // TODO update accordingly typedef short int int16; typedef unsigned short int uint16; typedef int int32; // sizeof (int) = sizeof (long) on 32bit data model; sizeof (int) < sizeof (long) on 64 bit. typedef unsigned int uint32; typedef unsigned int uint; typedef long long int64; // new definition typedef unsigned long long uint64; // new typedef float real4; typedef double real8; // ______ distinct flags ______ const int FORMATR8 = 108; // i/oformat -o float numbytes=%10 for new input const int FORMATR4 = 104; // i/oformat -o float numbytes=%10 for new input const int FORMATI2 = 102; // i/oformat -o float numbytes=%10 for new input const int FORMATUC1 = 101; // i/oformat -o uchar numbytes=%10 for new input const int SUNRASTER = 201; // i/oformat -o uchar + header + colmap +extrawidth(?) const int ASCII = 999; // oformat -o ascii // ______ formats are distinct, but format%10 must equal bytes per elem ______ const int FORMATCUC1= 1; // ==numbytes per real part of element %10 const int FORMATCC1 = 11; // ==numbytes per real part of element %10 const int FORMATCI2 = 12; // ==numbytes per real part of element %10 const int FORMATCI4 = 14; // ==numbytes per real part of element %10 const int FORMATCR4 = 24; // ==numbytes per real part of element %10 const int FORMATCR8 = 28; // ==numbytes per real part of element %10 // ______ distinct flags ______ const int MAGNITUDE = 51; // output magnitude const int PHASE = 52; // output phase const int REALPART = 53; // output real part const int IMAGPART = 54; // output imag part const int NORMAL = 55; // output as is const int MIXED = 56; // output sunraster/uc1 mag/pha overlay // ______ should be -1||1 used in loops ______ const int NOMIRROR = 1; // do no mirroring has to be 1 (used later) const int DOMIRROR = -1; // do mirroring has to be -1 (used later) // ====== Input variables ====== struct commandlineinput { //char ifile[128]; // last argv char ifile[1024]; // last argv [Prabu reported the long path names problem : MA fixed] int linelength; // -w mandatory float exponent; // -e [1.0] float scale; // -s [1.0] int firstline; // -l [1] int lastline; // -L [all] int firstpixel; // -p [1] int lastpixel; // -P [all] int sublines; // -S [1/1] int subpixels; // -S [1/1] int multilookL; // -M [1/1] int multilookP; // -M [1/1] int iformat; // -f ci2 [cr4] int oformat; // -o float uchar sunraster short [ascii] int dooutput; // -q [mag] phase real imag int verbose; // -V int mirrorX; // -m XY YX X Y int mirrorY; // -m XY YX X Y int headerlength; // -H 32 number of bytes to skip before matrix starts //char cmap[128]; // -c filename or identifier char cmap[512]; // -c filename or identifier bool dontohx; // -B s swapbytes, big endian to host bool dohtonx; // -B b swapbytes, host to big endian. bool scalebar; // -b add scalebar for sunraster //bool quiet; // -q TODO, -V // // ______ Derived ______ int numlines; // computed... int bytesperelement;// sizeof real part int bytesperpixel; // sizeof complex pixel int bytesperline; // for seekg bool realinput; // for simplicity double rangemin; // -r [0.1/1.0] minimum value of data, the same as clims [ 0.1 1.0 ] in Matlab [MA] double rangemax; // -r [0.1/1.0] maximum value of data, used for scalling of data. bool ignorenan ; // ignore nan values during scalling bool fullstat ; // during scalling use fullstatistic generation }; // ====== Prototypes of functions in this file ====== void shortexpl(); void usage(char *programname); void synopsis(char *programname); bool handleinput(int argc, char* argv[], commandlineinput &input); template void functie(Type, Type, const commandlineinput &input); void rescale(uchar *OUT, float *IN, const int numin, const float MIN, const float MAX, const float NEWMIN, const float NEWMAX); void rasterheader(unsigned int header[8], const int width, const int height); void makecmap(unsigned char CMAP[3][256], const commandlineinput &input); void makecmapmixed(unsigned char CMAP[3][256], const commandlineinput &input); /**************************************************************** * main * ****************************************************************/ int main(int argc,char* argv[]) { // ====== Handle input ====== // "what `which prog`" char ident[] = "@(#)Doris software, $Revision: 4.06 $, $Author: TUDelft $"; //if (input.verbose) cerr << ident << endl; commandlineinput input; if (handleinput(argc,argv,input)==false) synopsis(argv[0]); // ______ Call template function to deal with different io ______ char dummy = '1'; switch (input.iformat) { case FORMATCC1: // complex char functie(char(dummy),char(dummy),input); break; case FORMATUC1: // byte, fall through case FORMATCUC1: // unsigned complex char functie(uchar(dummy),uchar(dummy),input); break; case FORMATI2: // short signed int, fall through case FORMATCI2: // complex short integer functie(short(dummy),short(dummy),input); break; case FORMATCI4: // complex integer functie(int(dummy),int(dummy),input); break; case FORMATR4: // float, fall through case FORMATCR4: // complex float functie(float(dummy),float(dummy),input); break; case FORMATR8: // double, fall through case FORMATCR8: // complex double functie(double(dummy),double(dummy),input); break; default: cerr << argv[0] << ": PANIC: unknown format...\n"; } // ====== Tidy up ====== cerr << endl; return 0; } // END main /**************************************************************** * template read/comp/write function whole matrix * * may be speeded up by defining a function readline, but * * compiler can optimize this as well (?). * #%// BK 11-May-2000 * ****************************************************************/ template void functie(Type realpart, Type imagpart, const commandlineinput &input) { if (sizeof(Type) != input.bytesperelement) {cerr << "PANIC: impossible...\n"; exit(1);} ifstream inf(input.ifile, ios::in | ios::binary); if (!inf) { cerr << "cpxfiddle: ERROR: opening input file: " << input.ifile << "\n"; exit(1); } // register int i,j,k,realindex,start; // MA larger file size // MA this should be signed especially for j see case Magnitude // it is better to rearrange types int or long for these variables // j is a potential int whereas realindex seem unsigned long long, check again! 200806 register long long i,j,k,realindex; register streamoff start; // ___ it seems this is not allowed in g++v3.2. How to do it? ___ // use new way if binary to stdout: cout.write((char*)&x, sizeof(x)) //if (input.oformat!=ASCII) cout.write((char*)&x, sizeof(x));// binary to stdout! //if (input.oformat!=ASCII) cout.setf(ios::binary); // !! binary to stdout //if (input.oformat!=ASCII) cout.setf(ios::binary); // !! binary to stdout const float PI = 4.0*atan(1.0); // ______ read in the whole line (even if subsampling) // ______ because simplicity for mirroring in X. (later multilooking?) // ______ fill output 0:numoutput as 2b written to stdout ______ // ______ if MIXED: OUTPUT[1sthalf]==MAG, 2ndhalf==PHASE ______ Type *LINE; float *OUTPUT; // 2* for NORMAL output LINE = new Type[2*(input.lastpixel-input.firstpixel+1)]; // allocate memory OUTPUT = new float[2*(input.lastpixel-input.firstpixel+1)]; // allocate memory // ______ Allocate and set stuff for multilooking ______ // ______ sublines = multilook set in 'handle input' ______ Type *LINEML; // multilooked line if (input.multilookL != 1) // ie. >1 LINEML = new Type[2*(input.lastpixel-input.firstpixel+1)]; // allocate memory if (input.verbose) { int alloc = (int)(sizeof(LINE[0]) * 2 * (input.lastpixel - input.firstpixel+1) + sizeof(OUTPUT[0]) * 2 * (input.lastpixel-input.firstpixel+1)); if (input.multilookL != 1) alloc += (int)(sizeof(LINEML[0]) * 2 * (input.lastpixel-input.firstpixel+1)); cerr << "cpxfiddle: INFO: Allocating " << int(alloc/1000.) << "KB\n"; } // ______ Indices to loop forward/backward over file ______ const int starti = (input.mirrorY==NOMIRROR) ? input.firstline : input.lastline; int stopi = (input.mirrorY==NOMIRROR) ? input.lastline : -input.firstline; const int plusi = (input.mirrorY==NOMIRROR) ? input.sublines : -input.sublines; const int startj = (input.mirrorX==NOMIRROR) ? input.firstpixel : input.lastpixel; int stopj = (input.mirrorX==NOMIRROR) ? input.lastpixel : -input.firstpixel; const int plusj = (input.mirrorX==NOMIRROR) ? input.subpixels : -input.subpixels; // ______ Correct index for multilooking, avoid reading to far ______ if (input.multilookL!=1) stopi = int((stopi/plusi) * plusi); //stopi = int(floor(stopi/plusi) * plusi); if (input.multilookP!=1) stopj = int((stopj/plusj) * plusj); //stopj = int(floor(stopj/plusj) * plusj); // ______ number of elements to output per line ______ int numoutput = int(ceil(float(input.lastpixel-input.firstpixel+1.)/ float(input.subpixels))); if (input.multilookP!=1) numoutput = int(floor(float(input.lastpixel-input.firstpixel+1.)/ float(input.subpixels))); if (input.dooutput==NORMAL) { if (input.realinput == true) { if (input.verbose==true) { cerr << "cpxfiddle: INFO: real input format detected.\n"; cerr << "cpxfiddle: INFO: Number of (real) output pixels: " << numoutput << "\n"; } } else { if (input.verbose==true) { cerr << "cpxfiddle: INFO: Number of (complex) output pixels: " << numoutput << "\n"; } numoutput*=2; // output real&imag part, size of array. } } else cerr << "cpxfiddle: INFO: Number of output pixels: " << numoutput << "\n"; // ______ number of elements output height ______ int height = int(ceil(float(input.lastline-input.firstline+1.)/ float(input.sublines))); if (input.multilookL!=1) height = int(floor(float(input.lastline-input.firstline+1.)/ float(input.sublines))); if (input.verbose==true) cerr << "cpxfiddle: INFO: Number of output lines: " << height << "\n"; // ______ Write sunraster header (and cmap) if requested ______ double meanmag = -999999999.999;// to rescale sunraster magnitude image double min_input = +999999999.999; double max_input = -999999999.999; if (input.oformat==SUNRASTER) { // ______ Header (cmap length==256*3) ______ // unsigned long int HEADER[8]; // 8 long ints unsigned int HEADER[8]; // 8 long ints rasterheader(HEADER,numoutput,height); // create header if (input.verbose==true) cerr << "Writing 32 byte header of SUNraster file.\n"; /* << "\nmagic#: " << ntohl(HEADER[0]) << "\nwidth: " << ntohl(HEADER[1]) << "\nheight: " << ntohl(HEADER[2]) << "\ndepth: " << ntohl(HEADER[3]) << "\nlength: " << ntohl(HEADER[4]) << "\ntype: " << ntohl(HEADER[5]) << "\nmaptype: " << ntohl(HEADER[6]) << "\nmaplength: " << ntohl(HEADER[7]) << endl; */ cout.write((char*)&HEADER[0],32); // binary to stdout // ______ Cmap ______ // unsigned maplength = ntohl(HEADER[7]); // 3 * length per color unsigned int maplength = 3*256; // 3 * length per color unsigned char CMAP[3][256]; // colormap see rasterheader if (input.dooutput==MIXED) makecmapmixed(CMAP,input); // only [3][256] else makecmap(CMAP,input); // only [3][256] cout.write((char*)&CMAP[0],maplength); // binary to stdout // ______ For magnitude output, get mean value approximately ______ // ______ BK 4-apr-2001 ______ string stattag; // [MA] used in verbose (input.realinput == false) ? stattag = "magnitude" : stattag = "value" ; if ( (input.dooutput==MAGNITUDE || input.dooutput==MIXED || input.dooutput==NORMAL) && ( isnan(input.rangemin) || isnan(input.rangemax) ) ) // assume doris tricked for hgt. { meanmag = 0.0; int numsamples = 0; int samplesizeY = input.sublines; // subsample per x lines... int samplesizeX = input.subpixels; int nX = (input.lastline-input.firstline+1)/samplesizeY; // calculated for while loop int nY = (input.lastpixel-input.firstpixel+1)/samplesizeX; //cerr << "fullstat tag: " << input.fullstat << endl; while (nX*nY>250000 && !input.fullstat ) // 200x200 window is ok in general // insert as !input.fullstat than use window { samplesizeX *= 2; samplesizeY *= 3; // reading file iritating... nX = (input.lastline-input.firstline+1)/samplesizeY; nY = (input.lastpixel-input.firstpixel+1)/samplesizeX; } for (i=input.firstline; i<=input.lastline; i+=samplesizeY) { start = (streamoff) input.bytesperline*(i-1) + (input.firstpixel-1)*input.bytesperpixel; start += input.headerlength;// account for header. inf.seekg(start,ios::beg); inf.read((char*)&LINE[0], (input.lastpixel-input.firstpixel+1)*input.bytesperpixel); for (j=input.firstpixel; j<=input.lastpixel; j+=samplesizeX) { //realindex = 2*(j-input.firstpixel); // index in LINE realindex = (input.realinput == false) ? 2*(j-input.firstpixel) : // false --> cpx [default] (j-input.firstpixel); if (input.ignorenan) // [MA] ignore nan values during scaling { if ( (input.realinput == false) && (isnan( LINE[realindex] ) || isnan( LINE[realindex+1] ) || isinf( LINE[realindex] ) || isinf( LINE[realindex+1] ) ) ) { //cerr << "cpxskip nan...\n"; continue; } // cpx else if ( isnan( LINE[realindex] ) || isinf( LINE[realindex] )) {// cerr << "skip nan... line: "<< i << " pixel: " << j << "\n"; //cerr << "skip nan... \n"; continue; } // real } numsamples++; realpart = LINE[realindex]; imagpart = LINE[realindex+1]; // ______ Swap bytes if -B option specified ______ if (input.dontohx==true) { if (sizeof(Type)==sizeof(short)) { realpart = ntohs(short(realpart)); imagpart = ntohs(short(imagpart)); } else if (sizeof(Type)==sizeof(int)) { realpart = ntohl(short(realpart)); imagpart = ntohl(short(imagpart)); } } if (input.dohtonx==true) { if (sizeof(Type)==sizeof(short)) { realpart = htons(short(realpart)); imagpart = htons(short(imagpart)); } else if (sizeof(Type)==sizeof(int)) { realpart = htonl(short(realpart)); imagpart = htonl(short(imagpart)); } } if (input.exponent==1.) { meanmag += ( input.realinput == false ) ? sqrt(float(realpart)*float(realpart)+ float(imagpart)*float(imagpart)) : float(realpart); // non-complex due usual mean } else meanmag += ( input.realinput == false ) ? pow(sqrt(float(realpart)*float(realpart)+ float(imagpart)*float(imagpart)), input.exponent) : pow(float(realpart),input.exponent); // --- assume NORMAL input, unwrapped phase --- if (realpartmax_input) max_input = realpart; if (input.realinput == false && imagpart>max_input) max_input = imagpart; } } //meanmag = input.scale*meanmag/numsamples;// finally... meanmag = meanmag/numsamples;// finally... if (input.verbose==true || input.ignorenan) { cerr << "mean " << stattag << " based on " << numsamples << " samples: " << meanmag << endl; cerr << "min " << stattag << " based on " << numsamples << " samples: " << min_input << endl; cerr << "max " << stattag << " based on " << numsamples << " samples: " << max_input << endl; } } else if ( input.dooutput==MAGNITUDE || input.dooutput==MIXED || input.dooutput==NORMAL ) // [MA] then data rangemin,rangemax defined thus use them later to scale data range. { min_input = input.rangemin; max_input = input.rangemax; meanmag = (max_input)/2.0; if (input.verbose==true || !isnan(input.rangemin) ) { cerr << "mean " << stattag << " based on input" << " (rmin+rmax)/2: \t" << meanmag << endl; cerr << "min " << stattag << " based on input" << " rangemin: \t" << min_input << endl; cerr << "max " << stattag << " based on input" << " rangemax: \t" << max_input << endl; } } } // ______ Obtain information for placing scalebar for sunraster ______ int outputlinecnt = 0; int scalebarheight = int(height/25.); // of total height in output lines int scalebarwidth = int(numoutput/5.); // of total width in output pixels int line0scalebar = height - 2*scalebarheight; // position lower int lineNscalebar = line0scalebar+scalebarheight; // position int pixel0scalebar = numoutput -scalebarheight-scalebarwidth;// position right // ______ Swap bytes to host order ______ if (input.dontohx==true) if (input.verbose==true) cerr << "Swapping bytes (big endian to host type, function ntohs/ntohl).\n"; if (input.dohtonx==true) if (input.verbose==true) cerr << "Swapping bytes (host type to big endian, function htons/htonl).\n"; // ______ 10% should be multiple of plusi ______ bool giveprogress = (numoutput > 1000) ? true : false; if (input.verbose==false) giveprogress = false; int onepercent = int(floor(abs(starti-stopi)/100.)); //if (giveprogress) while ((tenpercent%plusi)) tenpercent--; if (giveprogress) while ((onepercent%plusi)) onepercent--; int percent = 0; // _____ Do normlize by number of looks, but not TYPE _______ double numlooks = double(input.multilookL)*double(input.multilookP); if (input.verbose==true) cerr << "cpxfiddle: INFO: Number of looks: " << numlooks << "\n"; // ====== Read file, compute output, write to stdout ====== // for (i=input.firstline; i<=input.lastline; i+=input.sublines) // ______ mirrorY in loop initialization ______ for (i=starti; i*input.mirrorY<=stopi; i+=plusi) // forwards or backwards { if (giveprogress==true) { if (!((i-starti)%onepercent)) { if (input.verbose==true) cerr << "\rprocessed: " << percent << "%"; percent += 1; //percent += 10; } } // ______ start is just before line i to be read ______ start = input.bytesperline*(i-1) + (input.firstpixel-1)*input.bytesperpixel; start += input.headerlength;// account for header. inf.seekg(start,ios::beg); inf.read((char*)&LINE[0],(input.lastpixel-input.firstpixel+1)*input.bytesperpixel); // ______ Swap bytes if -B option specified ______ if (input.dontohx==true) { if (sizeof(Type)==sizeof(short)) { for (k=0; k<2*(input.lastpixel-input.firstpixel+1); ++k) { LINE[k] = ntohs(short(LINE[k])); } } else if (sizeof(Type)==sizeof(int)) { for (k=0; k<2*(input.lastpixel-input.firstpixel+1); ++k) { LINE[k] = ntohl(short(LINE[k])); } } else cerr << "seems wrong, -B and not 2B/4B type, ignoring.\n"; } if (input.dohtonx==true) { if (sizeof(Type)==sizeof(short)) { for (k=0; k<2*(input.lastpixel-input.firstpixel+1); ++k) { LINE[k] = htons(short(LINE[k])); } } else if (sizeof(Type)==sizeof(int)) { for (k=0; k<2*(input.lastpixel-input.firstpixel+1); ++k) { LINE[k] = htonl(short(LINE[k])); } } else cerr << "seems wrong, -B and not type 2B/4B, ignoring.\n"; } // ______ Do multilooking in line direction here ______ for (int mll=1; mll [0,255] ______ // ______ only for -qphase for now ______ const int sizeoutput = sizeof(char); // output type is char uchar *OUT_UC; OUT_UC = new uchar[numoutput]; switch (input.dooutput) { case NORMAL: { // ______ Assume someone is trying to plot a R4 or HGT file ______ // ______ Fall through to PHASE for plotting______ // ______But first adapt OUTPUT to range -pi,pi______ // ______Because min/max may be unwrapped phase______ for (int ii=0; iimax_input) OUTPUT[ii]= PI;// avoid clipping else OUTPUT[ii] = (OUTPUT[ii]-min_input)* (2.0*PI/(max_input-min_input))-PI; } // ______ Fall through to PHASE for plotting______ } case PHASE: rescale(OUT_UC,OUTPUT,numoutput,-PI,PI,0,255); // fill uc // ______ Add scalebar if requested ______ // ______ by changing the data in lower right corner ______ if (input.scalebar) { if (outputlinecnt>=line0scalebar && outputlinecnt<=lineNscalebar) { // ______ change the data to [0:255] ______ for (int ii=pixel0scalebar; ii<=pixel0scalebar+scalebarwidth; ++ii) { OUT_UC[ii]= uchar(float(ii-pixel0scalebar)* (255./float(scalebarwidth))); } } } break; case MAGNITUDE: { // ______ First convert output to float 16:255, ______ // ______ then make integers. scale influences this. ______ // ______ so a larger scale factor thresholds more ______ // ______ data to max (white) ______ for (int ii=0; ii255) OUTPUT[ii]=255; } rescale(OUT_UC,OUTPUT,numoutput,0,255,0,255); // fill uc break; } case MIXED: { // ______ We have 2 arrays, magnitude: OUPUT, phase: OUT_PHA // ______ create OUTPUT = numcolorsphase*MAG+PHASE ______ float *OUT_PHA; // temp. store phase here as float OUT_PHA = new float[numoutput]; for (int ii=0; ii255) OUTPUT[ii]=255; } uchar *OUT_UC_MAG; // temp store for mag. OUT_UC_MAG = new uchar[numoutput]; rescale(OUT_UC_MAG,OUTPUT,numoutput,0,255,0,15); // fill ucmag with mag rescale(OUT_UC,OUT_PHA,numoutput,-PI,PI,0,15); // fill uc with phase // ______ transform data=16*mag+pha ______ for (int ii=0; ii=line0scalebar && outputlinecnt<=lineNscalebar) { // ______ change the data to [0:255] ______ for (int ii=pixel0scalebar; ii<=pixel0scalebar+scalebarwidth; ++ii) { OUT_UC[ii]= uchar(240+(float(ii-pixel0scalebar)* (16./float(scalebarwidth)))); } } } break; // switch } default: cerr << "unknown option with sunraster output, uc1, assuming phase\n"; rescale(OUT_UC,OUTPUT,numoutput,-PI,PI,0,255); // fill uc } cout.write((char*)&OUT_UC[0],numoutput*sizeoutput); // binary to stdout break; } default: cerr << "PANIC: Impossible no oformat...\n"; } // switch output format, write per output line // ______ Write some extra req. at end of line ______ if (input.oformat==ASCII) cout << endl; // ______ Write extra zero after each line if odd width ______ // ______ It seems format requires even width? (at least xv does) ______ if (input.oformat==SUNRASTER) { if ((numoutput%2)!=0) // originally odd { // ______ Header and colormap already written ______ // ______ But write extra 0 at end??? (why... bk) // ______ This seems to be req. for xv? uchar sameaslast; rescale(&sameaslast,&OUTPUT[numoutput-1],1,-PI,PI,0,255); cout.write((char*)&sameaslast,1); } } } // loop over lines if (giveprogress==true) cerr << endl; } // END function /**************************************************************** * rescale * * rescale data in IN(min,max) --> out[MIN,MAX] * * o(x) = (i(x)-min) * (newrange/oldrange) + newmin * #%// BK 17-Nov-2000 * ****************************************************************/ void rescale( uchar *OUT, float *IN, const int numin, const float MIN, const float MAX, const float NEWMIN, const float NEWMAX) { if (MIN>MAX) { cerr << "wrong input in recale: min>max\n"; exit (1); } if (NEWMIN>NEWMAX) { cerr << "wrong input in recale: newmin>newmax\n"; exit (1); } if (NEWMIN<0 || NEWMAX>255) { cerr << "wrong input in recale: newmin<0 or newmax>255\n"; exit (1); } //const float NEWMIN = 0.; //const float NEWMAX = 255.; const float NEWRANGE = NEWMAX-NEWMIN; const float RANGE = MAX-MIN; const float SCALE = NEWRANGE/RANGE; for (int ii=0; iiMAX) OUT[ii]=uchar(NEWMAX);// avoid clipping //else OUT[ii] = uchar(NEWMIN + (((IN[ii])-MIN) * SCALE)); OUT[ii] = uchar(NEWMIN + (((IN[ii])-MIN) * SCALE)); } } // END rescale /**************************************************************** * rasterheader * * or save as gif/jpg/bmp/tiff/etc? * * * * ***** SUNraster header defined as 8 integers: * * ras_magic: [0x59a66a95] magic number * * ras_width: [input] width (pixels) of image * * ras_height: [input] height (pixels) of image * * ras_depth: [8] depth (1, 8, or 24 bits) * * ras_length: [computed] length (bytes) of image * * ras_type: [1] file; see RT_* below * * ras_maptype: [1] colormap; see RMT_* below * * ras_maplength: [3*256] length (b) of following map * * * * ***** Sun supported ras_type's RT_ *** * * 0 Raw pixrect image in 68000 byte order * * 1 Raw pixrect image in 68000 byte order * * 2 Run-length compression of bytes * * 3 XRGB or RGB instead of XBGR or BGR * * 4 tiff <-> standard rasterfile * * 5 iff (TAAC format) <-> standard rasterfile * * 0xffff Reserved for testing * * * * ***** Sun registered ras_maptype's RMT_ *** * * 0 ras_maplength is expected to be 0 * * 1 red[ras_maplength/3],green[],blue[] * * 2 RMT_RAW * * * * It seems width must be even? (fix this) * #%// BK 17-Nov-2000 * ****************************************************************/ void rasterheader(unsigned int HEADER[8], const int width, const int height) { // ______ if not even width, make it even, and write last uchar twice ______ const int W = ((width%2)==0) ? width : width+1; HEADER[0] = htonl(0x59a66a95); // magic number, always same HEADER[1] = htonl(W); // #columns, force even width HEADER[2] = htonl(height); // #rows HEADER[3] = htonl(8); // #planes in bits HEADER[4] = htonl(W*height); // size in bytes HEADER[5] = htonl(1); // rect type HEADER[6] = htonl(1); // RMT_RGB follows, size = H[7] HEADER[7] = htonl(3*256); // rgb, foreach possible pixelvalue } // END rasterheader /**************************************************************** * makecmap * * input option -c: only for sunraster output: * * generate a cmap from a input file, or from a name "gray", ? * * input file consist of 256 ascii entries r g b * #%// BK 22-Nov-2000 * ****************************************************************/ void makecmap( unsigned char CMAP[3][256], const commandlineinput &input) { const int maplength = 256; // always if (input.oformat!=SUNRASTER) { cerr << "makecmap: oformat != sunraster.\n"; exit(1); } // ______ Start internal maps, length 256 ______ if (!strcmp(input.cmap,"gray")) { for (int color=0; color<3; ++color) { for (int ii=0; ii> map=round(255*ph(256)); // >> fid=fopen('map.txt','w'); // >> for ii=1:256 // fprintf(fid,'%i %i %i\n',map(ii,:)); // end // >> fclose(fid); // awk '{i++;print "CMAP[0]["i-1"]="$1";", "CMAP[1]["i-1"]="$2";", // "CMAP[2]["i-1"]="$3";"}' map.txt > map.code // vi: ":r map.code" // (spaces in vi: mark start with mb, end with me, then substitute // start of lnie with 4 spaces: ":'b,'e s/^/ /" { CMAP[0][0]=102; CMAP[1][0]=255; CMAP[2][0]=255; CMAP[0][1]=104; CMAP[1][1]=251; CMAP[2][1]=255; CMAP[0][2]=105; CMAP[1][2]=248; CMAP[2][2]=255; CMAP[0][3]=107; CMAP[1][3]=244; CMAP[2][3]=255; CMAP[0][4]=108; CMAP[1][4]=241; CMAP[2][4]=255; CMAP[0][5]=110; CMAP[1][5]=238; CMAP[2][5]=255; CMAP[0][6]=111; CMAP[1][6]=235; CMAP[2][6]=255; CMAP[0][7]=113; CMAP[1][7]=231; CMAP[2][7]=255; CMAP[0][8]=114; CMAP[1][8]=228; CMAP[2][8]=255; CMAP[0][9]=116; CMAP[1][9]=225; CMAP[2][9]=255; CMAP[0][10]=117; CMAP[1][10]=222; CMAP[2][10]=255; CMAP[0][11]=119; CMAP[1][11]=220; CMAP[2][11]=255; CMAP[0][12]=120; CMAP[1][12]=217; CMAP[2][12]=255; CMAP[0][13]=122; CMAP[1][13]=214; CMAP[2][13]=255; CMAP[0][14]=123; CMAP[1][14]=211; CMAP[2][14]=255; CMAP[0][15]=125; CMAP[1][15]=209; CMAP[2][15]=255; CMAP[0][16]=126; CMAP[1][16]=206; CMAP[2][16]=255; CMAP[0][17]=128; CMAP[1][17]=204; CMAP[2][17]=255; CMAP[0][18]=129; CMAP[1][18]=201; CMAP[2][18]=255; CMAP[0][19]=131; CMAP[1][19]=199; CMAP[2][19]=255; CMAP[0][20]=132; CMAP[1][20]=197; CMAP[2][20]=255; CMAP[0][21]=134; CMAP[1][21]=195; CMAP[2][21]=255; CMAP[0][22]=135; CMAP[1][22]=193; CMAP[2][22]=255; CMAP[0][23]=137; CMAP[1][23]=191; CMAP[2][23]=255; CMAP[0][24]=138; CMAP[1][24]=189; CMAP[2][24]=255; CMAP[0][25]=140; CMAP[1][25]=187; CMAP[2][25]=255; CMAP[0][26]=141; CMAP[1][26]=185; CMAP[2][26]=255; CMAP[0][27]=143; CMAP[1][27]=183; CMAP[2][27]=255; CMAP[0][28]=144; CMAP[1][28]=182; CMAP[2][28]=255; CMAP[0][29]=146; CMAP[1][29]=180; CMAP[2][29]=255; CMAP[0][30]=147; CMAP[1][30]=178; CMAP[2][30]=255; CMAP[0][31]=149; CMAP[1][31]=177; CMAP[2][31]=255; CMAP[0][32]=150; CMAP[1][32]=176; CMAP[2][32]=255; CMAP[0][33]=152; CMAP[1][33]=174; CMAP[2][33]=255; CMAP[0][34]=153; CMAP[1][34]=173; CMAP[2][34]=255; CMAP[0][35]=155; CMAP[1][35]=172; CMAP[2][35]=255; CMAP[0][36]=156; CMAP[1][36]=171; CMAP[2][36]=255; CMAP[0][37]=158; CMAP[1][37]=170; CMAP[2][37]=255; CMAP[0][38]=159; CMAP[1][38]=169; CMAP[2][38]=255; CMAP[0][39]=161; CMAP[1][39]=168; CMAP[2][39]=255; CMAP[0][40]=162; CMAP[1][40]=167; CMAP[2][40]=255; CMAP[0][41]=164; CMAP[1][41]=166; CMAP[2][41]=255; CMAP[0][42]=165; CMAP[1][42]=166; CMAP[2][42]=255; CMAP[0][43]=166; CMAP[1][43]=165; CMAP[2][43]=255; CMAP[0][44]=167; CMAP[1][44]=164; CMAP[2][44]=255; CMAP[0][45]=168; CMAP[1][45]=162; CMAP[2][45]=255; CMAP[0][46]=169; CMAP[1][46]=161; CMAP[2][46]=255; CMAP[0][47]=170; CMAP[1][47]=159; CMAP[2][47]=255; CMAP[0][48]=171; CMAP[1][48]=158; CMAP[2][48]=255; CMAP[0][49]=172; CMAP[1][49]=156; CMAP[2][49]=255; CMAP[0][50]=173; CMAP[1][50]=155; CMAP[2][50]=255; CMAP[0][51]=174; CMAP[1][51]=153; CMAP[2][51]=255; CMAP[0][52]=175; CMAP[1][52]=152; CMAP[2][52]=255; CMAP[0][53]=176; CMAP[1][53]=150; CMAP[2][53]=255; CMAP[0][54]=178; CMAP[1][54]=149; CMAP[2][54]=255; CMAP[0][55]=179; CMAP[1][55]=147; CMAP[2][55]=255; CMAP[0][56]=181; CMAP[1][56]=146; CMAP[2][56]=255; CMAP[0][57]=182; CMAP[1][57]=144; CMAP[2][57]=255; CMAP[0][58]=184; CMAP[1][58]=143; CMAP[2][58]=255; CMAP[0][59]=186; CMAP[1][59]=141; CMAP[2][59]=255; CMAP[0][60]=188; CMAP[1][60]=140; CMAP[2][60]=255; CMAP[0][61]=190; CMAP[1][61]=138; CMAP[2][61]=255; CMAP[0][62]=192; CMAP[1][62]=137; CMAP[2][62]=255; CMAP[0][63]=194; CMAP[1][63]=135; CMAP[2][63]=255; CMAP[0][64]=196; CMAP[1][64]=134; CMAP[2][64]=255; CMAP[0][65]=198; CMAP[1][65]=132; CMAP[2][65]=255; CMAP[0][66]=200; CMAP[1][66]=131; CMAP[2][66]=255; CMAP[0][67]=202; CMAP[1][67]=129; CMAP[2][67]=255; CMAP[0][68]=205; CMAP[1][68]=128; CMAP[2][68]=255; CMAP[0][69]=207; CMAP[1][69]=126; CMAP[2][69]=255; CMAP[0][70]=210; CMAP[1][70]=124; CMAP[2][70]=255; CMAP[0][71]=212; CMAP[1][71]=123; CMAP[2][71]=255; CMAP[0][72]=215; CMAP[1][72]=122; CMAP[2][72]=255; CMAP[0][73]=218; CMAP[1][73]=120; CMAP[2][73]=255; CMAP[0][74]=221; CMAP[1][74]=119; CMAP[2][74]=255; CMAP[0][75]=223; CMAP[1][75]=117; CMAP[2][75]=255; CMAP[0][76]=226; CMAP[1][76]=116; CMAP[2][76]=255; CMAP[0][77]=229; CMAP[1][77]=114; CMAP[2][77]=255; CMAP[0][78]=233; CMAP[1][78]=113; CMAP[2][78]=255; CMAP[0][79]=236; CMAP[1][79]=111; CMAP[2][79]=255; CMAP[0][80]=239; CMAP[1][80]=110; CMAP[2][80]=255; CMAP[0][81]=242; CMAP[1][81]=108; CMAP[2][81]=255; CMAP[0][82]=246; CMAP[1][82]=106; CMAP[2][82]=255; CMAP[0][83]=249; CMAP[1][83]=105; CMAP[2][83]=255; CMAP[0][84]=253; CMAP[1][84]=104; CMAP[2][84]=255; CMAP[0][85]=255; CMAP[1][85]=102; CMAP[2][85]=254; CMAP[0][86]=255; CMAP[1][86]=104; CMAP[2][86]=250; CMAP[0][87]=255; CMAP[1][87]=105; CMAP[2][87]=247; CMAP[0][88]=255; CMAP[1][88]=106; CMAP[2][88]=243; CMAP[0][89]=255; CMAP[1][89]=108; CMAP[2][89]=240; CMAP[0][90]=255; CMAP[1][90]=110; CMAP[2][90]=237; CMAP[0][91]=255; CMAP[1][91]=111; CMAP[2][91]=233; CMAP[0][92]=255; CMAP[1][92]=113; CMAP[2][92]=230; CMAP[0][93]=255; CMAP[1][93]=114; CMAP[2][93]=227; CMAP[0][94]=255; CMAP[1][94]=116; CMAP[2][94]=224; CMAP[0][95]=255; CMAP[1][95]=117; CMAP[2][95]=221; CMAP[0][96]=255; CMAP[1][96]=119; CMAP[2][96]=218; CMAP[0][97]=255; CMAP[1][97]=120; CMAP[2][97]=216; CMAP[0][98]=255; CMAP[1][98]=122; CMAP[2][98]=213; CMAP[0][99]=255; CMAP[1][99]=123; CMAP[2][99]=210; CMAP[0][100]=255; CMAP[1][100]=125; CMAP[2][100]=208; CMAP[0][101]=255; CMAP[1][101]=126; CMAP[2][101]=205; CMAP[0][102]=255; CMAP[1][102]=128; CMAP[2][102]=203; CMAP[0][103]=255; CMAP[1][103]=129; CMAP[2][103]=200; CMAP[0][104]=255; CMAP[1][104]=131; CMAP[2][104]=198; CMAP[0][105]=255; CMAP[1][105]=132; CMAP[2][105]=196; CMAP[0][106]=255; CMAP[1][106]=134; CMAP[2][106]=194; CMAP[0][107]=255; CMAP[1][107]=135; CMAP[2][107]=192; CMAP[0][108]=255; CMAP[1][108]=137; CMAP[2][108]=190; CMAP[0][109]=255; CMAP[1][109]=138; CMAP[2][109]=188; CMAP[0][110]=255; CMAP[1][110]=140; CMAP[2][110]=186; CMAP[0][111]=255; CMAP[1][111]=141; CMAP[2][111]=184; CMAP[0][112]=255; CMAP[1][112]=143; CMAP[2][112]=182; CMAP[0][113]=255; CMAP[1][113]=144; CMAP[2][113]=181; CMAP[0][114]=255; CMAP[1][114]=146; CMAP[2][114]=179; CMAP[0][115]=255; CMAP[1][115]=147; CMAP[2][115]=178; CMAP[0][116]=255; CMAP[1][116]=149; CMAP[2][116]=176; CMAP[0][117]=255; CMAP[1][117]=150; CMAP[2][117]=175; CMAP[0][118]=255; CMAP[1][118]=152; CMAP[2][118]=174; CMAP[0][119]=255; CMAP[1][119]=153; CMAP[2][119]=172; CMAP[0][120]=255; CMAP[1][120]=155; CMAP[2][120]=171; CMAP[0][121]=255; CMAP[1][121]=156; CMAP[2][121]=170; CMAP[0][122]=255; CMAP[1][122]=158; CMAP[2][122]=169; CMAP[0][123]=255; CMAP[1][123]=159; CMAP[2][123]=168; CMAP[0][124]=255; CMAP[1][124]=161; CMAP[2][124]=167; CMAP[0][125]=255; CMAP[1][125]=162; CMAP[2][125]=166; CMAP[0][126]=255; CMAP[1][126]=164; CMAP[2][126]=166; CMAP[0][127]=255; CMAP[1][127]=165; CMAP[2][127]=165; CMAP[0][128]=255; CMAP[1][128]=165; CMAP[2][128]=165; CMAP[0][129]=255; CMAP[1][129]=166; CMAP[2][129]=164; CMAP[0][130]=255; CMAP[1][130]=166; CMAP[2][130]=162; CMAP[0][131]=255; CMAP[1][131]=167; CMAP[2][131]=161; CMAP[0][132]=255; CMAP[1][132]=168; CMAP[2][132]=159; CMAP[0][133]=255; CMAP[1][133]=169; CMAP[2][133]=157; CMAP[0][134]=255; CMAP[1][134]=170; CMAP[2][134]=156; CMAP[0][135]=255; CMAP[1][135]=171; CMAP[2][135]=155; CMAP[0][136]=255; CMAP[1][136]=172; CMAP[2][136]=153; CMAP[0][137]=255; CMAP[1][137]=174; CMAP[2][137]=152; CMAP[0][138]=255; CMAP[1][138]=175; CMAP[2][138]=150; CMAP[0][139]=255; CMAP[1][139]=176; CMAP[2][139]=149; CMAP[0][140]=255; CMAP[1][140]=178; CMAP[2][140]=147; CMAP[0][141]=255; CMAP[1][141]=179; CMAP[2][141]=145; CMAP[0][142]=255; CMAP[1][142]=181; CMAP[2][142]=144; CMAP[0][143]=255; CMAP[1][143]=182; CMAP[2][143]=142; CMAP[0][144]=255; CMAP[1][144]=184; CMAP[2][144]=141; CMAP[0][145]=255; CMAP[1][145]=186; CMAP[2][145]=139; CMAP[0][146]=255; CMAP[1][146]=188; CMAP[2][146]=138; CMAP[0][147]=255; CMAP[1][147]=190; CMAP[2][147]=137; CMAP[0][148]=255; CMAP[1][148]=192; CMAP[2][148]=135; CMAP[0][149]=255; CMAP[1][149]=194; CMAP[2][149]=134; CMAP[0][150]=255; CMAP[1][150]=196; CMAP[2][150]=132; CMAP[0][151]=255; CMAP[1][151]=198; CMAP[2][151]=131; CMAP[0][152]=255; CMAP[1][152]=200; CMAP[2][152]=129; CMAP[0][153]=255; CMAP[1][153]=203; CMAP[2][153]=128; CMAP[0][154]=255; CMAP[1][154]=205; CMAP[2][154]=126; CMAP[0][155]=255; CMAP[1][155]=208; CMAP[2][155]=125; CMAP[0][156]=255; CMAP[1][156]=210; CMAP[2][156]=123; CMAP[0][157]=255; CMAP[1][157]=213; CMAP[2][157]=122; CMAP[0][158]=255; CMAP[1][158]=216; CMAP[2][158]=120; CMAP[0][159]=255; CMAP[1][159]=218; CMAP[2][159]=119; CMAP[0][160]=255; CMAP[1][160]=221; CMAP[2][160]=117; CMAP[0][161]=255; CMAP[1][161]=224; CMAP[2][161]=116; CMAP[0][162]=255; CMAP[1][162]=227; CMAP[2][162]=114; CMAP[0][163]=255; CMAP[1][163]=230; CMAP[2][163]=113; CMAP[0][164]=255; CMAP[1][164]=233; CMAP[2][164]=111; CMAP[0][165]=255; CMAP[1][165]=237; CMAP[2][165]=109; CMAP[0][166]=255; CMAP[1][166]=240; CMAP[2][166]=108; CMAP[0][167]=255; CMAP[1][167]=243; CMAP[2][167]=106; CMAP[0][168]=255; CMAP[1][168]=247; CMAP[2][168]=105; CMAP[0][169]=255; CMAP[1][169]=250; CMAP[2][169]=104; CMAP[0][170]=255; CMAP[1][170]=254; CMAP[2][170]=102; CMAP[0][171]=253; CMAP[1][171]=255; CMAP[2][171]=104; CMAP[0][172]=249; CMAP[1][172]=255; CMAP[2][172]=105; CMAP[0][173]=246; CMAP[1][173]=255; CMAP[2][173]=106; CMAP[0][174]=242; CMAP[1][174]=255; CMAP[2][174]=108; CMAP[0][175]=239; CMAP[1][175]=255; CMAP[2][175]=109; CMAP[0][176]=236; CMAP[1][176]=255; CMAP[2][176]=111; CMAP[0][177]=233; CMAP[1][177]=255; CMAP[2][177]=112; CMAP[0][178]=229; CMAP[1][178]=255; CMAP[2][178]=114; CMAP[0][179]=226; CMAP[1][179]=255; CMAP[2][179]=115; CMAP[0][180]=223; CMAP[1][180]=255; CMAP[2][180]=117; CMAP[0][181]=221; CMAP[1][181]=255; CMAP[2][181]=119; CMAP[0][182]=218; CMAP[1][182]=255; CMAP[2][182]=120; CMAP[0][183]=215; CMAP[1][183]=255; CMAP[2][183]=122; CMAP[0][184]=212; CMAP[1][184]=255; CMAP[2][184]=123; CMAP[0][185]=210; CMAP[1][185]=255; CMAP[2][185]=124; CMAP[0][186]=207; CMAP[1][186]=255; CMAP[2][186]=126; CMAP[0][187]=205; CMAP[1][187]=255; CMAP[2][187]=127; CMAP[0][188]=202; CMAP[1][188]=255; CMAP[2][188]=129; CMAP[0][189]=200; CMAP[1][189]=255; CMAP[2][189]=131; CMAP[0][190]=198; CMAP[1][190]=255; CMAP[2][190]=132; CMAP[0][191]=196; CMAP[1][191]=255; CMAP[2][191]=134; CMAP[0][192]=194; CMAP[1][192]=255; CMAP[2][192]=135; CMAP[0][193]=192; CMAP[1][193]=255; CMAP[2][193]=137; CMAP[0][194]=190; CMAP[1][194]=255; CMAP[2][194]=138; CMAP[0][195]=188; CMAP[1][195]=255; CMAP[2][195]=139; CMAP[0][196]=186; CMAP[1][196]=255; CMAP[2][196]=141; CMAP[0][197]=184; CMAP[1][197]=255; CMAP[2][197]=143; CMAP[0][198]=182; CMAP[1][198]=255; CMAP[2][198]=144; CMAP[0][199]=181; CMAP[1][199]=255; CMAP[2][199]=146; CMAP[0][200]=179; CMAP[1][200]=255; CMAP[2][200]=147; CMAP[0][201]=178; CMAP[1][201]=255; CMAP[2][201]=149; CMAP[0][202]=176; CMAP[1][202]=255; CMAP[2][202]=150; CMAP[0][203]=175; CMAP[1][203]=255; CMAP[2][203]=152; CMAP[0][204]=174; CMAP[1][204]=255; CMAP[2][204]=153; CMAP[0][205]=173; CMAP[1][205]=255; CMAP[2][205]=155; CMAP[0][206]=172; CMAP[1][206]=255; CMAP[2][206]=156; CMAP[0][207]=171; CMAP[1][207]=255; CMAP[2][207]=158; CMAP[0][208]=170; CMAP[1][208]=255; CMAP[2][208]=159; CMAP[0][209]=169; CMAP[1][209]=255; CMAP[2][209]=161; CMAP[0][210]=168; CMAP[1][210]=255; CMAP[2][210]=162; CMAP[0][211]=167; CMAP[1][211]=255; CMAP[2][211]=164; CMAP[0][212]=166; CMAP[1][212]=255; CMAP[2][212]=165; CMAP[0][213]=165; CMAP[1][213]=255; CMAP[2][213]=166; CMAP[0][214]=164; CMAP[1][214]=255; CMAP[2][214]=166; CMAP[0][215]=162; CMAP[1][215]=255; CMAP[2][215]=167; CMAP[0][216]=161; CMAP[1][216]=255; CMAP[2][216]=168; CMAP[0][217]=159; CMAP[1][217]=255; CMAP[2][217]=169; CMAP[0][218]=158; CMAP[1][218]=255; CMAP[2][218]=170; CMAP[0][219]=156; CMAP[1][219]=255; CMAP[2][219]=171; CMAP[0][220]=155; CMAP[1][220]=255; CMAP[2][220]=172; CMAP[0][221]=153; CMAP[1][221]=255; CMAP[2][221]=173; CMAP[0][222]=152; CMAP[1][222]=255; CMAP[2][222]=174; CMAP[0][223]=150; CMAP[1][223]=255; CMAP[2][223]=176; CMAP[0][224]=149; CMAP[1][224]=255; CMAP[2][224]=177; CMAP[0][225]=147; CMAP[1][225]=255; CMAP[2][225]=178; CMAP[0][226]=146; CMAP[1][226]=255; CMAP[2][226]=180; CMAP[0][227]=144; CMAP[1][227]=255; CMAP[2][227]=182; CMAP[0][228]=142; CMAP[1][228]=255; CMAP[2][228]=183; CMAP[0][229]=141; CMAP[1][229]=255; CMAP[2][229]=185; CMAP[0][230]=139; CMAP[1][230]=255; CMAP[2][230]=187; CMAP[0][231]=138; CMAP[1][231]=255; CMAP[2][231]=189; CMAP[0][232]=137; CMAP[1][232]=255; CMAP[2][232]=191; CMAP[0][233]=135; CMAP[1][233]=255; CMAP[2][233]=193; CMAP[0][234]=134; CMAP[1][234]=255; CMAP[2][234]=195; CMAP[0][235]=132; CMAP[1][235]=255; CMAP[2][235]=197; CMAP[0][236]=131; CMAP[1][236]=255; CMAP[2][236]=199; CMAP[0][237]=129; CMAP[1][237]=255; CMAP[2][237]=201; CMAP[0][238]=128; CMAP[1][238]=255; CMAP[2][238]=204; CMAP[0][239]=126; CMAP[1][239]=255; CMAP[2][239]=206; CMAP[0][240]=125; CMAP[1][240]=255; CMAP[2][240]=209; CMAP[0][241]=123; CMAP[1][241]=255; CMAP[2][241]=211; CMAP[0][242]=122; CMAP[1][242]=255; CMAP[2][242]=214; CMAP[0][243]=120; CMAP[1][243]=255; CMAP[2][243]=217; CMAP[0][244]=119; CMAP[1][244]=255; CMAP[2][244]=220; CMAP[0][245]=117; CMAP[1][245]=255; CMAP[2][245]=222; CMAP[0][246]=116; CMAP[1][246]=255; CMAP[2][246]=225; CMAP[0][247]=114; CMAP[1][247]=255; CMAP[2][247]=228; CMAP[0][248]=113; CMAP[1][248]=255; CMAP[2][248]=231; CMAP[0][249]=111; CMAP[1][249]=255; CMAP[2][249]=235; CMAP[0][250]=110; CMAP[1][250]=255; CMAP[2][250]=238; CMAP[0][251]=108; CMAP[1][251]=255; CMAP[2][251]=241; CMAP[0][252]=106; CMAP[1][252]=255; CMAP[2][252]=244; CMAP[0][253]=105; CMAP[1][253]=255; CMAP[2][253]=248; CMAP[0][254]=104; CMAP[1][254]=255; CMAP[2][254]=251; CMAP[0][255]=102; CMAP[1][255]=255; CMAP[2][255]=255; } else // load from ascii file, generated by, e.g., makecpt // line1: r g b (e.g. 255 0 255) // line2: r g b (e.g. 255 0 240) // ... ... { //ifstream cmap(input.cmap, ios::in | ios::nocreate); ifstream cmap(input.cmap, ios::in); if (!cmap) { cerr << "cpxfiddle: ERROR: Could not open colormap file: " << input.cmap << "\n"; exit(1); } char dummyline[128*2]; int value; for (int ii=0; ii> value; CMAP[color][ii] = uchar(value); } cmap.getline(dummyline,128,'\n'); } cmap.close(); } // ______ Display colormap for testing ______ if (input.verbose==true) { #define VERBOSE #ifdef VERBOSE cerr << "Color table for SUNraster (rgb):\n"; for (int ii=0; ii input.rangemax) { cerr << argv[0] << ": ERROR : range min: " << input.rangemin << " is bigger than max: " << input.rangemax << "\n"; exit(1); } else if ( input.rangemin == input.rangemax || isnan(input.rangemin) || isnan(input.rangemax) ) { cerr << argv[0] << ": ERROR : Check range min: " << input.rangemin << " & max: " << input.rangemax << " !\n"; exit(1); } break; } case 'b': input.scalebar = true; break; case 'V': input.verbose = true; break; case IGNORENAN_OPTION: input.ignorenan = true; cerr << "debug: ignorenan" << IGNORENAN_OPTION << "\n"; // clean up extern may be neccessary break; case FULLSTAT_OPTION: input.fullstat = true; cerr << "debug: fullstat" << IGNORENAN_OPTION << "\n"; // clean up extern may be neccessary break; case 'h': usage(argv[0]); break; case '?': synopsis(argv[0]); } // switch } // commandlineoptions // ______ Check input ______ if (input.linelength == 0) { cerr << argv[0] << ": ERROR: No width specified.\n"; return false; } // filename: last argument // cerr << "OPTARG: " << argv[argc-1] << endl; // cerr << "OPTARG: " << argv[optind] << endl; if (argv[optind]=='\0') { cerr << argv[0] << ": ERROR: No input file specified.\n"; return false; } strcpy(input.ifile,argv[optind]); // ______ Check for: "cpxfiddle --help" ______ if (!strcmp(input.ifile,"help")) usage(argv[0]); // ____ new option for real4 input, not intented usage _____ // ____ outformat must be normal for this _____ // BK 13-Apr-2003 if (input.iformat == FORMATR8 || input.iformat == FORMATR4 || input.iformat == FORMATUC1 || input.iformat == FORMATI2) input.realinput = true; if (input.realinput) { if (input.dooutput != NORMAL) { cerr << argv[0] << ": ERROR: for real input formats, use -q normal\n"; usage(argv[0]); } } // ______ Compute numlines ______ // rather either numlines or width and compute the other. //ifstream infile(input.ifile, ios::in | ios::nocreate); ifstream infile(input.ifile, ios::in); if (!infile) { cerr << argv[0] << ": ERROR: inputfile: " << input.ifile << "not found.\n"; synopsis(argv[0]); } infile.seekg(0,ios::end); // filepointer at end //const int fsize = int(infile.tellg()) - input.headerlength;// account for e.g., 32 byte header //MA file offset > 4 GB , 200803 const streamoff fsize = infile.tellg() - streamoff(input.headerlength); // account for e.g., 32 byte header // here infile.close(); cerr << "# fsize: " << fsize << "\n"; input.bytesperelement = input.iformat%10; // real/imag is read seperately input.bytesperpixel = 2*input.bytesperelement;// per complex pixel // ____ adapt bytes per pixel for real input. -q normal must be ____ // BK 13-Apr-2003 if (input.realinput) { cerr << argv[0] << ": WARNING: using real input, width in non-complex pixels\n"; input.bytesperpixel = input.bytesperelement;// hopefully this is we have to do } input.numlines = fsize / input.bytesperpixel / input.linelength; input.bytesperline = input.bytesperpixel * input.linelength; // ______ Set other defaults ______ if (input.lastline==-1) input.lastline = input.numlines; if (input.lastpixel==-1) input.lastpixel = input.linelength; // ______ Check wrong... ______ if (input.lastline>input.numlines) { cerr << "#" << argv[0] << ": WARNING: -L: lastline>numlines; continuing with numlines of file.\n"; input.lastline = input.numlines; } if (input.lastpixel>input.linelength) { cerr << "#" << argv[0] << ": WARNING: -P: lastpixel>numpixels; continuing with width of file.\n"; input.lastpixel = input.linelength; } // if (input.numlines*input.linelength*input.bytesperpixel != fsize) // MA error check fix if (streamoff(input.numlines)*streamoff(input.linelength)*streamoff(input.bytesperpixel) != fsize) { cerr << argv[0] << ": ERROR: -w does not seem ok (checked with numlines*bytes)\n"; cerr << argv[0] << ": ERROR: but continuing, see it yourself...\n\a\a"; //synopsis(argv[0]); } if (input.lastline&1 | less\" in bash for more help.)" << endl; } // END shortexpl /**************************************************************** * synopsis * #%// BK 11-May-2000 * ****************************************************************/ void synopsis(char *programname) { cerr << "\n PROGRAM: " << programname << " (version " << SWVERSION << ")\n"; cerr << "\n SYNOPSIS:\n\t" << programname << " -w width [-f informat] [-q output] [-o outformat]" << "\n\t[-e exp] [-s scale] [-l line]" << " [-L line] [-p pixel] [-P pixel]" << "\n\t[-S x/y] [-M x/y] [-m mirror] [-c file]" << " [-r rmin/rmax] [-B swap] " << "\n\t[-H bytes] [-V] [-b] [-h[elp]] " << "[--] [--ignorenan] [--fullstat] inputfile\n"; shortexpl(); cerr << endl; exit(-1); } // END synopsis /**************************************************************** * usage * #%// BK 11-May-2000 * ****************************************************************/ void usage(char *programname) { cerr << "\n PROGRAM: " << programname << " (version " << SWVERSION << ")\n"; shortexpl(); cerr << "\n\n" << "\n\t 1 range (X) -->" << "\n\t 1 ---------------------" << "\n\t | | " << "\n\t | |" << "\n\t | e.g. float (2x4B) | azimuth (Y)" << "\n\t | format | |" << "\n\t | | |" << "\n\t | (major row order) | |" << "\n\t | (pixel interleav.) | \\/" << "\n\t | | " << "\n\t ---------------------\n" << "\n First a cutout is made," << "\n then the data is mirrored," << "\n and afterwards multilooked or subsampled," << "\n and finally the data is scaled and exp-ed." << "\n This explains why a mirrored image is not equal to" << "\n the original if the number of lines cannot be exactly" << "\n divided by the multilook or subsampling factor.\n" << "\n\n DESCRIPTION [default]:" << "\n -w mandatory Line length (width, rangepixels, X direction)" << "\n -e [1.0] Exponent: out=scale*output^exp" << "\n -s [1.0] Scale out=scale*output^exp" << "\n -l [1] First (azimuth Y) line" << "\n -L [all] Last (azimuth Y) line" << "\n -p [1] First (range X) pixel" << "\n -P [all] Last (range X) pixel" << "\n -M [1/1] Multilook factor in X/Y direction (range/azimuth)" << "\n No subsampling can be used combined with this" << "\n option. (Multilooking takes complex sum over" << "\n window(X,Y), divides by number of looks)" << "\n Output size: [floor(P-p+1)/mlX; floor(L-l+1)/mlY]." << "\n -S [1/1] Subsample factor in X/Y (range/azimuth)" << "\n Output dimensionY = ceil((L-l+1)/Y)." << "\n The last line does not have to equal -L." << "\n Output dimensionX = ceil((P-p+1)/X)." << "\n The last pixel does not have to equal -P." << "\n -q [mag] What to output:" << "\n NORMAL | MAG | PHASE | MIXED | REAL | IMAG" << "\n normal = (real, imag)," << "\n magnitude = sqrt(real^2 + imag^2)," << "\n phase = atan2(imag,real)," << "\n mixed = phase overlay, only with -o sunraster" << "\n real = line[2*j]," << "\n imag = line[2*j+1]." << "\n Normal option can be (mis)used to fiddle with, e.g.," << "\n float files (though even linelength required?)." << "\n -f [cr4] Input format identifier:" << "\n CC1 | CUC1 | CI2 | CI4 | CR4 | CR8" << "\n for complex 2x1B char, unsigned char, " << "\n short integer, integer, float, double" << "\n (major row order pixel interleaved complex data.)" << "\n -o [ascii] Output format identifier (to stdout):" << "\n UCHAR | SUNRASTER | FLOAT | SHORT | ASCII" << "\n uchar, short, sunraster, and float options" << "\n write binary to stdout!" << "\n -c [gray] Colormap for \"-o sunraster\" option." << "\n FILENAME | GRAY | JET | HOT | COOL | BERT | HSV" << "\n If cmap is a filename, then a ascii file with" << "\n 256 lines, containing r g b [0:255] is assumed." << "\n If cmap is a identifier, this colormap is used." << "\n -m code Flag to mirror file content in X or Y direction:" << "\n X | Y | XY | YX" << "\n If mirroring Y then the first output line is" << "\n line number P (default last in file). This means" << "\n that if -Y is specified, the last line not" << "\n necessarely is line -l (firstline default 1)" << "\n The same is true for mirroring in X direction." << "\n -r [rmin/rmax] uses given minimum and maximum range on data as scalling parameters. " << "\n Basically, it skips data sampling step for statistics (min,max,mean) computation" << "\n and defines (min,max,mean) values from given parameters." << "\n It only effects magnitude, normal and mixed mode outputs." << "\n For example, use it to scale coherence maps to 0-1 range." << "\n Tip: no need to use --ignorenan when you are using -r option." << "\n --ignorenan ignores nan values during calculation of min, max and mean for scaling of sunraster outputs. " << "\n It only effects magnitude, normal and mixed mode output types." << "\n Additionally, when binary output is done for magnitude images 0 is set instead of nan values. " << "\n --fullstat compute min, max and mean evaluating every pixel for scaling of sunraster outputs. " << "\n -B b|s Swap bytes." << "\n if -Bs then swap to host order." << "\n (call ntohs or ntohl, thus swapping from big endian" << "\n to host type, which is small endian for X86 PC's.)" << "\n if -Bb then swap to network order." << "\n (call htons or htonl, thus swapping to big endian" << "\n from host type, which is small endian for X86 PC's.)" << "\n On a big endian platform both these functions are" << "\n defined as NULL macros, and do nothing." << "\n -b Add a scalebar in lower right corner for -o sunraster" << "\n Only for -q phase and mixed." << "\n -H bytes Skip Header bytes, e.g., for GENESIS SUNraster floats." << "\n -V Verbose." << "\n -h[elp] This help." << endl << "\n\n EXAMPLES:" << "\n Check first few values in complex short file (width 100, height 200):" << "\n " << programname << " -w100 -fci2 -qnormal -oascii -L5 -P3 -V -- cpxfile" << endl << "\n To generate a grd file for use with GMT, without creating a large" << "\n tmpfile, use something like:" << "\n " << programname << " -w100 -fci2 -qphase -ofloat -- cpxfile | \\" << "\n " << " xyz2grd -Gfile.grd -R1/100/1/200 -Zf" << endl << "\n To crop a binary complex float file of width 781 and height 501:" << "\n (redirect, or your screen will be flooded with binary output!)" << "\n " << programname << " -w781 -fcr4 -qnormal -ofloat -l101 -L200 \\" << "\n " << " -p51 -P750 cpxfile > cpxfile.cropped" << endl << "\n To convert the phase of the same file to SUNraster format:" << "\n " << programname << " -w781 -fcr4 -qphase -osunraster \\" << "\n " << " -ccmap.rainbow -- cpxfile > phase.ras" << "\n display phase.ras" << "\n Where the colortable file is generated by (using GMT):" << "\n makecpt -Crainbow -T0/256/1 | \\" << "\n awk '{if (NR>3&&NR<260){print $2, $3, $4}}' > cmap.rainbow" << endl << "\n To create a sort of 8 bit pixmap, visualize with ImageMagick's" << "\n display as gray format:" << "\n " << programname << " -qphase -fcr4 -ouchar -w1 -- cpxfile > phase.uc" << "\n display -size 781x501 gray:phase.uc" << "\n The file phase.uc could also be converted to another format, e.g.:" << "\n rawtopgm 781 501 phase.uc > phase.pgm" << "\n xv phase.pgm" << endl << "\n But easier would have been to use " << programname << " to generate the" << "\n SUNraster file. This can be done by:" << "\n " << programname << " -w100 -qmag -osunraster -e0.3 -s1.1 file.cr4 > file.ras" << endl << "\n Where file.cr4 is complex real4, -e is used to equalize the " << "\n histogram, and -s to threshold the data (larger scale means" << "\n more white). To overlay the phase as layer over the magnitude:" << "\n " << programname << " -w100 -qmixed -osunraster -e0.3 -- file.cr4 > file.ras" << "\n " << "xv file.ras" << endl << "\n\n To read the header of a (non complex!) sunraster file " << "\n (8 int32 values):" << "\n " << programname << " -w1 -L4 -qnormal -fci4 -- file.ras" << "\n This program can be tricked to crop float files (non complex)" << "\n This program can be used for conversions of files, trick with -w1" << "\n To crop a bigendian file on a linux PC, swap and crop like:" << "\n " << programname << " -w100 -fci2 -qnormal -oshort -Bs -- cpxfile > newfile" << endl << "\n\n To read the content of a (non complex!) float vector with 32 byte header" << "\n " << programname << " -w1 -qnormal -fr4 -H32 -oascii -- file.ras" << endl << "\n\n To scale the content of a float file: coherence map to [ 0 1 ] range." << "\n " << programname << " -w 1000 -q normal -o sunraster -b -c gray -f r4 cohmap.r4 -r 0,1 > cohmap.ras " << endl << "\n\n BUGS:" << "\n -M with -m: First mirrored then multilooked." << "\n -B: Not tested properly, but simply calls functions." << "\n all: If cpxfile is a symbolic link, filesize cannot be" << "\n determined, and therefor the number of lines." << "\n Solution: Use the full path or use a hard link." << "\n (lot of options, binary to screen, but these are features.)" << endl << "\n\n SEE ALSO:" << "\n cpx2ps, display, rawtopgm, makecpt (GMT)" << "\n\n Please send your comments to: TUDelft, doris_users@tudelft.nl" << "\n " << "\n (BTW: view this help by piping stderr: " << programname << " -h |& more in csh" << "\n or " << programname << " -h 2>&1 | less in bash.)" << endl << endl; exit(-1); } // END usage //#EOF Doris-5.0.3Beta/sar_tools/cpxmult.cc000066400000000000000000000122431312547014700174110ustar00rootroot00000000000000// cpxmult.c // baarda::g++ -O cpxmult.c -o cpxmult // usage: cpxmult infile infile2 [outfile [add]] // cpxmult: pixelwise complex subtraction of 2 files (if add=1 then adds). // files: major row order binary (complex) float pixel interleaved // // exit levels: // 0: successful exit; // -1: wrong input; // 1: input file cannot be opened; // 2: output file cannot be opened; // // $Revision: 3.5 $ $Date: 2003/04/14 06:25:52 $ // BK 19-Apr-2000 // MA 64-bit update 2009-10-13 using namespace std; #include // cout #include // file #include // exit #include // atan etc. #include // conj etc. #include // strcat // ====== Typedefs for portability ====== typedef long long int64; typedef unsigned long long uint64; void usage(char *programname) { cerr << "\nProgram: " << programname << " subtracts or adds phase of two complex float files\n" << "\n USAGE:\n\t" << programname << " infile1 infile2 [outfile [add==0]]\n\n" << " infile[12] contain complex values a+ib\n" << " outfile contains (a1+ib1)*conj(a2+ib2)\n\n" << " If add=1 then phase is added (not conj).\n\n" << " EXAMPLE:\n\t" << programname << " cint.raw cint2.raw subtract.raw" << "\ndefault output file == infile1.min.infile2\n\n" << "exit levels: 0:ok; -1: wrong input; 1:ifile; 2:ofile.\n\n\n"; exit(-1); } int main(int argc, char* argv[]) { char ident[] = "@(#)Doris software, doris_users@tudelft.nl"; const int ONE27 = 127; char ifile1[ONE27]; // input file name char ifile2[ONE27]; // input file name char ofile[ONE27] = " "; // output filename == "ifile.ml" bool add = false; // take conj by default const int sizeofelement = sizeof(complex); // data in file // ====== Handle input ====== switch (argc) { case 5: add=true; // should be checked... //--- fall through ---// case 4: strcpy(ofile,argv[3]); // output filename arg3 //--- fall through ---// case 3: strcpy(ifile2,argv[2]); // input filename arg1 //--- fall through ---// case 2: strcpy(ifile1,argv[1]); // input filename arg1 break; // --- ---// default: usage(argv[0]); } // switch input // ______ Set defaults if required _____ if (!strcmp(ofile," ")) // nothing specified { strcpy(ofile,ifile1); strcat(ofile,".min."); strcpy(ofile,ifile2); } // ______ Check / echo input ______ cerr << "Program parameters:\n\t" << argv[0] << " " << ifile1 << " " << ifile2 << " " << ofile << " " << add << endl; if (!strcmp(ofile,ifile1) || !strcmp(ofile,ifile2)) { cerr << "input file name same as other one: " << ifile1 << " =? " << ofile << " =? " << ifile2 << endl; usage(argv[0]); } // ====== Start complex multiply ====== //ifstream infile1(ifile1, ios::in | ios::nocreate | ios::binary); ifstream infile1(ifile1, ios::in | ios::binary); if (!infile1) cerr << "Problem opening file: " << ifile1 << endl, exit(1); infile1.seekg(0,ios::end); // filepointer at end //const int totalbytes1 = infile1.tellg(); const streamoff totalbytes1 = infile1.tellg(); // MA infile1.seekg(0,ios::beg); // start of file1 //ifstream infile2(ifile2, ios::in | ios::nocreate | ios::binary); ifstream infile2(ifile2, ios::in | ios::binary); if (!infile2) cerr << "Problem opening file: " << ifile2 << endl, exit(1); infile2.seekg(0,ios::end); // filepointer at end //const int totalbytes2 = infile2.tellg(); const streamoff totalbytes2 = infile2.tellg(); // MA infile2.seekg(0,ios::beg); // start of file2 if (totalbytes1!=totalbytes2) { cerr << "size of file1 != size of file2: " << totalbytes1 << "!=" << totalbytes2 << endl; exit(2); } const uint64 numberofpixels = totalbytes1/sizeofelement; ofstream outfile(ofile, ios::out | ios::binary | ios::trunc); if (!outfile) cerr << "Problem opening file: " << ofile << endl, exit(2); int tenpercent = int(floor(numberofpixels/10.)); int percent = 0; register complex value1; register complex value2; // ______ Good compiler would get rid of if in for loop, but 2b sure. if (add) { for (register int i=0; i // cout #include // sprintf? #include // exit() #include // strptime, strftime #include // strcpy /* ***** */ int main(int argc, char* argv[]) { bool verbose = false; //true; if (verbose) cerr << "argc: " << argc << endl; if (argc != 4) { cerr << argv[0] << " -- Format/convert dates\n\n" << "Usage: " << argv[0] << " datestr informat outformat\n" << " where datestr: string, e.g., 15-JUL-2000\n" << " informat: specifier of datestr, see man strptime\n" << " outformat: specifier for output format, see man strptime\n\n" << " examples:\n" << " to obtain the day number in the year:\n" << argv[0] << " \"15-JUL-2000\" \"%d-%b-%Y\" \"%j\"\n\n" << " to convert week number, day to date:\n" << argv[0] << " \"week 15, day 2\" \"week %W, day %w\" \"%a %d-%B-%Y\"\n\n\n" << " also see man ctime, man strptime, man strftime\n"; exit(1); } // --- Read input --------------------------------------------- char indatestring[128]; char informat[128]; char outformat[128]; strcpy(indatestring,argv[1]); strcpy(informat,argv[2]); strcpy(outformat,argv[3]); if (verbose) cerr << "input: " << indatestring << " " << informat << " " << outformat << endl; // --- fill tm struct using daynumber with strptime, re-format it using strftime --- struct tm tm_tmp; strptime(indatestring,informat,&tm_tmp); // --- And use strftime to format the output string --- char outdatestring[128];// output int q = (int)(strftime(outdatestring,127,outformat,&tm_tmp)); // --- man ctime -------------------------------------------- //int tm_sec; /* seconds after the minute - [0, 61] */ //int tm_min; /* minutes after the hour - [0, 59] */ //int tm_hour; /* hour since midnight - [0, 23] */ //int tm_mday; /* day of the month - [1, 31] */ //int tm_mon; /* months since January - [0, 11] */ //int tm_year; /* years since 1900 */ //int tm_wday; /* days since Sunday - [0, 6] */ //int tm_yday; /* days since January 1 - [0, 365] */ //int tm_isdst; /* flag for alternate daylight savings time */ if (verbose) cerr << "tm_tmp.tm_sec: " << tm_tmp.tm_sec << endl << "tm_tmp.tm_min: " << tm_tmp.tm_min << endl << "tm_tmp.tm_hour: " << tm_tmp.tm_hour << endl << "tm_tmp.tm_mday: " << tm_tmp.tm_mday << endl << "tm_tmp.tm_mon: " << tm_tmp.tm_mon << endl << "tm_tmp.tm_year: " << tm_tmp.tm_year << endl << "tm_tmp.tm_wday: " << tm_tmp.tm_wday << endl << "tm_tmp.tm_yday: " << tm_tmp.tm_yday << endl << "tm_tmp.tm_isdst: " << tm_tmp.tm_isdst << endl; // --------------------------------------------------------- cout << outdatestring << endl; exit(0); } //EOF Doris-5.0.3Beta/sar_tools/flapjack.cc000066400000000000000000000122771312547014700174770ustar00rootroot00000000000000// flapjack.c // baarda:: g++ -O flapjack.c -o flapjack // usage: flapjack infile int.number // // exit levels: // 0: successful exit; // -1: wrong input; // 1: input file cannot be opened; // 2: output file cannot be opened; // // BK 18-Oct-2000 // $Revision: 3.5 $ $Date: 2003/04/14 06:25:52 $ // // PM 29-May-2006 // $Revision: 3.6 $ $Date: 2006/05/29 17:34:00 $ // - now sstream compatible, see bzr for details // // MA 19-Dec-2008 // $Revision: 3.7 $ // - support file size > 4GB #include // cout //#include // file #include // file #include // file #include // exit #include // atan etc. #include // conj etc. #include // strcat #include // strcat // ====== Typedefs for portability ====== typedef long long int64; typedef unsigned long long uint64; using namespace std; void usage(char *programname) { cerr << "\nProgram: " << programname << " pixelwise complex integer multiplication of a float complex\n" << " file. To be used to make linear combinations. \n" << " See also: cpxmult... \n" << "\n USAGE:\n\t" << programname << " infile1 [factor==2]\n\n" << " EXAMPLE:\n\t" << programname << " cint.raw 3" << "\noutput file == infile1." << programname << ".factor\n\n" << "exit levels: 0:ok; -1: wrong input; 1:ifile; 2:ofile.\n" << "please sent comments to: doris_users@tudelft.nl\n\n\n"; exit(-1); } int main(int argc, char* argv[]) { char ident[] = "@(#)Doris software, doris_users@tudelft.nl"; cerr << ident << endl; const int ONE27 = 127; char ifile[ONE27]; // input file name const int sizeofelement = sizeof(complex); // data in file int factor = 2; // default // ====== Handle input ====== switch (argc) { case 3: factor = atoi(argv[2]); // input filename arg1 //--- fall through ---// case 2: strcpy(ifile,argv[1]); // input filename arg1 break; // --- ---// default: usage(argv[0]); } // switch input // ______ Check / echo input ______ cerr << "Program parameters:\n\t" << argv[0] << " " << ifile << " " << factor << endl; if (factor < 2) usage(argv[0]); /* */ // ______ Set defaults if required _____ char ofile[ONE27]; // output filename == "ifile.flapjack" // [PM:29.05.2006]: start // ostrstream omem(ofile,ONE27); ostringstream omem; // omem << ifile << "." << argv[0] << factor << ends; omem << ifile << "." << argv[0] << factor << ends; strcpy(ofile,omem.str().c_str()); //quick debugging //cout << "Test [omem_stream]: " << omem.str() << "\n"; //cout << "Test [ofile]: " << ofile << "\n"; // [PM:29.05.2006]: stop // ====== Start complex exp. ====== //ifstream infile1(ifile, ios::in | ios::nocreate | ios::binary); ifstream infile1(ifile, ios::in | ios::binary); if (!infile1) { cerr << "Problem opening file: " << ifile << endl; exit(1); } infile1.seekg(0,ios::end); // filepointer at end const streamoff totalbytes1 = infile1.tellg(); infile1.seekg(0,ios::beg); // start of file1 const uint64 numberofpixels = totalbytes1/sizeofelement; cerr << "Total number of complex pixels in \"" << ifile << "\": " << numberofpixels << endl; ofstream outfile(ofile, ios::out | ios::binary | ios::trunc); if (!outfile) { cerr << "Problem opening file: " << ofile << endl; exit(2); } int tenpercent = int(floor(numberofpixels/10.)); int percent = 0; register complex value,result; register float mag; if (factor==2) { for (register int i=0; i 3 { for (register int i=0; i 4GB // // BO 21-Feb-2013 // - Modified to generate masks using namespace std; #include // cout #include // file #include // file //#include // file #include // exit #include // atan etc. #include // conj etc. #include // strcat // ====== Typedefs for portability ====== typedef long long int64; typedef unsigned long long uint64; void usage(char *programname) { cerr << "\nProgram: " << programname << " pixelwise mask generation from a float file.\n" << " To be used to scale float files.\n" << " see also: floatmult, cpxmult, flapjack, cpxfiddle... \n" << "\n USAGE:\n\t" << programname << " infile1 gt|lt|eq [threshold] \n\n" << " EXAMPLE:\n\t" << programname << " interfero.coh lt 0.4 \n" << "\n default threshold is 0.5\n\n" << "\noutput file == infile1.gt|lt|eq.threshold\n\n" << "exit levels: 0:ok; -1: wrong input; 1:ifile; 2:ofile.\n" << "please send comments to: batu@gi.alaska.edu\n\n\n"; exit(-1); } bool (*check)(float, float) = NULL; bool gt(float a, float b){ return a>b; } bool lt(float a, float b){ return a 4GB using namespace std; #include // cout #include // file #include // file //#include // file #include // exit #include // atan etc. #include // conj etc. #include // strcat // ====== Typedefs for portability ====== typedef long long int64; typedef unsigned long long uint64; void usage(char *programname) { cerr << "\nProgram: " << programname << " pixelwise float multiplication of a (complex) float complex file.\n" << " To be used to scale float files, or magnitude of complex files.\n" << " see also: cpxmult, flapjack, cpxfiddle... \n" << "\n USAGE:\n\t" << programname << " infile1 [factor==2.]\n\n" << " EXAMPLE:\n\t" << programname << " cint.raw 1.47" << "\noutput file == infile1." << programname << ".factor\n\n" << "exit levels: 0:ok; -1: wrong input; 1:ifile; 2:ofile.\n" << "please sent comments to: doris_users@tudelft.nl\n\n\n"; exit(-1); } int main(int argc, char* argv[]) { char ident[] = "@(#)Doris software, doris_users@tudelft.nl"; const int ONE27 = 127; char ifile[ONE27]; // input file name const int sizeofelement = sizeof(float); // data in file float factor = 2.; // default // ====== Handle input ====== switch (argc) { case 3: factor = atof(argv[2]); // input filename arg1 //--- fall through ---// case 2: strcpy(ifile,argv[1]); // input filename arg1 break; // --- ---// default: usage(argv[0]); } // switch input // ______ Check / echo input ______ cerr << "Program parameters:\n\t" << argv[0] << " " << ifile << " " << factor << endl; if (factor == 1) usage(argv[0]); // ______ Set defaults if required _____ char ofile[ONE27]; // output filename == "ifile.flapjack" // [PM:29.05.2006]: start // ostrstream omem(ofile,ONE27); ostringstream omem; // omem << ifile << "." << argv[0] << factor << ends; omem << ifile << "." << argv[0] << factor << endl; strcpy(ofile,omem.str().c_str()); //quick debugging //cout << "Test [omem_stream]: " << omem.str() << "\n"; //cout << "Test [ofile]: " << ofile << "\n"; // [PM:29.05.2006]: stop // ====== Start complex exp. ====== //ifstream infile1(ifile, ios::in | ios::nocreate | ios::binary); ifstream infile1(ifile, ios::in | ios::binary); if (!infile1) { cerr << "Problem opening file: " << ifile << ends; exit(1); } infile1.seekg(0,ios::end); // filepointer at end const streamoff totalbytes1 = infile1.tellg(); infile1.seekg(0,ios::beg); // start of file1 const uint64 numberofpixels = totalbytes1/sizeofelement; cerr << "Total number of float pixels in \"" << ifile << "\": " << numberofpixels << endl; ofstream outfile(ofile, ios::out | ios::binary | ios::trunc); if (!outfile) { cerr << "Problem opening output file: " << ofile << endl; exit(2); } int tenpercent = int(floor(numberofpixels/10.)); int percent = 0; register float value; for (register int i=0; i #include #include #include // ntohl byteorder x86-HP unix int main (int argc,char *argv[]) { FILE *ofp; int c; //int bflg, aflg, errflg; extern char *optarg; //extern int optind, optopt; int header[8]; int width,height,depth,datatype,length,maplength,maptype; int wrong=0; int computelength=1; /* defaults */ width = 0; height = 0; depth = 8; length = 0; datatype = 0; maplength = 0; maptype = 0; while ((c = getopt(argc, argv, "w:h:d:t:l:L:m:")) != -1) { switch (c) { case 'w': width = atoi(optarg); break; case 'h': height = atoi(optarg); break; case 'd': depth = atoi(optarg); break; case 't': datatype = atoi(optarg); break; case 'l': maplength = atoi(optarg); break; case 'L': length = atoi(optarg); computelength = 0; break; case 'm': maptype = atoi(optarg); break; case '?': wrong = 1; break; } } if ( width == 0 ) wrong=1; if ( height == 0 ) wrong=1; /* check input */ if ( wrong == 1 ) { fprintf(stderr, "PROG: write header for sunraster file\n"); fprintf(stderr, " can be used together with cat.\n"); fprintf(stderr, " e.g. 1) make header\n"); fprintf(stderr, " 2) cat header datafile > sunrasterfile.ras\n"); fprintf(stderr, "\n"); fprintf(stderr, "SYNOPSIS: prog -w width -h height [-ddepth]\n"); fprintf(stderr, " [-Ldatalength] [-tdatatype] [-mmaptype]\n"); fprintf(stderr, " [-lmaplength]\n"); fprintf(stderr, "\n"); fprintf(stderr, "USAGE (a SUNraster header is defined as 8 integers):\n"); fprintf(stderr, " ras_magic: [0x59a66a95] magic number\n"); fprintf(stderr, " -w ras_width: [0] width (pixels) of image\n"); fprintf(stderr, " -h ras_height: [0] height (pixels) of image\n"); fprintf(stderr, " -d ras_depth: [8] depth (1, 8, or 24 bits) of pixel\n"); fprintf(stderr, " -L ras_length: [computed] length (bytes) of image\n"); fprintf(stderr, " -t ras_type: [0] type of file; see RT_* below\n"); fprintf(stderr, " -m ras_maptype: [0] type of colormap; see RMT_* below\n"); fprintf(stderr, " -l ras_maplength: [0] length (bytes) of following map\n"); fprintf(stderr, "\n"); fprintf(stderr, " /* Sun supported ras_type's RT_ */\n"); fprintf(stderr, "0 Raw pixrect image in 68000 byte order \n"); fprintf(stderr, "1 Raw pixrect image in 68000 byte order \n"); fprintf(stderr, "2 Run-length compression of bytes \n"); fprintf(stderr, "3 XRGB or RGB instead of XBGR or BGR \n"); fprintf(stderr, "4 tiff <-> standard rasterfile \n"); fprintf(stderr, "5 iff (TAAC format) <-> standard rasterfile \n"); fprintf(stderr, "0xffff Reserved for testing \n"); fprintf(stderr, "\n"); fprintf(stderr, " /* Sun registered ras_maptype's RMT_ */ \n"); fprintf(stderr, "0 ras_maplength is expected to be 0 \n"); fprintf(stderr, "1 red[ras_maplength/3],green[],blue[] \n"); fprintf(stderr, "2 RMT_RAW \n"); fprintf(stderr, "\n"); exit(1); } if (computelength==1) length = width * height * (int)(depth/8); fprintf(stderr, "\n"); fprintf(stderr, "arguments used:"); fprintf(stderr, "\n width: %i", width); fprintf(stderr, "\n height: %i", height); fprintf(stderr, "\n depth: %i", depth); fprintf(stderr, "\n length: %i", length); fprintf(stderr, "\n datatype: %i", datatype); fprintf(stderr, "\n maptype: %i", maptype); fprintf(stderr, "\n maplength: %i", maplength); fprintf(stderr, "\n"); header[0] = ntohl(0x59a66a95); /* magic number, always same(?) */ header[1] = ntohl(width); /* #columns */ header[2] = ntohl(height); /* #rows */ header[3] = ntohl(depth); /* in bits email s suchandt */ header[4] = ntohl(length); /* in bytes */ header[5] = ntohl(datatype); /* email s suchandt */ header[6] = ntohl(maptype); /* ... */ header[7] = ntohl(maplength); /* ... */ /* Write SUN raster file */ ofp=fopen("sunrasterheader","w"); fwrite(header, sizeof(int), 8, ofp); fclose(ofp); free(header); return 0; } Doris-5.0.3Beta/sar_tools/readrasterheader.cc000066400000000000000000000107261312547014700212260ustar00rootroot00000000000000// prog to read a header... // g++ -O readrasterheader.c -o readrasterheader // BK 21-Nov-2000 using namespace std; #include #include #include // exit() //#include #include // ntohl byteorder x86-HP unix typedef unsigned long ulong; typedef unsigned char uchar; // changed reading get,read,put, functions for g++v3.2 /* ************************************************************ */ #define RAS_MAGIC 0x59a66a95 struct header { ulong magic; /* magic number */ ulong width; /* width (pixels) of image */ ulong height; /* height (pixels) of image */ ulong depth; /* depth (1, 8, or 24 bits) of pixel */ ulong length; /* length (bytes) of image */ ulong type; /* type of file; see RT_* below */ ulong maptype; /* type of colormap; see RMT_* below */ ulong maplength; /* length (bytes) of following map */ /* color map follows for ras_maplength bytes, followed by image */ }; /* Sun supported ras_type's */ #define RT_OLD 0 /* Raw pixrect image in 68000 byte order */ #define RT_STANDARD 1 /* Raw pixrect image in 68000 byte order */ #define RT_BYTE_ENCODED 2 /* Run-length compression of bytes */ #define RT_FORMAT_RGB 3 /* XRGB or RGB instead of XBGR or BGR */ #define RT_FORMAT_TIFF 4 /* tiff <-> standard rasterfile */ #define RT_FORMAT_IFF 5 /* iff (TAAC format) <-> standard rasterfile */ /* Sun registered ras_maptype's */ #define RMT_RAW 2 /* Sun supported ras_maptype's */ #define RMT_NONE 0 /* ras_maplength is expected to be 0 */ #define RMT_EQUAL_RGB 1 /* red[ras_maplength/3],green[],blue[] */ typedef struct { int type; int length; unsigned char *map[3]; } colormap; /* ************************************************************ */ int main (int argc,char *argv[]) { if (argc<2) { cerr << argv[0] << " -- display header of SUN raster file.\n"; cerr << "usage: " << argv[0] << " rasfile\n"; cerr << "example: " << argv[0] << " file.ras\n"; cerr << "ex2: " << argv[0] << " file.ras |& head -n 9\n"; exit(1); } // ______ Open file ______ ifstream ifp(argv[1]); if (!ifp) {cerr << "infile " << argv[1] << " does not exist\n"; exit(1);} // ______ Read HEADER 32 bytes and convert to big endian ______ header HEADER; //cerr << "1: " << &HEADER << endl; //cerr << "1: " << (uchar *) &HEADER << endl; ifp.read(((char *) &HEADER), sizeof(HEADER)); // for(int i=0; i // cout #include // file #include // exit #include // atan etc. #include // strcat etc. void usage(char *programname) { cerr << "\nProgram: " << programname << " wraps float binary file to interval [a,b)\n" << "\n USAGE:\n\t" << programname << " infile [a b [ofile]]\n\n" << " EXAMPLE:\n\t" << programname << " interferogram.raw -4pi 4pi interf4.raw\n" << "\ndefault output file == infile.wrap" << "\ndefault interval [a b) == [-pi pi)\n\n"; exit(-1); } int main(int argc, char* argv[]) { //char ident[] = "@(#)Doris software, doris_users@tudelft.nl"; char ident[] = "@(#)wrap: Doris software, $Revision: 3.6 $, $Author: kampes $"; cerr << ident << endl; const int ONE27 = 127; const float PI = 4.*atan(1.); // pi char ifile[ONE27]; // input file name char ofile[ONE27] = " "; // output filename == "ifile.ml" char dummy[ONE27]; // dummy string //char dummy2[ONE27]; // dummy string float a = -999.; // start interval float b = -999.; // stop interval register int i; // general counter const int sizeofelement = sizeof(float); // data in float file // ====== Handle input ====== switch (argc) // wrap infile a b outfile { case 3: usage(argv[0]); // 3 arg. not allowed. break; // not required case 5: strcpy(ofile,argv[4]); // output filename arg4 //--- fall through ---// case 4: strcpy(dummy,argv[3]); // interval: b i = (int)strlen(dummy); if (dummy[i-1] == 'i') // likely to be pi { if (!strcmp(dummy,"pi")) b = PI; else if (!strcmp(dummy,"-pi")) b = -PI; else { dummy[i-2]='\0'; b = PI*atof(dummy); } } else { b = atof(dummy); } strcpy(dummy,argv[2]); // interval: a i = (int)strlen(dummy); if (dummy[i-1] == 'i') // likely to be pi { if (!strcmp(dummy,"pi")) a = PI; else if (!strcmp(dummy,"-pi")) a = -PI; else { dummy[i-2]='\0'; a = PI*atof(dummy); } } else { a = atof(dummy); } //--- fall through ---// case 2: strcpy(ifile,argv[1]); // input filename arg1 break; // --- ---// default: usage(argv[0]); } // switch input // ______ Set defaults if required _____ if (abs(a+999.) < 1e-10) a = -PI; if (abs(b+999.) < 1e-10) b = PI; if (!strcmp(ofile," ")) // nothing specified { strcpy(ofile,ifile); strcat(ofile,".wrap"); } // ______ Check input ______ if (a>=b) { cerr << "interval (a,b) = (" << a << "," << b << "): a should be smaller than b.\n"; usage(argv[0]); } if (abs(a+b)>1e-10 && abs(a)>1e-10) { cerr << "interval (a,b): should be either: a=-b or a=0\n"; usage(argv[0]); } if (!strcmp(ofile,ifile)) { cerr << "input file name same as output file name: " << ifile << " = " << ofile << endl; usage(argv[0]); } cerr << "Program parameters:\n\t" << argv[0] << " " << ifile << " " << a << " " << b << " " << ofile << endl; // ====== Start wrapping ====== //#if __GNUC__ >= 3 // ifstream image(ifile, ios::in | ios::nocreate | ios::binary); //#else ifstream image(ifile, ios::in | ios::binary); //#endif image.seekg(0,ios::end); // filepointer at end if (!image) cerr << "Problem opening file: " << ifile << endl, exit(1); const int totalbytes = image.tellg(); const int numberofpixels = totalbytes/sizeofelement; image.seekg(0,ios::beg); // start of file ofstream wrapped(ofile, ios::out | ios::binary | ios::trunc); if (!wrapped) cerr << "Problem opening file: " << ofile << endl, exit(2); register float phase; const float bereik = b-a; const float normal = (.5*bereik)/PI; bool ais0 = false; if (abs(a)<1e-10) ais0 = true; for (i=0; i